diff --git a/.agents/skills/add-block/SKILL.md b/.agents/skills/add-block/SKILL.md index f1f2045c4c1..8b71d3c7b9f 100644 --- a/.agents/skills/add-block/SKILL.md +++ b/.agents/skills/add-block/SKILL.md @@ -1081,6 +1081,9 @@ Validate the block against every tool in `tools.access`: tool must already be either a registered `InternalToolConfig.operation` or an absolute external HTTP(S) `ToolConfig.request`. If transport needs to change, use the `add-tools` skill; never add a same-origin `/api/...` hop or a `directExecution` property from the block. +8. **Verify every tool declares `effect`** — the block's catalog `effect` (and its per-operation + `operationEffects`) is derived from them, so a mislabelled tool misreports the block to agents + and Assistant. Fix the tool with the `add-tools` rules (Declaring the effect), never the block. ## Option Lists: `selectorKey` or `options`, never a per-block fetcher diff --git a/.agents/skills/add-integration/SKILL.md b/.agents/skills/add-integration/SKILL.md index 0b5dcadd9d7..6f15c8e6eef 100644 --- a/.agents/skills/add-integration/SKILL.md +++ b/.agents/skills/add-integration/SKILL.md @@ -190,6 +190,11 @@ Never point a tool at `/api/...`, construct an absolute URL back to Sim, declare resources. A real external/browser route and an in-process tool may share the same operation, but neither calls the other. Follow the full transport and handler rules in the `add-tools` skill. +Every tool declares `effect: 'read' | 'write'`, classified from the API docs you researched in Step 1 +by the rules in `add-tools` → Declaring the effect. `bun run check:tool-effects` checks only that the +label agrees with the HTTP method (or carries a `// tool-effect:` reason); classifying POST and +in-process operations is on you. + **types.ts:** ```typescript import type { ToolResponse } from '@/tools/types' @@ -506,6 +511,7 @@ If creating V2 versions (API-aligned outputs): - [ ] No tool points to `/api/...`, constructs a URL back to Sim, declares `request.internal` or a `directExecution` property (fails `bun run check:tool-request-boundary`), or has an HTTP fallback for an in-process operation - [ ] All params have correct visibility +- [ ] Every tool declares `effect` from its documented semantics; `bun run check:tool-effects` passes - [ ] All nullable fields use `?? null` - [ ] All optional outputs have `optional: true` - [ ] Created `index.ts` barrel export diff --git a/.agents/skills/add-tools/SKILL.md b/.agents/skills/add-tools/SKILL.md index f2b1972c215..7f45f81e0f7 100644 --- a/.agents/skills/add-tools/SKILL.md +++ b/.agents/skills/add-tools/SKILL.md @@ -82,6 +82,7 @@ export const {serviceName}{Action}Tool: ToolConfig< name: '{Service} {Action}', // Human readable description: 'Brief description', // One sentence version: '1.0.0', + effect: 'write', // 'read' only if it changes nothing outside Sim (see Declaring the effect) // Required whenever the tool takes a saved credential — browser OAuth or service account oauth: { @@ -164,6 +165,7 @@ export const {serviceName}{Action}Tool: InternalToolConfig< name: '{Service} {Action}', description: 'Brief description', version: '1.0.0', + effect: 'write', // `read` only once you have verified the operation changes nothing outside Sim params: { // Same canonical metadata as an external tool. }, @@ -183,6 +185,42 @@ trusted `request.context` for authority, forwards `request.signal`, and returns `Response` contract expected by the tool executor. It has no URL, method, request headers, fetch fallback, or caller-controlled `_context` authority. +## Declaring the effect + +Every tool declares `effect: 'read' | 'write'` (required by `ToolConfig`, so type-check fails a tool +without one). It is public catalog metadata: Assistant applies its read or write policy by it, and +`sim blocks get` and `sim workflows source params` show it to agents. +Labelling a write `read` is the one unsafe mistake, so classify from the provider's documented +semantics, never the name alone. + +`read` means the call changes nothing outside Sim: no create, update, delete, send, post, trigger, +enqueue, consume, or mark-read; starts no asynchronous provider job or query execution (one with its own id that +can keep running), even a short-lived one; a synchronous read-only query is fine; leaves no run, conversation, history item, or other resource in an account; no contact data revealed for credits; no external delivery. Usage billing for the call +itself does not count. `write` is anything else. + +**Contact reveals:** revealing a person's contact data (email, phone) for credits is `write`: an +email or phone finder, a person enrichment that returns an email or phone, and a domain search that +lists people's emails are `write` even over GET (carry `// tool-effect:`). Company/firmographic +lookups and verifications that only spend lookup credits are `read`: a company enrichment, a people +search that returns no email or phone, and an email verifier. + +- `read`: GET/HEAD reads, and POST endpoints the docs define as search, query, list, get, lookup, or + verify; LLM, embedding, transcription, TTS, and media-generation calls that leave nothing in the + provider account; queries the server enforces as read-only (a read-only transaction or setting, + never a client-side screen alone). +- `write`: an effect that depends on the params (a `method` param or function-valued + `request.method` that can pick PUT/PATCH/DELETE or a mutating POST, raw SQL or Cypher the server + does not restrict to reads, a generic RPC or command); a GET whose `transformResponse` or + `postProcess` then writes; a read that consumes or acknowledges (a queue receive, mark-as-read); + media generation, transcription, crawls, exports, and research or agent runs that leave a job, + run, asset, or history item in the provider account; a chat that keeps a conversation; a reveal + or enrichment that creates a resource or delivers to a webhook; anything that saves to the + workspace. When unsure, `write`. +- PUT/PATCH/DELETE are `write`. A static GET/HEAD labelled `write`, or PUT/PATCH/DELETE labelled + `read`, fails the audit unless the `effect` line carries `// tool-effect: ` on one of the + two lines above it; use it only for a genuine exception such as a GET that writes in `postProcess`. +- A factory that builds tools from definitions takes `effect` per definition and passes it through. + ## Critical Rules for Parameters ### Visibility Options @@ -606,6 +644,8 @@ If creating V2 tools (API-aligned outputs), use `_v2` suffix: ## Checklist Before Finishing - [ ] All tool IDs use snake_case +- [ ] Every tool declares `effect`, classified by the rules in Declaring the effect, and + `bun run check:tool-effects` passes - [ ] Chose exactly one boundary: registered `InternalToolConfig.operation` or absolute external HTTP(S) `ToolConfig.request` - [ ] No tool request points to `/api/...`, constructs a URL back to Sim, or declares diff --git a/.agents/skills/validate-integration/SKILL.md b/.agents/skills/validate-integration/SKILL.md index 40b2472510a..a9d69a3823e 100644 --- a/.agents/skills/validate-integration/SKILL.md +++ b/.agents/skills/validate-integration/SKILL.md @@ -77,6 +77,12 @@ For **every** tool file, check: - [ ] Tool `description` is a concise one-liner describing what it does - [ ] Tool `version` is set (`'1.0.0'` or `'2.0.0'` for V2) +### Effect +- [ ] Every tool declares `effect`, and the label matches the API docs, not the name (rules: + `add-tools` → Declaring the effect) +- [ ] Any `// tool-effect: ` sits on a genuine verb/label exception, and + `bun run check:tool-effects` passes + ### Params - [ ] All required API params are marked `required: true` - [ ] All optional API params are marked `required: false` diff --git a/.claude/rules/sim-workflow-code.md b/.claude/rules/sim-workflow-code.md index d7435063c05..24d4b87b2d8 100644 --- a/.claude/rules/sim-workflow-code.md +++ b/.claude/rules/sim-workflow-code.md @@ -48,6 +48,17 @@ workspace directory). | `apps/sim/blocks/sdk-names/.json` | Frozen SDK builder names, one file per block type | | `apps/sim/app/workspace/**/panel/components/code/` | The read-only Code tab | +Public docs live in `apps/docs/content/docs/workflows/code/`. The exit-code, diagnostic-code, limit +and per-kind layout tables of `exit-codes.mdx`, `diagnostics.mdx`, `limits.mdx` and `directory.mdx` sit between +`workflow-code-docs` markers and come from their owners (`source-exit-codes.ts`, SYNTAX.md and `workspace-code`'s +`diagnostics/codes.ts` TSDoc, the `*_LIMITS` constants, `WORKSPACE_KIND_SPECS`): edit the owner, then run +`bun run generate:workflow-code-docs` (`check:workflow-code-docs` fails on drift, a diagnostic code a page names that +no engine emits, a limit or diagnostic code with no docs entry, and a `typescript@x.y.z` pin other than the CLI's). +A limit also needs a label in the generator's `WORKFLOW_LIMIT_LABELS` or `WORKSPACE_LIMIT_LABELS`. +A new exit code also needs a `[#exit-]` section in `troubleshooting.mdx`, which the same check requires +for every non-zero code `sourceExitCodeRows` lists. Behaviour a user relies on (identity, stale, the three-way rule, +promotion) is explained once, in `how-it-works.mdx`; change it there when an engine changes it. + Dependencies point one way: `packages/workflow-types` → `packages/workflow-code` → `packages/workspace-code` and `packages/workflow-sdk` → the CLI and `apps/sim`. `check:boundaries` keeps both engines and `packages/table-cells` pure (no Node built-ins, `eval`, `globalThis`, dynamic import): they run in the browser, the CLI and the @@ -198,7 +209,7 @@ changed. | `.sim/base.json` (workspace) | `version: 1` | Same policy | | `workflow_source_meta` | `version: 1` | Same policy; a bump needs a data migration | | Fingerprints | `sf1:` (workflow), `rf1:` (resource) | Any change to canonicalize or a kind's `canonical()` output changes every stored fingerprint and makes every checkout stale; treat it as a format change | -| SDK surface | `// @sim-sdk 1`, `SDK_MAJOR`, `OLDEST_SDK_MAJOR` | Compile refuses a newer major and reads down to the floor | +| SDK surface | `// @sim-sdk 1`, `SDK_MAJOR` | Compile refuses any major but the server's | | `apps/sim/blocks/sdk-names/` | append-only | Never rename or remove a name | Nothing upgrades an old version: a bump is a hard refusal until a migration exists. A lock or base diff --git a/.cursor/rules/sim-workflow-code.mdc b/.cursor/rules/sim-workflow-code.mdc index 77d1474b0f1..100c3bdefe5 100644 --- a/.cursor/rules/sim-workflow-code.mdc +++ b/.cursor/rules/sim-workflow-code.mdc @@ -28,6 +28,17 @@ workspace directory). | `apps/sim/blocks/sdk-names/.json` | Frozen SDK builder names, one file per block type | | `apps/sim/app/workspace/**/panel/components/code/` | The read-only Code tab | +Public docs live in `apps/docs/content/docs/workflows/code/`. The exit-code, diagnostic-code, limit +and per-kind layout tables of `exit-codes.mdx`, `diagnostics.mdx`, `limits.mdx` and `directory.mdx` sit between +`workflow-code-docs` markers and come from their owners (`source-exit-codes.ts`, SYNTAX.md and `workspace-code`'s +`diagnostics/codes.ts` TSDoc, the `*_LIMITS` constants, `WORKSPACE_KIND_SPECS`): edit the owner, then run +`bun run generate:workflow-code-docs` (`check:workflow-code-docs` fails on drift, a diagnostic code a page names that +no engine emits, a limit or diagnostic code with no docs entry, and a `typescript@x.y.z` pin other than the CLI's). +A limit also needs a label in the generator's `WORKFLOW_LIMIT_LABELS` or `WORKSPACE_LIMIT_LABELS`. +A new exit code also needs a `[#exit-]` section in `troubleshooting.mdx`, which the same check requires +for every non-zero code `sourceExitCodeRows` lists. Behaviour a user relies on (identity, stale, the three-way rule, +promotion) is explained once, in `how-it-works.mdx`; change it there when an engine changes it. + Dependencies point one way: `packages/workflow-types` → `packages/workflow-code` → `packages/workspace-code` and `packages/workflow-sdk` → the CLI and `apps/sim`. `check:boundaries` keeps both engines and `packages/table-cells` pure (no Node built-ins, `eval`, `globalThis`, dynamic import): they run in the browser, the CLI and the @@ -178,7 +189,7 @@ changed. | `.sim/base.json` (workspace) | `version: 1` | Same policy | | `workflow_source_meta` | `version: 1` | Same policy; a bump needs a data migration | | Fingerprints | `sf1:` (workflow), `rf1:` (resource) | Any change to canonicalize or a kind's `canonical()` output changes every stored fingerprint and makes every checkout stale; treat it as a format change | -| SDK surface | `// @sim-sdk 1`, `SDK_MAJOR`, `OLDEST_SDK_MAJOR` | Compile refuses a newer major and reads down to the floor | +| SDK surface | `// @sim-sdk 1`, `SDK_MAJOR` | Compile refuses any major but the server's | | `apps/sim/blocks/sdk-names/` | append-only | Never rename or remove a name | Nothing upgrades an old version: a bump is a hard refusal until a migration exists. A lock or base diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 4b8a9c59d91..994baa9a673 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -473,6 +473,7 @@ In addition, you will need to update the registries: name: 'Pinecone Fetch', description: 'Fetch vectors from Pinecone database', version: '1.0.0', + effect: 'read', // 'write' unless it changes nothing outside Sim // OAuth configuration (if applicable) provider: 'pinecone', // ID of the OAuth provider diff --git a/.github/actions/image/action.yml b/.github/actions/image/action.yml index b4a3307c990..73654b5fae4 100644 --- a/.github/actions/image/action.yml +++ b/.github/actions/image/action.yml @@ -67,7 +67,7 @@ runs: # under 300 MB, sat at 249 GB. Sticky disks bill at ~$0.51/GB-month. - name: Set up Blacksmith builder if: inputs.provider == '' || inputs.provider == 'blacksmith' - uses: useblacksmith/setup-docker-builder@06dd9c83a5d541274d2e3ac67625560979275267 # v2 + uses: useblacksmith/setup-docker-builder@9657a6e02ca6445e6d6ce5ffaf370f4828dea50d # v2 with: cache-key: ${{ steps.cache-key.outputs.value }} diff --git a/.github/scripts/http-e2e.sh b/.github/scripts/http-e2e.sh index a27b9acd6bb..f67b72a5dbf 100755 --- a/.github/scripts/http-e2e.sh +++ b/.github/scripts/http-e2e.sh @@ -188,7 +188,7 @@ wait_ready() { case "$group" in scim) export NEXT_PUBLIC_FORCE_HOSTED=true - export BILLING_ENABLED=true NEXT_PUBLIC_BILLING_ENABLED=true + export BILLING_ENABLED=true export ENTERPRISE_ENABLED=true export SCIM_ENABLED=true export SSO_ENABLED=true diff --git a/.github/scripts/wait-for-e2e-build.sh b/.github/scripts/wait-for-e2e-build.sh index eca34e0de94..8c7e4631deb 100755 --- a/.github/scripts/wait-for-e2e-build.sh +++ b/.github/scripts/wait-for-e2e-build.sh @@ -1,8 +1,9 @@ #!/usr/bin/env bash # Blocks until this run's `build (e2e)` job finishes, so an e2e job can check out, install and # migrate while the build runs instead of after it. Exits 0 only when that job succeeded; a failed, -# cancelled or skipped build, a missing or duplicated build job, or a failed API call exits non-zero. -# The job's own timeout bounds the wait. +# cancelled or skipped build, a missing or duplicated build job, or an API that keeps failing exits +# non-zero. A single failed poll (GitHub occasionally returns a truncated body) is retried on the next +# one. The job's own timeout bounds the wait. # # Usage: wait-for-e2e-build.sh (reads GITHUB_REPOSITORY and GITHUB_RUN_ID; needs `actions: read`) set -euo pipefail @@ -11,14 +12,26 @@ set -euo pipefail : "${GITHUB_RUN_ID:?}" poll_seconds=${E2E_BUILD_POLL_SECONDS:-10} +max_api_failures=3 +api_failures=0 started=$SECONDS while :; do # `filter=latest` lists each job's latest attempt, so re-running only a failed e2e job still sees # the build an earlier attempt finished. Called from ci.yml the name carries a `checks / ` prefix. - state=$(gh api --paginate "repos/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID/jobs?filter=latest&per_page=100" \ + if ! state=$(gh api --paginate "repos/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID/jobs?filter=latest&per_page=100" \ --jq '.jobs[] | select(.name == "build (e2e)" or (.name | endswith(" / build (e2e)"))) - | "\(.status) \(.conclusion // "")"') + | "\(.status) \(.conclusion // "")"'); then + api_failures=$((api_failures + 1)) + if [ "$api_failures" -ge "$max_api_failures" ]; then + echo "::error::Could not read this run's jobs $api_failures times in a row." + exit 1 + fi + echo "::warning::Could not read this run's jobs; trying again." + sleep "$poll_seconds" + continue + fi + api_failures=0 matches=$(printf '%s' "$state" | grep -c . || true) if [ "$matches" -ne 1 ]; then echo "::error::Expected one build (e2e) job in this run, found $matches." diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e3505f145e3..c2e4e06a821 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -243,7 +243,7 @@ jobs: - name: Login to Amazon ECR id: login-ecr - uses: aws-actions/amazon-ecr-login@03f1aad4c6c7ffd436567f42f9384779290529bd # v2 + uses: aws-actions/amazon-ecr-login@7290e214a610b32bc0eef81748948b6d466a8783 # v2 - name: Login to Docker Hub uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4 @@ -409,7 +409,7 @@ jobs: - name: Login to Amazon ECR id: login-ecr - uses: aws-actions/amazon-ecr-login@03f1aad4c6c7ffd436567f42f9384779290529bd # v2 + uses: aws-actions/amazon-ecr-login@7290e214a610b32bc0eef81748948b6d466a8783 # v2 - name: Login to Docker Hub uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4 @@ -527,7 +527,7 @@ jobs: - name: Login to Amazon ECR id: login-ecr - uses: aws-actions/amazon-ecr-login@03f1aad4c6c7ffd436567f42f9384779290529bd # v2 + uses: aws-actions/amazon-ecr-login@7290e214a610b32bc0eef81748948b6d466a8783 # v2 # Deploy-tag moves must be monotonic: a re-run of an old run must never # retag latest/staging back to stale code. A superseded first-attempt diff --git a/.github/workflows/desktop-e2e.yml b/.github/workflows/desktop-e2e.yml index bbf18bb6d15..9999764568b 100644 --- a/.github/workflows/desktop-e2e.yml +++ b/.github/workflows/desktop-e2e.yml @@ -157,15 +157,15 @@ jobs: # The terminal-cancel suite drives a real tmux server; without tmux its tmux scenarios skip. - name: Install tmux run: brew install tmux + env: + HOMEBREW_NO_AUTO_UPDATE: '1' + HOMEBREW_NO_INSTALL_CLEANUP: '1' - name: Run Playwright _electron smoke suite working-directory: apps/desktop run: bun run ../../scripts/desktop-e2e.ts ${{ matrix.shard }}/${{ strategy.job-total }} env: PLAYWRIGHT_JSON_OUTPUT_FILE: test-results/desktop-smoke.json - BACKGROUND_EXECUTOR_REPORT_PATH: test-results/background-executor-report.json - TERMINAL_CANCEL_REPORT_PATH: test-results/terminal-cancel-report.json - CONTINUE_SIGN_IN_REPORT_PATH: test-results/continue-sign-in-report.json - name: Upload test results if: failure() @@ -244,14 +244,13 @@ jobs: # The terminal-cancel suite drives a real tmux server; without tmux its tmux scenarios skip. - name: Install tmux run: brew install tmux + env: + HOMEBREW_NO_AUTO_UPDATE: '1' + HOMEBREW_NO_INSTALL_CLEANUP: '1' - name: Run Playwright _electron smoke suite working-directory: apps/desktop run: bunx playwright test - env: - BACKGROUND_EXECUTOR_REPORT_PATH: test-results/background-executor-report.json - TERMINAL_CANCEL_REPORT_PATH: test-results/terminal-cancel-report.json - CONTINUE_SIGN_IN_REPORT_PATH: test-results/continue-sign-in-report.json - name: Upload test results if: failure() diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.yml index 836f2a2644d..32ff85e3945 100644 --- a/.github/workflows/desktop-release.yml +++ b/.github/workflows/desktop-release.yml @@ -221,15 +221,15 @@ jobs: - name: Install tmux run: brew install tmux + env: + HOMEBREW_NO_AUTO_UPDATE: '1' + HOMEBREW_NO_INSTALL_CLEANUP: '1' - name: Run Electron smoke partition working-directory: apps/desktop env: SIM_DESKTOP_DEFAULT_ORIGIN: ${{ needs.source.outputs.origin }} PLAYWRIGHT_JSON_OUTPUT_FILE: test-results/desktop-smoke.json - BACKGROUND_EXECUTOR_REPORT_PATH: test-results/background-executor-report.json - TERMINAL_CANCEL_REPORT_PATH: test-results/terminal-cancel-report.json - CONTINUE_SIGN_IN_REPORT_PATH: test-results/continue-sign-in-report.json run: bun run ../../scripts/desktop-e2e.ts ${{ matrix.shard }}/${{ strategy.job-total }} - name: Upload smoke coverage and timings diff --git a/.github/workflows/docs-negotiation.yml b/.github/workflows/docs-negotiation.yml index d1098a5f4f9..8e9cf5b492a 100644 --- a/.github/workflows/docs-negotiation.yml +++ b/.github/workflows/docs-negotiation.yml @@ -388,7 +388,7 @@ jobs: dotnet-version: '8.0.x' - name: Set up Go for copied request examples if: matrix.group == 'http' - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: go-version: '1.25.x' cache: false diff --git a/.github/workflows/helm.yml b/.github/workflows/helm.yml index 03c176d3dce..68e538a3bba 100644 --- a/.github/workflows/helm.yml +++ b/.github/workflows/helm.yml @@ -403,7 +403,7 @@ jobs: push-to-registry: true - name: Set up ORAS - uses: oras-project/setup-oras@5e2f2482b30b0cb3e14e67f89a80c88c659a7c63 # v2.0.3 + uses: oras-project/setup-oras@ac735097e22fe643015b0d19645f7c9a69942128 # v2.0.4 # Artifact Hub reads repository metadata from the reserved `artifacthub.io` # tag on the chart's own OCI repository. Pushed on every run, including diff --git a/.github/workflows/publish-sim-cli.yml b/.github/workflows/publish-sim-cli.yml index 7932e49c88d..2d77a608bdf 100644 --- a/.github/workflows/publish-sim-cli.yml +++ b/.github/workflows/publish-sim-cli.yml @@ -40,8 +40,8 @@ jobs: with: persist-credentials: false - # Vitest 5 requires Node 22.12+; the published bundle is still - # smoke-tested on Node 20 below, its minimum supported runtime. + # Vitest 5 requires Node 22.12+; the published bundle is also + # smoke-tested below on Node 22.18.0, its minimum supported runtime. - name: Setup workspace uses: ./.github/actions/setup with: @@ -131,10 +131,10 @@ jobs: working-directory: packages/sim-cli run: bun pm pack --ignore-scripts --filename "$RUNNER_TEMP/package.tgz" --quiet - - name: Setup Node 20 for the bundle smoke test + - name: Setup the minimum supported Node for the bundle smoke test uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v6 with: - node-version: '20' + node-version: '22.18.0' - name: Smoke-test packed Node bundle env: diff --git a/CLAUDE.md b/CLAUDE.md index 299ed9635b4..8988fd422ac 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -59,6 +59,7 @@ Use the `test-audit` skill whenever you write, change, or review tests; mechanic Build order **Tools** → **Block** → **Icon** → optional **Trigger**, from the service's API docs, using `/add-integration` (or `/add-tools`, `/add-block`, `/add-trigger`). - **Tool IDs are `snake_case`** (`service_action`), registered in `tools/registry.ts`; blocks register alphabetically in `blocks/registry-maps.ts`. +- **Every tool declares `effect: 'read' | 'write'`**: `read` only when the call changes nothing outside Sim, `write` otherwise and whenever unsure (`ToolEffect` in `tools/types.ts`; `check:tool-effects`; rules in `/add-tools` → Declaring the effect). - **Type coercions go in `tools.config.params`** (runs at execution), never `tools.config.tool` (runs at serialization, where `Number()` destroys `` references). - **Requests made for a workspace use `outboundFetch`** (`@/lib/core/network/outbound-fetch.server`), never the global `fetch` or another imported `fetch`, so an organization with a dedicated egress gateway keeps its static IPs; `check:organization-egress` enforces this, and a request that rightly goes direct (Sim's own infrastructure, an operator-local server) takes `// egress-direct: `. AWS SDK clients signing with customer credentials take `organizationAwsRequestHandler()`: no audit catches a missing one, so reviewers check it. - A surface listing integrations to a viewer reads `useIntegrationAccess`, never a raw catalog (`check:integration-access`). diff --git a/README.md b/README.md index 390f646094b..a21e9aafb57 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ macOS 12+, Apple Silicon and Intel. See the [desktop docs](https://docs.sim.ai/d ## Security and governance -- SOC 2 Type II, ISO 27001, and GDPR: reports and policies are in the [Trust Center](https://trust.sim.ai/) +- SOC 2 Type II (Security criterion), GDPR, and ISO 27001 certification in progress: reports and policies are in the [Trust Center](https://trust.sim.ai/) - [Single sign-on](https://docs.sim.ai/platform/enterprise/sso) with SAML 2.0 or OIDC, including Microsoft Entra ID, Okta, and Google Workspace - [SCIM directory provisioning](https://docs.sim.ai/platform/enterprise/scim) from Microsoft Entra ID or Okta - [Audit logs](https://docs.sim.ai/platform/enterprise/audit-logs) and [permission groups](https://docs.sim.ai/platform/enterprise/access-control) that restrict models, blocks, and tools by workspace and member @@ -137,7 +137,7 @@ npx sim-setup reset # archive .env and wipe managed data The setup package detects how you're running and acts accordingly. Use `--dir ` to create or manage a deployment somewhere other than `./sim`. -Sim also supports local models via [Ollama](https://ollama.ai) and [vLLM](https://docs.vllm.ai/). See the [self-hosting docs](https://docs.sim.ai/self-hosting/docker) for details. +Sim also supports local models via [Ollama](https://ollama.ai), [vLLM](https://docs.vllm.ai/), and [LiteLLM](https://docs.litellm.ai/). See the [self-hosting docs](https://docs.sim.ai/self-hosting/docker) for details. ## Chat API Keys diff --git a/apps/desktop/README.md b/apps/desktop/README.md index f6c2caafc8f..5a73dee13c5 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -205,7 +205,7 @@ Approved native reads can return bounded text, directory listings, images, or PD - `electron-updater` reads the deployment's `/api/desktop/update` feed; production resolves stable releases from `simstudioai/sim`, while dev/staging resolve prereleases from `simstudioai/sim-desktop-releases`. Artifact downloads go directly to GitHub and deltas use `.zip.blockmap`. Sim validates every candidate before starting its download. Developer ID builds installed under `/Applications` use a prompt (Restart and update / Later; Later installs on quit); other packaged builds offer a validated installer download — never forced mid-session. A staged or offered update keeps being re-checked on the normal cadence, and a newer release replaces it, so a shell left running across several releases installs the latest build in one restart instead of the stale one followed by another prompt. - Streams: production follows stable `X.Y.Z` releases, dev follows `-dev.N`, and staging follows `-staging.N`. The feed still recognizes legacy `-alpha.N`/`-beta.N` releases during migration. - Restart becomes available only after Squirrel confirms native staging. Replacing a staged update returns the UI to downloading; a failed transfer can retain the previous staged build, but a failure after the native feed is replaced requires a retry. Diagnostics record `update_downloaded` after native staging, `update_install` when an explicit restart is committed, and `update_install_result` on the next launch with the expected and installed versions. The staging checkpoint also covers updates installed on a normal quit. -- `bun run test:e2e e2e/updater.spec.ts` exercises the real Electron process, MacUpdater, downloads, retries, and installation checkpoints. Native verification and bundle replacement are simulated. Set `DESKTOP_UPDATER_REPORT_PATH` to choose the JSON report path; by default it is included in Playwright's test results and uploaded by CI on failure. +- `bun run test:e2e e2e/updater.spec.ts` exercises the real Electron process, MacUpdater, downloads, retries, and installation checkpoints. Native verification and bundle replacement are simulated. Each check is a Playwright step, so it appears in the run's JSON report and in the results CI uploads on failure. - Staged rollout: after publishing, edit `stagingPercentage: 10` into the release's `latest-mac.yml`, then raise as crash metrics stay clean. - Rollback: a pulled release must be superseded by a **higher** version — users on the broken build will not reinstall an equal one. (A blocked-versions kill-switch was removed as unwired dead code; reintroduce it in `updater.ts` if a remote config source ever exists to feed it.) - Ship the DMG and tell users to install to `/Applications` — App Translocation breaks Squirrel.Mac updates from quarantined paths. diff --git a/apps/desktop/e2e-durations.json b/apps/desktop/e2e-durations.json index 7d184cc16b2..f839f479f5f 100644 --- a/apps/desktop/e2e-durations.json +++ b/apps/desktop/e2e-durations.json @@ -7,7 +7,6 @@ "browser-sign-in-prompts.spec.ts": 29.02, "browser-tools.spec.ts": 136.49, "chat-panel.spec.ts": 19.81, - "check-report.spec.ts": 2.48, "computer-use.spec.ts": 3.62, "continue-sign-in.spec.ts": 10.93, "desktop-tools-live-sim.spec.ts": 0.0, diff --git a/apps/desktop/e2e/background-executor.spec.ts b/apps/desktop/e2e/background-executor.spec.ts index 5849198fbc5..79cb4d83a6a 100644 --- a/apps/desktop/e2e/background-executor.spec.ts +++ b/apps/desktop/e2e/background-executor.spec.ts @@ -1,26 +1,13 @@ -import { - existsSync, - mkdirSync, - mkdtempSync, - readFileSync, - renameSync, - rmSync, - writeFileSync, -} from 'node:fs' -import { tmpdir } from 'node:os' +import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs' import { join } from 'node:path' -import { type ElectronApplication, expect, test } from '@playwright/test' -import type { SimDesktopApi } from '@sim/desktop-bridge' -import { getErrorMessage } from '@sim/utils/errors' +import type { ElectronApplication, Page } from '@playwright/test' import { sleep } from '@sim/utils/helpers' -import { recordCheck } from './check-report' import { answerShellDialog, - type FixtureCall, FixtureSim, - launch, + journalState, + launchAgainst, processRunning, - RECONCILE_MS, readFileSafe, refFor, registeredDevice, @@ -28,18 +15,24 @@ import { sha256, WORKSPACE, } from './executor-sim' +import { type DesktopBridge, expect, test } from './harness' /** * The Sim desktop app's background executor against a fixture Sim that speaks the executor's * device protocol (register, inbox, doorbell, claim, lease, complete, import) the way Sim's * routes do. * The window navigates, reloads and leaves the chats while their calls run: nothing in this - * suite depends on a chat view, which is the point. Each check lands in a JSON report at - * BACKGROUND_EXECUTOR_REPORT_PATH as it finishes. + * suite depends on a chat view, which is the point. */ /** Sim's window for a device to claim an offered call (DESKTOP_TOOL_PICKUP_GRACE_MS in Sim). */ const SIM_PICKUP_GRACE_MS = 15_000 +/** + * Long enough that only the doorbell can explain a prompt reaction: with jitter, the device's own + * inbox reads come at least 24s apart. + */ +const SLOW_RECONCILE_MS = 30_000 +const DOORBELL_REACTION_MS = 10_000 const CHAT_A = 'chat-browser-a' const CHAT_B = 'chat-terminal-b' @@ -47,36 +40,78 @@ const CHAT_C = 'chat-idle-c' const sim = new FixtureSim() -/** Runs one check and adds its outcome to the report as soon as it is known. */ -async function check(name: string, body: () => Promise): Promise { - const startedAt = Date.now() - const record = (status: 'passed' | 'failed', error?: unknown) => - recordCheck(process.env.BACKGROUND_EXECUTOR_REPORT_PATH, 'background-executor', { - name, - status, - durationMs: Date.now() - startedAt, - retry: test.info().retry, - ...(error === undefined ? {} : { error: getErrorMessage(error) }), - }) - try { - await body() - record('passed') - } catch (error) { - record('failed', error) - throw error - } +type SleepBlockerProbe = typeof globalThis & { __heldSleepBlockers?: Map } + +/** Replaces the power blocker with one that records what is held, before any work arrives. */ +async function stubSleepBlockers(app: ElectronApplication): Promise { + await app.evaluate(({ powerSaveBlocker }) => { + const held = new Map() + let next = 1 + ;(globalThis as SleepBlockerProbe).__heldSleepBlockers = held + powerSaveBlocker.start = (type) => { + held.set(next, type) + return next++ + } + powerSaveBlocker.stop = (id) => held.delete(id) + powerSaveBlocker.isStarted = (id) => held.has(id) + }) +} + +function heldSleepBlockers(app: ElectronApplication): Promise { + return app.evaluate(() => [ + ...((globalThis as SleepBlockerProbe).__heldSleepBlockers?.values() ?? []), + ]) } -test.describe('background executor', () => { - let app: ElectronApplication | null = null +function offeredDevice(window: Page) { + return window.evaluate(() => + (globalThis as DesktopBridge).simDesktop.desktopExecutor?.getDevice() + ) +} + +/** + * The user presses Tab in the agent's page. Resolves once Chromium has delivered the key to the + * page, which is when the app records the input; `sendInputEvent` itself returns before that. + */ +async function userTypesInPage(app: ElectronApplication, pageUrl: string): Promise { + await app.evaluate(async ({ webContents }, pageUrl) => { + const page = webContents.getAllWebContents().find((contents) => contents.getURL() === pageUrl) + if (!page) throw new Error(`No page at ${pageUrl}`) + const delivered = new Promise((resolve) => { + const onInput = (_event: unknown, input: { type: string }) => { + if (input.type !== 'keyDown' && input.type !== 'rawKeyDown') return + page.removeListener('input-event', onInput) + resolve() + } + page.on('input-event', onInput) + }) + page.sendInputEvent({ type: 'keyDown', keyCode: 'Tab' }) + page.sendInputEvent({ type: 'keyUp', keyCode: 'Tab' }) + await delivered + }, pageUrl) +} +/** Inbox reads, without the doorbell stream. */ +function inboxReads(): number { + return sim.requests.filter((request) => request === 'GET /api/desktop/inbox').length +} + +/** + * Rings the doorbell and waits for the inbox read it causes. Reads never overlap, so once it + * starts, every read before it, and whatever that read made the device do, has finished. + */ +async function nextInboxRead(deviceId: string): Promise { + const before = inboxReads() + sim.ring(deviceId, 'approval') + await expect.poll(inboxReads).toBeGreaterThan(before) +} + +test.describe('background executor', () => { test.beforeAll(async () => { await sim.start() }) - test.afterEach(async () => { - await app?.close().catch(() => {}) - app = null + test.afterEach(() => { sim.reset() }) @@ -84,29 +119,31 @@ test.describe('background executor', () => { await sim.stop() }) - test('A: two chats run browser and terminal work while the user is elsewhere and reloads', async () => { - const userData = mkdtempSync(join(tmpdir(), 'sim-executor-a-')) - const launched = await launch(sim, userData) - app = launched.app - const window = launched.window + test('A: two chats run browser and terminal work while the user is elsewhere and reloads', async ({ + desktop, + }) => { + const { app, window, userData } = await launchAgainst(desktop, sim) + await stubSleepBlockers(app) const deviceId = await registeredDevice(sim) await window.goto(`${sim.origin}/workspace/${WORKSPACE}/chat/${CHAT_C}`) + await test.step('an enabled device offers itself for binding', async () => { + expect(await offeredDevice(window)).toEqual({ deviceId, protocolVersion: 1 }) + }) + const marker = join(userData, 'terminal-marker.txt') const releaseCommands = join(userData, 'release-commands') const readable = join(userData, 'notes.txt') writeFileSync(readable, 'background read fixture') - await check('A: chat A opens its page in the background', async () => { + const button = await test.step('chat A opens its page in the background', async () => { const opened = sim.issue(deviceId, CHAT_A, 'browser_open_url', { url: `${sim.origin}/counter?chat=A`, }) const completion = await settled(sim, opened) expect(completion.status, completion.message).toBe('success') + return refFor((completion.data?.snapshot as { outline: string }).outline, 'Count visit') }) - const opened = [...sim.calls.values()][0] as FixtureCall - const outline = (opened.completions[0]?.data?.snapshot as { outline: string }).outline - const button = refFor(outline, 'Count visit') const clicks = Array.from({ length: 10 }, () => sim.issue(deviceId, CHAT_A, 'browser_click', { elementId: button }) @@ -120,7 +157,7 @@ test.describe('background executor', () => { }, }) ) - const readConsent = launched.app.waitForEvent('window') + const readConsent = app.waitForEvent('window') const localRead = sim.issue(deviceId, CHAT_B, 'read_local_file', { path: readable }) try { await answerShellDialog(await readConsent, 'Allow folder') @@ -131,7 +168,7 @@ test.describe('background executor', () => { // Chat B's first command holds its queue until released, so a claim that waited for the // calls ahead of it to run could never happen in time. - await check("A: every call is claimed while chat B's first command still runs", async () => { + await test.step("every call is claimed while chat B's first command still runs", async () => { await expect .poll( () => @@ -149,16 +186,20 @@ test.describe('background executor', () => { } }) - await check('A: the lease is renewed while calls wait and run', async () => { + await test.step('the lease is renewed while calls wait and run', async () => { await expect .poll(() => terminalRuns.filter((id) => sim.requireCall(id).renewals === 0)) .toEqual([]) }) + + await test.step('the machine is kept awake while the commands run', async () => { + await expect.poll(() => heldSleepBlockers(app)).toEqual(['prevent-app-suspension']) + }) } finally { writeFileSync(releaseCommands, '') } - await check('A: every call completes exactly once with its own token', async () => { + await test.step('every call completes exactly once with its own token', async () => { for (const id of [...clicks, ...terminalRuns, localRead]) { const completion = await settled(sim, id, 90_000) const call = sim.requireCall(id) @@ -169,40 +210,43 @@ test.describe('background executor', () => { } }) - await check('A: the page saw each click exactly once', async () => { + await test.step('the machine may sleep again once every result is delivered', async () => { + await expect.poll(() => heldSleepBlockers(app)).toEqual([]) + }) + + await test.step('the page saw each click exactly once', async () => { await expect.poll(() => sim.hits.get('A')).toBe(10) }) - await check('A: chat B ran each command once, in order, in its own terminal', async () => { + await test.step('chat B ran each command once, in order, in its own terminal', async () => { expect(readFileSync(marker, 'utf8').trim().split('\n')).toEqual(['B-1', 'B-2', 'B-3']) const read = sim.requireCall(localRead).completions[0] expect(JSON.stringify(read?.data)).toContain('background read fixture') }) - await check("A: chat B cannot see chat A's tabs", async () => { + await test.step("chat B cannot see chat A's tabs", async () => { const listed = sim.issue(deviceId, CHAT_B, 'browser_list_tabs', {}) const completion = await settled(sim, listed) expect(JSON.stringify(completion.data)).not.toContain('/counter') }) - await check('A: no chat view executed or reported a call', async () => { - expect(sim.requests.filter((request) => request.includes('/api/copilot/confirm'))).toEqual([]) + await test.step('no chat view authorized a call', async () => { expect( sim.requests.filter((request) => request.includes('/api/desktop/tool/authorize')) ).toEqual([]) }) }) - test('background file reads require consent and Stop cancels pending permission', async () => { - const userData = mkdtempSync(join(tmpdir(), 'sim-executor-consent-')) - const launched = await launch(sim, userData) - app = launched.app + test('background file reads require consent and Stop cancels pending permission', async ({ + desktop, + }) => { + const { app, userData } = await launchAgainst(desktop, sim) const deviceId = await registeredDevice(sim) const readable = join(userData, 'private.txt') writeFileSync(readable, 'background consent fixture') - await check('background read stays pending until folder consent', async () => { - const shown = launched.app.waitForEvent('window', { timeout: 10_000 }) + await test.step('background read stays pending until folder consent', async () => { + const shown = app.waitForEvent('window', { timeout: 10_000 }) const call = sim.issue(deviceId, CHAT_B, 'read_local_file', { path: readable }) const prompt = await shown await expect(prompt.getByRole('button', { name: 'Allow folder', exact: true })).toBeVisible() @@ -213,8 +257,8 @@ test.describe('background executor', () => { expect(JSON.stringify(completion)).not.toContain('background consent fixture') }) - await check('Stop dismisses background consent without granting access', async () => { - const shown = launched.app.waitForEvent('window', { timeout: 10_000 }) + await test.step('Stop dismisses background consent without granting access', async () => { + const shown = app.waitForEvent('window', { timeout: 10_000 }) const call = sim.issue(deviceId, CHAT_B, 'read_local_file', { path: readable }) const prompt = await shown await expect(prompt.getByRole('button', { name: 'Allow folder', exact: true })).toBeVisible() @@ -224,8 +268,8 @@ test.describe('background executor', () => { expect(sim.requireCall(call).completions[0]?.outcome).toBe('superseded') }) - await check('approved background reads reuse the shared folder grant', async () => { - const shown = launched.app.waitForEvent('window', { timeout: 10_000 }) + await test.step('approved background reads reuse the shared folder grant', async () => { + const shown = app.waitForEvent('window', { timeout: 10_000 }) const call = sim.issue(deviceId, CHAT_B, 'read_local_file', { path: readable }) const prompt = await shown await answerShellDialog(prompt, 'Allow folder') @@ -237,130 +281,113 @@ test.describe('background executor', () => { }) }) - test('background consent cannot grant access when Sim cannot verify the call', async () => { - const userData = mkdtempSync(join(tmpdir(), 'sim-executor-offline-consent-')) - const launched = await launch(sim, userData) - app = launched.app + test('background consent cannot grant access when Sim cannot verify the call', async ({ + desktop, + }) => { + const { app, userData } = await launchAgainst(desktop, sim) const deviceId = await registeredDevice(sim) const readable = join(userData, 'private.txt') writeFileSync(readable, 'offline consent fixture') - await check('offline approval returns an error without remembering a grant', async () => { - const shown = launched.app.waitForEvent('window') - const call = sim.issue(deviceId, CHAT_B, 'read_local_file', { path: readable }) - const prompt = await shown - await expect(prompt.getByRole('button', { name: 'Allow folder', exact: true })).toBeVisible() - sim.disconnect() - await answerShellDialog(prompt, 'Allow folder') - await expect - .poll(() => - launched.app.evaluate(({ safeStorage }, toolCallId) => { - const fs = process.getBuiltinModule('node:fs') - const path = `${process.env.SIM_DESKTOP_USER_DATA}/desktop-executor-journal.json` - const envelope = JSON.parse(fs.readFileSync(path, 'utf8')) - const journal = JSON.parse( - safeStorage.decryptString(Buffer.from(envelope.ciphertext, 'base64')) - ) as { entries: { toolCallId: string; state: string }[] } - return journal.entries.find((entry) => entry.toolCallId === toolCallId)?.state - }, call) - ) - .toBe('result') + const shown = app.waitForEvent('window') + const call = sim.issue(deviceId, CHAT_B, 'read_local_file', { path: readable }) + const prompt = await shown + await expect(prompt.getByRole('button', { name: 'Allow folder', exact: true })).toBeVisible() + sim.disconnect() + await answerShellDialog(prompt, 'Allow folder') + + await test.step('offline approval returns an error', async () => { + await expect.poll(() => journalState(app, call)).toBe('result') sim.reconnect() const completion = await settled(sim, call) expect(completion.status).toBe('error') expect(JSON.stringify(completion)).not.toContain('offline consent fixture') - const nextPrompt = launched.app.waitForEvent('window') + }) + + await test.step('the approval left no grant behind', async () => { + const nextPrompt = app.waitForEvent('window') const next = sim.issue(deviceId, CHAT_B, 'read_local_file', { path: readable }) await answerShellDialog(await nextPrompt, "Don't allow") expect((await settled(sim, next)).status).toBe('error') }) }) - test('background consent does not reopen the main app after its windows are closed', async () => { + test('background consent does not reopen the main app after its windows are closed', async ({ + desktop, + }) => { test.skip(process.platform !== 'darwin', 'The macOS app remains running without a window.') - const userData = mkdtempSync(join(tmpdir(), 'sim-executor-windowless-consent-')) - const launched = await launch(sim, userData) - app = launched.app + const { app, window, userData } = await launchAgainst(desktop, sim) const deviceId = await registeredDevice(sim) const readable = join(userData, 'private.txt') writeFileSync(readable, 'windowless consent fixture') - await launched.window.close() + await window.close() - await check('only the standalone consent window opens for a background read', async () => { - const shown = launched.app.waitForEvent('window') - const call = sim.issue(deviceId, CHAT_B, 'read_local_file', { path: readable }) - const prompt = await shown - await expect(prompt.getByRole('button', { name: 'Allow folder', exact: true })).toBeVisible() - expect( - await launched.app.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().map((window) => window.getParentWindow() === null) - ) - ).toEqual([true]) - await answerShellDialog(prompt, "Don't allow") - expect((await settled(sim, call)).status).toBe('error') - }) + const shown = app.waitForEvent('window') + const call = sim.issue(deviceId, CHAT_B, 'read_local_file', { path: readable }) + const prompt = await shown + await expect(prompt.getByRole('button', { name: 'Allow folder', exact: true })).toBeVisible() + expect( + await app.evaluate(({ BrowserWindow }) => + BrowserWindow.getAllWindows().map((window) => window.getParentWindow() === null) + ) + ).toEqual([true]) + await answerShellDialog(prompt, "Don't allow") + expect((await settled(sim, call)).status).toBe('error') }) - test('sign-out clears folder grants even when desktop settings cannot be saved', async () => { - const userData = mkdtempSync(join(tmpdir(), 'sim-executor-grant-cleanup-')) - const launched = await launch(sim, userData) - app = launched.app + test('sign-out clears folder grants even when desktop settings cannot be saved', async ({ + desktop, + }) => { + const { app, window, userData } = await launchAgainst(desktop, sim) const deviceId = await registeredDevice(sim) const readable = join(userData, 'private.txt') writeFileSync(readable, 'cleanup consent fixture') - const shown = launched.app.waitForEvent('window') + const shown = app.waitForEvent('window') const call = sim.issue(deviceId, CHAT_B, 'read_local_file', { path: readable }) await answerShellDialog(await shown, 'Allow folder') expect((await settled(sim, call)).status).toBe('success') const grants = join(userData, 'local-filesystem-grants.json') expect(existsSync(grants)).toBe(true) - await launched.window.evaluate(() => { + await window.evaluate(() => { const button = document.createElement('button') button.textContent = 'Enable full file access' button.onclick = async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - await api.settings.setFullFileAccess?.(true) + await (globalThis as DesktopBridge).simDesktop.settings.setFullFileAccess?.(true) button.textContent = 'Full file access enabled' } document.body.append(button) }) - await launched.window - .getByRole('button', { name: 'Enable full file access', exact: true }) - .click() + await window.getByRole('button', { name: 'Enable full file access', exact: true }).click() await expect( - launched.window.getByRole('button', { name: 'Full file access enabled', exact: true }) + window.getByRole('button', { name: 'Full file access enabled', exact: true }) ).toBeVisible() const settings = join(userData, 'settings.json') if (existsSync(settings)) renameSync(settings, `${settings}.backup`) mkdirSync(settings) try { - await check( - 'failed settings persistence does not skip independent grant cleanup', - async () => { - const failedSignOut = launched.app.waitForEvent('window') - await launched.app.evaluate(({ Menu }) => { - const item = Menu.getApplicationMenu() - ?.items.flatMap((entry) => entry.submenu?.items ?? []) - .find((entry) => entry.label === 'Sign Out') - if (!item) throw new Error('Missing Sign Out menu item') - item.click() - }) - const failure = await failedSignOut - await answerShellDialog(failure, 'OK') - expect(existsSync(join(userData, 'account-data-teardown-required.json'))).toBe(true) - await expect.poll(() => existsSync(grants)).toBe(false) - } - ) + const failedSignOut = app.waitForEvent('window') + await app.evaluate(({ Menu }) => { + const item = Menu.getApplicationMenu() + ?.items.flatMap((entry) => entry.submenu?.items ?? []) + .find((entry) => entry.label === 'Sign Out') + if (!item) throw new Error('Missing Sign Out menu item') + item.click() + }) + await answerShellDialog(await failedSignOut, 'OK') + expect(existsSync(join(userData, 'account-data-teardown-required.json'))).toBe(true) + await expect.poll(() => existsSync(grants)).toBe(false) } finally { + // The app saves its settings again as it quits. rmSync(settings, { recursive: true, force: true }) if (existsSync(`${settings}.backup`)) renameSync(`${settings}.backup`, settings) } }) - test('B: a result produced while the network is cut is delivered once after reconnecting', async () => { - const userData = mkdtempSync(join(tmpdir(), 'sim-executor-b-')) - app = (await launch(sim, userData)).app + test('B: a result produced while the network is cut is delivered once after reconnecting', async ({ + desktop, + }) => { + const { app } = await launchAgainst(desktop, sim) const deviceId = await registeredDevice(sim) const run = sim.issue(deviceId, CHAT_B, 'terminal', { @@ -370,27 +397,25 @@ test.describe('background executor', () => { await expect.poll(() => sim.requireCall(run).claims).toBe(1) sim.disconnect() - await check( - 'B: the cut drops the doorbell and nothing reaches Sim while it lasts', - async () => { - await expect.poll(() => sim.streams.get(deviceId)?.size ?? 0).toBe(0) - await expect.poll(() => sim.droppedWhileOffline, { timeout: 15_000 }).toBeGreaterThan(0) - await sleep(4_000) - expect(sim.requireCall(run).completions).toHaveLength(0) - } - ) + await test.step('the cut drops the doorbell, and the result waits on the machine', async () => { + await expect.poll(() => sim.streams.get(deviceId)?.size ?? 0).toBe(0) + await expect.poll(() => journalState(app, run), { timeout: 30_000 }).toBe('result') + await expect.poll(() => sim.droppedWhileOffline, { timeout: 15_000 }).toBeGreaterThan(0) + expect(sim.requireCall(run).completions).toHaveLength(0) + }) sim.reconnect() - await check('B: the result arrives once after reconnecting', async () => { + await test.step('the result arrives once after reconnecting', async () => { const completion = await settled(sim, run, 60_000) expect(completion.status, completion.message).toBe('success') expect(JSON.stringify(completion.data)).toContain('offline-done') - await sleep(3_000) + // Forgotten only once Sim acknowledged it, so nothing is left to send again. + await expect.poll(() => journalState(app, run)).toBeUndefined() expect(sim.requireCall(run).completions).toHaveLength(1) expect(sim.requireCall(run).claims).toBe(1) }) - await check('B: the device reopens its doorbell and picks up new work', async () => { + await test.step('the device reopens its doorbell and picks up new work', async () => { await expect.poll(() => sim.streams.get(deviceId)?.size ?? 0, { timeout: 45_000 }).toBe(1) const after = sim.issue(deviceId, CHAT_B, 'browser_list_tabs', {}) const completion = await settled(sim, after) @@ -398,10 +423,11 @@ test.describe('background executor', () => { }) }) - test('C: a crash mid-command reports the outcome as unknown and never reruns it', async () => { - const userData = mkdtempSync(join(tmpdir(), 'sim-executor-c-')) - const marker = join(userData, 'crash-marker.txt') - const first = await launch(sim, userData) + test('C: a crash mid-command reports the outcome as unknown and never reruns it', async ({ + desktop, + }) => { + const first = await launchAgainst(desktop, sim) + const marker = join(first.userData, 'crash-marker.txt') const deviceId = await registeredDevice(sim) const run = sim.issue(deviceId, CHAT_B, 'terminal', { @@ -409,26 +435,24 @@ test.describe('background executor', () => { args: { command: `echo started >> '${marker}'; sleep 40`, waitSeconds: 60 }, }) await expect.poll(() => readFileSafe(marker), { timeout: 30_000 }).toContain('started') - first.app.process().kill('SIGKILL') + first.child.kill('SIGKILL') sim.streams.get(deviceId)?.clear() - app = (await launch(sim, userData)).app + await launchAgainst(desktop, sim, { userData: first.userData }) - await check('C: the restarted app reports the lost result as outcome unknown', async () => { + await test.step('the restarted app reports the lost result as outcome unknown', async () => { const completion = await settled(sim, run, 60_000) expect(completion.data).toMatchObject({ outcomeUnknown: true, doNotRetry: true }) }) - await check('C: the command ran exactly once', async () => { + await test.step('the command ran exactly once', async () => { expect(sim.requireCall(run).claims).toBe(1) expect(readFileSafe(marker).trim().split('\n')).toEqual(['started']) }) }) - test('D: a folder import lands in Sim while the user is in another chat', async () => { - const userData = mkdtempSync(join(tmpdir(), 'sim-executor-d-')) - const launched = await launch(sim, userData) - app = launched.app + test('D: a folder import lands in Sim while the user is in another chat', async ({ desktop }) => { + const { app, window, userData } = await launchAgainst(desktop, sim) const deviceId = await registeredDevice(sim) const source = join(userData, 'Reports') mkdirSync(join(source, 'q3'), { recursive: true }) @@ -436,9 +460,9 @@ test.describe('background executor', () => { // Larger than one 8 MB read, so the file crosses Electron in several chunks. const large = Buffer.alloc(9 * 1024 * 1024, 7) writeFileSync(join(source, 'q3', 'export.bin'), large) - await launched.window.goto(`${sim.origin}/workspace/${WORKSPACE}/chat/${CHAT_C}`) + await window.goto(`${sim.origin}/workspace/${WORKSPACE}/chat/${CHAT_C}`) - const importConsent = launched.app.waitForEvent('window') + const importConsent = app.waitForEvent('window') const call = sim.issue(deviceId, CHAT_B, 'import_local_files', { path: source, targetWorkspaceId: WORKSPACE, @@ -447,7 +471,7 @@ test.describe('background executor', () => { await answerShellDialog(await importConsent, 'Allow folder') - await check('D: the import completes with every entry it stored', async () => { + await test.step('the import completes with every entry it stored', async () => { const completion = await settled(sim, call, 60_000) expect(completion.status).toBe('success') expect(completion.data).toMatchObject({ @@ -464,7 +488,7 @@ test.describe('background executor', () => { }) }) - await check('D: Sim received the tree with the bytes on disk, once', async () => { + await test.step('Sim received the tree with the bytes on disk, once', async () => { expect(sim.imported).toEqual([ { toolCallId: call, kind: 'directory', sourceName: 'Reports', relativePath: '' }, { @@ -489,9 +513,11 @@ test.describe('background executor', () => { }) }) - test('E: Stop from another chat stops a running browser wait and terminal command', async () => { - const userData = mkdtempSync(join(tmpdir(), 'sim-executor-e-')) - app = (await launch(sim, userData)).app + test('E: Stop from another chat stops a running browser wait and terminal command', async ({ + desktop, + }) => { + sim.reconcileMs = SLOW_RECONCILE_MS + await launchAgainst(desktop, sim) const deviceId = await registeredDevice(sim) const opened = sim.issue(deviceId, CHAT_A, 'browser_open_url', { @@ -514,266 +540,152 @@ test.describe('background executor', () => { sim.stopCall(wait) sim.stopCall(run) - await check('E: both stopped calls are acknowledged within seconds', async () => { - await settled(sim, wait, 10_000) - await settled(sim, run, 15_000) - expect(sim.requireCall(wait).completions[0]?.outcome).toBe('superseded') - expect(sim.requireCall(run).completions[0]?.outcome).toBe('superseded') - expect((sim.requireCall(wait).completions[0]?.at ?? 0) - stoppedAt).toBeLessThan(5_000) + await test.step('both stopped calls are acknowledged through the doorbell', async () => { + for (const call of [wait, run]) { + const completion = await settled(sim, call, DOORBELL_REACTION_MS) + expect(completion.outcome).toBe('superseded') + expect(completion.at - stoppedAt).toBeLessThan(DOORBELL_REACTION_MS) + } }) - await check('E: the stopped command no longer runs on the machine', async () => { + await test.step('the stopped command no longer runs on the machine', async () => { await expect.poll(() => processRunning(command), { timeout: 10_000 }).toBe(false) }) }) - test('F: a call waiting for approval in a background chat notifies, then runs once approved', async () => { - const userData = mkdtempSync(join(tmpdir(), 'sim-executor-f-')) - app = (await launch(sim, userData)).app + test('F: a call held for approval in a background chat notifies, runs only once approved, and never once declined', async ({ + desktop, + }) => { + sim.reconcileMs = SLOW_RECONCILE_MS + const { app, userData } = await launchAgainst(desktop, sim) await app.evaluate(({ Notification }) => { const shown: Array<{ title: string; body: string }> = [] - const target = globalThis as typeof globalThis & { __shownNotifications?: typeof shown } - target.__shownNotifications = shown + ;( + globalThis as typeof globalThis & { __shownNotifications?: typeof shown } + ).__shownNotifications = shown Notification.prototype.show = function show(this: { title: string; body: string }) { shown.push({ title: this.title, body: this.body }) } }) + const shownNotifications = () => + app.evaluate( + () => + (globalThis as { __shownNotifications?: Array<{ title: string; body: string }> }) + .__shownNotifications ?? [] + ) const deviceId = await registeredDevice(sim) + const marker = join(userData, 'declined-marker.txt') - const gated = sim.issue( + const approved = sim.issue( deviceId, CHAT_B, 'terminal', { operation: 'run', args: { command: 'echo approved-run', waitSeconds: 30 } }, 'awaiting_approval' ) - - await check('F: the user is notified, without the command in the notification', async () => { - await expect - .poll( - () => - app?.evaluate( - () => - (globalThis as { __shownNotifications?: Array<{ body: string }> }) - .__shownNotifications ?? [] - ), - { timeout: 15_000 } - ) - .toHaveLength(1) - const shown = await app?.evaluate( - () => - (globalThis as { __shownNotifications?: Array<{ body: string }> }).__shownNotifications - ) - expect(JSON.stringify(shown)).not.toContain('approved-run') - }) - - await check('F: nothing runs before approval', async () => { - await sleep(RECONCILE_MS * 2) - expect(sim.requireCall(gated).claims).toBe(0) - }) - - sim.approve(gated) - const approvedAt = Date.now() - await check('F: the approved call is claimed promptly and runs once', async () => { - const completion = await settled(sim, gated) - expect((sim.requireCall(gated).claimedAt ?? 0) - approvedAt).toBeLessThan(1_500) - expect(JSON.stringify(completion.data)).toContain('approved-run') - }) - }) - - test('F: a call the user declines in a background chat never runs', async () => { - const userData = mkdtempSync(join(tmpdir(), 'sim-executor-f-declined-')) - const marker = join(userData, 'declined-marker.txt') - app = (await launch(sim, userData)).app - const deviceId = await registeredDevice(sim) - const pulls = () => - sim.requests.filter((request) => request.startsWith('GET /api/desktop/inbox')).length - const claimAttempts = () => - sim.requests.filter((request) => request === 'POST /api/desktop/tool/claim').length - const pullsBefore = pulls() - const claimAttemptsBefore = claimAttempts() - - const gated = sim.issue( + const declined = sim.issue( deviceId, CHAT_B, 'terminal', { operation: 'run', args: { command: `echo ran >> '${marker}'`, waitSeconds: 30 } }, 'awaiting_approval' ) - // The device has pulled its inbox and seen the call waiting for approval. - await expect.poll(pulls).toBeGreaterThan(pullsBefore) - sim.decline(gated) - await check('F: the declined call is never claimed, and its command never runs', async () => { - await sleep(RECONCILE_MS * 2) - // Attempts, not successful claims: the fixture refuses a declined call's claim itself. - expect(claimAttempts() - claimAttemptsBefore).toBe(0) - expect(sim.requireCall(gated).completions).toEqual([]) - expect(readFileSafe(marker)).toBe('') + await test.step('the user is notified of each call, without its command', async () => { + await expect.poll(shownNotifications, { timeout: 15_000 }).toHaveLength(2) + const shown = JSON.stringify(await shownNotifications()) + expect(shown).not.toContain('approved-run') + expect(shown).not.toContain('declined-marker') }) - }) - test('G: only the device a turn is bound to claims its calls', async () => { - const first = await launch(sim, mkdtempSync(join(tmpdir(), 'sim-executor-g1-'))) - const firstDevice = await registeredDevice(sim) - const second = await launch(sim, mkdtempSync(join(tmpdir(), 'sim-executor-g2-'))) - const secondDevice = await registeredDevice(sim, new Set([firstDevice])) - app = first.app + await test.step('nothing is claimed while the calls wait for approval', async () => { + await nextInboxRead(deviceId) + expect(sim.requireCall(approved).claimAttempts).toBe(0) + expect(sim.requireCall(declined).claimAttempts).toBe(0) + }) - const call = sim.issue(firstDevice, CHAT_A, 'browser_list_tabs', {}) - await check('G: the bound device runs it and the other never claims it', async () => { - await settled(sim, call) - expect(sim.requireCall(call).claims).toBe(1) - expect( - sim.requests.filter((request) => request === 'POST /api/desktop/tool/claim').length - ).toBe(1) - expect(secondDevice).not.toBe(firstDevice) + sim.decline(declined) + sim.approve(approved) + const decidedAt = Date.now() + + await test.step('the approved call is claimed through the doorbell and runs once', async () => { + const completion = await settled(sim, approved) + expect((sim.requireCall(approved).claimedAt ?? 0) - decidedAt).toBeLessThan( + DOORBELL_REACTION_MS + ) + expect(sim.requireCall(approved).claims).toBe(1) + expect(JSON.stringify(completion.data)).toContain('approved-run') + }) + + await test.step('the declined call is never claimed, and its command never runs', async () => { + await nextInboxRead(deviceId) + // Attempts, not successful claims: the fixture refuses a declined call's claim itself. + expect(sim.requireCall(declined).claimAttempts).toBe(0) + expect(sim.requireCall(declined).completions).toEqual([]) + expect(readFileSafe(marker)).toBe('') }) - await second.app.close() }) - test('H: a device Sim has not enabled offers no binding', async () => { + test('H: a device Sim has not enabled offers no binding', async ({ desktop }) => { sim.enabled = false - const launched = await launch(sim, mkdtempSync(join(tmpdir(), 'sim-executor-h-'))) - app = launched.app - await launched.window.goto(`${sim.origin}/workspace/${WORKSPACE}/chat/${CHAT_C}`) - await expect.poll(() => sim.requests.includes('POST /api/desktop/devices')).toBe(true) - - await check( - 'H: the composer gets no device, so its turns stay with the chat view', - async () => { - const device = await launched.window.evaluate(() => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.desktopExecutor?.getDevice() - ) - expect(device).toBeNull() - } - ) + const { window, output } = await launchAgainst(desktop, sim, { env: { LOG_LEVEL: 'INFO' } }) + await window.goto(`${sim.origin}/workspace/${WORKSPACE}/chat/${CHAT_C}`) + // Logged once the app has acted on Sim's answer, so the device read below is the settled one. + await expect.poll(output, { timeout: 30_000 }).toContain('Desktop executor registered') - sim.enabled = true - await launched.app.close() - const enabled = await launch(sim, mkdtempSync(join(tmpdir(), 'sim-executor-h2-'))) - app = enabled.app - const deviceId = await registeredDevice(sim) - await enabled.window.goto(`${sim.origin}/workspace/${WORKSPACE}/chat/${CHAT_C}`) - await check('H: an enabled device offers itself for binding', async () => { - const device = await enabled.window.evaluate(() => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.desktopExecutor?.getDevice() - ) - expect(device).toEqual({ deviceId, protocolVersion: 1 }) - }) + expect(await offeredDevice(window)).toBeNull() }) - test('I: the agent yields its page while the user works in it, then takes it back', async () => { - app = (await launch(sim, mkdtempSync(join(tmpdir(), 'sim-executor-i-')))).app + test('I: the agent yields its page while the user works in it, then takes it back', async ({ + desktop, + }) => { + const { app } = await launchAgainst(desktop, sim) const deviceId = await registeredDevice(sim) - const opened = sim.issue(deviceId, CHAT_A, 'browser_open_url', { - url: `${sim.origin}/counter?chat=I`, - }) + const pageUrl = `${sim.origin}/counter?chat=I` + const opened = sim.issue(deviceId, CHAT_A, 'browser_open_url', { url: pageUrl }) const outline = ((await settled(sim, opened)).data?.snapshot as { outline: string }).outline const button = refFor(outline, 'Count visit') - const typeInAgentPage = () => - app?.evaluate(({ webContents }) => { - const page = webContents - .getAllWebContents() - .find((contents) => contents.getURL().includes('/counter?chat=I')) - page?.sendInputEvent({ type: 'keyDown', keyCode: 'Tab' }) - page?.sendInputEvent({ type: 'keyUp', keyCode: 'Tab' }) - }) - await typeInAgentPage() - const click = sim.issue(deviceId, CHAT_A, 'browser_click', { elementId: button }) - for (let i = 0; i < 4; i++) { - await sleep(500) - await typeInAgentPage() - } + await userTypesInPage(app, pageUrl) const lastUserInputAt = Date.now() + const click = sim.issue(deviceId, CHAT_A, 'browser_click', { elementId: button }) - await check('I: the click waits until the user stops, then runs once', async () => { - const completion = await settled(sim, click, 30_000) - expect(completion.status, completion.message).toBe('success') - expect(completion.at - lastUserInputAt).toBeGreaterThanOrEqual(3_000) - await expect.poll(() => sim.hits.get('I')).toBe(1) - }) + const completion = await settled(sim, click, 30_000) + expect(completion.status, completion.message).toBe('success') + expect(completion.at - lastUserInputAt).toBeGreaterThanOrEqual(3_000) + await expect.poll(() => sim.hits.get('I')).toBe(1) }) - test('I: an action the user never stops working long enough for does not run', async () => { - app = (await launch(sim, mkdtempSync(join(tmpdir(), 'sim-executor-i2-')))).app + test('I: an action the user never stops working long enough for does not run', async ({ + desktop, + }) => { + const { app } = await launchAgainst(desktop, sim) const deviceId = await registeredDevice(sim) - const opened = sim.issue(deviceId, CHAT_A, 'browser_open_url', { - url: `${sim.origin}/counter?chat=I2`, - }) + const pageUrl = `${sim.origin}/counter?chat=I2` + const opened = sim.issue(deviceId, CHAT_A, 'browser_open_url', { url: pageUrl }) const outline = ((await settled(sim, opened)).data?.snapshot as { outline: string }).outline const button = refFor(outline, 'Count visit') - const typeInAgentPage = () => - app?.evaluate(({ webContents }) => { - const page = webContents - .getAllWebContents() - .find((contents) => contents.getURL().includes('/counter?chat=I2')) - page?.sendInputEvent({ type: 'keyDown', keyCode: 'Tab' }) - page?.sendInputEvent({ type: 'keyUp', keyCode: 'Tab' }) - }) - await typeInAgentPage() + await userTypesInPage(app, pageUrl) const click = sim.issue(deviceId, CHAT_A, 'browser_click', { elementId: button }) let typing = true + // A keypress a second, well inside the quiet the agent waits for before it acts. const keepTyping = (async () => { while (typing) { - await typeInAgentPage() + await userTypesInPage(app, pageUrl) await sleep(1_000) } })() - await check('I: the click reports it never ran, instead of timing out', async () => { + try { const completion = await settled(sim, click, 60_000) - typing = false - await keepTyping expect(completion.status).toBe('error') expect(completion.message).toContain('Not run: the user kept working in this page') expect(completion.data).not.toMatchObject({ outcomeUnknown: true }) expect(sim.hits.get('I2') ?? 0).toBe(0) - }) - }) - - test('J: the machine stays awake only while a chat has work running', async () => { - app = (await launch(sim, mkdtempSync(join(tmpdir(), 'sim-executor-j-')))).app - await app.evaluate(({ powerSaveBlocker }) => { - const log: string[] = [] - const active = new Set() - let next = 1 - const target = globalThis as typeof globalThis & { __sleepBlocks?: string[] } - target.__sleepBlocks = log - powerSaveBlocker.start = (type) => { - log.push(`start:${type}`) - active.add(next) - return next++ - } - powerSaveBlocker.stop = (id) => { - log.push('stop') - active.delete(id) - return true - } - powerSaveBlocker.isStarted = (id) => active.has(id) - }) - const deviceId = await registeredDevice(sim) - const sleepLog = () => - app?.evaluate(() => (globalThis as { __sleepBlocks?: string[] }).__sleepBlocks ?? []) - - const run = sim.issue(deviceId, CHAT_B, 'terminal', { - operation: 'run', - args: { command: 'sleep 3; echo awake', waitSeconds: 30 }, - }) - await check('J: a blocker is held while the command runs', async () => { - await expect.poll(sleepLog, { timeout: 15_000 }).toEqual(['start:prevent-app-suspension']) - }) - await check('J: it is released once the result is delivered', async () => { - await settled(sim, run) - await expect - .poll(sleepLog, { timeout: 10_000 }) - .toEqual(['start:prevent-app-suspension', 'stop']) - }) + } finally { + typing = false + await keepTyping + } }) }) diff --git a/apps/desktop/e2e/browser-chrome.spec.ts b/apps/desktop/e2e/browser-chrome.spec.ts index c5857f80ea0..b0f703c7442 100644 --- a/apps/desktop/e2e/browser-chrome.spec.ts +++ b/apps/desktop/e2e/browser-chrome.spec.ts @@ -1,107 +1,73 @@ -import { mkdtempSync, readFileSync, rmSync } from 'node:fs' -import { createServer, type Server } from 'node:http' -import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' -import { _electron as electron, expect, test } from '@playwright/test' -import type { SimDesktopApi } from '@sim/desktop-bridge' -import { build } from 'esbuild' -import postcss from 'postcss' -import loadPostcssConfig from 'postcss-load-config' +import type { Page } from '@playwright/test' +import { + bundleSimFixture, + type DesktopBridge, + expect, + focusFirstWindow, + SIM_DIR, + serve, + test, +} from './harness' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) -const SIM_DIR = fileURLToPath(new URL('../../sim/', import.meta.url)) const FIXTURE = fileURLToPath(new URL('./fixtures/browser-chrome.tsx', import.meta.url)) const SCOPE = 'browser-chrome-fixture' -test('crowded tabs and renderer overlays work with a real native browser page', async () => { - const testInfo = test.info() - let server: Server | undefined - let userData: string | undefined - let app: Awaited> | undefined - try { - const config = await loadPostcssConfig({}, SIM_DIR) - const stylesheet = join(SIM_DIR, 'app/_styles/globals.css') - const css = await postcss(config.plugins).process( - `${readFileSync(stylesheet, 'utf8')}\n@source ${JSON.stringify(FIXTURE)};`, - { from: stylesheet } - ) - const hook = join( - SIM_DIR, - 'app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/browser-panel-occlusion.ts' - ) - const bundle = await build({ - stdin: { - contents: `import { mountBrowserChromeFixture } from ${JSON.stringify(FIXTURE)}; +test('crowded tabs and renderer overlays work with a real native browser page', async ({ + desktop, +}, testInfo) => { + const hook = join( + SIM_DIR, + 'app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/browser-panel-occlusion.ts' + ) + const bundle = await bundleSimFixture( + { + source: `import { mountBrowserChromeFixture } from ${JSON.stringify(FIXTURE)}; import { useBrowserPanelOcclusion } from ${JSON.stringify(hook)}; mountBrowserChromeFixture(useBrowserPanelOcclusion);`, - resolveDir: SIM_DIR, - loader: 'tsx', - }, - bundle: true, - write: false, - outfile: testInfo.outputPath('fixture.js'), - external: ['node:async_hooks'], - banner: { js: 'var process={env:{NODE_ENV:"development"},browser:true};' }, - format: 'iife', - platform: 'browser', - tsconfig: join(SIM_DIR, 'tsconfig.json'), - define: { 'process.env.NODE_ENV': '"development"' }, - }) - server = createServer((request, response) => { - const path = new URL(request.url ?? '/', 'http://localhost').pathname - if (path === '/fixture.js' || path === '/fixture.css') { - response.setHeader('Content-Type', path.endsWith('.js') ? 'text/javascript' : 'text/css') - response.end( - path.endsWith('.js') - ? bundle.outputFiles.find((file) => file.path.endsWith('.js'))?.text - : `${css.css}\n${bundle.outputFiles.find((file) => file.path.endsWith('.css'))?.text ?? ''}` - ) - return - } - if (path.startsWith('/api/')) { - response.setHeader('Content-Type', 'application/json') - response.end( - path === '/api/auth/get-session' - ? JSON.stringify({ user: { id: 'fixture-user' }, session: { id: 'fixture-session' } }) - : '{}' - ) - return - } - response.writeHead(200, { - 'Content-Type': 'text/html', - 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; SameSite=Lax; Path=/', - }) + }, + { sources: [FIXTURE] } + ) + const server = await serve((_request, response, url) => { + const path = url.pathname + if (path === '/fixture.js' || path === '/fixture.css') { + response.setHeader('Content-Type', path.endsWith('.js') ? 'text/javascript' : 'text/css') + response.end(path.endsWith('.js') ? bundle.js : bundle.css) + return + } + if (path.startsWith('/api/')) { + response.setHeader('Content-Type', 'application/json') response.end( - path === '/page' - ? '

Browser fixture

A live page behind the application chrome.

' - : '
' + path === '/api/auth/get-session' + ? JSON.stringify({ user: { id: 'fixture-user' }, session: { id: 'fixture-session' } }) + : '{}' ) + return + } + response.writeHead(200, { + 'Content-Type': 'text/html', + 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; SameSite=Lax; Path=/', }) - await new Promise((resolve) => server?.listen(0, resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - userData = mkdtempSync(join(tmpdir(), 'sim-browser-chrome-e2e-')) - app = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { - ...process.env, - SIM_DESKTOP_ORIGIN: `http://127.0.0.1:${address.port}`, - SIM_DESKTOP_USER_DATA: userData, - }, - }) - const shell = app - const page = await shell.firstWindow() - await shell.evaluate(({ app, BrowserWindow }) => { - const window = BrowserWindow.getAllWindows()[0] - window.setContentSize(1100, 750) - window.webContents.setBackgroundThrottling(false) - app.focus({ steal: true }) - window.focus() + response.end( + path === '/page' + ? '

Browser fixture

A live page behind the application chrome.

' + : '
' + ) + }) + let shellPage: Page | undefined + try { + const { app } = await desktop.launch({ + origin: server.origin, }) + const page = await app.firstWindow() + shellPage = page + await app.evaluate(({ BrowserWindow }) => + BrowserWindow.getAllWindows()[0].setContentSize(1100, 750) + ) + await focusFirstWindow(app) const nativeVisible = () => - shell.evaluate(({ BrowserWindow, WebContentsView }) => + app.evaluate(({ BrowserWindow, WebContentsView }) => BrowserWindow.getAllWindows()[0] .contentView.children.find( (view) => view instanceof WebContentsView && view.webContents.getURL().endsWith('/page') @@ -118,7 +84,6 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, ) expect(geometry.every((tab) => tab.width < 160)).toBe(true) expect(geometry.at(-1)?.right).toBeLessThan(1070) - await page.screenshot({ path: testInfo.outputPath('tabs.png') }) }) await test.step('Crowded tabs keep readable labels when selected, hovered, and focused', async () => { await page.locator('#many-tabs').click() @@ -165,17 +130,6 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, await expect .poll(() => label.evaluate((element) => element.getBoundingClientRect().width)) .toBeGreaterThanOrEqual(48) - await page.mouse.move(200, 180) - await page.screenshot({ - path: testInfo.outputPath('crowded-tabs.png'), - animations: 'disabled', - }) - await page.evaluate(() => document.documentElement.classList.remove('dark')) - await page.screenshot({ - path: testInfo.outputPath('crowded-tabs-light.png'), - animations: 'disabled', - }) - await page.evaluate(() => document.documentElement.classList.add('dark')) await page.keyboard.press('Home') await expect(page.getByRole('tab').first()).toBeInViewport({ ratio: 1 }) await page.locator('#eight-tabs').click() @@ -218,7 +172,6 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, ) }) ).toBe(true) - await page.screenshot({ path: testInfo.outputPath('crowded-tabs-touch.png') }) const beforeSelection = await attention.evaluate( (element: HTMLElement) => element.offsetWidth ) @@ -228,11 +181,15 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, beforeSelection ) await page.locator('#toggle-activity').click() + await expect(indicator).toHaveCount(0) expect(await attention.evaluate((element: HTMLElement) => element.offsetWidth)).toBe( beforeSelection ) await page.locator('#toggle-activity').click() await page.locator('#medium-tabs').click() + await expect(page.locator('[data-tab-strip-item] [data-overflow-text]')).toHaveText( + Array(4).fill('Medium title') + ) await page.getByRole('tab').first().click() const intrinsicWidth = await attention.evaluate( (element: HTMLElement) => element.offsetWidth @@ -244,6 +201,7 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, intrinsicWidth ) await page.locator('#toggle-activity').click() + await expect(indicator).toHaveCount(0) expect(await attention.evaluate((element: HTMLElement) => element.offsetWidth)).toBe( intrinsicWidth ) @@ -256,6 +214,9 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, }) await test.step('Short labels stay below the maximum tab width', async () => { await page.locator('#short-tabs').click() + await expect(page.locator('[data-tab-strip-item] [data-overflow-text]')).toHaveText( + Array(8).fill('A') + ) const widths = await page .locator('[data-tab-strip-item]') .evaluateAll((tabs) => tabs.map((tab) => tab.getBoundingClientRect().width)) @@ -268,9 +229,7 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, expect( await page.evaluate( (scope) => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.browserAgent.capturePanelSnapshot(scope), + (globalThis as DesktopBridge).simDesktop.browserAgent.capturePanelSnapshot(scope), SCOPE ) ).toBeNull() @@ -289,7 +248,6 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, await expect(page.getByRole('tooltip')).toBeVisible() await expect.poll(nativeVisible).toBe(false) await expect(page.locator('#snapshot')).toBeVisible() - await page.screenshot({ path: testInfo.outputPath('tooltip.png') }) }) await test.step('Leaving the tooltip restores the native browser', async () => { await page.mouse.move(200, 180) @@ -309,7 +267,7 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, await expect(page.locator('#snapshot')).toBeVisible() }) await test.step('Resizing with an open menu refreshes the captured viewport', async () => { - await shell.evaluate(({ BrowserWindow }) => + await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].setContentSize(1000, 750) ) await expect @@ -318,7 +276,6 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, ) .toBe(450) await expect.poll(nativeVisible).toBe(false) - await page.screenshot({ path: testInfo.outputPath('menu.png') }) }) await test.step('Escape dismisses the menu and restores the native browser', async () => { await page.keyboard.press('Escape') @@ -327,7 +284,7 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, await expect(page.locator('#snapshot')).toHaveCount(0) }) } catch (error) { - const page = app?.windows()[0] + const page = shellPage if (page && !page.isClosed()) { await page.screenshot({ path: testInfo.outputPath('failure.png') }) const overlays = await page.locator('[data-native-surface-overlay]').evaluateAll((elements) => @@ -345,13 +302,6 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, } throw error } finally { - await app?.close() - if (server?.listening) { - const listener = server - await new Promise((resolve, reject) => - listener.close((error) => (error ? reject(error) : resolve())) - ) - } - if (userData) rmSync(userData, { recursive: true, force: true }) + await server.close() } }) diff --git a/apps/desktop/e2e/browser-focus.spec.ts b/apps/desktop/e2e/browser-focus.spec.ts index 86e13ee3726..d6a5de1ebee 100644 --- a/apps/desktop/e2e/browser-focus.spec.ts +++ b/apps/desktop/e2e/browser-focus.spec.ts @@ -1,196 +1,158 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { createServer, type Server } from 'node:http' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { fileURLToPath } from 'node:url' +import type { BrowserPanelAction, BrowserToolName } from '@sim/browser-protocol' +import { refFor } from './executor-sim' import { - type ElectronApplication, - _electron as electron, + attachBrowserPanel, + type DesktopBridge, expect, - type Page, + focusFirstWindow, + hideBrowserPanel, + serve, + ToolAuthorizer, test, -} from '@playwright/test' -import type { BrowserToolName } from '@sim/browser-protocol' -import type { SimDesktopApi } from '@sim/desktop-bridge' -import { getErrorMessage } from '@sim/utils/errors' +} from './harness' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) const SCOPE = 'browser-focus-e2e' const PRIMARY = process.platform === 'darwin' ? 'meta' : 'control' +const PANEL_TOP = 120 const SHELL_FIXTURE = 'Sim fixture

Browser focus fixture

' const page = (name: string) => `${name}Open popup` -type Bridge = typeof globalThis & { simDesktop: SimDesktopApi; shellMarker?: string } +type Bridge = DesktopBridge & { shellMarker?: string } +/** What the test installs in the main process. */ +type MainFixture = typeof globalThis & { pageLoads?: Map; countedPage?: number } /** * The browser shares one window with Sim, so focus and shortcuts decide whether - * a keystroke lands in chat, in the page, or reloads all of Sim. These checks + * a keystroke lands in chat, in the page, or reloads all of Sim. These steps * drive the real shell and native tab views. */ -test('browser focus and shortcuts stay with the surface the user is using', async () => { - const reportPath = - process.env.DESKTOP_BROWSER_FOCUS_REPORT_PATH ?? test.info().outputPath('browser-focus.json') - const checks: { - name: string - status: 'passed' | 'failed' - durationMs: number - error?: string - }[] = [] - const check = async (name: string, run: () => Promise) => { - const started = Date.now() - try { - await test.step(name, run) - checks.push({ name, status: 'passed', durationMs: Date.now() - started }) - } catch (error) { - checks.push({ - name, - status: 'failed', - durationMs: Date.now() - started, - error: getErrorMessage(error), - }) - throw error - } - } - const calls = new Map() - const server: Server = createServer(async (request, response) => { - const path = new URL(request.url ?? '/', 'http://localhost').pathname - if (path === '/api/desktop/tool/authorize') { - let body = '' - for await (const chunk of request) body += chunk.toString() - const authorization = calls.get(JSON.parse(body).toolCallId) - response.writeHead(authorization ? 200 : 403, { 'Content-Type': 'application/json' }) - response.end(JSON.stringify(authorization ?? {})) - return - } +test('browser focus and shortcuts stay with the surface the user is using', async ({ desktop }) => { + const authorizer = new ToolAuthorizer('browser-focus') + const server = await serve(async (request, response, url) => { + if (await authorizer.handle(request, response, url)) return // The app origin serves the shell; the same server on localhost is the web. const isSite = request.headers.host?.startsWith('localhost') === true response.writeHead(200, { 'Content-Type': 'text/html', ...(isSite ? {} : { 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; Path=/' }), }) - response.end(isSite ? page(path.slice(1)) : SHELL_FIXTURE) + response.end(isSite ? page(url.pathname.slice(1)) : SHELL_FIXTURE) }) - const userData = mkdtempSync(join(tmpdir(), 'sim-browser-focus-e2e-')) - let app: ElectronApplication | undefined - let passed = false try { - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - const origin = `http://127.0.0.1:${address.port}` - /** Pages outside the app origin browse in the agent partition, like any third-party site. */ - const site = origin.replace('127.0.0.1', 'localhost') - const shellApp = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { ...process.env, SIM_DESKTOP_ORIGIN: origin, SIM_DESKTOP_USER_DATA: userData }, - }) - app = shellApp - const shell: Page = await shellApp.firstWindow() - await shellApp.evaluate(({ app, BrowserWindow }) => { - const host = BrowserWindow.getAllWindows()[0] - host.webContents.setBackgroundThrottling(false) - app.focus({ steal: true }) - host.focus() + const { site } = server + const { app } = await desktop.launch({ + origin: server.origin, }) + const shell = await app.firstWindow() + await focusFirstWindow(app) await expect(shell.getByRole('heading')).toHaveText('Browser focus fixture') - await shell.evaluate(async (scope) => { - const api = (globalThis as Bridge).simDesktop.browserAgent - await api.activateScope(scope) - const updateBounds = () => - api.setPanelBounds( - { x: 0, y: 120, width: innerWidth, height: innerHeight - 120 }, - null, - scope - ) - updateBounds() - ;(globalThis as Bridge & { boundsTimer?: number }).boundsTimer = window.setInterval( - updateBounds, - 200 - ) + await attachBrowserPanel(shell, SCOPE, PANEL_TOP) + await shell.evaluate(() => { ;(globalThis as Bridge).shellMarker = 'alive' - }, SCOPE) + }) - let callCount = 0 - const execute = async (tool: BrowserToolName, args: Record) => { - const callId = `browser-focus-${++callCount}` - calls.set(callId, { chatId: SCOPE, toolName: tool, args }) - const result = await shell.evaluate( - ({ callId, tool, args, scope }) => - (globalThis as Bridge).simDesktop.browserAgent.executeTool(callId, tool, args, scope), - { callId, tool, args, scope: SCOPE } - ) - expect(result.ok, result.error).toBe(true) - return result.ok ? result.result : undefined - } - const panelAction = (action: Record) => + const execute = (tool: BrowserToolName, args: Record = {}) => + authorizer.execute(shell, SCOPE, tool, args) + /** + * Fire-and-forget browser IPC, followed by an invoke round trip from the same renderer so the + * main process has handled the sends before the test acts. + */ + const send = (message: { panelAction: BrowserPanelAction } | { panelFocused: boolean }) => shell.evaluate( - ({ action, scope }) => - (globalThis as Bridge).simDesktop.browserAgent.panelAction( - action as unknown as Parameters[0], - scope - ), - { action, scope: SCOPE } - ) - const setPanelFocused = (focused: boolean) => - shell.evaluate( - ({ focused, scope }) => - (globalThis as Bridge).simDesktop.browserAgent.setPanelFocused(focused, scope), - { focused, scope: SCOPE } + async ({ message, scope }) => { + const api = (globalThis as Bridge).simDesktop.browserAgent + if ('panelAction' in message) api.panelAction(message.panelAction, scope) + else api.setPanelFocused(message.panelFocused, scope) + await api.activateScope(scope) + }, + { message, scope: SCOPE } ) - const tabCount = () => + const tabs = () => shell.evaluate( async (scope) => - (await (globalThis as Bridge).simDesktop.browserAgent.activateScope(scope)).tabs.length, + (await (globalThis as Bridge).simDesktop.browserAgent.activateScope(scope)).tabs, SCOPE ) + const tabCount = async () => (await tabs()).length const shellAlive = () => shell.evaluate(() => (globalThis as Bridge).shellMarker === 'alive').catch(() => false) const composerFocused = () => shell.evaluate(() => document.hasFocus() && document.activeElement?.id === 'composer') const focusedPageUrls = () => - shellApp.evaluate(({ BrowserWindow, WebContentsView }) => + app.evaluate(({ BrowserWindow, WebContentsView }) => BrowserWindow.getAllWindows()[0] .contentView.children.filter( (view) => view instanceof WebContentsView && view.webContents.isFocused() ) .map((view) => (view as Electron.WebContentsView).webContents.getURL()) ) - const visiblePageUrl = () => - shellApp.evaluate(({ BrowserWindow, WebContentsView }) => { + const visiblePage = () => + app.evaluate(({ BrowserWindow, WebContentsView }) => { const view = BrowserWindow.getAllWindows()[0].contentView.children.find( (child) => child instanceof WebContentsView && child.getVisible() ) as Electron.WebContentsView | undefined - return view?.webContents.getURL() ?? null + return view + ? { url: view.webContents.getURL(), loading: view.webContents.isLoading() } + : null }) - /** Counts main-frame loads of the visible page from now on. */ + const visiblePageUrl = async () => (await visiblePage())?.url ?? null + /** Whether a page at exactly `url` finished loading, visible or not. */ + const pageLoaded = (url: string) => + app.evaluate( + ({ webContents }, url) => + webContents + .getAllWebContents() + .some((contents) => contents.getURL() === url && !contents.isLoading()), + url + ) + /** How many popup pages have finished loading, wherever they are in the strip. */ + const loadedPopups = () => + app.evaluate( + ({ webContents }, url) => + webContents + .getAllWebContents() + .filter((contents) => contents.getURL() === url && !contents.isLoading()).length, + `${site}/popup` + ) + /** Counts main-frame loads of the page on screen from now on, keyed to its contents. */ const countVisiblePageLoads = () => - shellApp.evaluate(({ BrowserWindow, WebContentsView }) => { + app.evaluate(({ BrowserWindow, WebContentsView }) => { const view = BrowserWindow.getAllWindows()[0].contentView.children.find( (child) => child instanceof WebContentsView && child.getVisible() ) as Electron.WebContentsView - const counter = globalThis as typeof globalThis & { pageLoads?: number; counted?: boolean } - counter.pageLoads = 0 - if (!counter.counted) { - counter.counted = true - view.webContents.on('did-finish-load', () => { - counter.pageLoads = (counter.pageLoads ?? 0) + 1 - }) + const fixture = globalThis as MainFixture + const loads = (fixture.pageLoads ??= new Map()) + const contents = view.webContents + if (!loads.has(contents.id)) { + contents.on('did-finish-load', () => + loads.set(contents.id, (loads.get(contents.id) ?? 0) + 1) + ) } + loads.set(contents.id, 0) + fixture.countedPage = contents.id }) const pageLoads = () => - shellApp.evaluate(() => (globalThis as typeof globalThis & { pageLoads?: number }).pageLoads) - const focusVisiblePage = () => - shellApp.evaluate(({ BrowserWindow, WebContentsView }) => { + app.evaluate(() => { + const fixture = globalThis as MainFixture + return fixture.countedPage === undefined + ? undefined + : fixture.pageLoads?.get(fixture.countedPage) + }) + /** Focuses the page on screen and waits until it holds keyboard focus. */ + const focusVisiblePage = async () => { + const url = await app.evaluate(({ BrowserWindow, WebContentsView }) => { const view = BrowserWindow.getAllWindows()[0].contentView.children.find( (child) => child instanceof WebContentsView && child.getVisible() ) as Electron.WebContentsView view.webContents.focus() + return view.webContents.getURL() }) + await expect.poll(focusedPageUrls).toEqual([url]) + } const pressInPage = (keyCode: string, modifiers: string[]) => - shellApp.evaluate( + app.evaluate( ({ BrowserWindow, WebContentsView }, { keyCode, modifiers }) => { const view = BrowserWindow.getAllWindows()[0].contentView.children.find( (child) => child instanceof WebContentsView && child.getVisible() @@ -203,7 +165,7 @@ test('browser focus and shortcuts stay with the surface the user is using', asyn ) /** Clicks an application-menu item the way its accelerator would. */ const clickMenu = (label: string) => - shellApp.evaluate(({ BrowserWindow, Menu }, label) => { + app.evaluate(({ BrowserWindow, Menu }, label) => { const win = BrowserWindow.getAllWindows()[0] const find = (items: Electron.MenuItem[]): Electron.MenuItem | null => { for (const item of items) { @@ -217,53 +179,50 @@ test('browser focus and shortcuts stay with the surface the user is using', asyn if (!item) throw new Error(`No menu item ${label}`) item.click(undefined, win, win.webContents) }, label) + const clickPopupLink = async () => { + const before = await loadedPopups() + const snapshot = (await execute('browser_snapshot')) as { outline: string } + await execute('browser_click', { elementId: refFor(snapshot.outline, 'Open popup') }) + await expect.poll(loadedPopups).toBe(before + 1) + } - await check('the agent working never takes the caret from the composer', async () => { + await test.step('the agent working never takes the caret from the composer', async () => { await shell.locator('#composer').click() await shell.keyboard.type('draft') - for (const [tool, args] of [ - ['browser_open_url', { url: `${site}/one` }], - ['browser_navigate', { url: `${site}/two` }], - ['browser_open_tab', { url: `${site}/three` }], + for (const [tool, path] of [ + ['browser_open_url', '/one'], + ['browser_navigate', '/two'], + ['browser_open_tab', '/three'], ] as const) { - await execute(tool, args) - await expect.poll(visiblePageUrl).not.toBeNull() + await execute(tool, { url: `${site}${path}` }) + // browser_open_tab works in a background tab, so the page need not be the visible one. + await expect.poll(() => pageLoaded(`${site}${path}`)).toBe(true) expect(await composerFocused()).toBe(true) expect(await focusedPageUrls()).toEqual([]) } // A link without an opener is focused by Chromium itself as it is created. - const snapshot = await execute('browser_snapshot', {}) - const ref = /"Open popup" \[ref=(\d+)\]/.exec( - String((snapshot as { outline?: string }).outline) - )?.[1] - expect(ref, 'snapshot lists the popup link').toBeTruthy() - await execute('browser_click', { elementId: Number(ref) }) - await expect.poll(tabCount).toBe(3) - await expect.poll(focusedPageUrls).toEqual([]) + await clickPopupLink() + expect(await tabCount()).toBe(3) + expect(await focusedPageUrls()).toEqual([]) expect(await composerFocused()).toBe(true) await shell.keyboard.type(' continues') await expect(shell.locator('#composer')).toHaveValue('draft continues') }) - await check('an omnibox navigation hands focus to the page it loads', async () => { - await panelAction({ action: 'switch-tab', tabId: '1' }) - await panelAction({ action: 'navigate', url: `${site}/four` }) + await test.step('an omnibox navigation hands focus to the page it loads', async () => { + await send({ panelAction: { action: 'switch-tab', tabId: '1' } }) + await send({ panelAction: { action: 'navigate', url: `${site}/four` } }) await expect.poll(focusedPageUrls).toEqual([`${site}/four`]) }) - await check('a popup the agent opens hands focus back to the page the user is in', async () => { + await test.step('a popup the agent opens hands focus back to the page the user is in', async () => { const before = await tabCount() - const snapshot = await execute('browser_snapshot', {}) - const ref = /"Open popup" \[ref=(\d+)\]/.exec( - String((snapshot as { outline?: string }).outline) - )?.[1] - expect(ref, 'snapshot lists the popup link').toBeTruthy() - await execute('browser_click', { elementId: Number(ref) }) - await expect.poll(tabCount).toBe(before + 1) + await clickPopupLink() + expect(await tabCount()).toBe(before + 1) await expect.poll(focusedPageUrls).toEqual([`${site}/four`]) }) - await check('reload keys typed in the page reload only that page', async () => { + await test.step('reload keys typed in the page reload only that page', async () => { for (const [keyCode, modifiers] of [ ['R', [PRIMARY]], ['R', [PRIMARY, 'shift']], @@ -276,19 +235,19 @@ test('browser focus and shortcuts stay with the surface the user is using', asyn } }) - await check('the page keeps its shortcut claim after the chrome reports blur', async () => { - await setPanelFocused(true) + await test.step('the page keeps its shortcut claim after the chrome reports blur', async () => { + await send({ panelFocused: true }) await focusVisiblePage() - await setPanelFocused(false) + await send({ panelFocused: false }) await countVisiblePageLoads() await clickMenu('Reload') await expect.poll(pageLoads).toBe(1) expect(await shellAlive()).toBe(true) }) - await check('Back and Forward move through the focused page history', async () => { - await panelAction({ action: 'navigate', url: `${site}/five` }) - await expect.poll(visiblePageUrl).toBe(`${site}/five`) + await test.step('Back and Forward move through the focused page history', async () => { + await send({ panelAction: { action: 'navigate', url: `${site}/five` } }) + await expect.poll(visiblePage).toEqual({ url: `${site}/five`, loading: false }) await focusVisiblePage() await clickMenu('Back') await expect.poll(visiblePageUrl).toBe(`${site}/four`) @@ -297,50 +256,42 @@ test('browser focus and shortcuts stay with the surface the user is using', asyn await expect.poll(visiblePageUrl).toBe(`${site}/five`) }) - await check('browser shortcuts work while renderer chrome hides the page', async () => { + await test.step('browser shortcuts work while renderer chrome hides the page', async () => { const before = await tabCount() - await shell.evaluate((scope) => { - const bridge = globalThis as Bridge & { boundsTimer?: number } - window.clearInterval(bridge.boundsTimer) - bridge.simDesktop.browserAgent.setPanelBounds(null, null, scope) - }, SCOPE) - await setPanelFocused(true) + await hideBrowserPanel(shell, SCOPE) + await send({ panelFocused: true }) await clickMenu('New Tab') await expect.poll(tabCount).toBe(before + 1) }) - await check( - 'a revealed page resumes throttling in its own chat after switching chats', - async () => { - await panelAction({ action: 'switch-tab', tabId: '1' }) - await shell.evaluate(async (scope) => { + + await test.step('a revealed page resumes throttling in its own chat after switching chats', async () => { + await send({ panelAction: { action: 'switch-tab', tabId: '1' } }) + await shell.evaluate( + async ({ scope, top }) => { const api = (globalThis as Bridge).simDesktop.browserAgent api.setPanelBounds( - { x: 0, y: 120, width: innerWidth, height: innerHeight - 120 }, + { x: 0, y: top, width: innerWidth, height: innerHeight - top }, null, scope ) await api.activateScope('browser-focus-other-chat') - }, SCOPE) - await expect - .poll(() => - shellApp.evaluate( - ({ webContents }, url) => - webContents - .getAllWebContents() - .find((contents) => contents.getURL() === url) - ?.getBackgroundThrottling(), - `${site}/five` - ) + }, + { scope: SCOPE, top: PANEL_TOP } + ) + await expect + .poll(() => + app.evaluate( + ({ webContents }, url) => + webContents + .getAllWebContents() + .find((contents) => contents.getURL() === url) + ?.getBackgroundThrottling(), + `${site}/five` ) - .toBe(true) - } - ) - passed = true + ) + .toBe(true) + }) } finally { - mkdirSync(dirname(reportPath), { recursive: true }) - writeFileSync(reportPath, JSON.stringify({ passed, checks }, null, 2)) - await app?.close() - await new Promise((resolve) => server.close(() => resolve())) - rmSync(userData, { recursive: true, force: true }) + await server.close() } }) diff --git a/apps/desktop/e2e/browser-page-dialogs.spec.ts b/apps/desktop/e2e/browser-page-dialogs.spec.ts index 7a79887abb7..58582581496 100644 --- a/apps/desktop/e2e/browser-page-dialogs.spec.ts +++ b/apps/desktop/e2e/browser-page-dialogs.spec.ts @@ -1,28 +1,28 @@ -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { createServer, type Server } from 'node:http' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { fileURLToPath } from 'node:url' +import { join } from 'node:path' +import type { Dialog, Page } from '@playwright/test' +import type { BrowserPageDialog, BrowserPanelAction, BrowserToolName } from '@sim/browser-protocol' import { - type Dialog, - type ElectronApplication, - _electron as electron, + BROWSER_SESSION_COMPONENTS, + focusedPageUrl, + inPage, + openShell, + panelAction, + serveShellAndSite, + titleAt, + userInput, +} from './browser-page' +import { + bundleSimFixture, + type DesktopBridge, expect, - type Page, + hideBrowserPanel, + SIM_DIR, + ToolAuthorizer, test, -} from '@playwright/test' -import type { BrowserPageDialog, BrowserToolName } from '@sim/browser-protocol' -import type { SimDesktopApi } from '@sim/desktop-bridge' -import { getErrorMessage } from '@sim/utils/errors' -import { build } from 'esbuild' -import postcss from 'postcss' -import loadPostcssConfig from 'postcss-load-config' +} from './harness' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) const SCOPE = 'browser-page-dialogs-e2e' -const SIM_DIR = fileURLToPath(new URL('../../sim/', import.meta.url)) -const SHELL_FIXTURE = - 'Sim fixture

Browser dialogs fixture

' +const SHELL = { heading: 'Browser dialogs fixture', top: 80 } const FORM_FIXTURE = `form @@ -31,11 +31,9 @@ const FORM_FIXTURE = `form if (document.getElementById('draft').value) { event.preventDefault(); event.returnValue = '' } })` -type Bridge = typeof globalThis & { - simDesktop: SimDesktopApi +type FixtureGlobals = DesktopBridge & { pageDialog?: BrowserPageDialog | null pageIssue?: string | null - boundsTimer?: number } /** @@ -43,42 +41,15 @@ type Bridge = typeof globalThis & { * the page: the user on the tab they are looking at, the agent during its own * action. These checks drive the real shell and native tab views. */ -test('page dialogs wait for the user on their page and stay automatic for the agent', async () => { - const reportPath = - process.env.DESKTOP_BROWSER_DIALOGS_REPORT_PATH ?? - test.info().outputPath('browser-page-dialogs.json') - const checks: { - name: string - status: 'passed' | 'failed' - durationMs: number - error?: string - }[] = [] - const check = async (name: string, run: () => Promise) => { - const started = Date.now() - try { - await test.step(name, run) - checks.push({ name, status: 'passed', durationMs: Date.now() - started }) - } catch (error) { - checks.push({ - name, - status: 'failed', - durationMs: Date.now() - started, - error: getErrorMessage(error), - }) - throw error - } - } - const browserComponents = join( - SIM_DIR, - 'app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session' - ) - const bundle = await build({ - stdin: { - contents: `import { createElement } from 'react'; +test('page dialogs wait for the user on their page and stay automatic for the agent', async ({ + desktop, +}) => { + const bundle = await bundleSimFixture({ + source: `import { createElement } from 'react'; import { createRoot } from 'react-dom/client'; import { useBrowserSessionStore as store } from ${JSON.stringify(join(SIM_DIR, 'stores/browser-session/store.ts'))}; -import { BrowserPageDialogModal } from ${JSON.stringify(join(browserComponents, 'browser-page-dialog.tsx'))}; -import { useBrowserPanelOcclusion } from ${JSON.stringify(join(browserComponents, 'browser-panel-occlusion.ts'))}; +import { BrowserPageDialogModal } from ${JSON.stringify(join(BROWSER_SESSION_COMPONENTS, 'browser-page-dialog.tsx'))}; +import { useBrowserPanelOcclusion } from ${JSON.stringify(join(BROWSER_SESSION_COMPONENTS, 'browser-panel-occlusion.ts'))}; const scope = ${JSON.stringify(SCOPE)}; const api = globalThis.simDesktop.browserAgent; api.onPageState(state => store.getState().setPageState(state)); @@ -96,128 +67,47 @@ function Fixture() { }); } createRoot(document.getElementById('root')).render(createElement(Fixture));`, - resolveDir: SIM_DIR, - loader: 'tsx', - }, - bundle: true, - write: false, - outfile: test.info().outputPath('fixture.js'), - external: ['node:async_hooks'], - banner: { js: 'var process={env:{NODE_ENV:"development"},browser:true};' }, - format: 'iife', - platform: 'browser', - tsconfig: join(SIM_DIR, 'tsconfig.json'), - define: { 'process.env.NODE_ENV': '"development"' }, }) - const config = await loadPostcssConfig({}, SIM_DIR) - const stylesheet = join(SIM_DIR, 'app/_styles/globals.css') - const css = await postcss(config.plugins).process(readFileSync(stylesheet, 'utf8'), { - from: stylesheet, - }) - const calls = new Map() - const server: Server = createServer(async (request, response) => { - const path = new URL(request.url ?? '/', 'http://localhost').pathname - if (path === '/fixture.js' || path === '/fixture.css') { - response.setHeader('Content-Type', path.endsWith('.js') ? 'text/javascript' : 'text/css') + const authorizer = new ToolAuthorizer('browser-dialogs') + const server = await serveShellAndSite({ + ...SHELL, + bundle, + authorizer, + site: (_request, response, url) => { + if (url.pathname === '/broken') { + response.destroy() + return + } + response.writeHead(200, { 'Content-Type': 'text/html' }) response.end( - path.endsWith('.js') - ? bundle.outputFiles.find((file) => file.path.endsWith('.js'))?.text - : css.css - ) - return - } - if (path === '/api/desktop/tool/authorize') { - let body = '' - for await (const chunk of request) body += chunk.toString() - const authorization = calls.get(JSON.parse(body).toolCallId) - response.writeHead(authorization ? 200 : 403, { 'Content-Type': 'application/json' }) - response.end(JSON.stringify(authorization ?? {})) - return - } - if (path === '/broken') { - response.destroy() - return - } - // The app origin serves the shell; the same server on localhost is the web. - const isSite = request.headers.host?.startsWith('localhost') === true - response.writeHead(200, { - 'Content-Type': 'text/html', - ...(isSite ? {} : { 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; Path=/' }), - }) - response.end( - !isSite - ? SHELL_FIXTURE - : path === '/form' || path === '/agent' + url.pathname === '/form' || url.pathname === '/agent' ? FORM_FIXTURE : 'next' - ) + ) + }, }) - const userData = mkdtempSync(join(tmpdir(), 'sim-browser-dialogs-e2e-')) - let app: ElectronApplication | undefined - let passed = false try { - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - const origin = `http://127.0.0.1:${address.port}` - const site = origin.replace('127.0.0.1', 'localhost') - const shellApp = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { ...process.env, SIM_DESKTOP_ORIGIN: origin, SIM_DESKTOP_USER_DATA: userData }, - }) - app = shellApp + const { site } = server + const form = `${site}/form` + const { app } = await desktop.launch({ origin: server.origin }) // A dialog listener stops Playwright auto-dismissing page dialogs, so the desktop's own // handling decides their outcome exactly as it does in production. const nativeDialogs: Dialog[] = [] - const leaveDialogsToDesktop = (page: Page) => - page.on('dialog', (dialog) => nativeDialogs.push(dialog)) + const captureDialogs = (page: Page) => page.on('dialog', (dialog) => nativeDialogs.push(dialog)) + app.context().pages().forEach(captureDialogs) + app.context().on('page', captureDialogs) const nextNativeDialog = async () => { await expect.poll(() => nativeDialogs.length).toBeGreaterThan(0) const dialog = nativeDialogs.shift() if (!dialog) throw new Error('Missing native dialog') return dialog } - shellApp.context().pages().forEach(leaveDialogsToDesktop) - shellApp.context().on('page', leaveDialogsToDesktop) - const shell = await shellApp.firstWindow() - await shellApp.evaluate(({ app, BrowserWindow }) => { - const host = BrowserWindow.getAllWindows()[0] - if (!host) throw new Error('Missing host window') - app.focus({ steal: true }) - host.focus() - }) - await expect(shell.getByRole('heading')).toHaveText('Browser dialogs fixture') - await shell.evaluate(async (scope) => { - const bridge = globalThis as Bridge - const api = bridge.simDesktop.browserAgent - await api.activateScope(scope) - const updateBounds = () => - api.setPanelBounds( - { x: 0, y: 80, width: innerWidth, height: innerHeight - 80 }, - null, - scope - ) - updateBounds() - bridge.boundsTimer = window.setInterval(updateBounds, 200) - bridge.pageDialog = null - }, SCOPE) + const shell = await openShell(app, SCOPE, SHELL) - let callCount = 0 - const execute = async (tool: BrowserToolName, args: Record) => { - const callId = `browser-dialogs-${++callCount}` - calls.set(callId, { chatId: SCOPE, toolName: tool, args }) - const result = await shell.evaluate( - ({ callId, tool, args, scope }) => - (globalThis as Bridge).simDesktop.browserAgent.executeTool(callId, tool, args, scope), - { callId, tool, args, scope: SCOPE } - ) - expect(result.ok, result.error).toBe(true) - return result.ok ? result.result : undefined - } - const pageDialog = () => shell.evaluate(() => (globalThis as Bridge).pageDialog ?? null) - /** Browser-chrome actions are user gestures, so each follows a real click in Sim. */ - const panelAction = async (action: Record) => { + const execute = (tool: BrowserToolName, args: Record = {}) => + authorizer.execute(shell, SCOPE, tool, args) + const pageDialog = () => shell.evaluate(() => (globalThis as FixtureGlobals).pageDialog ?? null) + const act = async (action: BrowserPanelAction) => { // The store holds a dialog before its modal finishes the native-surface handshake and // renders, so a live dialog is answered through the modal once it appears. if ( @@ -225,111 +115,75 @@ createRoot(document.getElementById('root')).render(createElement(Fixture));`, (await pageDialog())?.requestId === action.requestId ) { await shell - .getByRole('button', { - name: action.allowed ? 'Leave' : 'Stay', - exact: true, - }) + .getByRole('button', { name: action.allowed ? 'Leave' : 'Stay', exact: true }) .click() return } - await shell.getByRole('heading').click() - await shell.evaluate( - ({ action, scope }) => - (globalThis as Bridge).simDesktop.browserAgent.panelAction( - action as unknown as Parameters[0], - scope - ), - { action, scope: SCOPE } - ) + await panelAction(shell, SCOPE, action) } - const inPage = (script: string) => - shellApp.evaluate( - async ({ webContents }, { script, url }) => - (await webContents - .getAllWebContents() - .find((contents) => contents.getURL().startsWith(url)) - ?.executeJavaScript(script)) as T, - { script, url: site } - ) - /** Read from the shell: a script cannot run in a page while its dialog is open. */ - const pageTitle = () => - shellApp.evaluate( - ({ webContents }, url) => - webContents - .getAllWebContents() - .find((contents) => contents.getURL().startsWith(url)) - ?.getTitle() ?? null, - site - ) + const formTitle = () => titleAt(app, form) + const draft = (url = form) => inPage(app, url, "document.getElementById('draft').value") + /** Types into the draft field and waits until the queued keys have landed. */ + const typeDraft = async (text: string) => { + const before = await draft() + await userInput(app, form, '#draft', text) + await expect.poll(() => draft()).toBe(before + text) + } + /** The URL of the one tab on the fixture site, whichever page it is showing. */ const pageUrl = () => - shellApp.evaluate( - ({ webContents }, url) => + app.evaluate( + ({ webContents }, site) => webContents .getAllWebContents() - .find((contents) => contents.getURL().startsWith(url)) + .find((contents) => contents.getURL().startsWith(site)) ?.getURL() ?? null, site ) - /** Trusted input into the page, the way the user's own mouse and keys arrive. */ - const userInput = (selector: string, text = '') => - shellApp.evaluate( - async ({ webContents }, { selector, text, url }) => { - const contents = webContents - .getAllWebContents() - .find((candidate) => candidate.getURL().startsWith(url)) - if (!contents) throw new Error('No page') - const rect: { x: number; y: number } = await contents.executeJavaScript( - `(() => { const { x, y } = document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect(); return { x, y } })()` - ) - const point = { x: Math.round(rect.x + 5), y: Math.round(rect.y + 5) } - contents.sendInputEvent({ type: 'mouseDown', ...point, button: 'left', clickCount: 1 }) - contents.sendInputEvent({ type: 'mouseUp', ...point, button: 'left', clickCount: 1 }) - for (const character of text) - contents.sendInputEvent({ type: 'char', keyCode: character }) - }, - { selector, text, url: site } - ) + const answerLeave = async (allowed: boolean) => { + await expect.poll(pageDialog).toMatchObject({ kind: 'beforeunload' }) + const dialog = await pageDialog() + await act({ action: 'respond-dialog', requestId: dialog?.requestId, allowed }) + } - await check('without a renderer that shows dialogs, the shell still answers them', async () => { - await execute('browser_open_url', { url: `${site}/form` }) - await panelAction({ action: 'switch-tab', tabId: '1' }) - await userInput('#delete') - await expect.poll(() => pageTitle()).toBe('confirm:false') + await test.step('without a renderer that shows dialogs, the shell still answers them', async () => { + await execute('browser_open_url', { url: form }) + await act({ action: 'switch-tab', tabId: '1' }) + await userInput(app, form, '#delete') + await expect.poll(formTitle).toBe('confirm:false') expect(await pageDialog()).toBeNull() }) - await panelAction({ action: 'enable-page-dialogs' }) - await inPage("document.title = 'form'") - + await act({ action: 'enable-page-dialogs' }) + await inPage(app, form, "document.title = 'form'") nativeDialogs.length = 0 - await check("the user's confirm waits for their answer without a duplicate modal", async () => { - await userInput('#delete') + + await test.step("the user's confirm waits for their answer without a duplicate modal", async () => { + await userInput(app, form, '#delete') const dialog = await nextNativeDialog() expect(dialog.type()).toBe('confirm') expect(dialog.message()).toBe('Delete the report?') - expect(await pageTitle()).toBe('form') + expect(await formTitle()).toBe('form') expect(await pageDialog()).toBeNull() await expect(shell.getByRole('dialog')).toHaveCount(0) await dialog.accept() - await expect.poll(() => pageTitle()).toBe('confirm:true') + await expect.poll(formTitle).toBe('confirm:true') }) - await check('a user sees the complete decision text beyond the diagnostic limit', async () => { - await userInput('#long-message') + await test.step('a user sees the complete decision text beyond the diagnostic limit', async () => { + await userInput(app, form, '#long-message') const dialog = await nextNativeDialog() expect(dialog.message()).toBe(`${'Details '.repeat(150)}Final decision detail`) await dialog.accept() }) - await check('automation leaves a user-owned confirmation unanswered', async () => { - await inPage("document.title = 'form'") - await userInput('#delete') + await test.step('automation leaves a user-owned confirmation unanswered', async () => { + await inPage(app, form, "document.title = 'form'") + await userInput(app, form, '#delete') const dialog = await nextNativeDialog() - const callId = `browser-dialogs-${++callCount}` - calls.set(callId, { chatId: SCOPE, toolName: 'browser_snapshot', args: {} }) + const callId = authorizer.issue(SCOPE, 'browser_snapshot', {}) const result = await shell.evaluate( ({ callId, scope }) => - (globalThis as Bridge).simDesktop.browserAgent.executeTool( + (globalThis as DesktopBridge).simDesktop.browserAgent.executeTool( callId, 'browser_snapshot', {}, @@ -340,109 +194,105 @@ createRoot(document.getElementById('root')).render(createElement(Fixture));`, expect(result.ok).toBe(false) await shell.evaluate( ({ callId, scope }) => - (globalThis as Bridge).simDesktop.browserAgent.cancelTool?.(callId, scope), + (globalThis as DesktopBridge).simDesktop.browserAgent.cancelTool?.(callId, scope), { callId, scope: SCOPE } ) - expect(await pageTitle()).toBe('form') + expect(await formTitle()).toBe('form') await dialog.accept() - await expect.poll(() => pageTitle()).toBe('confirm:true') + await expect.poll(formTitle).toBe('confirm:true') }) - await check("the agent's dialogs never wait on the user", async () => { - await inPage("document.title = 'form'") - const snapshot = await execute('browser_snapshot', {}) + await test.step("the agent's dialogs never wait on the user", async () => { + await inPage(app, form, "document.title = 'form'") + const snapshot = await execute('browser_snapshot') const ref = /button "Delete" \[ref=(\d+)\]/.exec( String((snapshot as { outline?: string }).outline) )?.[1] expect(ref, 'snapshot lists the Delete button').toBeTruthy() await execute('browser_click', { elementId: Number(ref) }) - await expect.poll(() => pageTitle()).toBe('confirm:false') + await expect.poll(formTitle).toBe('confirm:false') expect(await pageDialog()).toBeNull() - await inPage("document.title = 'form'") + await inPage(app, form, "document.title = 'form'") await execute('browser_click', { elementId: Number(ref), dialog: { accept: true } }) - await expect.poll(() => pageTitle()).toBe('confirm:true') + await expect.poll(formTitle).toBe('confirm:true') expect(await pageDialog()).toBeNull() }) // CDP answers the JavaScript call but Electron owns its native sheet. Reload // ends the native dialogs before testing the renderer's leave-site modal. - await panelAction({ action: 'reload' }) - await expect.poll(() => pageTitle()).toBe('form') + await act({ action: 'reload' }) + await expect.poll(formTitle).toBe('form') - await check('clean reloads and navigation never ask to discard changes', async () => { - await inPage("document.documentElement.dataset.reloadProbe = 'before'") - await panelAction({ action: 'reload' }) + await test.step('clean reloads and navigation never ask to discard changes', async () => { + await inPage(app, form, "document.documentElement.dataset.reloadProbe = 'before'") + await act({ action: 'reload' }) await expect - .poll(() => inPage('document.documentElement.dataset.reloadProbe')) + .poll(() => + inPage(app, form, 'document.documentElement.dataset.reloadProbe') + ) .toBeUndefined() - await expect.poll(() => pageTitle()).toBe('form') + await expect.poll(formTitle).toBe('form') expect(await pageDialog()).toBeNull() - await panelAction({ action: 'navigate', url: `${site}/next` }) + await act({ action: 'navigate', url: `${site}/next` }) await expect.poll(pageUrl).toBe(`${site}/next`) expect(await pageDialog()).toBeNull() - await panelAction({ action: 'back' }) - await expect.poll(pageUrl).toBe(`${site}/form`) + await act({ action: 'back' }) + await expect.poll(pageUrl).toBe(form) expect(await pageDialog()).toBeNull() }) - await check('clearing a draft removes the leave warning', async () => { - await userInput('#draft', 'temporary draft') - await inPage("document.getElementById('draft').value = ''") - await panelAction({ action: 'navigate', url: `${site}/next` }) + await test.step('clearing a draft removes the leave warning', async () => { + await typeDraft('temporary draft') + await inPage(app, form, "document.getElementById('draft').value = ''") + await act({ action: 'navigate', url: `${site}/next` }) await expect.poll(pageUrl).toBe(`${site}/next`) expect(await pageDialog()).toBeNull() - await panelAction({ action: 'navigate', url: `${site}/form` }) - await expect.poll(pageUrl).toBe(`${site}/form`) + await act({ action: 'navigate', url: form }) + await expect.poll(pageUrl).toBe(form) }) - await check('same-page navigation preserves a draft without a leave warning', async () => { - await userInput('#draft', 'same-page draft') - await panelAction({ action: 'navigate', url: `${site}/form#section` }) - await expect.poll(pageUrl).toBe(`${site}/form#section`) + await test.step('same-page navigation preserves a draft without a leave warning', async () => { + await typeDraft('same-page draft') + await act({ action: 'navigate', url: `${form}#section` }) + await expect.poll(pageUrl).toBe(`${form}#section`) expect(await pageDialog()).toBeNull() - expect(await inPage("document.getElementById('draft').value")).toBe('same-page draft') - await panelAction({ action: 'back' }) - await expect.poll(pageUrl).toBe(`${site}/form`) + expect(await draft(`${form}#section`)).toBe('same-page draft') + await act({ action: 'back' }) + await expect.poll(pageUrl).toBe(form) expect(await pageDialog()).toBeNull() - await inPage(`setTimeout(() => { location.href = ${JSON.stringify(`${site}/next`)} })`) + await inPage( + app, + form, + `setTimeout(() => { location.href = ${JSON.stringify(`${site}/next`)} })` + ) await expect.poll(pageUrl).toBe(`${site}/next`) expect(await pageDialog()).toBeNull() - await panelAction({ action: 'navigate', url: `${site}/form` }) - await expect.poll(pageUrl).toBe(`${site}/form`) + await act({ action: 'navigate', url: form }) + await expect.poll(pageUrl).toBe(form) }) - await check('leaving a draft from the URL bar asks, and Stay keeps it', async () => { - await userInput('#draft', 'draft') - await expect - .poll(() => inPage("document.getElementById('draft').value")) - .toBe('draft') - await panelAction({ action: 'navigate', url: `${site}/next` }) - await expect.poll(pageDialog).toMatchObject({ kind: 'beforeunload' }) - const dialog = await pageDialog() - await panelAction({ action: 'respond-dialog', requestId: dialog?.requestId, allowed: false }) + await test.step('leaving a draft from the URL bar asks, and Stay keeps it', async () => { + await typeDraft('draft') + await act({ action: 'navigate', url: `${site}/next` }) + await answerLeave(false) await expect.poll(pageDialog).toBeNull() - expect(await pageUrl()).toBe(`${site}/form`) - expect(await inPage("document.getElementById('draft').value")).toBe('draft') + expect(await pageUrl()).toBe(form) + expect(await draft()).toBe('draft') }) - await check('Reload of a draft asks too, and Stay keeps it', async () => { - await panelAction({ action: 'reload' }) - await expect.poll(pageDialog).toMatchObject({ kind: 'beforeunload' }) - const dialog = await pageDialog() - await panelAction({ action: 'respond-dialog', requestId: dialog?.requestId, allowed: false }) + await test.step('Reload of a draft asks too, and Stay keeps it', async () => { + await act({ action: 'reload' }) + await answerLeave(false) await expect.poll(pageDialog).toBeNull() - expect(await inPage("document.getElementById('draft').value")).toBe('draft') + expect(await draft()).toBe('draft') }) - await check('Escape keeps the draft and returns typing to the page', async () => { - await userInput('#draft') - await panelAction({ action: 'reload' }) - await expect(shell.getByRole('button', { name: 'Stay', exact: true })).toBeFocused() - await shell.getByRole('dialog').screenshot({ - path: test.info().outputPath('leave-page-modal.png'), - animations: 'allow', - caret: 'initial', - }) + await test.step('Escape keeps the draft and returns typing to the page', async () => { + await userInput(app, form, '#draft') + // The click is queued input: reloading before the page takes focus lets that focus land + // after the modal's, leaving the Sim window without keyboard focus. + await expect.poll(() => focusedPageUrl(app)).toBe(form) + await act({ action: 'reload' }) await expect(shell.getByRole('button', { name: 'Stay', exact: true })).toBeFocused() const shown = await pageDialog() await shell.keyboard.press('Escape') @@ -451,123 +301,97 @@ createRoot(document.getElementById('root')).render(createElement(Fixture));`, message: `dialog ${shown?.requestId} was showing when Escape was pressed`, }) .toBeNull() - await expect - .poll(() => - shellApp.evaluate(({ webContents }) => webContents.getFocusedWebContents()?.getURL()) - ) - .toBe(`${site}/form`) - await shellApp.evaluate(({ webContents }) => { + await expect.poll(() => focusedPageUrl(app)).toBe(form) + await app.evaluate(({ webContents }) => { const contents = webContents.getFocusedWebContents() if (!contents) throw new Error('Missing focused page') contents.sendInputEvent({ type: 'char', keyCode: 'x' }) }) - expect(await inPage("document.getElementById('draft').value")).toBe('xdraft') + await expect.poll(() => draft()).toBe('xdraft') }) - await check('Leave lets the navigation through without asking again', async () => { - await panelAction({ action: 'navigate', url: `${site}/next` }) - await expect.poll(pageDialog).toMatchObject({ kind: 'beforeunload' }) - const dialog = await pageDialog() - await panelAction({ action: 'respond-dialog', requestId: dialog?.requestId, allowed: true }) + await test.step('Leave lets the navigation through without asking again', async () => { + await act({ action: 'navigate', url: `${site}/next` }) + await answerLeave(true) await expect.poll(pageUrl).toBe(`${site}/next`) expect(await pageDialog()).toBeNull() }) - await check('a crashed page drops its pending Leave decision', async () => { - await panelAction({ action: 'navigate', url: `${site}/form` }) - await expect.poll(pageUrl).toBe(`${site}/form`) - await userInput('#draft', 'draft') - await panelAction({ action: 'reload' }) + + await test.step('a crashed page drops its pending Leave decision', async () => { + await act({ action: 'navigate', url: form }) + await expect.poll(pageUrl).toBe(form) + await typeDraft('draft') + await act({ action: 'reload' }) await expect.poll(pageDialog).toMatchObject({ kind: 'beforeunload' }) const stale = await pageDialog() - await shellApp.evaluate(({ webContents }, url) => { + await app.evaluate(({ webContents }, url) => { webContents .getAllWebContents() .find((contents) => contents.getURL() === url) ?.forcefullyCrashRenderer() - }, `${site}/form`) + }, form) await expect.poll(pageDialog).toBeNull() - await panelAction({ action: 'respond-dialog', requestId: stale?.requestId, allowed: true }) - await panelAction({ action: 'reload' }) - await expect.poll(() => pageTitle()).toBe('form') + await act({ action: 'respond-dialog', requestId: stale?.requestId, allowed: true }) + await act({ action: 'reload' }) + await expect.poll(formTitle).toBe('form') await expect.poll(pageDialog).toBeNull() }) - await check('Back from a failed load does not capture a later page navigation', async () => { - await userInput('#draft', 'draft') - await panelAction({ action: 'navigate', url: `${site}/broken` }) - await expect.poll(pageDialog).toMatchObject({ kind: 'beforeunload' }) - const dialog = await pageDialog() - await panelAction({ action: 'respond-dialog', requestId: dialog?.requestId, allowed: true }) + await test.step('Back from a failed load does not capture a later page navigation', async () => { + await typeDraft('draft') + await act({ action: 'navigate', url: `${site}/broken` }) + await answerLeave(true) await expect - .poll(() => shell.evaluate(() => (globalThis as Bridge).pageIssue)) + .poll(() => shell.evaluate(() => (globalThis as FixtureGlobals).pageIssue)) .toBe('load-error') - await panelAction({ action: 'back' }) - await inPage(`setTimeout(() => { location.href = ${JSON.stringify(`${site}/next`)} })`) + await act({ action: 'back' }) + // The page navigates itself from whatever document Back left in the tab. + const current = await pageUrl() + if (!current) throw new Error('No page on the fixture site after Back') + await inPage( + app, + current, + `setTimeout(() => { location.href = ${JSON.stringify(`${site}/next`)} })` + ) await expect.poll(pageUrl).toBe(`${site}/next`) expect(await pageDialog()).toBeNull() }) - /** Opens a page-initiated confirm (no user gesture) on the tab at `path`. */ - const confirmFromPage = (path: string) => - shellApp.evaluate(({ webContents }, url) => { - const contents = webContents.getAllWebContents().find((c) => c.getURL() === url) - if (!contents) throw new Error(`No page at ${url}`) - void contents.executeJavaScript( - "setTimeout(() => { document.title = 'confirm:' + confirm('Continue?') })" - ) - }, `${site}${path}`) - const titleAt = (path: string) => - shellApp.evaluate( - ({ webContents }, url) => - webContents - .getAllWebContents() - .find((c) => c.getURL() === url) - ?.getTitle() ?? null, - `${site}${path}` + /** Opens a page-initiated confirm (no user gesture) on the tab at `url`. */ + const confirmFromPage = (url: string) => + inPage( + app, + url, + "setTimeout(() => { document.title = 'confirm:' + confirm('Continue?') }); 'scheduled'" ) - - await check( - "a dialog on the agent's page stays automatic until the user takes it", - async () => { - await execute('browser_open_tab', { url: `${site}/agent` }) - const tabs = await shell.evaluate( - async (scope) => - (await (globalThis as Bridge).simDesktop.browserAgent.activateScope(scope)).tabs, - SCOPE - ) - const agentTabId = tabs.find((tab) => tab.url === `${site}/agent`)?.tabId - // The resource strip mirrors the agent's tab on screen without the user claiming it. - await panelAction({ action: 'switch-tab', tabId: agentTabId, claim: false }) - await confirmFromPage('/agent') - await expect.poll(() => titleAt('/agent')).toBe('confirm:false') - expect(await pageDialog()).toBeNull() - } - ) - - await check('a dialog while the browser is off screen stays automatic', async () => { - const tabs = await shell.evaluate( - async (scope) => - (await (globalThis as Bridge).simDesktop.browserAgent.activateScope(scope)).tabs, + const agentTabId = async () => { + const { tabs } = await shell.evaluate( + (scope) => (globalThis as DesktopBridge).simDesktop.browserAgent.activateScope(scope), SCOPE ) const tabId = tabs.find((tab) => tab.url === `${site}/agent`)?.tabId - expect(tabId).toBeTruthy() - await panelAction({ action: 'switch-tab', tabId }) - await shell.evaluate((scope) => { - const bridge = globalThis as Bridge - window.clearInterval(bridge.boundsTimer) - bridge.simDesktop.browserAgent.setPanelBounds(null, null, scope) - }, SCOPE) - await confirmFromPage('/agent') - await expect.poll(() => titleAt('/agent')).toBe('confirm:false') + expect(tabId, 'the agent tab is listed').toBeTruthy() + return tabId + } + + await test.step("a dialog on the agent's page stays automatic until the user takes it", async () => { + await execute('browser_open_tab', { url: `${site}/agent` }) + // The resource strip mirrors the agent's tab on screen without the user claiming it. + await act({ action: 'switch-tab', tabId: await agentTabId(), claim: false }) + await confirmFromPage(`${site}/agent`) + await expect.poll(() => titleAt(app, `${site}/agent`)).toBe('confirm:false') + expect(await pageDialog()).toBeNull() + }) + + await test.step('a dialog while the browser is off screen stays automatic', async () => { + await act({ action: 'switch-tab', tabId: await agentTabId() }) + await hideBrowserPanel(shell, SCOPE) + await inPage(app, `${site}/agent`, "document.title = 'agent'") + await confirmFromPage(`${site}/agent`) + await expect.poll(() => titleAt(app, `${site}/agent`)).toBe('confirm:false') expect(await pageDialog()).toBeNull() }) - passed = true } finally { - mkdirSync(dirname(reportPath), { recursive: true }) - writeFileSync(reportPath, JSON.stringify({ passed, checks }, null, 2)) - await app?.close() - await new Promise((resolve) => server.close(() => resolve())) - rmSync(userData, { recursive: true, force: true }) + await server.close() } }) diff --git a/apps/desktop/e2e/browser-page-parity.spec.ts b/apps/desktop/e2e/browser-page-parity.spec.ts index ec1c1256536..ec59c5f70d5 100644 --- a/apps/desktop/e2e/browser-page-parity.spec.ts +++ b/apps/desktop/e2e/browser-page-parity.spec.ts @@ -1,29 +1,25 @@ -import { mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs' -import { createServer, type ServerResponse } from 'node:http' -import { tmpdir } from 'node:os' +import { readdirSync, readFileSync } from 'node:fs' import { join } from 'node:path' -import { fileURLToPath } from 'node:url' +import type { ElectronApplication, Page } from '@playwright/test' +import type { BrowserPageDialog, BrowserPanelAction } from '@sim/browser-protocol' import { - type ElectronApplication, - _electron as electron, + attachBrowserPanel, + type DesktopBridge, expect, - type Page, + type FixtureServer, + focusFirstWindow, + serve, + ToolAuthorizer, test, -} from '@playwright/test' -import type { BrowserPageDialog, BrowserToolName } from '@sim/browser-protocol' -import type { SimDesktopApi } from '@sim/desktop-bridge' -import { getErrorMessage } from '@sim/utils/errors' -import { recordCheck } from './check-report' +} from './harness' /** * The embedded browser against what a user expects of Chrome: the page menu, * history and tab keys, Escape on a slow load, and a video's fullscreen * button. Each test drives the real shell and native tab views with trusted - * input, and lands in a JSON report at BROWSER_PAGE_PARITY_REPORT_PATH - * (test-results/browser-page-parity-report.json by default) as it finishes. + * input. */ -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) const SCOPE = 'browser-page-parity-e2e' const IS_MAC = process.platform === 'darwin' const SHELL_FIXTURE = 'Sim fixture

Browser parity fixture

' @@ -51,127 +47,79 @@ document.onfullscreenchange = () => { if (!document.fullscreenElement) document. `, } -type Bridge = typeof globalThis & { - simDesktop: SimDesktopApi - pageDialog?: BrowserPageDialog | null - boundsTimer?: number -} +type Bridge = DesktopBridge & { pageDialog?: BrowserPageDialog | null } /** What the suite installs in the main process. */ type MainFixture = typeof globalThis & { agentMenus?: (Electron.MenuItemConstructorOptions | Electron.MenuItem)[][] visibleView?: () => Electron.WebContentsView | undefined } -const reportPath = () => - process.env.BROWSER_PAGE_PARITY_REPORT_PATH ?? - join(test.info().project.outputDir, 'browser-page-parity-report.json') - -/** Runs one check and adds its outcome to the report as soon as it is known. */ -async function check(name: string, body: () => Promise): Promise { - const startedAt = Date.now() - const record = (status: 'passed' | 'failed', error?: unknown) => - recordCheck(reportPath(), 'browser-page-parity', { - name, - status, - durationMs: Date.now() - startedAt, - retry: test.info().retry, - ...(error === undefined ? {} : { error: getErrorMessage(error) }), - }) - try { - await body() - record('passed') - } catch (error) { - record('failed', error) - throw error - } -} - -/** A test whose outcome is also one check in the suite's report. */ -function checkedTest(name: string, body: () => Promise): void { - test(name, () => check(name, body)) -} - test.describe('browser page parity with Chrome', () => { - let app: ElectronApplication | undefined - let shell: Page + let server: FixtureServer let site = '' - let userData = '' + let app: ElectronApplication + let shell: Page let downloads = '' - /** Held responses for the slow page, released when the suite ends. */ - const held = new Set() /** The Referer each load of the link target arrived with. */ const referrers: (string | undefined)[] = [] /** The Referer each request for the image arrived with. */ const imageReferrers: (string | undefined)[] = [] - const calls = new Map() - const server = createServer(async (request, response) => { - const path = new URL(request.url ?? '/', 'http://localhost').pathname - if (path === '/api/desktop/tool/authorize') { - let body = '' - for await (const chunk of request) body += chunk.toString() - const authorization = calls.get(JSON.parse(body).toolCallId) - response.writeHead(authorization ? 200 : 403, { 'Content-Type': 'application/json' }) - response.end(JSON.stringify(authorization ?? {})) - return - } - if (path === '/pixel.png') { - imageReferrers.push(request.headers.referer) - // Hotlink-protected, like many image hosts: a request without the page as referrer fails. - if (!request.headers.referer) { - response.writeHead(403) - response.end() + const authorizer = new ToolAuthorizer('browser-parity') + + test.beforeAll(async () => { + server = await serve(async (request, response, url) => { + if (await authorizer.handle(request, response, url)) return + const path = url.pathname + if (path === '/pixel.png') { + imageReferrers.push(request.headers.referer) + // Hotlink-protected, like many image hosts: a request without the page as referrer fails. + if (!request.headers.referer) { + response.writeHead(403) + response.end() + return + } + response.writeHead(200, { 'Content-Type': 'image/png', 'Cache-Control': 'no-store' }) + response.end(PNG) return } - response.writeHead(200, { 'Content-Type': 'image/png', 'Cache-Control': 'no-store' }) - response.end(PNG) - return - } - if (path === '/landing') referrers.push(request.headers.referer) - if (path === '/slow') { - held.add(response) - return - } - // The app origin serves the shell; the same server on localhost is the web. - const isSite = request.headers.host?.startsWith('localhost') === true - response.writeHead(200, { - 'Content-Type': 'text/html', - ...(isSite ? {} : { 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; Path=/' }), + if (path === '/landing') referrers.push(request.headers.referer) + // Never answered; closing the server drops it. + if (path === '/slow') return + // The app origin serves the shell; the same server on localhost is the web. + const isSite = request.headers.host?.startsWith('localhost') === true + response.writeHead(200, { + 'Content-Type': 'text/html', + ...(isSite ? {} : { 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; Path=/' }), + }) + response.end( + isSite + ? (PAGES[path] ?? `${path.slice(1)}

${path}

`) + : SHELL_FIXTURE + ) }) - response.end( - isSite - ? (PAGES[path] ?? `${path.slice(1)}

${path}

`) - : SHELL_FIXTURE - ) + site = server.site }) - test.beforeAll(async () => { - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - const origin = `http://127.0.0.1:${address.port}` - site = origin.replace('127.0.0.1', 'localhost') - userData = mkdtempSync(join(tmpdir(), 'sim-browser-parity-e2e-')) - downloads = mkdtempSync(join(tmpdir(), 'sim-browser-parity-downloads-')) - app = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { ...process.env, SIM_DESKTOP_ORIGIN: origin, SIM_DESKTOP_USER_DATA: userData }, + test.afterAll(async () => { + await server?.close() + }) + + test.beforeEach(async ({ desktop }) => { + referrers.length = 0 + imageReferrers.length = 0 + downloads = desktop.tempDir('sim-browser-parity-downloads-') + const launched = await desktop.launch({ + origin: server.origin, + // The desktop's own handling decides a page's leave-site question, as in production. + leaveDialogsToDesktop: true, }) - // A dialog listener stops Playwright auto-dismissing a page's leave-site - // question, so the desktop's own handling decides it as in production. - const leaveDialogsToDesktop = (page: Page) => page.on('dialog', () => {}) - app.context().pages().forEach(leaveDialogsToDesktop) - app.context().on('page', leaveDialogsToDesktop) + app = launched.app shell = await app.firstWindow() await app.evaluate(({ app, BrowserWindow, Menu, WebContentsView }, downloads) => { // Downloads default to the OS folder; keep the suite's files out of the user's. app.setPath('downloads', downloads) - const host = BrowserWindow.getAllWindows()[0] - host.webContents.setBackgroundThrottling(false) - app.focus({ steal: true }) - host.focus() // A native menu blocks the main process while it is open; keep each page - // menu's items so a check can choose one the way a click would. + // menu's items so a test can choose one the way a click would. const capture = globalThis as MainFixture capture.visibleView = () => BrowserWindow.getAllWindows()[0].contentView.children.find( @@ -187,65 +135,38 @@ test.describe('browser page parity with Chrome', () => { return menu } }, downloads) + await focusFirstWindow(app) await expect(shell.getByRole('heading')).toHaveText('Browser parity fixture') - await shell.evaluate(async (scope) => { + await shell.evaluate(() => { const bridge = globalThis as Bridge - const api = bridge.simDesktop.browserAgent - await api.activateScope(scope) - api.onPageState((state) => { + bridge.simDesktop.browserAgent.onPageState((state) => { bridge.pageDialog = state.dialog ?? null }) - const updateBounds = () => - api.setPanelBounds( - { x: 0, y: 80, width: innerWidth, height: innerHeight - 80 }, - null, - scope - ) - updateBounds() - bridge.boundsTimer = window.setInterval(updateBounds, 200) - }, SCOPE) - await execute('browser_open_url', { url: `${site}/start` }) + }) + await attachBrowserPanel(shell, SCOPE) + await authorizer.execute(shell, SCOPE, 'browser_open_url', { url: `${site}/start` }) await panelAction({ action: 'switch-tab', tabId: '1' }) await panelAction({ action: 'enable-page-dialogs' }) }) - test.afterAll(async () => { - for (const response of held) response.destroy() - await app?.close() - server.closeAllConnections() - await new Promise((resolve) => server.close(() => resolve())) - rmSync(userData, { recursive: true, force: true }) - rmSync(downloads, { recursive: true, force: true }) - }) - - let callCount = 0 - async function execute(tool: BrowserToolName, args: Record) { - const callId = `browser-parity-${++callCount}` - calls.set(callId, { chatId: SCOPE, toolName: tool, args }) - const result = await shell.evaluate( - ({ callId, tool, args, scope }) => - (globalThis as Bridge).simDesktop.browserAgent.executeTool(callId, tool, args, scope), - { callId, tool, args, scope: SCOPE } - ) - expect(result.ok, result.error).toBe(true) - } - - /** Browser-chrome actions are user gestures, so each follows a real click in Sim. */ - async function panelAction(action: Record) { + /** + * Browser-chrome actions are user gestures, so each follows a real click in Sim. The action is a + * send; the invoke after it from the same renderer returns once main has handled it. + */ + async function panelAction(action: BrowserPanelAction) { await shell.getByRole('heading').click() await shell.evaluate( - ({ action, scope }) => - (globalThis as Bridge).simDesktop.browserAgent.panelAction( - action as unknown as Parameters[0], - scope - ), + async ({ action, scope }) => { + const api = (globalThis as Bridge).simDesktop.browserAgent + api.panelAction(action, scope) + await api.activateScope(scope) + }, { action, scope: SCOPE } ) } /** Reads one property of the page on screen from the main process. */ function visiblePage(read: string): Promise { - if (!app) throw new Error('App not launched') return app.evaluate(({ BrowserWindow }, read) => { const view = (globalThis as MainFixture).visibleView?.() if (!view) return null @@ -254,7 +175,7 @@ test.describe('browser page parity with Chrome', () => { url: contents.getURL(), title: contents.getTitle(), loading: contents.isLoadingMainFrame(), - zoom: contents.getZoomFactor(), + focused: contents.isFocused(), bounds: view.getBounds(), windowFullScreen: BrowserWindow.getAllWindows()[0].isFullScreen(), } @@ -266,6 +187,16 @@ test.describe('browser page parity with Chrome', () => { const pageTitle = () => visiblePage('title') const pageDialog = () => shell.evaluate(() => (globalThis as Bridge).pageDialog ?? null) + /** Gives the page on screen keyboard focus, as the user's click into it would. */ + async function focusPage(): Promise { + await app.evaluate(() => { + const view = (globalThis as MainFixture).visibleView?.() + if (!view) throw new Error('No visible page') + view.webContents.focus() + }) + await expect.poll(() => visiblePage('focused')).toBe(true) + } + /** Trusted input into the page on screen, the way the user's own mouse and keys arrive. */ async function inPage( action: @@ -274,7 +205,7 @@ test.describe('browser page parity with Chrome', () => { | { kind: 'key'; keyCode: string; modifiers?: string[] } | { kind: 'script'; script: string } ): Promise { - if (!app) throw new Error('App not launched') + if (action.kind === 'type' || action.kind === 'key') await focusPage() return app.evaluate(async (_electron, action) => { const view = (globalThis as MainFixture).visibleView?.() if (!view) throw new Error('No visible page') @@ -291,7 +222,6 @@ test.describe('browser page parity with Chrome', () => { keyCode: action.keyCode, modifiers: action.modifiers ?? [], } as Electron.KeyboardInputEvent - contents.focus() contents.sendInputEvent({ ...input, type: 'keyDown' }) contents.sendInputEvent({ ...input, type: 'keyUp' }) return null @@ -312,9 +242,7 @@ test.describe('browser page parity with Chrome', () => { /** Right-clicks `selector` and returns the page menu's item labels. */ async function openPageMenu(selector: string, offsetX?: number): Promise { - if (!app) throw new Error('App not launched') - const menus = () => - app?.evaluate(() => (globalThis as MainFixture).agentMenus?.length ?? 0) ?? 0 + const menus = () => app.evaluate(() => (globalThis as MainFixture).agentMenus?.length ?? 0) const before = await menus() await inPage({ kind: 'right-click', selector, offsetX }) await expect.poll(menus).toBeGreaterThan(before) @@ -327,7 +255,6 @@ test.describe('browser page parity with Chrome', () => { /** Chooses an item from the page menu opened last. */ async function choosePageMenuItem(label: string): Promise { - if (!app) throw new Error('App not launched') await app.evaluate((_electron, label) => { const item = (globalThis as MainFixture).agentMenus ?.at(-1) @@ -343,7 +270,7 @@ test.describe('browser page parity with Chrome', () => { await expect.poll(() => visiblePage('loading')).toBe(false) } - checkedTest("the page menu's Back asks before leaving unsaved changes", async () => { + test("the page menu's Back asks before leaving unsaved changes", async () => { await navigate('/next') await navigate('/form') await inPage({ kind: 'click', selector: '#draft' }) @@ -367,50 +294,45 @@ test.describe('browser page parity with Chrome', () => { await expect.poll(pageUrl).toBe(`${site}/next`) }) - checkedTest( - "the page menu's Save Image lands through the browser's downloads, with the page as referrer", - async () => { - for (const file of readdirSync(downloads)) rmSync(join(downloads, file), { force: true }) - await navigate('/image') - await expect - .poll(() => inPage({ kind: 'script', script: 'document.getElementById("pic").complete' })) - .toBe(true) - const labels = await openPageMenu('#pic') - expect(labels).toEqual( - expect.arrayContaining(['Open Image in New Tab', 'Copy Image', 'Copy Image Address']) - ) - imageReferrers.length = 0 - await choosePageMenuItem('Save Image') - await expect.poll(() => readdirSync(downloads)).toEqual(['pixel.png']) - expect(readFileSync(join(downloads, 'pixel.png')).equals(PNG)).toBe(true) - expect(imageReferrers).toEqual([`${site}/image`]) - } - ) + test("the page menu's Save Image lands through the browser's downloads, with the page as referrer", async () => { + await navigate('/image') + await expect + .poll(() => inPage({ kind: 'script', script: 'document.getElementById("pic").complete' })) + .toBe(true) + const labels = await openPageMenu('#pic') + expect(labels).toEqual( + expect.arrayContaining(['Open Image in New Tab', 'Copy Image', 'Copy Image Address']) + ) + imageReferrers.length = 0 + await choosePageMenuItem('Save Image') + await expect.poll(() => readdirSync(downloads)).toEqual(['pixel.png']) + expect(readFileSync(join(downloads, 'pixel.png')).equals(PNG)).toBe(true) + expect(imageReferrers).toEqual([`${site}/image`]) + }) - checkedTest("the page menu's Open Link in New Tab sends the page as referrer", async () => { - referrers.length = 0 + test("the page menu's Open Link in New Tab sends the page as referrer", async () => { await navigate('/links') await openPageMenu('#link') await choosePageMenuItem('Open Link in New Tab') await expect.poll(() => referrers).toEqual([`${site}/links`]) }) - checkedTest('tab keys, and history keys off macOS, typed in the page follow Chrome', async () => { + test('tab keys, and history keys off macOS, typed in the page follow Chrome', async () => { await navigate('/one') - await execute('browser_open_tab', { url: `${site}/two` }) - await execute('browser_open_tab', { url: `${site}/three` }) + await authorizer.execute(shell, SCOPE, 'browser_open_tab', { url: `${site}/two` }) + await authorizer.execute(shell, SCOPE, 'browser_open_tab', { url: `${site}/three` }) const tabs = await shell.evaluate( async (scope) => (await (globalThis as Bridge).simDesktop.browserAgent.activateScope(scope)).tabs, SCOPE ) - // Earlier checks may have left tabs open; the keys move to the neighbours in strip order. + // The keys move to the strip neighbours, in whatever order the strip placed the new tabs. const urls = tabs.map((tab) => tab.url) + expect([...urls].sort()).toEqual([`${site}/one`, `${site}/three`, `${site}/two`]) const index = urls.indexOf(`${site}/one`) const next = urls[(index + 1) % urls.length] const previous = urls[(index - 1 + urls.length) % urls.length] - expect(urls.length).toBeGreaterThan(2) - await panelAction({ action: 'switch-tab', tabId: tabs[index]?.tabId }) + await panelAction({ action: 'switch-tab', tabId: tabs[index].tabId }) await expect.poll(pageUrl).toBe(`${site}/one`) if (IS_MAC) { @@ -437,7 +359,7 @@ test.describe('browser page parity with Chrome', () => { } }) - checkedTest('Escape stops a page that is still loading', async () => { + test('Escape stops a page that is still loading', async () => { await navigate('/before-slow') await panelAction({ action: 'navigate', url: `${site}/slow` }) await expect.poll(() => visiblePage('loading')).toBe(true) @@ -445,7 +367,7 @@ test.describe('browser page parity with Chrome', () => { await expect.poll(() => visiblePage('loading'), { timeout: 3_000 }).toBe(false) }) - checkedTest("a page's fullscreen fills the browser panel and Escape leaves it", async () => { + test("a page's fullscreen fills the browser panel and Escape leaves it", async () => { await navigate('/fullscreen') const bounds = await visiblePage('bounds') await inPage({ kind: 'click', selector: '#go' }) diff --git a/apps/desktop/e2e/browser-page.ts b/apps/desktop/e2e/browser-page.ts new file mode 100644 index 00000000000..98dc2b65748 --- /dev/null +++ b/apps/desktop/e2e/browser-page.ts @@ -0,0 +1,157 @@ +/** + * Shared pieces for specs that drive a page in the desktop's native browser panel from a Sim shell + * fixture: the fixture server, the shell bring-up, browser-chrome actions, and reads and trusted + * input aimed at the page with an exact URL. + */ +import { join } from 'node:path' +import type { ElectronApplication, Page } from '@playwright/test' +import type { BrowserPanelAction } from '@sim/browser-protocol' +import { + attachBrowserPanel, + type DesktopBridge, + expect, + type FixtureHandler, + type FixtureServer, + focusFirstWindow, + SIM_DIR, + type SimFixtureBundle, + serve, + type ToolAuthorizer, +} from './harness' + +export const BROWSER_SESSION_COMPONENTS = join( + SIM_DIR, + 'app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session' +) + +interface ShellFixtureOptions { + heading: string + /** Where the native browser panel starts below the shell's own UI. */ + top: number +} + +/** + * Serves the shell on the app origin (with a session cookie) and hands requests to the `site` + * alias, which the browser panel treats as the web, to `site`. + */ +export function serveShellAndSite( + options: ShellFixtureOptions & { + bundle: SimFixtureBundle + authorizer: ToolAuthorizer + site: FixtureHandler + } +): Promise { + const html = `Sim fixture

${options.heading}

` + return serve(async (request, response, url) => { + if (url.pathname === '/fixture.js' || url.pathname === '/fixture.css') { + const js = url.pathname.endsWith('.js') + response.setHeader('Content-Type', js ? 'text/javascript' : 'text/css') + response.end(js ? options.bundle.js : options.bundle.css) + return + } + if (await options.authorizer.handle(request, response, url)) return + if (request.headers.host?.startsWith('localhost')) { + await options.site(request, response, url) + return + } + response.writeHead(200, { + 'Content-Type': 'text/html', + 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; Path=/', + }) + response.end(html) + }) +} + +/** Focuses the shell window, waits for its fixture UI, and puts the browser panel below it. */ +export async function openShell( + app: ElectronApplication, + scope: string, + options: ShellFixtureOptions +): Promise { + const shell = await app.firstWindow() + await focusFirstWindow(app) + await expect(shell.getByRole('heading')).toHaveText(options.heading) + await attachBrowserPanel(shell, scope, options.top) + return shell +} + +/** Browser-chrome actions are user gestures, so each follows a real click in Sim. */ +export async function panelAction( + shell: Page, + scope: string, + action: BrowserPanelAction +): Promise { + await shell.getByRole('heading').click() + await shell.evaluate( + async ({ action, scope }) => { + const api = (globalThis as DesktopBridge).simDesktop.browserAgent + api.panelAction(action, scope) + // panelAction is a send; this invoke from the same renderer returns after main handled it. + await api.activateScope(scope) + }, + { action, scope } + ) +} + +/** Runs a script in the page at exactly `url`; throws while no page is there, so polls retry. */ +export function inPage( + app: ElectronApplication, + url: string, + script: string, + { userGesture = false } = {} +): Promise { + return app.evaluate( + async ({ webContents }, { url, script, userGesture }) => { + const contents = webContents + .getAllWebContents() + .find((candidate) => !candidate.isDestroyed() && candidate.getURL() === url) + if (!contents) throw new Error(`No page at ${url}`) + return (await contents.executeJavaScript(script, userGesture)) as T + }, + { url, script, userGesture } + ) +} + +/** Read from the main process: a script cannot run in a page while its dialog is open. */ +export function titleAt(app: ElectronApplication, url: string): Promise { + return app.evaluate( + ({ webContents }, url) => + webContents + .getAllWebContents() + .find((candidate) => !candidate.isDestroyed() && candidate.getURL() === url) + ?.getTitle() ?? null, + url + ) +} + +export function focusedPageUrl(app: ElectronApplication): Promise { + return app.evaluate(({ webContents }) => webContents.getFocusedWebContents()?.getURL()) +} + +/** + * Trusted input into the page at `url`, the way the user's own mouse and keys arrive: a click on + * `selector`, then `text` typed. The events are queued, so callers wait for their effect. + */ +export function userInput( + app: ElectronApplication, + url: string, + selector: string, + text = '' +): Promise { + return app.evaluate( + async ({ webContents }, { url, selector, text }) => { + const contents = webContents + .getAllWebContents() + .find((candidate) => !candidate.isDestroyed() && candidate.getURL() === url) + if (!contents) throw new Error(`No page at ${url}`) + const rect: { x: number; y: number } = await contents.executeJavaScript( + `(() => { const { x, y } = document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect(); return { x, y } })()` + ) + const point = { x: Math.round(rect.x + 3), y: Math.round(rect.y + 3) } + contents.sendInputEvent({ type: 'mouseDown', ...point, button: 'left', clickCount: 1 }) + contents.sendInputEvent({ type: 'mouseUp', ...point, button: 'left', clickCount: 1 }) + for (const character of text) contents.sendInputEvent({ type: 'char', keyCode: character }) + }, + { url, selector, text } + ) +} diff --git a/apps/desktop/e2e/browser-sign-in-prompts.spec.ts b/apps/desktop/e2e/browser-sign-in-prompts.spec.ts index d52d13cd97d..6a077dd4ea1 100644 --- a/apps/desktop/e2e/browser-sign-in-prompts.spec.ts +++ b/apps/desktop/e2e/browser-sign-in-prompts.spec.ts @@ -1,82 +1,56 @@ -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { type ElectronApplication, _electron as electron, expect, test } from '@playwright/test' +import { join } from 'node:path' +import type { ElectronApplication, Page } from '@playwright/test' import type { BrowserAppLaunchNotice, BrowserPagePrompt, + BrowserPanelAction, BrowserToolName, } from '@sim/browser-protocol' -import type { SimDesktopApi } from '@sim/desktop-bridge' -import { getErrorMessage } from '@sim/utils/errors' import { sleep } from '@sim/utils/helpers' -import { build } from 'esbuild' -import postcss from 'postcss' -import loadPostcssConfig from 'postcss-load-config' +import { + BROWSER_SESSION_COMPONENTS, + focusedPageUrl, + inPage, + openShell, + panelAction, + serveShellAndSite, + titleAt, + userInput, +} from './browser-page' +import { + test as base, + bundleSimFixture, + type DesktopBridge, + expect, + type FixtureHandler, + SIM_DIR, + type SimFixtureBundle, + serve, + ToolAuthorizer, +} from './harness' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) const SCOPE = 'browser-sign-in-prompts-e2e' -const SIM_DIR = fileURLToPath(new URL('../../sim/', import.meta.url)) -const SHELL_FIXTURE = - 'Sim fixture

Browser sign-in fixture

' +const SHELL = { heading: 'Browser sign-in fixture', top: 120 } const CREDENTIALS = `Basic ${Buffer.from('alice:s3cret').toString('base64')}` /** Long enough for a refused request to have surfaced if it were going to. */ const QUIET_MS = 1_500 -type Bridge = typeof globalThis & { - simDesktop: SimDesktopApi +type FixtureGlobals = DesktopBridge & { pagePrompt?: BrowserPagePrompt | null launchNotice?: BrowserAppLaunchNotice | null - boundsTimer?: number } type MainGlobals = typeof globalThis & { openedExternal?: string[] } -/** - * A browser tab's sign-in challenges and links to other apps belong to the - * user: Sim shows the question for the tab that asked, only a click in Sim - * answers it, and nothing is asked of an older renderer that cannot show it. - * These checks drive the real shell, native tab views, and Sim's prompt UI. - */ -test('sign-in and app-launch prompts wait for the user on the page that asked', async () => { - test.setTimeout(180_000) - const reportPath = - process.env.DESKTOP_BROWSER_SIGNIN_REPORT_PATH ?? - test.info().outputPath('browser-sign-in-prompts.json') - const checks: { - name: string - status: 'passed' | 'failed' - durationMs: number - error?: string - }[] = [] - const check = async (name: string, run: () => Promise) => { - const started = Date.now() - try { - await test.step(name, run) - checks.push({ name, status: 'passed', durationMs: Date.now() - started }) - } catch (error) { - checks.push({ - name, - status: 'failed', - durationMs: Date.now() - started, - error: getErrorMessage(error), - }) - throw error - } - } - const browserComponents = join( - SIM_DIR, - 'app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session' - ) - const bundle = await build({ - stdin: { - contents: `import { createElement } from 'react'; +let fixtureBundle: Promise | undefined +function shellBundle(): Promise { + if (!fixtureBundle) { + fixtureBundle = bundleSimFixture({ + source: `import { createElement } from 'react'; import { createRoot } from 'react-dom/client'; import { useBrowserSessionStore as store } from ${JSON.stringify(join(SIM_DIR, 'stores/browser-session/store.ts'))}; -import { BrowserAppLaunchNoticeBar, BrowserPagePromptModal } from ${JSON.stringify(join(browserComponents, 'browser-page-prompt.tsx'))}; -import { useBrowserPanelOcclusion } from ${JSON.stringify(join(browserComponents, 'browser-panel-occlusion.ts'))}; +import { BrowserAppLaunchNoticeBar, BrowserPagePromptModal } from ${JSON.stringify(join(BROWSER_SESSION_COMPONENTS, 'browser-page-prompt.tsx'))}; +import { useBrowserPanelOcclusion } from ${JSON.stringify(join(BROWSER_SESSION_COMPONENTS, 'browser-panel-occlusion.ts'))}; const scope = ${JSON.stringify(SCOPE)}; const api = globalThis.simDesktop.browserAgent; api.onPageState(state => store.getState().setPageState(state)); @@ -93,409 +67,283 @@ function Fixture() { createElement(BrowserPagePromptModal, { prompt: page?.prompt, open: Boolean(page?.prompt), onRespond: respond })); } createRoot(document.getElementById('root')).render(createElement(Fixture));`, - resolveDir: SIM_DIR, - loader: 'tsx', - }, - bundle: true, - write: false, - outfile: test.info().outputPath('fixture.js'), - external: ['node:async_hooks'], - banner: { js: 'var process={env:{NODE_ENV:"development"},browser:true};' }, - format: 'iife', - platform: 'browser', - tsconfig: join(SIM_DIR, 'tsconfig.json'), - define: { 'process.env.NODE_ENV': '"development"' }, - }) - const config = await loadPostcssConfig({}, SIM_DIR) - const stylesheet = join(SIM_DIR, 'app/_styles/globals.css') - const css = await postcss(config.plugins).process(readFileSync(stylesheet, 'utf8'), { - from: stylesheet, - }) - const calls = new Map() - const challenges: string[] = [] - let otherPort = 0 - const handleSite = (request: IncomingMessage, response: ServerResponse, port: number) => { - const path = new URL(request.url ?? '/', 'http://localhost').pathname - if (path === '/basic') { - challenges.push(`${port}${path}`) - if (request.headers.authorization === CREDENTIALS) { - response.writeHead(200, { 'Content-Type': 'text/html' }) - response.end('secret') - return - } - response.writeHead(401, { - 'Content-Type': 'text/html', - 'WWW-Authenticate': 'Basic realm="Fixture realm"', - }) - response.end('denied') - return - } - response.writeHead(200, { 'Content-Type': 'text/html' }) - if (path === '/subresource') { - response.end( - `sub` - ) - return - } - if (path === '/links') { - response.end(`links + }) + } + return fixtureBundle +} + +/** Every link records trusted and agent clicks, so a test can tell a click landed. */ +const LINKS_FIXTURE = `links +

Join meeting

Diagnostics

Unhandled

-

Mail

-`) - return - } - if (path === '/auto') { - response.end( - `auto` - ) - return - } - response.end('next') - } - const server: Server = createServer(async (request, response) => { - const path = new URL(request.url ?? '/', 'http://localhost').pathname - if (path === '/fixture.js' || path === '/fixture.css') { - response.setHeader('Content-Type', path.endsWith('.js') ? 'text/javascript' : 'text/css') - response.end( - path.endsWith('.js') - ? bundle.outputFiles.find((file) => file.path.endsWith('.js'))?.text - : css.css - ) - return - } - if (path === '/api/desktop/tool/authorize') { - let body = '' - for await (const chunk of request) body += chunk.toString() - const authorization = calls.get(JSON.parse(body).toolCallId) - response.writeHead(authorization ? 200 : 403, { 'Content-Type': 'application/json' }) - response.end(JSON.stringify(authorization ?? {})) - return - } - // The app origin serves the shell; the same server on localhost is the web. - if (request.headers.host?.startsWith('localhost')) { - const address = server.address() - handleSite(request, response, typeof address === 'object' && address ? address.port : 0) - return - } - response.writeHead(200, { - 'Content-Type': 'text/html', - 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; Path=/', - }) - response.end(SHELL_FIXTURE) - }) - const otherSite: Server = createServer((request, response) => - handleSite(request, response, otherPort) - ) - const userData = mkdtempSync(join(tmpdir(), 'sim-browser-signin-e2e-')) - let app: ElectronApplication | undefined - let passed = false - try { - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - await new Promise((resolve) => otherSite.listen(0, '127.0.0.1', resolve)) - const address = server.address() - const otherAddress = otherSite.address() - if ( - !address || - typeof address === 'string' || - !otherAddress || - typeof otherAddress === 'string' - ) - throw new Error('Missing fixture address') - otherPort = otherAddress.port - const origin = `http://127.0.0.1:${address.port}` - const site = `http://localhost:${address.port}` - const crossSite = `http://localhost:${otherPort}` - const shellApp = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { ...process.env, SIM_DESKTOP_ORIGIN: origin, SIM_DESKTOP_USER_DATA: userData }, - }) - app = shellApp - // Launching real apps is out of scope: record what the shell would hand the OS, - // and register a fixture handler for the schemes the page links to. - await shellApp.evaluate(({ app, shell }) => { - const main = globalThis as MainGlobals - main.openedExternal = [] - shell.openExternal = async (url: string) => { - main.openedExternal?.push(url) +

Mail

` + +interface SignInBrowser { + app: ElectronApplication + shell: Page + /** The web, on the shell's own server. */ + site: string + /** A second web origin, for cross-origin challenges. */ + crossSite: string + /** `site/basic` or `cross-site/basic`, per challenge served. */ + challenges: string[] + act(action: BrowserPanelAction): Promise + startTool( + tool: BrowserToolName, + args: Record + ): Promise<{ ok: boolean; error?: string }> + execute(tool: BrowserToolName, args: Record): Promise + pagePrompt(): Promise + launchNotice(): Promise + openedExternal(): Promise + /** Navigates from the URL bar and waits for the page to finish loading with `title`. */ + navigate(url: string, title: string): Promise + /** A trusted click on a link, waited on until the page saw it. */ + clickLink(url: string, selector: string): Promise + /** Signs in through the visible sign-in prompt the way the user does. */ + signInAs(username: string, password: string): Promise + /** Nothing asks and nothing opens, after a click that landed. */ + expectQuiet(openedBefore: string[]): Promise +} + +/** + * A browser tab's sign-in challenges and links to other apps belong to the + * user: Sim shows the question for the tab that asked, only a click in Sim + * answers it, and nothing is asked of an older renderer that cannot show it. + * These checks drive the real shell, native tab views, and Sim's prompt UI. + */ +const test = base.extend<{ signIn: SignInBrowser }>({ + signIn: async ({ desktop }, use) => { + const challenges: string[] = [] + const siteHandler = + (label: string): FixtureHandler => + (request, response, url) => { + if (url.pathname === '/basic') { + challenges.push(`${label}/basic`) + if (request.headers.authorization === CREDENTIALS) { + response.writeHead(200, { 'Content-Type': 'text/html' }) + response.end('secret') + return + } + response.writeHead(401, { + 'Content-Type': 'text/html', + 'WWW-Authenticate': 'Basic realm="Fixture realm"', + }) + response.end('denied') + return + } + response.writeHead(200, { 'Content-Type': 'text/html' }) + if (url.pathname === '/subresource') { + response.end( + `sub` + ) + } else if (url.pathname === '/links') { + response.end(LINKS_FIXTURE) + } else if (url.pathname === '/auto') { + response.end( + `auto` + ) + } else { + response.end('next') + } } - app.getApplicationNameForProtocol = (url: string) => - /^(simfixture|ms-msdt|mailto):/i.test(url) ? 'Fixture Meetings' : '' - }) - const openedExternal = () => - shellApp.evaluate(() => [...((globalThis as MainGlobals).openedExternal ?? [])]) - const shell = await shellApp.firstWindow() - await shellApp.evaluate(({ app, BrowserWindow }) => { - const host = BrowserWindow.getAllWindows()[0] - if (!host) throw new Error('Missing host window') - app.focus({ steal: true }) - host.focus() + const crossSite = await serve(siteHandler('cross-site')) + const authorizer = new ToolAuthorizer('browser-signin') + const server = await serveShellAndSite({ + ...SHELL, + bundle: await shellBundle(), + authorizer, + site: siteHandler('site'), }) - await expect(shell.getByRole('heading')).toHaveText('Browser sign-in fixture') - await shell.evaluate(async (scope) => { - const bridge = globalThis as Bridge - const api = bridge.simDesktop.browserAgent - await api.activateScope(scope) - const updateBounds = () => - api.setPanelBounds( - { x: 0, y: 120, width: innerWidth, height: innerHeight - 120 }, - null, - scope + try { + const { app } = await desktop.launch({ origin: server.origin }) + // Launching real apps is out of scope: record what the shell would hand the OS, + // and register a fixture handler for the schemes the page links to. + await app.evaluate(({ app, shell }) => { + const main = globalThis as MainGlobals + main.openedExternal = [] + shell.openExternal = async (url: string) => { + main.openedExternal?.push(url) + } + app.getApplicationNameForProtocol = (url: string) => + /^(simfixture|ms-msdt|mailto):/i.test(url) ? 'Fixture Meetings' : '' + }) + const shell = await openShell(app, SCOPE, SHELL) + const site = server.site + const act = (action: BrowserPanelAction) => panelAction(shell, SCOPE, action) + const startTool = (tool: BrowserToolName, args: Record) => { + const callId = authorizer.issue(SCOPE, tool, args) + return shell.evaluate( + ({ callId, tool, args, scope }) => + (globalThis as DesktopBridge).simDesktop.browserAgent.executeTool( + callId, + tool, + args, + scope + ), + { callId, tool, args, scope: SCOPE } ) - updateBounds() - bridge.boundsTimer = window.setInterval(updateBounds, 200) - }, SCOPE) + } + const pagePrompt = () => + shell.evaluate(() => (globalThis as FixtureGlobals).pagePrompt ?? null) + const launchNotice = () => + shell.evaluate(() => (globalThis as FixtureGlobals).launchNotice ?? null) + const openedExternal = () => + app.evaluate(() => [...((globalThis as MainGlobals).openedExternal ?? [])]) - let callCount = 0 - const startTool = (tool: BrowserToolName, args: Record) => { - const callId = `browser-signin-${++callCount}` - calls.set(callId, { chatId: SCOPE, toolName: tool, args }) - return shell.evaluate( - ({ callId, tool, args, scope }) => - (globalThis as Bridge).simDesktop.browserAgent.executeTool(callId, tool, args, scope), - { callId, tool, args, scope: SCOPE } - ) - } - const execute = async (tool: BrowserToolName, args: Record) => { - const result = await startTool(tool, args) - expect(result.ok, result.error).toBe(true) - return result.result - } - /** Browser-chrome actions are user gestures, so each follows a real click in Sim. */ - const panelAction = async (action: Record) => { - await shell.getByRole('heading').click() - await shell.evaluate( - ({ action, scope }) => - (globalThis as Bridge).simDesktop.browserAgent.panelAction( - action as unknown as Parameters[0], - scope - ), - { action, scope: SCOPE } - ) - } - const pagePrompt = () => shell.evaluate(() => (globalThis as Bridge).pagePrompt ?? null) - const launchNotice = () => shell.evaluate(() => (globalThis as Bridge).launchNotice ?? null) - /** The page currently at `url`; `read` is `title` or a script evaluated in it. */ - const pageAt = (url: string, read: string) => - shellApp.evaluate( - async ({ webContents }, { url, read }) => { - const contents = webContents - .getAllWebContents() - .find((candidate) => !candidate.isDestroyed() && candidate.getURL() === url) - if (!contents) return null - if (read === 'title') return contents.getTitle() as T - return (await contents.executeJavaScript(read, true)) as T + await authorizer.execute(shell, SCOPE, 'browser_open_url', { url: `${site}/next` }) + await act({ action: 'switch-tab', tabId: '1' }) + await expect.poll(() => titleAt(app, `${site}/next`)).toBe('next') + + await use({ + app, + shell, + site, + crossSite: crossSite.site, + challenges, + act, + startTool, + execute: (tool, args) => authorizer.execute(shell, SCOPE, tool, args), + pagePrompt, + launchNotice, + openedExternal, + async navigate(url, title) { + await act({ action: 'navigate', url }) + await expect.poll(() => titleAt(app, url)).toBe(title) + await expect.poll(() => inPage(app, url, 'document.readyState')).toBe('complete') }, - { url, read } - ) - const titleAt = (url: string) => () => pageAt(url, 'title') - const navigate = async (url: string) => { - await panelAction({ action: 'navigate', url }) - await expect.poll(() => pageAt(url, 'title')).not.toBeNull() - } - /** Trusted input into the page, the way the user's own click arrives and focuses it. */ - const userClick = (url: string, selector: string) => - shellApp.evaluate( - async ({ webContents }, { url, selector }) => { - const contents = webContents - .getAllWebContents() - .find((candidate) => !candidate.isDestroyed() && candidate.getURL() === url) - if (!contents) throw new Error(`No page at ${url}`) - const rect: { x: number; y: number } = await contents.executeJavaScript( - `(() => { const { x, y } = document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect(); return { x, y } })()` - ) - const point = { x: Math.round(rect.x + 3), y: Math.round(rect.y + 3) } - contents.focus() - contents.sendInputEvent({ type: 'mouseDown', ...point, button: 'left', clickCount: 1 }) - contents.sendInputEvent({ type: 'mouseUp', ...point, button: 'left', clickCount: 1 }) + async clickLink(url, selector) { + const clicks = () => + inPage( + app, + url, + `Number(document.querySelector(${JSON.stringify(selector)}).dataset.clicks ?? 0)` + ) + const before = await clicks() + await userInput(app, url, selector) + await expect.poll(clicks).toBe(before + 1) }, - { url, selector } - ) - /** Types into the visible sign-in prompt the way the user does: the password field unlocks on focus. */ - const signInAs = async (username: string, password: string) => { - const dialog = shell.getByRole('dialog') - await expect(dialog).toHaveCount(1) - await expect(async () => { - await dialog.getByRole('textbox', { name: 'Username' }).fill(username) - await dialog.getByRole('textbox', { name: 'Password' }).click() - await shell.keyboard.press('ControlOrMeta+A') - await shell.keyboard.type(password) - await expect(dialog.getByRole('textbox', { name: 'Username' })).toHaveValue(username, { - timeout: 1_000, - }) - await expect(dialog.getByRole('textbox', { name: 'Password' })).toHaveValue(password, { - timeout: 1_000, - }) - }).toPass({ timeout: 10_000 }) - } - const expectQuiet = async (openedBefore: string[]) => { - await sleep(QUIET_MS) - expect(await pagePrompt()).toBeNull() - expect(await launchNotice()).toBeNull() - expect(await openedExternal()).toEqual(openedBefore) + async signInAs(username, password) { + const dialog = shell.getByRole('dialog') + await expect(dialog).toHaveCount(1) + const usernameField = dialog.getByRole('textbox', { name: 'Username' }) + const passwordField = dialog.getByRole('textbox', { name: 'Password' }) + // Kept from the original suite: the Username field can come back empty right after the + // prompt appears (seen in CI, cause not yet found), so the entry repeats until both hold. + await expect(async () => { + await usernameField.fill(username) + // The password field stays read-only until it takes focus, which keeps autofill out. + await passwordField.click() + await expect(passwordField).toBeEditable({ timeout: 1_000 }) + await passwordField.fill(password) + await expect(usernameField).toHaveValue(username, { timeout: 1_000 }) + await expect(passwordField).toHaveValue(password, { timeout: 1_000 }) + }).toPass({ timeout: 10_000 }) + }, + async expectQuiet(openedBefore) { + await sleep(QUIET_MS) + expect(await pagePrompt()).toBeNull() + expect(await launchNotice()).toBeNull() + expect(await openedExternal()).toEqual(openedBefore) + }, + }) + } finally { + await server.close() + await crossSite.close() } + }, +}) - await execute('browser_open_url', { url: `${site}/next` }) - await panelAction({ action: 'switch-tab', tabId: '1' }) - await expect.poll(titleAt(`${site}/next`)).toBe('next') - - await check('an older renderer leaves sign-in challenges and app links refused', async () => { - await panelAction({ action: 'enable-page-dialogs' }) - await navigate(`${site}/basic`) - await expect.poll(titleAt(`${site}/basic`)).toBe('denied') - expect(await pagePrompt()).toBeNull() - await navigate(`${site}/links`) - await expect.poll(titleAt(`${site}/links`)).toBe('links') - await userClick(`${site}/links`, '#app') - await expectQuiet([]) - }) - - await panelAction({ action: 'enable-page-dialogs', pagePrompts: true }) - - await check( - 'basic auth asks for the page, re-asks after a wrong password, then signs in', - async () => { - await panelAction({ action: 'navigate', url: `${site}/basic` }) - await expect.poll(pagePrompt).toMatchObject({ - kind: 'http-auth', - origin: site, - proxy: false, - insecure: true, - retry: false, - }) - await expect(shell.getByText('Your connection to this site is not private.')).toBeVisible() - await signInAs('alice', 'wrong') - await shell.getByRole('button', { name: 'Sign in', exact: true }).click() - await expect.poll(pagePrompt).toMatchObject({ kind: 'http-auth', retry: true }) - await expect(shell.getByText('Incorrect username or password.')).toBeVisible() - await signInAs('alice', 's3cret') - await shell.getByRole('button', { name: 'Sign in', exact: true }).click() - await expect.poll(titleAt(`${site}/basic`)).toBe('secret') - expect(await pagePrompt()).toBeNull() - } - ) - - await check('a cross-origin subresource challenge never asks', async () => { - const before = challenges.length - await navigate(`${site}/subresource`) - await expect.poll(titleAt(`${site}/subresource`)).toBe('img-failed') - expect(challenges.slice(before)).toContain(`${otherPort}/basic`) - expect(await pagePrompt()).toBeNull() - }) - - await check( - "the agent's sign-in challenge waits for the user instead of being answered", - async () => { - const navigation = startTool('browser_navigate', { url: `${crossSite}/basic` }) - await expect.poll(pagePrompt).toMatchObject({ kind: 'http-auth', origin: crossSite }) - await sleep(QUIET_MS) - expect(await pagePrompt()).toMatchObject({ kind: 'http-auth', retry: false }) - await signInAs('alice', 's3cret') - await shell.getByRole('button', { name: 'Sign in', exact: true }).click() - const result = await navigation - expect(result.ok, result.error).toBe(true) - await expect.poll(titleAt(`${crossSite}/basic`)).toBe('secret') - } - ) +test('sign-in challenges and passkeys wait for the user on the page that asked', async ({ + signIn, +}) => { + const { app, shell, site, crossSite } = signIn + const titleOf = (url: string) => () => titleAt(app, url) + const signInButton = shell.getByRole('button', { name: 'Sign in', exact: true }) - await check("the agent's clicks never open another app", async () => { - await navigate(`${site}/links`) - const opened = await openedExternal() - const snapshot = await execute('browser_snapshot', {}) - const ref = /link "Join meeting" \[ref=(\d+)\]/.exec( - String((snapshot as { outline?: string }).outline) - )?.[1] - expect(ref, 'snapshot lists the Join meeting link').toBeTruthy() - const result = await execute('browser_click', { elementId: Number(ref) }) - await expectQuiet(opened) - const notices = [ - ...((result as { notices?: string[] }).notices ?? []), - ...(((await execute('browser_snapshot', {})) as { notices?: string[] }).notices ?? []), - ] - expect(notices.join('\n')).toContain('never open from agent actions') - }) + await test.step('an older renderer leaves sign-in challenges refused', async () => { + await signIn.act({ action: 'enable-page-dialogs' }) + await signIn.navigate(`${site}/basic`, 'denied') + expect(await signIn.pagePrompt()).toBeNull() + }) - await check('a link to another app asks after a click and opens only on Open', async () => { - await userClick(`${site}/links`, '#app') - await expect.poll(pagePrompt).toMatchObject({ - kind: 'external-app', - origin: site, - appName: 'Fixture Meetings', - canAlwaysAllow: false, - }) - const open = shell.getByRole('button', { name: 'Open', exact: true }) - await expect(open).toBeVisible() - expect(await openedExternal()).toEqual([]) - await expect(open).toBeEnabled() - await open.click() - await expect.poll(openedExternal).toEqual(['simfixture://join?id=7']) - expect(await pagePrompt()).toBeNull() - }) + await signIn.act({ action: 'enable-page-dialogs', pagePrompts: true }) - await check('without a click, a page only offers to open the app', async () => { - await navigate(`${site}/auto`) - await expect.poll(launchNotice).toMatchObject({ appName: 'Fixture Meetings', origin: site }) - expect(await pagePrompt()).toBeNull() - expect(await openedExternal()).toEqual(['simfixture://join?id=7']) - await shell.getByRole('button', { name: 'Open', exact: true }).click() - await expect.poll(openedExternal).toEqual(['simfixture://join?id=7', 'simfixture://auto']) - await expect.poll(launchNotice).toBeNull() + await test.step('basic auth asks for the page, re-asks after a wrong password, then signs in', async () => { + await signIn.act({ action: 'navigate', url: `${site}/basic` }) + await expect.poll(signIn.pagePrompt).toMatchObject({ + kind: 'http-auth', + origin: site, + proxy: false, + insecure: true, + retry: false, }) + await expect(shell.getByText('Your connection to this site is not private.')).toBeVisible() + await signIn.signInAs('alice', 'wrong') + await signInButton.click() + await expect.poll(signIn.pagePrompt).toMatchObject({ kind: 'http-auth', retry: true }) + await expect(shell.getByText('Incorrect username or password.')).toBeVisible() + await signIn.signInAs('alice', 's3cret') + await signInButton.click() + await expect.poll(titleOf(`${site}/basic`)).toBe('secret') + expect(await signIn.pagePrompt()).toBeNull() + }) - await check('a page cannot keep asking to open apps', async () => { - await navigate(`${site}/links`) - await userClick(`${site}/links`, '#app') - await expectQuiet(['simfixture://join?id=7', 'simfixture://auto']) - }) + await test.step('a cross-origin subresource challenge never asks', async () => { + const before = signIn.challenges.length + await signIn.navigate(`${site}/subresource`, 'img-failed') + expect(signIn.challenges.slice(before)).toContain('cross-site/basic') + expect(await signIn.pagePrompt()).toBeNull() + }) - await check( - 'denied and unhandled schemes never open, mail links open after a click', - async () => { - await shell.evaluate( - (scope) => (globalThis as Bridge).simDesktop.browserAgent.openTab?.(scope), - SCOPE - ) - const opened = await openedExternal() - // A fresh document per link: one page's refused launch must not mask the next. - let links = '' - for (const [index, selector] of ['#denied', '#unhandled'].entries()) { - links = `${site}/links?tab=2&link=${index}` - await navigate(links) - await userClick(links, selector) - await expectQuiet(opened) - } - await userClick(links, '#mail') - await expect.poll(openedExternal).toEqual([...opened, 'mailto:a@example.com?subject=Hi']) - expect(await pagePrompt()).toBeNull() - } - ) + await test.step("the agent's sign-in challenge waits for the user instead of being answered", async () => { + const navigation = signIn.startTool('browser_navigate', { url: `${crossSite}/basic` }) + await expect.poll(signIn.pagePrompt).toMatchObject({ kind: 'http-auth', origin: crossSite }) + await sleep(QUIET_MS) + expect(await signIn.pagePrompt()).toMatchObject({ kind: 'http-auth', retry: false }) + await signIn.signInAs('alice', 's3cret') + await signInButton.click() + const result = await navigation + expect(result.ok, result.error).toBe(true) + await expect.poll(titleOf(`${crossSite}/basic`)).toBe('secret') + }) - await check('a passkey sign-in lets the user choose the account', async () => { - const passkeyPage = `${site}/next?passkey` - await navigate(passkeyPage) - await shellApp.evaluate(async ({ webContents }) => { - const contents = webContents - .getAllWebContents() - .find((candidate) => candidate.getURL().includes('/next?passkey')) - if (!contents) throw new Error('No passkey page') - if (!contents.debugger.isAttached()) contents.debugger.attach('1.3') - await contents.debugger.sendCommand('WebAuthn.enable', { enableUI: false }) - await contents.debugger.sendCommand('WebAuthn.addVirtualAuthenticator', { - options: { - protocol: 'ctap2', - transport: 'internal', - hasResidentKey: true, - hasUserVerification: true, - isUserVerified: true, - automaticPresenceSimulation: true, - }, - }) + await test.step('a passkey sign-in lets the user choose the account', async () => { + const passkeyPage = `${site}/next?passkey` + await signIn.navigate(passkeyPage, 'next') + // WebAuthn only answers a focused document, and the user's click is what focuses it. + await userInput(app, passkeyPage, 'html') + await expect.poll(() => focusedPageUrl(app)).toBe(passkeyPage) + await app.evaluate(async ({ webContents }, url) => { + const contents = webContents.getAllWebContents().find((c) => c.getURL() === url) + if (!contents) throw new Error(`No page at ${url}`) + if (!contents.debugger.isAttached()) contents.debugger.attach('1.3') + await contents.debugger.sendCommand('WebAuthn.enable', { enableUI: false }) + await contents.debugger.sendCommand('WebAuthn.addVirtualAuthenticator', { + options: { + protocol: 'ctap2', + transport: 'internal', + hasResidentKey: true, + hasUserVerification: true, + isUserVerified: true, + automaticPresenceSimulation: true, + }, }) - const created = await pageAt( - passkeyPage, - `(async () => { + }, passkeyPage) + const askForPasskey = `globalThis.passkeyOutcome = 'pending' + navigator.credentials.get({ publicKey: { + challenge: new Uint8Array(16), rpId: 'localhost', userVerification: 'preferred', + } }).then((credential) => new TextDecoder().decode(credential.response.userHandle), + (error) => 'error:' + error.name).then((outcome) => { globalThis.passkeyOutcome = outcome })` + const created = await inPage( + app, + passkeyPage, + `(async () => { const make = (id, name) => navigator.credentials.create({ publicKey: { challenge: new Uint8Array(16), rp: { id: 'localhost', name: 'Fixture' }, user: { id: new TextEncoder().encode(id), name, displayName: name }, @@ -504,57 +352,128 @@ createRoot(document.getElementById('root')).render(createElement(Fixture));`, } }) await make('user-ada', 'ada@example.com') await make('user-grace', 'grace@example.com') - globalThis.passkeyOutcome = 'pending' - navigator.credentials.get({ publicKey: { - challenge: new Uint8Array(16), rpId: 'localhost', userVerification: 'preferred', - } }).then((credential) => new TextDecoder().decode(credential.response.userHandle), - (error) => 'error:' + error.name).then((outcome) => { globalThis.passkeyOutcome = outcome }) + ${askForPasskey} return 'created' - })()` - ) - expect(created).toBe('created') - await expect.poll(pagePrompt).toMatchObject({ - kind: 'passkey-account', - relyingPartyId: 'localhost', - }) - const prompt = await pagePrompt() - expect( - prompt?.kind === 'passkey-account' && prompt.accounts.map((account) => account.name).sort() - ).toEqual(['ada@example.com', 'grace@example.com']) - // A stray Enter must never send an identity: nothing is preselected and Enter does not - // continue. It dismisses when the prompt has keyboard focus and is ignored when it does - // not (as on a CI runner without window focus); either way, refuse and ask again. - const passkeyOutcome = () => pageAt(passkeyPage, 'globalThis.passkeyOutcome') - await shell.keyboard.press('Enter') - await sleep(QUIET_MS) - expect(['pending', 'error:NotAllowedError']).toContain(await passkeyOutcome()) - if ((await passkeyOutcome()) === 'pending') { - await shell.getByRole('button', { name: 'Cancel', exact: true }).click() - } - await expect.poll(passkeyOutcome).toBe('error:NotAllowedError') - await pageAt( - passkeyPage, - `globalThis.passkeyOutcome = 'pending' - navigator.credentials.get({ publicKey: { - challenge: new Uint8Array(16), rpId: 'localhost', userVerification: 'preferred', - } }).then((credential) => new TextDecoder().decode(credential.response.userHandle), - (error) => 'error:' + error.name).then((outcome) => { globalThis.passkeyOutcome = outcome }); 'asked'` - ) - await expect.poll(pagePrompt).toMatchObject({ kind: 'passkey-account' }) - const dialog = shell.getByRole('dialog') - await dialog.getByRole('button').filter({ hasText: 'Choose an account' }).click() - await shell.getByRole('menuitemradio', { name: 'grace@example.com' }).click() - await shell.getByRole('button', { name: 'Continue', exact: true }).click() - await expect.poll(passkeyOutcome).toBe('user-grace') - expect(await pagePrompt()).toBeNull() + })()`, + { userGesture: true } + ) + expect(created).toBe('created') + await expect.poll(signIn.pagePrompt).toMatchObject({ + kind: 'passkey-account', + relyingPartyId: 'localhost', }) - passed = true - } finally { - mkdirSync(dirname(reportPath), { recursive: true }) - writeFileSync(reportPath, JSON.stringify({ passed, checks }, null, 2)) - await app?.close() - await new Promise((resolve) => server.close(() => resolve())) - await new Promise((resolve) => otherSite.close(() => resolve())) - rmSync(userData, { recursive: true, force: true }) - } + const prompt = await signIn.pagePrompt() + expect( + prompt?.kind === 'passkey-account' && prompt.accounts.map((account) => account.name).sort() + ).toEqual(['ada@example.com', 'grace@example.com']) + + // A stray Enter in the prompt must never send an identity: nothing is preselected and + // Enter does not continue. + const passkeyOutcome = () => inPage(app, passkeyPage, 'globalThis.passkeyOutcome') + const dialog = shell.getByRole('dialog') + await dialog.focus() + await expect(dialog).toBeFocused() + await shell.keyboard.press('Enter') + await sleep(QUIET_MS) + expect(await passkeyOutcome()).toBe('pending') + expect(await signIn.pagePrompt()).toMatchObject({ kind: 'passkey-account' }) + await shell.getByRole('button', { name: 'Cancel', exact: true }).click() + await expect.poll(passkeyOutcome).toBe('error:NotAllowedError') + + await inPage(app, passkeyPage, `${askForPasskey}; 'asked'`, { userGesture: true }) + await expect.poll(signIn.pagePrompt).toMatchObject({ kind: 'passkey-account' }) + await dialog.getByRole('button').filter({ hasText: 'Choose an account' }).click() + await shell.getByRole('menuitemradio', { name: 'grace@example.com' }).click() + await shell.getByRole('button', { name: 'Continue', exact: true }).click() + await expect.poll(passkeyOutcome).toBe('user-grace') + expect(await signIn.pagePrompt()).toBeNull() + }) +}) + +test("links to other apps open only after the user's click and their answer", async ({ + signIn, +}) => { + const { shell, site } = signIn + const links = `${site}/links` + const open = shell.getByRole('button', { name: 'Open', exact: true }) + + await test.step('an older renderer leaves app links refused', async () => { + await signIn.act({ action: 'enable-page-dialogs' }) + await signIn.navigate(links, 'links') + await signIn.clickLink(links, '#app') + await signIn.expectQuiet([]) + }) + + await signIn.act({ action: 'enable-page-dialogs', pagePrompts: true }) + + await test.step("the agent's clicks never open another app", async () => { + await signIn.navigate(links, 'links') + const snapshot = await signIn.execute('browser_snapshot', {}) + const ref = /link "Join meeting" \[ref=(\d+)\]/.exec( + String((snapshot as { outline?: string }).outline) + )?.[1] + expect(ref, 'snapshot lists the Join meeting link').toBeTruthy() + const result = await signIn.execute('browser_click', { elementId: Number(ref) }) + await signIn.expectQuiet([]) + const notices = [ + ...((result as { notices?: string[] }).notices ?? []), + ...(((await signIn.execute('browser_snapshot', {})) as { notices?: string[] }).notices ?? []), + ] + expect(notices.join('\n')).toContain('never open from agent actions') + }) + + await test.step('a link to another app asks after a click and opens only on Open', async () => { + await signIn.clickLink(links, '#app') + await expect.poll(signIn.pagePrompt).toMatchObject({ + kind: 'external-app', + origin: site, + appName: 'Fixture Meetings', + canAlwaysAllow: false, + }) + await expect(open).toBeVisible() + expect(await signIn.openedExternal()).toEqual([]) + await expect(open).toBeEnabled() + await open.click() + await expect.poll(signIn.openedExternal).toEqual(['simfixture://join?id=7']) + expect(await signIn.pagePrompt()).toBeNull() + }) + + await test.step('without a click, a page only offers to open the app', async () => { + await signIn.navigate(`${site}/auto`, 'auto') + await expect + .poll(signIn.launchNotice) + .toMatchObject({ appName: 'Fixture Meetings', origin: site }) + expect(await signIn.pagePrompt()).toBeNull() + expect(await signIn.openedExternal()).toEqual(['simfixture://join?id=7']) + await open.click() + await expect + .poll(signIn.openedExternal) + .toEqual(['simfixture://join?id=7', 'simfixture://auto']) + await expect.poll(signIn.launchNotice).toBeNull() + }) + + await test.step('a page cannot keep asking to open apps', async () => { + await signIn.navigate(links, 'links') + await signIn.clickLink(links, '#app') + await signIn.expectQuiet(['simfixture://join?id=7', 'simfixture://auto']) + }) + + await test.step('denied and unhandled schemes never open, mail links open after a click', async () => { + await shell.evaluate( + (scope) => (globalThis as DesktopBridge).simDesktop.browserAgent.openTab?.(scope), + SCOPE + ) + const opened = await signIn.openedExternal() + // A fresh document per link: one page's refused launch must not mask the next. + let page = '' + for (const [index, selector] of ['#denied', '#unhandled'].entries()) { + page = `${site}/links?tab=2&link=${index}` + await signIn.navigate(page, 'links') + await signIn.clickLink(page, selector) + await signIn.expectQuiet(opened) + } + await signIn.clickLink(page, '#mail') + await expect.poll(signIn.openedExternal).toEqual([...opened, 'mailto:a@example.com?subject=Hi']) + expect(await signIn.pagePrompt()).toBeNull() + }) }) diff --git a/apps/desktop/e2e/browser-tools.spec.ts b/apps/desktop/e2e/browser-tools.spec.ts index bf3d323751f..5df89210c67 100644 --- a/apps/desktop/e2e/browser-tools.spec.ts +++ b/apps/desktop/e2e/browser-tools.spec.ts @@ -1,20 +1,24 @@ -import { mkdtempSync } from 'node:fs' -import { createServer, type IncomingMessage, type Server } from 'node:http' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { fileURLToPath } from 'node:url' +import type { ElectronApplication, Page } from '@playwright/test' +import type { BrowserTabsState, BrowserToolName, BrowserToolResponse } from '@sim/browser-protocol' +import { refFor } from './executor-sim' import { - type ElectronApplication, - _electron as electron, + attachBrowserPanel, + test as base, + type DesktopBridge, expect, - type Page, - test, -} from '@playwright/test' -import type { BrowserToolName } from '@sim/browser-protocol' -import type { SimDesktopApi } from '@sim/desktop-bridge' + focusFirstWindow, + serve, + ToolAuthorizer, +} from './harness' + +/** + * Browser tools against the real desktop, one app per test. Sharing an app would need a scope per + * test that can be disposed afterwards, and only provisional scopes can be, while tool calls are + * authorized only for real chat ids. + */ -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) const SCOPE = 'browser-tools-e2e' + const FORM = `Form fixture @@ -53,7 +57,6 @@ const CLICK_FIXTURE = `Click fixture ` const CAPABILITIES_FIXTURE = `Capabilities fixture -
Report row
Drop a receipt
@@ -83,12 +86,6 @@ const popupsFixture = ( }); ` -async function readBody(request: IncomingMessage): Promise { - let body = '' - for await (const chunk of request) body += chunk.toString() - return body -} - const echoPage = (method: string | undefined, body: string) => `${method} ${body}` @@ -120,385 +117,498 @@ const UPLOAD_TARGET_FIXTURE = `Upload target fixture</titl } </script>` -test.describe('browser tools', () => { - const calls = new Map< - string, - { chatId: string; toolName: BrowserToolName | 'terminal'; args: Record<string, unknown> } - >() - const claimed = new Map<string, { args: Record<string, unknown> }>() - let server: Server - let popupServer: Server - let origin: string - let site: string - let popupOrigin: string - let app: ElectronApplication - let window: Page - let callCount = 0 - let beforeUploadResponse: (() => Promise<void>) | undefined - const appEchoes: string[] = [] - - test.beforeAll(async () => { - server = createServer(async (request, response) => { - const path = new URL(request.url ?? '/', 'http://127.0.0.1').pathname - if (path === '/redirect') { - response.writeHead(302, { Location: `${origin.replace('127.0.0.1', 'localhost')}/landing` }) - response.end() - return - } - if (path === '/enter-sim') { - response.writeHead(302, { Location: `${origin}/private-chat` }) - response.end() - return - } - if (path === '/api/auth/get-session') { - response.writeHead(200, { 'Content-Type': 'application/json' }) - response.end( - JSON.stringify( - request.headers.cookie?.includes('better-auth.session_token=fixture') - ? { user: { id: 'browser-auth-fixture' }, session: { id: 'fixture-session' } } - : null - ) - ) - return +const UPLOADED = { + original: [{ name: 'receipt.txt', text: 'receipt-bytes' }], + decoy: [], + currentCount: 1, +} +const NOT_UPLOADED = { original: [], decoy: [], currentCount: 0 } + +const PDF = + '%PDF-1.4\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >> endobj\ntrailer << /Root 1 0 R >>\n%%EOF\n' + +const PRIVATE_CHAT = + '<!doctype html><title>Private deployed chat

Authenticated deployed chat

' +const PRIVATE_PREVIEW = `Private HTML preview

Authenticated HTML preview

` + +const SESSION_COOKIE = 'better-auth.session_token=fixture' + +/** The fixture servers every test in the file shares. */ +interface ToolsSite { + origin: string + /** The app server as localhost: outside the app origin, so it browses in the agent partition. */ + site: string + popupOrigin: string + authorizer: ToolAuthorizer + /** Requests that reached the app origin's `/echo`. */ + appEchoes: string[] + /** Runs once before the next upload file is served, to change the page mid-staging. */ + beforeUploadResponse: (() => Promise) | undefined +} + +interface Shell { + app: ElectronApplication + shell: Page +} + +interface BrowserTools extends Shell { + scope: string + /** Runs a tool and returns its outcome, failed or not. */ + call(tool: BrowserToolName, args?: Record): Promise + /** Runs a tool and returns its result, failing the test on a tool error. */ + run(tool: BrowserToolName, args?: Record): Promise + /** Opens `url` and returns its snapshot outline. */ + open(url: string): Promise + tabs(): Promise + /** + * Runs script with a user gesture in the page at `url` (or its query-string variants) once it + * finished loading. Throws when no page has that URL. + */ + inPage(url: string, code: string): Promise + /** `inPage` for polling: undefined while no page has that URL. */ + pollPage(url: string, code: string): Promise +} + +async function openShell(app: ElectronApplication): Promise { + const shell = await app.firstWindow() + await focusFirstWindow(app) + await expect(shell.getByRole('heading')).toHaveText('Browser tools fixture') + return shell +} + +function browserTools( + { app, shell }: Shell, + scope: string, + authorizer: ToolAuthorizer +): BrowserTools { + const call = (tool: BrowserToolName, args: Record = {}) => { + const callId = authorizer.issue(scope, tool, args) + return shell.evaluate( + ({ callId, tool, args, scope }) => + (globalThis as DesktopBridge).simDesktop.browserAgent.executeTool( + callId, + tool, + args, + scope + ), + { callId, tool, args, scope } + ) + } + const run = (tool: BrowserToolName, args: Record = {}) => + authorizer.execute(shell, scope, tool, args) + const pageScript = (url: string, code: string, required: boolean) => + app.evaluate( + async ({ webContents }, { url, code, required }) => { + const contents = webContents + .getAllWebContents() + .find((page) => page.getURL() === url || page.getURL().startsWith(`${url}?`)) + if (!contents) { + if (required) throw new Error(`No page at ${url}`) + return undefined + } + if (contents.isLoading()) { + await new Promise((resolve) => contents.once('did-stop-loading', () => resolve())) + } + return contents.executeJavaScript(code, true) + }, + { url, code, required } + ) + return { + app, + shell, + scope, + call, + run, + async open(url) { + const result = (await run('browser_open_url', { url })) as { snapshot: { outline: string } } + return result.snapshot.outline + }, + tabs: () => + shell.evaluate( + (scope) => (globalThis as DesktopBridge).simDesktop.browserAgent.activateScope(scope), + scope + ), + inPage: (url, code) => pageScript(url, code, true), + pollPage: (url, code) => pageScript(url, code, false), + } +} + +const test = base.extend<{ tools: BrowserTools }, { toolsSite: ToolsSite }>({ + toolsSite: [ + // biome-ignore lint/correctness/noEmptyPattern: Playwright reads a fixture's dependencies from this destructuring, and this one has none. + async ({}, use) => { + const fixture: ToolsSite = { + origin: '', + site: '', + popupOrigin: '', + authorizer: new ToolAuthorizer('browser-fixture'), + appEchoes: [], + beforeUploadResponse: undefined, } - if (path === '/api/auth/sign-out') { - response.writeHead(200, { - 'Content-Type': 'application/json', - 'Set-Cookie': 'better-auth.session_token=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0', - }) - response.end('{}') - return + const readBody = async (request: AsyncIterable) => { + let body = '' + for await (const chunk of request) body += chunk.toString() + return body } - if (path === '/private-chat' || path === '/private-preview') { - if (!request.headers.cookie?.includes('better-auth.session_token=fixture')) { - response.writeHead(302, { Location: '/login' }) - response.end() - return + const appServer = await serve(async (request, response, url) => { + if (await fixture.authorizer.handle(request, response, url)) return + const path = url.pathname + const signedIn = request.headers.cookie?.includes(SESSION_COOKIE) === true + const reply = ( + status: number, + headers: Record, + body: string | Buffer = '' + ) => { + response.writeHead(status, headers) + response.end(body) } - response.writeHead(200, { 'Content-Type': 'text/html' }) - response.end( - path === '/private-chat' - ? 'Private deployed chat

Authenticated deployed chat

' - : `Private HTML preview

Authenticated HTML preview

` - ) - return - } - if (path === '/api/desktop/tool/file') { - const body = await readBody(request) - const { toolCallId, index } = JSON.parse(body) - const reference = claimed.get(toolCallId)?.args.paths - const found = Array.isArray(reference) && reference[index] === 'files/receipt.txt' - const beforeResponse = beforeUploadResponse - beforeUploadResponse = undefined - try { - await beforeResponse?.() - } catch (error) { - response.writeHead(500, { 'Content-Type': 'text/plain' }) - response.end(String(error)) - return + switch (path) { + case '/redirect': + return reply(302, { Location: `${fixture.site}/landing` }) + case '/enter-sim': + return reply(302, { Location: `${fixture.origin}/private-chat` }) + case '/api/auth/get-session': + return reply( + 200, + { 'Content-Type': 'application/json' }, + JSON.stringify( + signedIn + ? { user: { id: 'browser-auth-fixture' }, session: { id: 'fixture-session' } } + : null + ) + ) + case '/api/auth/sign-out': + return reply( + 200, + { + 'Content-Type': 'application/json', + 'Set-Cookie': + 'better-auth.session_token=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0', + }, + '{}' + ) + case '/private-chat': + case '/private-preview': + if (!signedIn) return reply(302, { Location: '/login' }) + return reply( + 200, + { 'Content-Type': 'text/html' }, + path === '/private-chat' ? PRIVATE_CHAT : PRIVATE_PREVIEW + ) + case '/api/desktop/tool/file': { + const { toolCallId, index } = JSON.parse(await readBody(request)) + const args = fixture.authorizer.calls.get(toolCallId)?.args as + | { paths?: unknown } + | undefined + const found = Array.isArray(args?.paths) && args.paths[index] === 'files/receipt.txt' + const beforeResponse = fixture.beforeUploadResponse + fixture.beforeUploadResponse = undefined + try { + await beforeResponse?.() + } catch (error) { + return reply(500, { 'Content-Type': 'text/plain' }, String(error)) + } + return found + ? reply( + 200, + { + 'Content-Type': 'application/octet-stream', + 'Content-Disposition': 'attachment; filename="receipt.txt"', + }, + 'receipt-bytes' + ) + : reply( + 404, + { 'Content-Type': 'application/json' }, + JSON.stringify({ error: 'File not found' }) + ) + } + case '/upload-target': + return reply(200, { 'Content-Type': 'text/html' }, UPLOAD_TARGET_FIXTURE) + case '/upload-host': { + const frameOrigin = + url.searchParams.get('kind') === 'oopif' ? fixture.origin : fixture.site + return reply( + 200, + { 'Content-Type': 'text/html' }, + `Upload frame fixture` + ) + } + case '/doc.pdf': + return reply(200, { 'Content-Type': 'application/pdf' }, PDF) + case '/echo': { + const body = await readBody(request) + fixture.appEchoes.push(`${request.method} ${body}`) + return reply(200, { 'Content-Type': 'text/html' }, echoPage(request.method, body)) + } + case '/authorize': + return reply(200, { 'Content-Type': 'text/html' }, POPUP_FIXTURE) + case '/popups': + return reply( + 200, + { 'Content-Type': 'text/html' }, + popupsFixture(fixture.origin, fixture.popupOrigin) + ) } - response.writeHead(found ? 200 : 404, { - 'Content-Type': found ? 'application/octet-stream' : 'application/json', - ...(found ? { 'Content-Disposition': 'attachment; filename="receipt.txt"' } : {}), - }) - response.end(found ? 'receipt-bytes' : JSON.stringify({ error: 'File not found' })) - return - } - if (path === '/upload-target' || path === '/upload-host') { - const params = new URL(request.url ?? '/', 'http://127.0.0.1').searchParams - const frameOrigin = params.get('kind') === 'oopif' ? origin : site - response.writeHead(200, { 'Content-Type': 'text/html' }) - response.end( - path === '/upload-target' - ? UPLOAD_TARGET_FIXTURE - : `Upload frame fixture` + const page = + path === '/click' + ? CLICK_FIXTURE + : path === '/capabilities' + ? CAPABILITIES_FIXTURE + : path === '/form' + ? FORM + : 'Sim fixture

Browser tools fixture

' + reply( + 200, + { + 'Content-Type': 'text/html', + ...(path === '/workspace' || path === '/home' || path === '/' + ? { 'Set-Cookie': `${SESSION_COOKIE}; HttpOnly; SameSite=Lax; Path=/` } + : {}), + }, + page ) - return - } - if (path === '/doc.pdf') { - response.writeHead(200, { 'Content-Type': 'application/pdf' }) + }) + const popupServer = await serve(async (request, response, url) => { + response.writeHead(200, { 'Content-Type': 'text/html' }) response.end( - '%PDF-1.4\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >> endobj\ntrailer << /Root 1 0 R >>\n%%EOF\n' + url.pathname === '/echo' + ? echoPage(request.method, await readBody(request)) + : POPUP_FIXTURE ) - return - } - if (path === '/echo') { - const body = await readBody(request) - appEchoes.push(`${request.method} ${body}`) - response.writeHead(200, { 'Content-Type': 'text/html' }) - response.end(echoPage(request.method, body)) - return - } - if (path === '/authorize') { - response.writeHead(200, { 'Content-Type': 'text/html' }) - response.end(POPUP_FIXTURE) - return - } - if (path === '/popups') { - response.writeHead(200, { 'Content-Type': 'text/html' }) - response.end(popupsFixture(origin, popupOrigin)) - return - } - if (path === '/api/desktop/tool/authorize') { - const body = await readBody(request) - const authorization = calls.get(JSON.parse(body).toolCallId) - calls.delete(JSON.parse(body).toolCallId) - if (authorization) claimed.set(JSON.parse(body).toolCallId, authorization) - response.writeHead(authorization ? 200 : 403, { 'Content-Type': 'application/json' }) - response.end(JSON.stringify(authorization ?? {})) - return - } - response.writeHead(200, { - 'Content-Type': 'text/html', - ...(path === '/workspace' || path === '/home' || path === '/' - ? { 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; SameSite=Lax; Path=/' } - : {}), }) - response.end( - path === '/click' - ? CLICK_FIXTURE - : path === '/capabilities' - ? CAPABILITIES_FIXTURE - : path === '/form' - ? FORM - : 'Sim fixture

Browser tools fixture

' - ) - }) - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - origin = `http://127.0.0.1:${address.port}` - /** Pages outside the app origin browse in the agent partition, like any third-party site. */ - site = origin.replace('127.0.0.1', 'localhost') - popupServer = createServer(async (request, response) => { - response.writeHead(200, { 'Content-Type': 'text/html' }) - response.end( - request.url === '/echo' ? echoPage(request.method, await readBody(request)) : POPUP_FIXTURE - ) + fixture.origin = appServer.origin + fixture.site = appServer.site + fixture.popupOrigin = popupServer.site + await use(fixture) + await appServer.close() + await popupServer.close() + }, + { scope: 'worker' }, + ], + + tools: async ({ toolsSite, desktop }, use) => { + const { app } = await desktop.launch({ + origin: toolsSite.origin, + leaveDialogsToDesktop: true, }) - await new Promise((resolve) => popupServer.listen(0, '127.0.0.1', resolve)) - const popupAddress = popupServer.address() - if (!popupAddress || typeof popupAddress === 'string') throw new Error('Missing popup address') - popupOrigin = `http://localhost:${popupAddress.port}` - }) + const shell = await openShell(app) + await attachBrowserPanel(shell, SCOPE) + await use(browserTools({ app, shell }, SCOPE, toolsSite.authorizer)) + toolsSite.appEchoes.length = 0 + toolsSite.beforeUploadResponse = undefined + }, +}) - test.beforeEach(async () => { - app = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { - ...process.env, - SIM_DESKTOP_ORIGIN: origin, - SIM_DESKTOP_USER_DATA: mkdtempSync(join(tmpdir(), 'sim-browser-tools-e2e-')), - }, - }) - // A dialog listener stops Playwright auto-dismissing page dialogs, so the desktop's own CDP - // dialog handling decides their outcome exactly as it does in production. - const leaveDialogsToDesktop = (page: Page) => page.on('dialog', () => {}) - app.context().pages().forEach(leaveDialogsToDesktop) - app.context().on('page', leaveDialogsToDesktop) - window = await app.firstWindow() - await app.evaluate(({ app, BrowserWindow }) => { - const host = BrowserWindow.getAllWindows()[0] - host.webContents.setBackgroundThrottling(false) - app.focus({ steal: true }) - host.focus() - }) - await expect - .poll(() => app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].isFocused())) - .toBe(true) - await expect(window.getByRole('heading')).toHaveText('Browser tools fixture') - await window.evaluate(async (scope) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - await api.browserAgent.activateScope(scope) - const updateBounds = () => - api.browserAgent.setPanelBounds( - { x: 0, y: 80, width: innerWidth, height: innerHeight - 80 }, - null, - scope - ) - updateBounds() - setInterval(updateBounds, 200) - }, SCOPE) - }) +async function openForm(tools: BrowserTools, origin: string) { + const outline = await tools.open(`${origin}/form`) + expect(outline).toContain('Name') + return (name: string) => refFor(outline, name) +} - test.afterEach(async () => { - beforeUploadResponse = undefined - appEchoes.length = 0 - await app?.close() - calls.clear() - claimed.clear() - }) +function formState(tools: BrowserTools, origin: string) { + return tools.inPage<{ + name: string + plan: string + updates: boolean + password: string + route: string + scrollLeft: number + }>( + `${origin}/form`, + `({ + name: document.getElementById('name').value, + plan: document.getElementById('plan').value, + updates: document.getElementById('updates').checked, + password: document.getElementById('password').value, + route: document.getElementById('route').value, + scrollLeft: document.getElementById('horizontal').scrollLeft + })` + ) +} - test.afterAll(async () => { - for (const listener of [server, popupServer]) { - await new Promise((resolve, reject) => - listener.close((error) => (error ? reject(error) : resolve())) - ) - } - }) +async function openCapabilities(tools: BrowserTools, site: ToolsSite) { + const url = `${site.site}/capabilities?popup=${encodeURIComponent(`${site.popupOrigin}/authorize`)}` + const outline = await tools.open(url) + return { + ref: (name: string) => refFor(outline, name), + dataset: () => tools.pollPage>(url, '({ ...document.body.dataset })'), + } +} - async function execute(tool: BrowserToolName, args: Record) { - const callId = `browser-fixture-${++callCount}` - calls.set(callId, { chatId: SCOPE, toolName: tool, args }) - return window.evaluate( - async ({ callId, tool, args, scope }) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - return api.browserAgent.executeTool(callId, tool, args, scope) +async function openUploadTarget( + tools: BrowserTools, + site: string, + kind: 'root' | 'same-origin' | 'oopif' | 'shadow', + steal = false +) { + const framed = kind === 'same-origin' || kind === 'oopif' + const url = framed + ? `${site}/upload-host?kind=${kind}` + : `${site}/upload-target?shadow=${kind === 'shadow' ? '1' : '0'}&steal=${steal ? '1' : '0'}` + await tools.run('browser_open_url', { url }) + /** Runs script in the upload frame, or the top page; undefined while that frame is missing. */ + const evaluate = (expression: string, inTopFrame = false) => + tools.app.evaluate( + ({ webContents }, { url, framed, expression }) => { + const contents = webContents.getAllWebContents().find((page) => page.getURL() === url) + if (!contents) throw new Error(`No page at ${url}`) + const frame = framed ? contents.mainFrame.frames[0] : contents.mainFrame + return frame?.executeJavaScript(expression) }, - { callId, tool, args, scope: SCOPE } + { url, framed: framed && !inTopFrame, expression } ) + await expect.poll(() => evaluate('typeof window.uploadTestState')).toBe('function') + if (kind === 'oopif') { + expect( + await tools.app.evaluate(({ webContents }, url) => { + const contents = webContents.getAllWebContents().find((page) => page.getURL() === url) + const child = contents?.mainFrame.frames[0] + return child && child.processId !== contents?.mainFrame.processId + }, url) + ).toBe(true) } + const { outline } = (await tools.run('browser_snapshot')) as { outline: string } + return { elementId: refFor(outline, 'Upload original'), evaluate } +} - async function openForm() { - const response = await execute('browser_open_url', { url: `${origin}/form` }) - expect(response.ok, response.error).toBe(true) - const result = response.result as { snapshot: { outline: string } } - expect(result.snapshot.outline).toContain('Name') - return (name: string) => { - const line = result.snapshot.outline - .split('\n') - .find((line) => line.includes(`"${name}"`) && /\[ref=\d+\]/.test(line)) - const match = line?.match(/\[ref=(\d+)\]/) - if (!match) throw new Error(`No reference for ${name}: ${result.snapshot.outline}`) - return Number(match[1]) - } - } +/** The first pixel of a screenshot, as [red, green, blue]. */ +function firstPixel(app: ElectronApplication, dataUrl: string) { + return app.evaluate(({ nativeImage }, dataUrl) => { + const bitmap = nativeImage.createFromDataURL(dataUrl).toBitmap() + return [bitmap[2], bitmap[1], bitmap[0]] + }, dataUrl) +} - async function openCapabilities() { - const url = `${site}/capabilities?popup=${encodeURIComponent(`${popupOrigin}/authorize`)}` - const response = await execute('browser_open_url', { url }) - expect(response.ok, response.error).toBe(true) - const outline = (response.result as { snapshot: { outline: string } }).snapshot.outline - const ref = (name: string) => { - const match = outline - .split('\n') - .find((line) => line.includes(`"${name}"`) && /\[ref=\d+\]/.test(line)) - ?.match(/\[ref=(\d+)\]/) - if (!match) throw new Error(`No reference for ${name}: ${outline}`) - return Number(match[1]) +/** Paints the form page `color` and checks that a screenshot shows it. */ +async function expectCapturedColor( + tools: BrowserTools, + origin: string, + color: string, + dominantChannel: number +) { + await tools.inPage( + `${origin}/form`, + `document.body.style.background = ${JSON.stringify(color)}; + new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))` + ) + const shot = (await tools.run('browser_screenshot')) as { dataUrl: string } + const pixel = await firstPixel(tools.app, shot.dataUrl) + expect(pixel[dominantChannel], `${color}: ${pixel}`).toBeGreaterThan(180) + for (let channel = 0; channel < 3; channel++) { + if (channel !== dominantChannel) { + expect(pixel[dominantChannel] - pixel[channel], `${color}: ${pixel}`).toBeGreaterThan(80) } - const dataset = () => - app.evaluate( - ({ webContents }, url) => - webContents - .getAllWebContents() - .find((contents) => contents.getURL() === url) - ?.executeJavaScript('({ ...document.body.dataset })'), - url - ) - return { ref, dataset } } +} - test('answers confirm dialogs only when the action asks and right-clicks reach the page', async () => { - const { ref, dataset } = await openCapabilities() - - const dismissed = await execute('browser_click', { elementId: ref('Delete report') }) - expect(JSON.stringify(dismissed.result)).toContain('which was dismissed') - expect(await dataset()).toMatchObject({ deleted: 'false' }) +/** The window and form page state a screenshot must leave as it was. */ +function windowState(tools: BrowserTools, origin: string) { + return tools.app.evaluate(async ({ BrowserWindow, webContents }, origin) => { + const win = BrowserWindow.getAllWindows()[0] + const contents = webContents + .getAllWebContents() + .find((page) => page.getURL() === `${origin}/form`) + if (!contents) throw new Error('Missing screenshot fixture') + return { + id: contents.id, + visible: win.isVisible(), + minimized: win.isMinimized(), + bounds: win.getBounds(), + focused: BrowserWindow.getFocusedWindow()?.id ?? null, + page: await contents.executeJavaScript( + "({width:innerWidth,height:innerHeight,scrollX,scrollY,html:document.body.innerHTML,focus:document.activeElement?.id,value:document.getElementById('name').value})" + ), + } + }, origin) +} - const accepted = await execute('browser_click', { - elementId: ref('Delete report'), - dialog: { accept: true }, +/** Takes screenshots of the form page, checking each image and that nothing else changed. */ +async function expectCapturesLeaveStateUnchanged(tools: BrowserTools, origin: string) { + const before = await windowState(tools, origin) + for (let i = 0; i < 3; i++) { + const shot = (await tools.run('browser_screenshot')) as { + dataUrl: string + scale: number + viewport: { width: number; height: number } + } + expect(shot.viewport.width).toBeGreaterThan(0) + expect(shot.viewport.height).toBeGreaterThan(0) + const image = await tools.app.evaluate(({ nativeImage }, dataUrl) => { + const image = nativeImage.createFromDataURL(dataUrl) + return { empty: image.isEmpty(), ...image.getSize() } + }, shot.dataUrl) + expect(image).toEqual({ + empty: false, + width: Math.round(shot.viewport.width * shot.scale), + height: Math.round(shot.viewport.height * shot.scale), }) - expect(JSON.stringify(accepted.result)).toContain('accepted as requested') - expect(await dataset()).toMatchObject({ deleted: 'true' }) + expect(await windowState(tools, origin)).toEqual(before) + } + return before +} - const menu = await execute('browser_click', { +/** Blurs the window and waits until no window has focus. */ +async function blurWindow(tools: BrowserTools) { + await tools.app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].blur()) + await expect + .poll(() => + tools.app.evaluate(({ BrowserWindow }) => BrowserWindow.getFocusedWindow()?.id ?? null) + ) + .toBeNull() +} + +test.describe('browser tools', () => { + test('right-clicks with modifiers reach the page', async ({ tools, toolsSite }) => { + const { ref, dataset } = await openCapabilities(tools, toolsSite) + await tools.run('browser_click', { elementId: ref('Report row'), button: 'right', modifiers: ['Shift'], }) - expect(menu.ok, menu.error).toBe(true) expect(await dataset()).toMatchObject({ menu: '2:true' }) }) - test('uploads a workspace file into the hidden input behind a drop zone', async () => { - const { ref, dataset } = await openCapabilities() - - const upload = await execute('browser_upload_file', { + test('uploads a workspace file into the hidden input behind a drop zone', async ({ + tools, + toolsSite, + }) => { + const { ref, dataset } = await openCapabilities(tools, toolsSite) + const upload = await tools.run('browser_upload_file', { elementId: ref('Attach receipt'), paths: ['files/receipt.txt'], }) - - expect(upload.ok, upload.error).toBe(true) - expect(upload.result).toMatchObject({ + expect(upload).toMatchObject({ uploaded: [{ name: 'receipt.txt', size: 13 }], effectObserved: true, }) await expect.poll(dataset).toMatchObject({ upload: 'receipt.txt:receipt-bytes' }) }) - async function openUploadTarget( - kind: 'root' | 'same-origin' | 'oopif' | 'shadow', - steal = false - ) { - const framed = kind === 'same-origin' || kind === 'oopif' - const url = framed - ? `${site}/upload-host?kind=${kind}` - : `${site}/upload-target?shadow=${kind === 'shadow' ? '1' : '0'}&steal=${steal ? '1' : '0'}` - const response = await execute('browser_open_url', { url }) - expect(response.ok, response.error).toBe(true) - const evaluate = (expression: string, inTopFrame = false) => - app.evaluate( - ({ webContents }, { url, framed, expression }) => { - const contents = webContents - .getAllWebContents() - .find((contents) => contents.getURL() === url) - const frame = framed ? contents?.mainFrame.frames[0] : contents?.mainFrame - if (!frame) throw new Error('Missing upload fixture frame') - return frame.executeJavaScript(expression) - }, - { url, framed: framed && !inTopFrame, expression } - ) - await expect.poll(() => evaluate('typeof window.uploadTestState')).toBe('function') - if (kind === 'oopif') { - expect( - await app.evaluate(({ webContents }, url) => { - const contents = webContents - .getAllWebContents() - .find((contents) => contents.getURL() === url) - const child = contents?.mainFrame.frames[0] - return child && child.processId !== contents?.mainFrame.processId - }, url) - ).toBe(true) - } - const snapshot = await execute('browser_snapshot', {}) - expect(snapshot.ok, snapshot.error).toBe(true) - const outline = (snapshot.result as { outline: string }).outline - const match = outline - .split('\n') - .find((line) => line.includes('"Upload original"')) - ?.match(/\[ref=(\d+)\]/) - expect(match, outline).toBeTruthy() - return { elementId: Number(match?.[1]), evaluate } - } - - test('pins uploads to the original input when page code steals a DOM marker', async () => { - const { elementId, evaluate } = await openUploadTarget('root', true) - const upload = await execute('browser_upload_file', { elementId, paths: ['files/receipt.txt'] }) - - expect(upload.ok, upload.error).toBe(true) - expect(await evaluate('window.uploadTestState()')).toEqual({ - original: [{ name: 'receipt.txt', text: 'receipt-bytes' }], - decoy: [], - currentCount: 1, - }) + test('pins uploads to the original input when page code steals a DOM marker', async ({ + tools, + toolsSite, + }) => { + const { elementId, evaluate } = await openUploadTarget(tools, toolsSite.site, 'root', true) + await tools.run('browser_upload_file', { elementId, paths: ['files/receipt.txt'] }) + expect(await evaluate('window.uploadTestState()')).toEqual(UPLOADED) }) - test('reports an unconfirmed upload when cancelled before Chromium acknowledgement arrives', async () => { - const { elementId, evaluate } = await openUploadTarget('root') - await app.evaluate(({ webContents }, site) => { - const contents = webContents - .getAllWebContents() - .find((contents) => contents.getURL() === `${site}/upload-target?shadow=0&steal=0`) + test('reports an unconfirmed upload when cancelled before Chromium acknowledgement arrives', async ({ + tools, + toolsSite, + }) => { + type Held = { count: number; applied: boolean; release: () => void; restore: () => void } + const { elementId, evaluate } = await openUploadTarget(tools, toolsSite.site, 'root') + await tools.app.evaluate(({ webContents }, url) => { + const contents = webContents.getAllWebContents().find((page) => page.getURL() === url) if (!contents) throw new Error('Missing upload acknowledgement fixture') const original = contents.debugger.sendCommand let release = () => {} const acknowledgement = new Promise((resolve) => { release = resolve }) - const state = { + const state: Held = { count: 0, applied: false, release, @@ -506,8 +616,9 @@ test.describe('browser tools', () => { contents.debugger.sendCommand = original }, } - const globals = globalThis as typeof globalThis & { heldUploadAcknowledgement?: typeof state } - globals.heldUploadAcknowledgement = state + ;( + globalThis as typeof globalThis & { heldUploadAcknowledgement?: Held } + ).heldUploadAcknowledgement = state contents.debugger.sendCommand = async (method, params, sessionId) => { if (method !== 'DOM.setFileInputFiles') { return original.call(contents.debugger, method, params, sessionId) @@ -518,36 +629,35 @@ test.describe('browser tools', () => { await acknowledgement return result } - }, site) - const pending = execute('browser_upload_file', { elementId, paths: ['files/receipt.txt'] }) - const toolCallId = `browser-fixture-${callCount}` + }, `${toolsSite.site}/upload-target?shadow=0&steal=0`) + const held = () => + tools.app.evaluate(() => { + const state = (globalThis as typeof globalThis & { heldUploadAcknowledgement?: Held }) + .heldUploadAcknowledgement + return state && { count: state.count, applied: state.applied } + }) + const args = { elementId, paths: ['files/receipt.txt'] } + const toolCallId = toolsSite.authorizer.issue(tools.scope, 'browser_upload_file', args) + const pending = tools.shell.evaluate( + ({ toolCallId, args, scope }) => + (globalThis as DesktopBridge).simDesktop.browserAgent.executeTool( + toolCallId, + 'browser_upload_file', + args, + scope + ), + { toolCallId, args, scope: tools.scope } + ) try { - await expect - .poll(() => evaluate('window.uploadTestState()')) - .toEqual({ - original: [{ name: 'receipt.txt', text: 'receipt-bytes' }], - decoy: [], - currentCount: 1, - }) - await expect - .poll(() => - app.evaluate( - () => - ( - globalThis as typeof globalThis & { - heldUploadAcknowledgement?: { applied: boolean } - } - ).heldUploadAcknowledgement?.applied - ) - ) - .toBe(true) - await window.evaluate( + await expect.poll(() => evaluate('window.uploadTestState()')).toEqual(UPLOADED) + await expect.poll(held).toMatchObject({ applied: true }) + await tools.shell.evaluate( async ({ toolCallId, scope }) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - if (!api.browserAgent.cancelTool) throw new Error('Browser cancellation is unavailable') - await api.browserAgent.cancelTool(toolCallId, scope) + const api = (globalThis as DesktopBridge).simDesktop.browserAgent + if (!api.cancelTool) throw new Error('Browser cancellation is unavailable') + await api.cancelTool(toolCallId, scope) }, - { toolCallId, scope: SCOPE } + { toolCallId, scope: tools.scope } ) const upload = await pending @@ -558,22 +668,11 @@ test.describe('browser tools', () => { note: expect.stringContaining('Inspect the page'), }) expect(upload.result).not.toHaveProperty('dispatched', true) - expect((await execute('browser_list_tabs', {})).ok).toBe(true) - expect( - await app.evaluate( - () => - ( - globalThis as typeof globalThis & { - heldUploadAcknowledgement?: { count: number } - } - ).heldUploadAcknowledgement?.count - ) - ).toBe(1) + await tools.run('browser_list_tabs') + expect(await held()).toMatchObject({ count: 1 }) } finally { - await app.evaluate(() => { - const globals = globalThis as typeof globalThis & { - heldUploadAcknowledgement?: { release: () => void; restore: () => void } - } + await tools.app.evaluate(() => { + const globals = globalThis as typeof globalThis & { heldUploadAcknowledgement?: Held } globals.heldUploadAcknowledgement?.release() globals.heldUploadAcknowledgement?.restore() globals.heldUploadAcknowledgement = undefined @@ -583,12 +682,17 @@ test.describe('browser tools', () => { }) for (const mutation of ['replace', 'disable', 'navigate-frame'] as const) { - test(`refuses uploads when the target changes during staging: ${mutation}`, async () => { + test(`refuses uploads when the target changes during staging: ${mutation}`, async ({ + tools, + toolsSite, + }) => { const { elementId, evaluate } = await openUploadTarget( + tools, + toolsSite.site, mutation === 'navigate-frame' ? 'same-origin' : 'root' ) let mutated = false - beforeUploadResponse = async () => { + toolsSite.beforeUploadResponse = async () => { if (mutation === 'navigate-frame') { await evaluate('parent.previousUploadInput = document.querySelector("#original")') await evaluate('location.replace("/upload-target?after=1")') @@ -599,35 +703,34 @@ test.describe('browser tools', () => { } mutated = true } - const upload = await execute('browser_upload_file', { + const upload = await tools.call('browser_upload_file', { elementId, paths: ['files/receipt.txt'], }) expect(mutated).toBe(true) expect(upload.ok, JSON.stringify(upload)).toBe(false) - expect(await evaluate('window.uploadTestState()')).toEqual({ - original: [], - decoy: [], - currentCount: 0, - }) + expect(await evaluate('window.uploadTestState()')).toEqual(NOT_UPLOADED) if (mutation === 'navigate-frame') { expect(await evaluate('parent.previousUploadInput.files.length')).toBe(0) } }) } - test('refuses uploads after their same-origin frame is removed during staging', async () => { - const { elementId, evaluate } = await openUploadTarget('same-origin') + test('refuses uploads after their same-origin frame is removed during staging', async ({ + tools, + toolsSite, + }) => { + const { elementId, evaluate } = await openUploadTarget(tools, toolsSite.site, 'same-origin') let removed = false - beforeUploadResponse = async () => { + toolsSite.beforeUploadResponse = async () => { await evaluate( 'window.removedUploadInput = document.querySelector("iframe").contentDocument.querySelector("#original"); document.querySelector("iframe").remove()', true ) removed = true } - const upload = await execute('browser_upload_file', { + const upload = await tools.call('browser_upload_file', { elementId, paths: ['files/receipt.txt'], }) @@ -638,155 +741,159 @@ test.describe('browser tools', () => { }) for (const kind of ['same-origin', 'oopif', 'shadow'] as const) { - test(`uploads through a pinned input in a ${kind} context`, async () => { - const { elementId, evaluate } = await openUploadTarget(kind) - const upload = await execute('browser_upload_file', { + test(`uploads through a pinned input in a ${kind} context`, async ({ tools, toolsSite }) => { + const { elementId, evaluate } = await openUploadTarget(tools, toolsSite.site, kind) + const upload = await tools.run('browser_upload_file', { elementId, paths: ['files/receipt.txt'], }) - - expect(upload.ok, upload.error).toBe(true) - expect(upload.result).toMatchObject({ uploaded: [{ name: 'receipt.txt', size: 13 }] }) - expect(await evaluate('window.uploadTestState()')).toEqual({ - original: [{ name: 'receipt.txt', text: 'receipt-bytes' }], - decoy: [], - currentCount: 1, - }) + expect(upload).toMatchObject({ uploaded: [{ name: 'receipt.txt', size: 13 }] }) + expect(await evaluate('window.uploadTestState()')).toEqual(UPLOADED) }) } - test('keeps window.opener for page popups and returns to the opener when they close', async () => { - const { ref, dataset } = await openCapabilities() + test('keeps window.opener for page popups and returns to the opener when they close', async ({ + tools, + toolsSite, + }) => { + const { ref, dataset } = await openCapabilities(tools, toolsSite) + const popupUrl = `${toolsSite.popupOrigin}/authorize` - expect((await execute('browser_click', { elementId: ref('Connect') })).ok).toBe(true) - const popup = await execute('browser_snapshot', {}) - const allow = (popup.result as { outline: string }).outline.match( - /button "Allow" \[ref=(\d+)\]/ - )?.[1] - expect(allow, JSON.stringify(popup.result)).toBeTruthy() - const allowed = await execute('browser_click', { elementId: Number(allow) }) - expect(allowed.ok, allowed.error).toBe(true) + await tools.run('browser_click', { elementId: ref('Connect') }) + await expect.poll(() => tools.pollPage(popupUrl, 'true')).toBe(true) + const { outline } = (await tools.run('browser_snapshot')) as { outline: string } + await tools.run('browser_click', { elementId: refFor(outline, 'Allow') }) await expect.poll(dataset).toMatchObject({ connected: 'granted' }) await expect - .poll( - async () => ((await execute('browser_list_tabs', {})).result as { tabs: unknown[] }).tabs - ) + .poll(async () => ((await tools.run('browser_list_tabs')) as { tabs: unknown[] }).tabs) .toHaveLength(1) }) - const tabsState = () => - window.evaluate( - (scope) => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.browserAgent.activateScope(scope), - SCOPE - ) - const tabUrls = async () => (await tabsState()).tabs.map((tab) => tab.url) - /** Runs script in a page with a user gesture, as the user's own click would. */ - const inPage = (url: string, code: string) => - app.evaluate( - ({ webContents }, { url, code }) => - webContents - .getAllWebContents() - .find((contents) => contents.getURL() === url) - ?.executeJavaScript(code, true), - { url, code } - ) - const pageDataset = (url: string) => inPage(url, '({ ...document.body.dataset })') - - test('adopts a blank popup that keeps its opener and returns there when it closes', async () => { + test('adopts a blank popup that keeps its opener and returns there when it closes', async ({ + tools, + toolsSite, + }) => { + const { site, popupOrigin } = toolsSite const openerUrl = `${site}/popups` - expect((await execute('browser_open_url', { url: openerUrl })).ok).toBe(true) + const tabUrls = async () => (await tools.tabs()).tabs.map((tab) => tab.url) + await tools.run('browser_open_url', { url: openerUrl }) // A second tab makes the strip neighbour differ from the opener. - expect((await execute('browser_open_tab', { url: `${site}/other` })).ok).toBe(true) - const openerTabId = (await tabsState()).tabs.find((tab) => tab.url === openerUrl)?.tabId + await tools.run('browser_open_tab', { url: `${site}/other` }) + const openerTabId = (await tools.tabs()).tabs.find((tab) => tab.url === openerUrl)?.tabId expect(openerTabId).toBeTruthy() - await inPage(openerUrl, 'signIn()') + await tools.inPage(openerUrl, 'signIn()') await expect - .poll(() => pageDataset(openerUrl)) + .poll(() => tools.pollPage(openerUrl, '({ ...document.body.dataset })')) .toMatchObject({ handle: 'true', blank: 'ready' }) await expect.poll(tabUrls).toContain(`${popupOrigin}/authorize`) - const popupTab = (await tabsState()).tabs.find((tab) => tab.url === `${popupOrigin}/authorize`) + const popupTab = (await tools.tabs()).tabs.find((tab) => tab.url === `${popupOrigin}/authorize`) expect(popupTab?.active).toBe(true) - await inPage(`${popupOrigin}/authorize`, "document.querySelector('button').click()") - await expect.poll(() => pageDataset(openerUrl)).toMatchObject({ connected: 'granted' }) - await expect.poll(async () => (await tabsState()).tabs.length).toBe(2) - expect((await tabsState()).activeTabId).toBe(openerTabId) + await tools.inPage(`${popupOrigin}/authorize`, "document.querySelector('button').click()") + await expect + .poll(() => tools.pollPage(openerUrl, '({ ...document.body.dataset })')) + .toMatchObject({ connected: 'granted' }) + await expect.poll(async () => (await tools.tabs()).tabs.length).toBe(2) + expect((await tools.tabs()).activeTabId).toBe(openerTabId) }) - test('forgets the opener once the user switches tabs, closing the popup to its neighbour', async () => { + test('forgets the opener once the user switches tabs, closing the popup to its neighbour', async ({ + tools, + toolsSite, + }) => { + const { site, popupOrigin } = toolsSite const openerUrl = `${site}/popups` - expect((await execute('browser_open_url', { url: openerUrl })).ok).toBe(true) - expect((await execute('browser_open_tab', { url: `${site}/other` })).ok).toBe(true) - const otherTabId = (await tabsState()).tabs.find((tab) => tab.url === `${site}/other`)?.tabId - await inPage(openerUrl, 'signIn()') - await expect.poll(tabUrls).toContain(`${popupOrigin}/authorize`) - const popupTabId = (await tabsState()).tabs.find( + await tools.run('browser_open_url', { url: openerUrl }) + await tools.run('browser_open_tab', { url: `${site}/other` }) + const otherTabId = (await tools.tabs()).tabs.find((tab) => tab.url === `${site}/other`)?.tabId + await tools.inPage(openerUrl, 'signIn()') + await expect + .poll(async () => (await tools.tabs()).tabs.map((tab) => tab.url)) + .toContain(`${popupOrigin}/authorize`) + const popupTabId = (await tools.tabs()).tabs.find( (tab) => tab.url === `${popupOrigin}/authorize` )?.tabId for (const tabId of [otherTabId, popupTabId]) { - await window.evaluate( + await tools.shell.evaluate( ({ tabId, scope }) => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.browserAgent.panelAction({ action: 'switch-tab', tabId }, scope), - { tabId, scope: SCOPE } + (globalThis as DesktopBridge).simDesktop.browserAgent.panelAction( + { action: 'switch-tab', tabId }, + scope + ), + { tabId, scope: tools.scope } ) - await expect.poll(async () => (await tabsState()).activeTabId).toBe(tabId) + await expect.poll(async () => (await tools.tabs()).activeTabId).toBe(tabId) } - await inPage(`${popupOrigin}/authorize`, "document.querySelector('button').click()") - await expect.poll(() => pageDataset(openerUrl)).toMatchObject({ connected: 'granted' }) - await expect.poll(async () => (await tabsState()).tabs.length).toBe(2) - expect((await tabsState()).activeTabId).toBe(otherTabId) + await tools.inPage(`${popupOrigin}/authorize`, "document.querySelector('button').click()") + await expect + .poll(() => tools.pollPage(openerUrl, '({ ...document.body.dataset })')) + .toMatchObject({ connected: 'granted' }) + await expect.poll(async () => (await tools.tabs()).tabs.length).toBe(2) + expect((await tools.tabs()).activeTabId).toBe(otherTabId) }) - test('keeps data: popups denied', async () => { - const openerUrl = `${site}/popups` - expect((await execute('browser_open_url', { url: openerUrl })).ok).toBe(true) - expect(await inPage(openerUrl, "String(window.open('data:text/html,x') !== null)")).toBe( + test('keeps data: popups denied', async ({ tools, toolsSite }) => { + const openerUrl = `${toolsSite.site}/popups` + await tools.run('browser_open_url', { url: openerUrl }) + expect(await tools.inPage(openerUrl, "String(window.open('data:text/html,x') !== null)")).toBe( 'false' ) - expect((await tabsState()).tabs).toHaveLength(1) + // The handler decides popups in order, so once this one is listed the data: popup was decided. + await tools.inPage(openerUrl, `void window.open('${toolsSite.site}/sentinel')`) + await expect + .poll(async () => (await tools.tabs()).tabs.map((tab) => tab.url)) + .toContain(`${toolsSite.site}/sentinel`) + expect((await tools.tabs()).tabs).toHaveLength(2) }) - test('posts a same-session form popup and refuses to reissue a cross-session one', async () => { + test('posts a same-session form popup and refuses to reissue a cross-session one', async ({ + tools, + toolsSite, + }) => { + const { site, popupOrigin } = toolsSite const openerUrl = `${site}/popups` - expect((await execute('browser_open_url', { url: openerUrl })).ok).toBe(true) - await inPage(openerUrl, "document.getElementById('same-session').requestSubmit()") - await expect.poll(() => inPage(`${popupOrigin}/echo`, 'document.title')).toBe('POST note=hello') + await tools.run('browser_open_url', { url: openerUrl }) + await tools.inPage(openerUrl, "document.getElementById('same-session').requestSubmit()") + await expect + .poll(() => tools.pollPage(`${popupOrigin}/echo`, 'document.title')) + .toBe('POST note=hello') - const before = (await tabsState()).tabs.length - await inPage(openerUrl, "document.getElementById('cross-session').requestSubmit()") + const before = (await tools.tabs()).tabs.length + await tools.inPage(openerUrl, "document.getElementById('cross-session').requestSubmit()") // The handler decides popups in order, so once this one is listed the post was decided. - await inPage(openerUrl, `void window.open('${site}/sentinel')`) - await expect.poll(tabUrls).toContain(`${site}/sentinel`) - expect((await tabsState()).tabs).toHaveLength(before + 1) - expect(appEchoes).toEqual([]) + await tools.inPage(openerUrl, `void window.open('${site}/sentinel')`) + await expect + .poll(async () => (await tools.tabs()).tabs.map((tab) => tab.url)) + .toContain(`${site}/sentinel`) + expect((await tools.tabs()).tabs).toHaveLength(before + 1) + expect(toolsSite.appEchoes).toEqual([]) }) - test('keeps the opener of a Sim page blank popup that navigates within Sim', async () => { + test('keeps the opener of a Sim page blank popup that navigates within Sim', async ({ + tools, + toolsSite, + }) => { + const { origin } = toolsSite const openerUrl = `${origin}/popups?next=${encodeURIComponent(`${origin}/authorize`)}` - expect((await execute('browser_open_url', { url: openerUrl })).ok).toBe(true) - await inPage(openerUrl, 'signIn()') - await expect.poll(tabUrls).toContain(`${origin}/authorize`) - await inPage(`${origin}/authorize`, "document.querySelector('button').click()") + await tools.run('browser_open_url', { url: openerUrl }) + await tools.inPage(openerUrl, 'signIn()') await expect - .poll(() => pageDataset(openerUrl)) + .poll(async () => (await tools.tabs()).tabs.map((tab) => tab.url)) + .toContain(`${origin}/authorize`) + await tools.inPage(`${origin}/authorize`, "document.querySelector('button').click()") + await expect + .poll(() => tools.pollPage(openerUrl, '({ ...document.body.dataset })')) .toMatchObject({ handle: 'true', connected: 'granted' }) }) - test('renders PDFs in the built-in viewer', async () => { - const response = await execute('browser_open_url', { url: `${site}/doc.pdf` }) - expect(response.ok, response.error).toBe(true) - + test('renders PDFs in the built-in viewer', async ({ tools, toolsSite }) => { + await tools.run('browser_open_url', { url: `${toolsSite.site}/doc.pdf` }) await expect .poll(() => - app.evaluate( + tools.app.evaluate( ({ webContents }, url) => webContents .getAllWebContents() @@ -794,18 +901,24 @@ test.describe('browser tools', () => { ?.mainFrame.framesInSubtree.some((frame) => frame.url.startsWith('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/') ), - `${site}/doc.pdf` + `${toolsSite.site}/doc.pdf` ) ) .toBe(true) }) - test('shares desktop authentication for private HTML previews and deployed chats', async () => { + test('shares desktop authentication for private HTML previews and deployed chats', async ({ + tools, + toolsSite, + }) => { + const { origin } = toolsSite for (const path of ['/private-preview', '/private-chat']) { - const result = await execute('browser_open_url', { url: `${origin}${path}` }) - expect(result.ok, result.error).toBe(true) - expect(result.result).toMatchObject({ url: `${origin}${path}` }) - const state = await app.evaluate(async ({ webContents, BrowserWindow }, url) => { + const result = (await tools.run('browser_open_url', { url: `${origin}${path}` })) as { + url: string + snapshot: { outline: string } + } + expect(result.url).toBe(`${origin}${path}`) + const state = await tools.app.evaluate(async ({ webContents, BrowserWindow }, url) => { const host = BrowserWindow.getAllWindows()[0].webContents const page = webContents.getAllWebContents().find((contents) => contents.getURL() === url) if (!page) throw new Error('Missing protected page') @@ -818,20 +931,13 @@ test.describe('browser tools', () => { escaped: await page.executeJavaScript('document.body.dataset.escaped === "true"'), } }, `${origin}${path}`) - expect(state.sharedSession).toBe(true) - expect(state.hasDesktopBridge).toBe(false) + expect(state).toMatchObject({ sharedSession: true, hasDesktopBridge: false, escaped: false }) expect(state.heading).toContain('Authenticated') - expect(state.escaped).toBe(false) if (path === '/private-preview') { - const outline = (result.result as { snapshot: { outline: string } }).snapshot.outline - const button = outline - .split('\n') - .find((line) => line.includes('"Test quiz"') && /\[ref=\d+\]/.test(line)) - ?.match(/\[ref=(\d+)\]/)?.[1] - expect(button, JSON.stringify(result.result)).toBeTruthy() - const click = await execute('browser_click', { elementId: Number(button) }) - expect(click.ok, click.error).toBe(true) - const frameState = await app.evaluate(async ({ webContents }, url) => { + await tools.run('browser_click', { + elementId: refFor(result.snapshot.outline, 'Test quiz'), + }) + const frameState = await tools.app.evaluate(async ({ webContents }, url) => { const page = webContents.getAllWebContents().find((contents) => contents.getURL() === url) const frame = page?.mainFrame.frames.find((frame) => frame.url === 'about:srcdoc') if (!frame) throw new Error('Missing sandboxed preview') @@ -842,119 +948,97 @@ test.describe('browser tools', () => { expect(frameState).toEqual({ clicked: 'true', isolated: 'true', bridge: 'undefined' }) } } - const typed = await execute('browser_open_url', { url: `${origin}/private-chat` }) - expect(typed.ok, typed.error).toBe(true) - const result = typed.result as { snapshot: { outline: string } } - const message = result.snapshot.outline - .split('\n') - .find((line) => line.includes('"Message"') && /\[ref=\d+\]/.test(line)) - ?.match(/\[ref=(\d+)\]/)?.[1] - const send = result.snapshot.outline - .split('\n') - .find((line) => line.includes('"Send"') && /\[ref=\d+\]/.test(line)) - ?.match(/\[ref=(\d+)\]/)?.[1] - expect(message, result.snapshot.outline).toBeTruthy() - expect(send, result.snapshot.outline).toBeTruthy() - expect( - (await execute('browser_type', { elementId: Number(message), text: 'Session works' })).ok - ).toBe(true) - expect((await execute('browser_click', { elementId: Number(send) })).ok).toBe(true) - expect(JSON.stringify(await execute('browser_snapshot', {}))).toContain('Session works') + const outline = await tools.open(`${origin}/private-chat`) + await tools.run('browser_type', { + elementId: refFor(outline, 'Message'), + text: 'Session works', + }) + await tools.run('browser_click', { elementId: refFor(outline, 'Send') }) + await expect + .poll(() => + tools.pollPage(`${origin}/private-chat`, "document.getElementById('reply').textContent") + ) + .toBe('Session works') }) - test('keeps external navigation isolated and authenticates redirects back into Sim', async () => { - expect((await execute('browser_open_url', { url: `${origin}/private-chat` })).ok).toBe(true) - const external = origin.replace('127.0.0.1', 'localhost') - const result = await execute('browser_open_url', { url: `${origin}/redirect` }) - expect(result.ok, result.error).toBe(true) - expect(result.result).toMatchObject({ url: `${external}/landing` }) + test('keeps external navigation isolated and authenticates redirects back into Sim', async ({ + tools, + toolsSite, + }) => { + const { origin, site } = toolsSite + await tools.run('browser_open_url', { url: `${origin}/private-chat` }) + const result = await tools.run('browser_open_url', { url: `${origin}/redirect` }) + expect(result).toMatchObject({ url: `${site}/landing` }) expect( - await app.evaluate(({ webContents, BrowserWindow }, url) => { + await tools.app.evaluate(({ webContents, BrowserWindow }, url) => { const page = webContents.getAllWebContents().find((contents) => contents.getURL() === url) - return page?.session === BrowserWindow.getAllWindows()[0].webContents.session - }, `${external}/landing`) + if (!page) throw new Error(`No page at ${url}`) + return page.session === BrowserWindow.getAllWindows()[0].webContents.session + }, `${site}/landing`) ).toBe(false) - const back = await execute('browser_open_url', { url: `${external}/enter-sim` }) - expect(back.ok, back.error).toBe(true) - expect(back.result).toMatchObject({ url: `${origin}/private-chat` }) + const back = await tools.run('browser_open_url', { url: `${site}/enter-sim` }) + expect(back).toMatchObject({ url: `${origin}/private-chat` }) }) - test('sign-out clears authenticated browser pages with the desktop session', async () => { - const opened = await execute('browser_open_url', { url: `${origin}/private-chat` }) - expect(opened.ok, opened.error).toBe(true) - expect(opened.result).toMatchObject({ url: `${origin}/private-chat` }) - await window.evaluate(async () => { + test('sign-out clears authenticated browser pages with the desktop session', async ({ + tools, + toolsSite, + }) => { + const { origin } = toolsSite + const opened = await tools.run('browser_open_url', { url: `${origin}/private-chat` }) + expect(opened).toMatchObject({ url: `${origin}/private-chat` }) + await tools.shell.evaluate(async () => { await fetch('/api/auth/sign-out', { method: 'POST' }) }) await expect .poll(() => - app.evaluate( + tools.app.evaluate( ({ webContents }, url) => webContents.getAllWebContents().some((contents) => contents.getURL() === url), `${origin}/private-chat` ) ) .toBe(false) - await expect(window).toHaveURL(`${origin}/login`) + await expect(tools.shell).toHaveURL(`${origin}/login`) }) - async function formState() { - return app.evaluate(async ({ webContents }, origin) => { - const page = webContents - .getAllWebContents() - .find((contents) => contents.getURL().startsWith(`${origin}/form`)) - if (!page) throw new Error('Missing browser fixture') - return page.executeJavaScript(`({ - name: document.getElementById('name').value, - plan: document.getElementById('plan').value, - updates: document.getElementById('updates').checked, - password: document.getElementById('password').value, - route: document.getElementById('route').value, - scrollLeft: document.getElementById('horizontal').scrollLeft - })`) - }, origin) - } - - test('sets and clears multiple selections without partial writes for invalid options', async () => { - const ref = await openForm() - const selected = await execute('browser_select_option', { + test('sets and clears multiple selections without partial writes for invalid options', async ({ + tools, + toolsSite, + }) => { + const ref = await openForm(tools, toolsSite.origin) + const selected = await tools.run('browser_select_option', { elementId: ref('Regions'), values: ['A', 'B'], }) - expect(selected.ok, selected.error).toBe(true) - expect(selected.result).toMatchObject({ + expect(selected).toMatchObject({ values: ['a', 'b'], effectObserved: true, readback: { values: ['a', 'b'] }, }) - const invalid = await execute('browser_select_option', { + const invalid = await tools.call('browser_select_option', { elementId: ref('Regions'), values: ['B', 'C'], }) expect(invalid.ok).toBe(false) - const values = await app.evaluate(async ({ webContents }, origin) => { - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL() === `${origin}/form`) - if (!contents) throw new Error('Missing form fixture') - return contents.executeJavaScript( + expect( + await tools.inPage( + `${toolsSite.origin}/form`, 'Array.from(document.getElementById("regions").selectedOptions, option => option.value)' ) - }, origin) - expect(values).toEqual(['a', 'b']) - const cleared = await execute('browser_select_option', { + ).toEqual(['a', 'b']) + const cleared = await tools.run('browser_select_option', { elementId: ref('Regions'), values: [], }) - expect(cleared.result).toMatchObject({ - values: [], - effectObserved: true, - readback: { values: [] }, - }) + expect(cleared).toMatchObject({ values: [], effectObserved: true, readback: { values: [] } }) }) - test('fills structured native fields and leaves invalid dates unchanged', async () => { - const ref = await openForm() + test('fills structured native fields and leaves invalid dates unchanged', async ({ + tools, + toolsSite, + }) => { + const ref = await openForm(tools, toolsSite.origin) for (const [name, text] of [ ['Date', '2026-09-15'], ['Time', '15:48'], @@ -964,27 +1048,18 @@ test.describe('browser tools', () => { ['Color', '#AABBCC'], ['Range', '75'], ]) { - const response = await execute('browser_type', { elementId: ref(name), text }) - expect(response.ok, response.error).toBe(true) - expect(response.result).toMatchObject({ - trusted: false, - dispatched: true, - effectObserved: true, - }) + const typed = await tools.run('browser_type', { elementId: ref(name), text }) + expect(typed).toMatchObject({ trusted: false, dispatched: true, effectObserved: true }) } - const invalid = await execute('browser_type', { elementId: ref('Date'), text: '2026-02-30' }) + const invalid = await tools.call('browser_type', { elementId: ref('Date'), text: '2026-02-30' }) expect(invalid.ok).toBe(false) expect(invalid.error).toContain('Invalid value') - const state = await app.evaluate(async ({ webContents }, origin) => { - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL() === `${origin}/form`) - if (!contents) throw new Error('Missing form fixture') - return contents.executeJavaScript( + expect( + await tools.inPage( + `${toolsSite.origin}/form`, '({date:document.getElementById("date").value,time:document.getElementById("time").value,appointment:document.getElementById("appointment").value,month:document.getElementById("month").value,week:document.getElementById("week").value,color:document.getElementById("color").value,range:document.getElementById("range").value,events:document.getElementById("date").dataset.events})' ) - }, origin) - expect(state).toEqual({ + ).toEqual({ date: '2026-09-15', time: '15:48', appointment: '2026-09-15T15:48', @@ -997,55 +1072,47 @@ test.describe('browser tools', () => { }) for (const mode of ['menu', 'sticky']) { - test(`clicks a ${mode} target without losing its identity`, async () => { - const opened = await execute('browser_open_url', { url: `${origin}/click?mode=${mode}` }) - expect(opened.ok, opened.error).toBe(true) - await app.evaluate( - async ({ webContents }, { origin, mode }) => { - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL().startsWith(`${origin}/click`)) - if (!contents) throw new Error('Missing click fixture') - await contents.executeJavaScript(` - history.scrollRestoration = 'manual'; - document.getElementById('target').style.top = ${mode === 'sticky' ? '1010' : 'innerHeight - 100'} + 'px'; - scrollTo(0, ${mode === 'sticky' ? '1000' : '0'}); - new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => { - document.body.dataset.scrolls = '0'; document.body.dataset.armed = 'true'; resolve(); - }))) - `) - }, - { origin, mode } + test(`clicks a ${mode} target without losing its identity`, async ({ tools, toolsSite }) => { + const url = `${toolsSite.origin}/click?mode=${mode}` + await tools.run('browser_open_url', { url }) + await tools.inPage( + url, + `history.scrollRestoration = 'manual'; + document.getElementById('target').style.top = ${mode === 'sticky' ? '1010' : 'innerHeight - 100'} + 'px'; + scrollTo(0, ${mode === 'sticky' ? '1000' : '0'}); + new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => { + document.body.dataset.scrolls = '0'; document.body.dataset.armed = 'true'; resolve(); + })))` + ) + const { outline } = (await tools.run('browser_snapshot')) as { outline: string } + await tools.run('browser_click', { elementId: refFor(outline, 'Choose option') }) + const state = await tools.inPage<{ clicks: string; scrolls: string; scrollY: number }>( + url, + '({clicks:document.body.dataset.clicks,scrolls:document.body.dataset.scrolls,scrollY})' ) - const snapshot = await execute('browser_snapshot', {}) - expect(snapshot.ok, snapshot.error).toBe(true) - const outline = (snapshot.result as { outline: string }).outline - const line = outline.split('\n').find((line) => line.includes('"Choose option"')) - const match = line?.match(/\[ref=(\d+)\]/) - if (!match) throw new Error(`Missing target: ${outline}`) - const result = await execute('browser_click', { elementId: Number(match[1]) }) - expect(result.ok, result.error).toBe(true) - const state = await app.evaluate(async ({ webContents }, origin) => { - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL().startsWith(`${origin}/click`)) - if (!contents) throw new Error('Missing click fixture') - return contents.executeJavaScript( - '({clicks:document.body.dataset.clicks,scrolls:document.body.dataset.scrolls,scrollY})' - ) - }, origin) expect(state.clicks).toBe('1') if (mode === 'menu') expect(state).toMatchObject({ scrolls: '0', scrollY: 0 }) else expect(state.scrollY).toBeLessThan(1000) }) } - test('recovers a permanently pending native capture without losing the page', async () => { - await openForm() - const before = await app.evaluate(async ({ webContents }, origin) => { - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL() === `${origin}/form`) + test('captures fresh pixels after a resize and recovers a permanently pending native capture without losing the page', async ({ + tools, + toolsSite, + }) => { + const { origin } = toolsSite + await openForm(tools, origin) + const viewportWidth = () => tools.inPage(`${origin}/form`, 'innerWidth') + const beforeWidth = await viewportWidth() + await tools.app.evaluate(({ BrowserWindow }) => + BrowserWindow.getAllWindows()[0].setSize(1280, 900) + ) + await expect.poll(viewportWidth).not.toBe(beforeWidth) + await expectCapturedColor(tools, origin, 'rgb(240, 20, 30)', 0) + await expectCapturedColor(tools, origin, 'rgb(30, 40, 230)', 2) + + const before = await tools.app.evaluate(async ({ webContents }, url) => { + const contents = webContents.getAllWebContents().find((page) => page.getURL() === url) if (!contents) throw new Error('Missing capture fixture') await contents.executeJavaScript(` document.getElementById('name').value = 'Unsaved work'; @@ -1053,37 +1120,15 @@ test.describe('browser tools', () => { `) contents.capturePage = () => new Promise(() => {}) return { id: contents.id, url: contents.getURL() } - }, origin) + }, `${origin}/form`) for (const [color, dominantChannel] of [ ['rgb(240, 20, 30)', 0], ['rgb(30, 40, 230)', 2], ['rgb(20, 220, 50)', 1], ] as const) { - await app.evaluate( - async ({ webContents }, { id, color }) => { - const contents = webContents.fromId(id) - if (!contents) throw new Error('Capture fixture was replaced') - await contents.executeJavaScript(` - document.body.style.background = ${JSON.stringify(color)}; - new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))) - `) - }, - { id: before.id, color } - ) - const response = await execute('browser_screenshot', {}) - expect(response.ok, response.error).toBe(true) - const shot = response.result as { dataUrl: string } - const pixel = await app.evaluate(({ nativeImage }, dataUrl) => { - const bitmap = nativeImage.createFromDataURL(dataUrl).toBitmap() - return [bitmap[2], bitmap[1], bitmap[0]] - }, shot.dataUrl) - expect(pixel[dominantChannel]).toBeGreaterThan(180) - for (let channel = 0; channel < 3; channel++) { - if (channel !== dominantChannel) - expect(pixel[dominantChannel] - pixel[channel]).toBeGreaterThan(80) - } + await expectCapturedColor(tools, origin, color, dominantChannel) } - const after = await app.evaluate(async ({ webContents }, id) => { + const after = await tools.app.evaluate(async ({ webContents }, id) => { const contents = webContents.fromId(id) if (!contents) throw new Error('Capture fixture was replaced') return { @@ -1097,39 +1142,32 @@ test.describe('browser tools', () => { expect(after).toEqual({ ...before, page: { value: 'Unsaved work', focus: 'name' } }) }) - test('maps a fractional narrow crop back to its actual viewport position', async () => { - await openForm() - const target = await app.evaluate(async ({ webContents }, origin) => { - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL() === `${origin}/form`) - if (!contents) throw new Error('Missing crop fixture') - return contents.executeJavaScript(` - const button = document.createElement('button'); - button.textContent = 'Narrow target'; - button.style.cssText = 'position:absolute;left:20.1px;top:60.1px;width:1.1px;height:100px;padding:0;border:0;overflow:hidden'; - button.onclick = () => { document.body.dataset.cropClicks = Number(document.body.dataset.cropClicks || 0) + 1 }; - document.body.append(button); - const rect = button.getBoundingClientRect(); - ({x:rect.x,y:rect.y,width:rect.width,height:rect.height,devicePixelRatio}); - `) as Promise<{ - x: number - y: number - width: number - height: number - devicePixelRatio: number - }> - }, origin) - const snapshot = await execute('browser_snapshot', {}) - expect(snapshot.ok, snapshot.error).toBe(true) - const line = (snapshot.result as { outline: string }).outline - .split('\n') - .find((line) => line.includes('"Narrow target"')) - const match = line?.match(/\[ref=(\d+)\]/) - if (!match) throw new Error('Missing narrow target reference') - const response = await execute('browser_screenshot', { elementId: Number(match[1]) }) - expect(response.ok, response.error).toBe(true) - const shot = response.result as { + test('maps a fractional narrow crop back to its actual viewport position', async ({ + tools, + toolsSite, + }) => { + const formUrl = `${toolsSite.origin}/form` + await openForm(tools, toolsSite.origin) + const target = await tools.inPage<{ + x: number + y: number + width: number + height: number + devicePixelRatio: number + }>( + formUrl, + `const button = document.createElement('button'); + button.textContent = 'Narrow target'; + button.style.cssText = 'position:absolute;left:20.1px;top:60.1px;width:1.1px;height:100px;padding:0;border:0;overflow:hidden'; + button.onclick = () => { document.body.dataset.cropClicks = Number(document.body.dataset.cropClicks || 0) + 1 }; + document.body.append(button); + const rect = button.getBoundingClientRect(); + ({x:rect.x,y:rect.y,width:rect.width,height:rect.height,devicePixelRatio});` + ) + const { outline } = (await tools.run('browser_snapshot')) as { outline: string } + const shot = (await tools.run('browser_screenshot', { + elementId: refFor(outline, 'Narrow target'), + })) as { imageSize: { width: number; height: number } clip: { x: number; y: number; width: number; height: number } scale: number @@ -1141,305 +1179,191 @@ test.describe('browser tools', () => { expect(target.x - shot.clip.x).toBeLessThan(1 / target.devicePixelRatio) expect(target.y - shot.clip.y).toBeLessThan(1 / target.devicePixelRatio) expect(shot.scale).toBeCloseTo(shot.imageSize.width / shot.clip.width) - const clicked = await execute('browser_click_at', { + await tools.run('browser_click_at', { x: shot.clip.x + shot.clip.width / 2, y: shot.clip.y + shot.clip.height / 2, }) - expect(clicked.ok, clicked.error).toBe(true) - const count = await app.evaluate(async ({ webContents }, origin) => { - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL() === `${origin}/form`) - return contents?.executeJavaScript('document.body.dataset.cropClicks') - }, origin) - expect(count).toBe('1') + expect(await tools.inPage(formUrl, 'document.body.dataset.cropClicks')).toBe('1') }) - for (const mode of ['hidden', 'minimized']) { - test(`recovers a stalled capture after restoring a ${mode} window`, async () => { - test.skip(mode === 'minimized' && process.platform !== 'darwin', 'Requires minimize events') - await openForm() - await app.evaluate( - async ({ BrowserWindow, webContents }, { origin, mode }) => { - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL() === `${origin}/form`) - if (!contents) throw new Error('Missing capture fixture') - contents.capturePage = () => new Promise(() => {}) - await contents.executeJavaScript("document.getElementById('name').value = 'Unsaved work'") - const win = BrowserWindow.getAllWindows()[0] - win.blur() - if (mode === 'hidden') win.hide() - else { - const minimized = new Promise((resolve) => win.once('minimize', resolve)) - win.minimize() - await minimized - } - }, - { origin, mode } - ) - const state = () => - app.evaluate(async ({ BrowserWindow, webContents }, origin) => { - const win = BrowserWindow.getAllWindows()[0] - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL() === `${origin}/form`) - if (!contents) throw new Error('Missing capture fixture') - return { - id: contents.id, - visible: win.isVisible(), - minimized: win.isMinimized(), - focused: BrowserWindow.getFocusedWindow()?.id ?? null, - bounds: win.getBounds(), - value: await contents.executeJavaScript("document.getElementById('name').value"), - } - }, origin) - const before = await state() - const start = Date.now() - const hiddenCapture = await execute('browser_screenshot', {}) - expect(Date.now() - start).toBeLessThan(12_000) - if (!hiddenCapture.ok) - expect(hiddenCapture.error).toContain('Screenshot frame capture timed out') - expect(await state()).toEqual(before) - await app.evaluate(({ BrowserWindow }, mode) => { - const win = BrowserWindow.getAllWindows()[0] - if (mode === 'minimized') win.restore() - else win.showInactive() - }, mode) - for (let attempt = 0; attempt < 2; attempt++) { - const response = await execute('browser_screenshot', {}) - expect(response.ok, response.error).toBe(true) - } - expect(await state()).toMatchObject({ id: before.id, value: 'Unsaved work' }) - }) - } - - for (const mode of ['visible', 'hidden', 'minimized']) { - test(`captures a ${mode} window without changing its state`, async () => { - test.skip( - mode === 'minimized' && process.platform !== 'darwin', - 'Requires a window manager with minimize events' - ) - await openForm() - await app.evaluate(async ({ BrowserWindow }, mode) => { + for (const mode of ['hidden', 'minimized'] as const) { + test(`captures a ${mode} window without changing its state, and recovers a stalled capture after restoring it`, async ({ + tools, + toolsSite, + }) => { + const { origin } = toolsSite + await openForm(tools, origin) + await tools.inPage(`${origin}/form`, "document.getElementById('name').value = 'Unsaved work'") + await blurWindow(tools) + await tools.app.evaluate(async ({ BrowserWindow }, mode) => { const win = BrowserWindow.getAllWindows()[0] - win.blur() if (mode === 'hidden') win.hide() - if (mode === 'minimized') { - const minimized = new Promise((resolve) => win.once('minimize', () => resolve())) + else { + const minimized = new Promise((resolve) => win.once('minimize', resolve)) win.minimize() await minimized } }, mode) - const state = () => - app.evaluate(async ({ BrowserWindow, webContents }, origin) => { - const win = BrowserWindow.getAllWindows()[0] - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL() === `${origin}/form`) - if (!contents) throw new Error('Missing screenshot fixture') - return { - visible: win.isVisible(), - minimized: win.isMinimized(), - bounds: win.getBounds(), - focused: BrowserWindow.getFocusedWindow()?.id ?? null, - page: await contents.executeJavaScript( - '({width:innerWidth,height:innerHeight,scrollX,scrollY,html:document.body.innerHTML,focus:document.activeElement?.id})' - ), - } - }, origin) - const before = await state() - for (let i = 0; i < 3; i++) { - const response = await execute('browser_screenshot', {}) - expect(response.ok, response.error).toBe(true) - const shot = response.result as { - dataUrl: string - scale: number - viewport: { width: number; height: number } - } - expect(shot.dataUrl.length).toBeGreaterThan(1000) - expect(shot.viewport.width).toBeGreaterThan(0) - expect(shot.viewport.height).toBeGreaterThan(0) - const image = await app.evaluate(({ nativeImage }, dataUrl) => { - const image = nativeImage.createFromDataURL(dataUrl) - return { empty: image.isEmpty(), ...image.getSize() } - }, shot.dataUrl) - expect(image).toEqual({ - empty: false, - width: Math.round(shot.viewport.width * shot.scale), - height: Math.round(shot.viewport.height * shot.scale), - }) - expect(await state()).toEqual(before) - } + + const before = await expectCapturesLeaveStateUnchanged(tools, origin) + + await tools.app.evaluate(({ webContents }, url) => { + const contents = webContents.getAllWebContents().find((page) => page.getURL() === url) + if (!contents) throw new Error('Missing capture fixture') + contents.capturePage = () => new Promise(() => {}) + }, `${origin}/form`) + const start = Date.now() + const stalled = await tools.call('browser_screenshot') + expect(Date.now() - start).toBeLessThan(12_000) + if (!stalled.ok) expect(stalled.error).toContain('Screenshot frame capture timed out') + expect(await windowState(tools, origin)).toEqual(before) + + await tools.app.evaluate(({ BrowserWindow }, mode) => { + const win = BrowserWindow.getAllWindows()[0] + if (mode === 'minimized') win.restore() + else win.showInactive() + }, mode) + await expect + .poll(() => + tools.app.evaluate(({ BrowserWindow }) => { + const win = BrowserWindow.getAllWindows()[0] + return !win.isMinimized() && win.isVisible() + }) + ) + .toBe(true) + for (let attempt = 0; attempt < 2; attempt++) await tools.run('browser_screenshot') + expect(await windowState(tools, origin)).toMatchObject({ + id: before.id, + page: { value: 'Unsaved work' }, + }) }) } - test('captures fresh pixels after resizing and repainting the viewport', async () => { - await openForm() - const viewportWidth = () => - app.evaluate(async ({ webContents }, origin) => { - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL() === `${origin}/form`) - return contents?.executeJavaScript('innerWidth') - }, origin) - const beforeWidth = await viewportWidth() - await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].setSize(1280, 900)) - await expect.poll(viewportWidth).not.toBe(beforeWidth) - for (const color of ['red', 'blue']) { - await app.evaluate( - async ({ webContents }, { origin, color }) => { - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL() === `${origin}/form`) - if (!contents) throw new Error('Missing screenshot fixture') - await contents.executeJavaScript( - `document.body.style.background = ${JSON.stringify(color)}; - new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))` - ) - }, - { origin, color } - ) - const response = await execute('browser_screenshot', {}) - expect(response.ok, response.error).toBe(true) - const shot = response.result as { dataUrl: string } - const pixel = await app.evaluate(({ nativeImage }, dataUrl) => { - const image = nativeImage.createFromDataURL(dataUrl) - return Array.from(image.toBitmap().subarray(0, 4)) - }, shot.dataUrl) - const dominant = pixel[color === 'red' ? 2 : 0] - const other = pixel[color === 'red' ? 0 : 2] - expect(dominant - other, `${color}: ${pixel}`).toBeGreaterThan(150) - } + test('captures a visible window without changing its state', async ({ tools, toolsSite }) => { + await openForm(tools, toolsSite.origin) + await blurWindow(tools) + await expectCapturesLeaveStateUnchanged(tools, toolsSite.origin) }) - test('opens with references, fills in order, and scrolls a horizontal pane', async () => { - const ref = await openForm() - const fill = await execute('browser_fill_form', { + test('opens with references, fills in order, and scrolls a horizontal pane', async ({ + tools, + toolsSite, + }) => { + const { origin } = toolsSite + const ref = await openForm(tools, origin) + const fill = await tools.run('browser_fill_form', { fields: [ { elementId: ref('Name'), kind: 'text', text: 'Example User' }, { elementId: ref('Plan'), kind: 'select', value: 'pro' }, { elementId: ref('Updates'), kind: 'checked', checked: true }, ], }) - expect(fill.ok, fill.error).toBe(true) - expect(fill.result, JSON.stringify(fill.result)).toMatchObject({ - completed: true, - completedCount: 3, + expect(fill, JSON.stringify(fill)).toMatchObject({ completed: true, completedCount: 3 }) + expect(await formState(tools, origin)).toMatchObject({ + name: 'Example User', + plan: 'pro', + updates: true, }) - expect(await formState()).toMatchObject({ name: 'Example User', plan: 'pro', updates: true }) - const cleared = await execute('browser_fill_form', { + const cleared = await tools.run('browser_fill_form', { fields: [{ elementId: ref('Name'), kind: 'text', text: '' }], }) - expect(cleared.result, JSON.stringify(cleared.result)).toMatchObject({ completed: true }) - expect(await formState()).toMatchObject({ name: '' }) + expect(cleared, JSON.stringify(cleared)).toMatchObject({ completed: true }) + expect(await formState(tools, origin)).toMatchObject({ name: '' }) - const scroll = await execute('browser_scroll', { + const scroll = await tools.run('browser_scroll', { direction: 'right', amount: 240, elementId: ref('Wide table'), }) - expect(scroll.ok, scroll.error).toBe(true) - expect(scroll.result).toMatchObject({ movedBy: 240 }) - expect(Math.round((await formState()).scrollLeft)).toBe(240) - await execute('browser_scroll', { + expect(scroll).toMatchObject({ movedBy: 240 }) + expect(Math.round((await formState(tools, origin)).scrollLeft)).toBe(240) + await tools.run('browser_scroll', { direction: 'left', amount: 240, elementId: ref('Wide table'), }) - expect(await formState()).toMatchObject({ scrollLeft: 0 }) + expect(await formState(tools, origin)).toMatchObject({ scrollLeft: 0 }) }) - test('batches an action with a fresh observation without replaying form fields', async () => { - const ref = await openForm() - const fill = await execute('browser_fill_form', { + test('batches an action with a fresh observation without replaying form fields', async ({ + tools, + toolsSite, + }) => { + const { origin } = toolsSite + const ref = await openForm(tools, origin) + const fill = (await tools.run('browser_fill_form', { fields: [{ elementId: ref('Name'), kind: 'text', text: 'Observed value' }], observe: { query: 'Name' }, - }) - expect(fill.ok, fill.error).toBe(true) - expect(fill.result).toMatchObject({ + })) as { observation: { result: { matches: { elementId: number }[] } } } + expect(fill).toMatchObject({ completed: true, completedCount: 1, observation: { ok: true, result: { totalMatches: 1 } }, }) - expect(await formState()).toMatchObject({ name: 'Observed value' }) - const result = fill.result as { observation: { result: { matches: { elementId: number }[] } } } - const freshId = result.observation.result.matches[0].elementId + expect(await formState(tools, origin)).toMatchObject({ name: 'Observed value' }) + const freshId = fill.observation.result.matches[0].elementId expect(freshId).toBe(ref('Name')) - const clear = await execute('browser_type', { elementId: freshId, text: '', observe: {} }) - expect(clear.ok, clear.error).toBe(true) - expect(clear.result).toMatchObject({ observation: { ok: true } }) - expect(await formState()).toMatchObject({ name: '' }) + const clear = await tools.run('browser_type', { elementId: freshId, text: '', observe: {} }) + expect(clear).toMatchObject({ observation: { ok: true } }) + expect(await formState(tools, origin)).toMatchObject({ name: '' }) }) - test('stops after a route change without writing the next field', async () => { - const ref = await openForm() - const fill = await execute('browser_fill_form', { + test('stops after a route change without writing the next field', async ({ + tools, + toolsSite, + }) => { + const { origin } = toolsSite + const ref = await openForm(tools, origin) + const fill = await tools.call('browser_fill_form', { fields: [ { elementId: ref('Route'), kind: 'text', text: 'change route' }, { elementId: ref('Name'), kind: 'text', text: 'Must not be written' }, ], }) - expect(fill.result, JSON.stringify(fill.result)).toMatchObject({ - completed: false, - doNotRetry: true, - }) - expect(await formState()).toMatchObject({ name: '', route: 'change route' }) + expect(fill.result, JSON.stringify(fill)).toMatchObject({ completed: false, doNotRetry: true }) + expect(await formState(tools, origin)).toMatchObject({ name: '', route: 'change route' }) }) - test('follows a link and cross-origin redirect without a website approval prompt', async () => { - await openForm() - await app.evaluate(async ({ webContents }, url) => { - const page = webContents.getAllWebContents().find((contents) => contents.getURL() === url) - if (!page) throw new Error('Missing browser fixture') - await page.executeJavaScript("document.querySelector('a').click()") - }, `${origin}/form`) - - const destination = `${origin.replace('127.0.0.1', 'localhost')}/landing` - await expect - .poll(() => - app.evaluate( - ({ webContents }, url) => - webContents.getAllWebContents().some((contents) => contents.getURL() === url), - destination - ) - ) - .toBe(true) - expect(await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows().length)).toBe(1) - await expect(window.getByRole('heading')).toHaveText('Browser tools fixture') + test('follows a link and cross-origin redirect without a website approval prompt', async ({ + tools, + toolsSite, + }) => { + const { origin, site } = toolsSite + await openForm(tools, origin) + await tools.inPage(`${origin}/form`, "document.querySelector('a').click()") + await expect.poll(() => tools.pollPage(`${site}/landing`, 'true')).toBe(true) + expect( + await tools.app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows().length) + ).toBe(1) + await expect(tools.shell.getByRole('heading')).toHaveText('Browser tools fixture') }) - test('stops when a new popup exceeds the page summary limit', async () => { - const ref = await openForm() - await app.evaluate(async ({ webContents }, origin) => { - const page = webContents - .getAllWebContents() - .find((contents) => contents.getURL().startsWith(`${origin}/form`)) - if (!page) throw new Error('Missing browser fixture') - await page.executeJavaScript(` - for (let index = 0; index < 10; index++) { - const toolbar = document.createElement('div') - toolbar.setAttribute('role', 'toolbar') - toolbar.textContent = 'Toolbar ' + index - document.body.append(toolbar) - } - document.getElementById('name').addEventListener('input', () => { - const popup = document.createElement('div') - popup.setAttribute('role', 'listbox') - popup.textContent = 'Suggestions' - document.body.append(popup) - }, { once: true }) - `) - }, origin) + test('stops when a new popup exceeds the page summary limit', async ({ tools, toolsSite }) => { + const { origin } = toolsSite + const ref = await openForm(tools, origin) + await tools.inPage( + `${origin}/form`, + `for (let index = 0; index < 10; index++) { + const toolbar = document.createElement('div') + toolbar.setAttribute('role', 'toolbar') + toolbar.textContent = 'Toolbar ' + index + document.body.append(toolbar) + } + document.getElementById('name').addEventListener('input', () => { + const popup = document.createElement('div') + popup.setAttribute('role', 'listbox') + popup.textContent = 'Suggestions' + document.body.append(popup) + }, { once: true })` + ) - const fill = await execute('browser_fill_form', { + const fill = await tools.run('browser_fill_form', { fields: [ { elementId: ref('Name'), kind: 'text', text: 'Example User' }, { elementId: ref('Plan'), kind: 'select', value: 'pro' }, ], }) - expect(fill.ok, fill.error).toBe(true) - expect(fill.result, JSON.stringify(fill.result)).toMatchObject({ + expect(fill, JSON.stringify(fill)).toMatchObject({ completed: false, completedCount: 1, stoppedIndex: 0, @@ -1447,51 +1371,22 @@ test.describe('browser tools', () => { doNotRetry: true, error: expect.stringContaining('could not be fully verified'), }) - expect(await formState()).toMatchObject({ name: 'Example User', plan: 'basic' }) + expect(await formState(tools, origin)).toMatchObject({ name: 'Example User', plan: 'basic' }) }) - test('refuses credential fields and leaves subsequent fields untouched', async () => { - const ref = await openForm() - const fill = await execute('browser_fill_form', { + test('refuses credential fields and leaves subsequent fields untouched', async ({ + tools, + toolsSite, + }) => { + const { origin } = toolsSite + const ref = await openForm(tools, origin) + const fill = await tools.call('browser_fill_form', { fields: [ { elementId: ref('Password'), kind: 'text', text: 'must-not-be-entered' }, { elementId: ref('Name'), kind: 'text', text: 'Must not be written' }, ], }) expect(fill.result).toMatchObject({ completed: false, completedCount: 0 }) - expect(await formState()).toMatchObject({ name: '', password: '' }) - }) - test('local terminal executes through its native PTY and refuses repeated authorization', async () => { - await window.evaluate(async (scope) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - await api.terminal.activateScope(scope) - await api.terminal.openTerminal(undefined, scope) - }, SCOPE) - calls.set('local-cwd', { - chatId: SCOPE, - toolName: 'terminal', - args: { operation: 'cwd', args: {} }, - }) - const cwd = await window.evaluate(async (scope) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - return api.terminal.executeTool('local-cwd', 'cwd', {}, scope) - }, SCOPE) - expect(cwd.ok).toBe(true) - calls.set('local-run', { - chatId: SCOPE, - toolName: 'terminal', - args: { operation: 'run', args: { command: "printf 'SIM_NATIVE_TERMINAL_VERIFIED\\n'" } }, - }) - const result = await window.evaluate(async (scope) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - return api.terminal.executeTool('local-run', 'run', {}, scope) - }, SCOPE) - expect(result.ok).toBe(true) - expect(JSON.stringify(result)).toContain('SIM_NATIVE_TERMINAL_VERIFIED') - const replay = await window.evaluate(async (scope) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - return api.terminal.executeTool('local-run', 'run', {}, scope) - }, SCOPE) - expect(replay.ok).toBe(false) + expect(await formState(tools, origin)).toMatchObject({ name: '', password: '' }) }) }) diff --git a/apps/desktop/e2e/chat-panel.spec.ts b/apps/desktop/e2e/chat-panel.spec.ts index 9731e6011d2..090c31f66a9 100644 --- a/apps/desktop/e2e/chat-panel.spec.ts +++ b/apps/desktop/e2e/chat-panel.spec.ts @@ -1,146 +1,64 @@ -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { createServer } from 'node:http' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' -import { _electron as electron, expect, test } from '@playwright/test' -import type { SimDesktopApi } from '@sim/desktop-bridge' -import { getErrorMessage } from '@sim/utils/errors' -import { build } from 'esbuild' -import postcss from 'postcss' -import loadPostcssConfig from 'postcss-load-config' +import { bundleSimFixture, type DesktopBridge, expect, test } from './harness' +import { serveSignedIn } from './session-fixture' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) -const SIM_DIR = fileURLToPath(new URL('../../sim/', import.meta.url)) const FIXTURE = fileURLToPath(new URL('../../sim/scripts/fixtures/chat-panel.tsx', import.meta.url)) -test('chat panel sizes survive navigation, chat switches, collapse, and layout constraints', async () => { - const reportPath = process.env.CHAT_PANEL_REPORT_PATH ?? test.info().outputPath('chat-panel.json') - const checks: { - name: string - status: 'passed' | 'failed' - durationMs: number - error?: string - }[] = [] - const check = async (name: string, run: () => Promise) => { - const started = Date.now() - try { - await test.step(name, run) - checks.push({ name, status: 'passed', durationMs: Date.now() - started }) - } catch (error) { - checks.push({ - name, - status: 'failed', - durationMs: Date.now() - started, - error: getErrorMessage(error), - }) - throw error - } - } - const userData = mkdtempSync(join(tmpdir(), 'sim-chat-panel-e2e-')) - let app: Awaited> | undefined - const errors: string[] = [] - let desktopExit: { code: number | null; signal: string | null } | null = null - let rendererCrashed = false - let passed = false - let javascript = '' - let stylesheet = '' - const server = createServer((request, response) => { - const path = new URL(request.url ?? '/', 'http://localhost').pathname - if (path === '/page') { - response.setHeader('Content-Type', 'text/html') - response.end('Native browser resize fixture') - } else if (path === '/fixture.js' || path === '/fixture.css') { - response.setHeader('Content-Type', path.endsWith('.js') ? 'text/javascript' : 'text/css') - response.end(path.endsWith('.js') ? javascript : stylesheet) - } else if (path.startsWith('/api/')) { - response.setHeader('Content-Type', 'application/json') - response.end( - path === '/api/auth/get-session' - ? JSON.stringify({ user: { id: 'fixture-user' }, session: { id: 'fixture-session' } }) - : '{}' - ) - } else { - response.setHeader('Content-Type', 'text/html') - response.setHeader( - 'Set-Cookie', - 'better-auth.session_token=fixture; HttpOnly; SameSite=Lax; Path=/' - ) - response.end( - '
' - ) - } +test('chat panel sizes survive navigation, chat switches, collapse, and layout constraints', async ({ + desktop, +}) => { + const { js, css } = await bundleSimFixture({ file: FIXTURE }) + const fixture = await serveSignedIn({ + page: '
', + handle: (_request, response, url) => { + if (url.pathname === '/page') { + response.writeHead(200, { 'Content-Type': 'text/html' }) + response.end('Native browser resize fixture') + return true + } + if (url.pathname === '/fixture.js' || url.pathname === '/fixture.css') { + const script = url.pathname.endsWith('.js') + response.writeHead(200, { 'Content-Type': script ? 'text/javascript' : 'text/css' }) + response.end(script ? js : css) + return true + } + return false + }, }) - try { - await check('load the production resource panel resize hook in Electron', async () => { - const config = await loadPostcssConfig({}, SIM_DIR) - const cssPath = join(SIM_DIR, 'app/_styles/globals.css') - const css = await postcss(config.plugins).process( - `${readFileSync(cssPath, 'utf8')}\n@source ${JSON.stringify(FIXTURE)};`, - { from: cssPath } - ) - const bundle = await build({ - entryPoints: [FIXTURE], - bundle: true, - write: false, - outfile: test.info().outputPath('fixture.js'), - external: ['node:async_hooks'], - banner: { js: 'var process={env:{NODE_ENV:"development"},browser:true};' }, - format: 'iife', - platform: 'browser', - tsconfig: join(SIM_DIR, 'tsconfig.json'), - define: { 'process.env.NODE_ENV': '"development"' }, - }) - javascript = bundle.outputFiles.find((file) => file.path.endsWith('.js'))?.text ?? '' - stylesheet = `${css.css}\n${bundle.outputFiles.find((file) => file.path.endsWith('.css'))?.text ?? ''}` - await new Promise((resolve) => server.listen(0, resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - app = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { - ...process.env, - SIM_DESKTOP_ORIGIN: `http://127.0.0.1:${address.port}`, - SIM_DESKTOP_USER_DATA: userData, - }, - }) + const { app } = await desktop.launch({ + origin: fixture.origin, }) - if (!app) throw new Error('Electron did not launch') - app.process().once('exit', (code, signal) => { - desktopExit = { code, signal } - }) - const shell = app - const page = await shell.firstWindow() - const inputSession = await page.context().newCDPSession(page) + const page = await app.firstWindow() + const errors: string[] = [] page.on('pageerror', (error) => errors.push(error.message)) - page.on('crash', () => { - rendererCrashed = true - }) - await shell.evaluate(({ app, BrowserWindow }) => { + const inputSession = await page.context().newCDPSession(page) + const focusShell = async () => { + await app.evaluate(({ app, BrowserWindow }) => { + app.focus({ steal: true }) + BrowserWindow.getAllWindows()[0].focus() + }) + await expect + .poll(() => + app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].isFocused()) + ) + .toBe(true) + } + await app.evaluate(({ BrowserWindow }) => { const window = BrowserWindow.getAllWindows()[0] // Keep the physical window inside the small displays used by macOS CI. window.setMinimumSize(0, 0) window.setContentSize(720, 400) window.webContents.setBackgroundThrottling(false) - app.focus({ steal: true }) - window.focus() }) await page.reload() - await shell.evaluate(({ app, BrowserWindow }) => { - const window = BrowserWindow.getAllWindows()[0] - window.webContents.setZoomFactor(0.5) - app.focus({ steal: true }) - window.focus() - }) + await app.evaluate(({ BrowserWindow }) => + BrowserWindow.getAllWindows()[0].webContents.setZoomFactor(0.5) + ) expect(errors).toEqual([]) - await expect - .poll(() => - shell.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].isFocused()) - ) - .toBe(true) + await focusShell() await expect.poll(() => page.evaluate(() => window.innerWidth)).toBe(1440) + const storage = () => page.evaluate(() => JSON.stringify(localStorage)) const panel = page.locator('[data-mothership-panel]') const divider = page.getByRole('separator', { name: 'Resize resource view' }) const width = () => panel.evaluate((element) => element.getBoundingClientRect().width) @@ -148,15 +66,7 @@ test('chat panel sizes survive navigation, chat switches, collapse, and layout c await expect.poll(width).toBeCloseTo(expected, 0) } const beginDrag = async () => { - await shell.evaluate(({ app, BrowserWindow }) => { - app.focus({ steal: true }) - BrowserWindow.getAllWindows()[0].focus() - }) - await expect - .poll(() => - shell.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].isFocused()) - ) - .toBe(true) + await focusShell() await divider.hover({ position: { x: 4, y: 100 } }) const rect = await panel.boundingBox() if (!rect) throw new Error('Missing panel bounds') @@ -173,7 +83,7 @@ test('chat panel sizes survive navigation, chat switches, collapse, and layout c await expectWidth(target) } - await check('a chosen width survives a settings round trip and reload', async () => { + await test.step('a chosen width survives a settings round trip and reload', async () => { await expectWidth(720) await dragTo(620) await page.getByRole('button', { name: 'Settings', exact: true }).click() @@ -184,67 +94,61 @@ test('chat panel sizes survive navigation, chat switches, collapse, and layout c await expectWidth(620) }) - await check( - 'workspace and organization chats restore independent widths without remounting', - async () => { - await page.getByRole('button', { name: 'workspace-chat-b', exact: true }).click() - await expectWidth(720) - await dragTo(830) - await page.getByRole('button', { name: 'organization-chat-a', exact: true }).click() - await expectWidth(720) - await dragTo(560) - await page.getByRole('button', { name: 'Settings', exact: true }).click() - await page.getByRole('button', { name: 'Back', exact: true }).click() - await expectWidth(560) - await page.getByRole('button', { name: 'workspace-chat-a', exact: true }).click() - await expectWidth(620) - await page.getByRole('button', { name: 'workspace-chat-b', exact: true }).click() - await expectWidth(830) - } - ) + await test.step('workspace and organization chats restore independent widths without remounting', async () => { + await page.getByRole('button', { name: 'workspace-chat-b', exact: true }).click() + await expectWidth(720) + await dragTo(830) + await page.getByRole('button', { name: 'organization-chat-a', exact: true }).click() + await expectWidth(720) + await dragTo(560) + await page.getByRole('button', { name: 'Settings', exact: true }).click() + await page.getByRole('button', { name: 'Back', exact: true }).click() + await expectWidth(560) + await page.getByRole('button', { name: 'workspace-chat-a', exact: true }).click() + await expectWidth(620) + await page.getByRole('button', { name: 'workspace-chat-b', exact: true }).click() + await expectWidth(830) + }) - await check( - 'collapse preserves the expanded preference, including keyboard changes', - async () => { - await page.getByRole('button', { name: 'Collapse resource view' }).click() - await expectWidth(0) - await page.getByRole('button', { name: 'Expand resource view' }).click() - await expectWidth(830) - await divider.focus() - await page.keyboard.press('ArrowRight') - await expectWidth(798) - await page.getByRole('button', { name: 'Settings', exact: true }).click() - await page.getByRole('button', { name: 'Back', exact: true }).click() - await expectWidth(798) - } - ) + await test.step('collapse preserves the expanded preference, including keyboard changes', async () => { + await page.getByRole('button', { name: 'Collapse resource view' }).click() + await expectWidth(0) + await page.getByRole('button', { name: 'Expand resource view' }).click() + await expectWidth(830) + await divider.focus() + await page.keyboard.press('ArrowRight') + await expectWidth(798) + await page.getByRole('button', { name: 'Settings', exact: true }).click() + await page.getByRole('button', { name: 'Back', exact: true }).click() + await expectWidth(798) + }) - await check('container and window clamps do not overwrite the preferred width', async () => { + await test.step('container and window clamps do not overwrite the preferred width', async () => { await page.getByRole('button', { name: 'Resize container' }).click() await expectWidth(520) await page.getByRole('button', { name: 'Resize container' }).click() await expectWidth(798) - await shell.evaluate(({ BrowserWindow }) => + await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].setContentSize(525, 400) ) await expectWidth(570) await page.getByRole('button', { name: 'Settings', exact: true }).click() await page.getByRole('button', { name: 'Back', exact: true }).click() await expectWidth(570) - await shell.evaluate(({ BrowserWindow }) => + await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].setContentSize(720, 400) ) await expectWidth(798) }) - await check('resizing writes storage only when the gesture ends', async () => { - const before = await page.evaluate(() => JSON.stringify(localStorage)) + await test.step('resizing writes storage only when the gesture ends', async () => { + const before = await storage() const rect = await beginDrag() await page.mouse.move(rect.x + 100, rect.y + 100, { steps: 12 }) await expectWidth(698) - expect(await page.evaluate(() => JSON.stringify(localStorage))).toBe(before) + expect(await storage()).toBe(before) await page.mouse.up() - expect(await page.evaluate(() => JSON.stringify(localStorage))).not.toBe(before) + await expect.poll(storage).not.toBe(before) }) for (const interruption of [ @@ -255,69 +159,66 @@ test('chat panel sizes survive navigation, chat switches, collapse, and layout c 'chat switch', ] as const) { const keepsDraggedWidth = interruption === 'capture loss' || interruption === 'blur' - await check( - `${interruption} keeps the ${keepsDraggedWidth ? 'dragged' : 'previous saved'} width`, - async () => { - const before = await page.evaluate(() => JSON.stringify(localStorage)) - const rect = await beginDrag() - await page.mouse.move(rect.x + 100, rect.y + 100, { steps: 12 }) + await test.step(`${interruption} keeps the ${keepsDraggedWidth ? 'dragged' : 'previous saved'} width`, async () => { + const before = await storage() + const rect = await beginDrag() + await page.mouse.move(rect.x + 100, rect.y + 100, { steps: 12 }) + await expectWidth(598) + if (interruption === 'pointercancel') { + await divider.dispatchEvent('pointercancel', { pointerId: 1 }) + } else if (interruption === 'capture loss') { + await divider.evaluate((element) => element.releasePointerCapture(1)) + await page.mouse.move(rect.x + 100, rect.y + 100) + } else if (interruption === 'blur') { + // Reloads restore Playwright's focus emulation; native blur must reach the document. + await inputSession.send('Emulation.setFocusEmulationEnabled', { enabled: false }) + await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].blur()) + await expect.poll(() => page.evaluate(() => document.hasFocus())).toBe(false) + } else if (interruption === 'chat switch') { + await page + .getByRole('button', { name: 'organization-chat-a', exact: true }) + .evaluate((element: HTMLButtonElement) => element.click()) + await expectWidth(560) + } else { + await page + .getByRole('button', { name: 'Settings', exact: true }) + .evaluate((element: HTMLButtonElement) => element.click()) + await expect(panel).toHaveCount(0) + } + if (keepsDraggedWidth) { await expectWidth(598) - if (interruption === 'pointercancel') { - await divider.dispatchEvent('pointercancel', { pointerId: 1 }) - } else if (interruption === 'capture loss') { - await divider.evaluate((element) => element.releasePointerCapture(1)) - await page.mouse.move(rect.x + 100, rect.y + 100) - } else if (interruption === 'blur') { - // Reloads restore Playwright's focus emulation; native blur must reach the document. - await inputSession.send('Emulation.setFocusEmulationEnabled', { enabled: false }) - await shell.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].blur()) - await expect.poll(() => page.evaluate(() => document.hasFocus())).toBe(false) - } else if (interruption === 'chat switch') { - await page - .getByRole('button', { name: 'organization-chat-a', exact: true }) - .evaluate((element: HTMLButtonElement) => element.click()) - await expectWidth(560) - } else { - await page - .getByRole('button', { name: 'Settings', exact: true }) - .evaluate((element: HTMLButtonElement) => element.click()) - await expect(panel).toHaveCount(0) - } - if (keepsDraggedWidth) { - await expectWidth(598) - expect(await page.evaluate(() => JSON.stringify(localStorage))).not.toBe(before) - if (interruption === 'blur') { - await shell.evaluate(({ app, BrowserWindow }) => { - app.focus({ steal: true }) - BrowserWindow.getAllWindows()[0].focus() - }) - } - await page.mouse.move(rect.x + 150, rect.y + 100) - await expectWidth(598) - } - await page.mouse.up() - if (interruption === 'chat switch') { - await page.getByRole('button', { name: 'workspace-chat-b', exact: true }).click() - } - if (interruption === 'detach') { - await page.getByRole('button', { name: 'Back', exact: true }).click() - } - await expectWidth(keepsDraggedWidth ? 598 : 698) - if (keepsDraggedWidth) { - await page.reload() - await page.getByRole('button', { name: 'workspace-chat-b', exact: true }).click() - await expectWidth(598) - await dragTo(698) - } else { - expect(await page.evaluate(() => JSON.stringify(localStorage))).toBe(before) + await expect.poll(storage).not.toBe(before) + if (interruption === 'blur') { + await app.evaluate(({ app, BrowserWindow }) => { + app.focus({ steal: true }) + BrowserWindow.getAllWindows()[0].focus() + }) } + await page.mouse.move(rect.x + 150, rect.y + 100) + await expectWidth(598) } - ) + await page.mouse.up() + if (interruption === 'chat switch') { + await page.getByRole('button', { name: 'workspace-chat-b', exact: true }).click() + } + if (interruption === 'detach') { + await page.getByRole('button', { name: 'Back', exact: true }).click() + } + await expectWidth(keepsDraggedWidth ? 598 : 698) + if (keepsDraggedWidth) { + await page.reload() + await page.getByRole('button', { name: 'workspace-chat-b', exact: true }).click() + await expectWidth(598) + await dragTo(698) + } else { + expect(await storage()).toBe(before) + } + }) } for (const button of ['middle', 'right'] as const) { - await check(`${button}-button drags leave the panel width unchanged`, async () => { - const before = await page.evaluate(() => JSON.stringify(localStorage)) + await test.step(`${button}-button drags leave the panel width unchanged`, async () => { + const before = await storage() await divider.hover({ position: { x: 4, y: 100 } }) const rect = await panel.boundingBox() if (!rect) throw new Error('Missing panel bounds') @@ -325,11 +226,11 @@ test('chat panel sizes survive navigation, chat switches, collapse, and layout c await page.mouse.move(rect.x + 100, rect.y + 100, { steps: 12 }) await page.mouse.up({ button }) await expectWidth(698) - expect(await page.evaluate(() => JSON.stringify(localStorage))).toBe(before) + expect(await storage()).toBe(before) }) } - await check('a touch drag resizes the panel without becoming a scroll gesture', async () => { + await test.step('a touch drag resizes the panel without becoming a scroll gesture', async () => { const rect = await panel.boundingBox() if (!rect) throw new Error('Missing panel bounds') await inputSession.send('Emulation.setTouchEmulationEnabled', { enabled: true }) @@ -352,32 +253,32 @@ test('chat panel sizes survive navigation, chat switches, collapse, and layout c await dragTo(698) }) - await check('a viewport change during a drag clamps the committed display width', async () => { + await test.step('a viewport change during a drag clamps the committed display width', async () => { await expectWidth(698) const rect = await beginDrag() await page.mouse.move(rect.x + 20, rect.y + 100, { steps: 12 }) await expectWidth(678) - await shell.evaluate(({ BrowserWindow }) => + await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].setContentSize(500, 400) ) await expect.poll(() => page.evaluate(() => window.innerWidth)).toBe(1000) await page.mouse.up() await expectWidth(520) - await shell.evaluate(({ BrowserWindow }) => + await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].setContentSize(720, 400) ) await expectWidth(678) await dragTo(698) }) - await check('another account cannot inherit the current chat width', async () => { + await test.step('another account cannot inherit the current chat width', async () => { await page.getByRole('button', { name: 'Switch account' }).click() await expectWidth(720) await dragTo(580) await page.getByRole('button', { name: 'Switch account' }).click() await expectWidth(698) }) - await check('assigning a permanent chat ID lets an active drag finish', async () => { + await test.step('assigning a permanent chat ID lets an active drag finish', async () => { await page.getByRole('button', { name: 'pending:chat', exact: true }).click() await expectWidth(720) await dragTo(620) @@ -399,32 +300,32 @@ test('chat panel sizes survive navigation, chat switches, collapse, and layout c await expectWidth(698) }) - await check( - 'cancelling before the first animation frame restores native browser bounds', - async () => { + const nativeBounds = () => + app.evaluate(({ BrowserWindow, WebContentsView }) => { + const view = BrowserWindow.getAllWindows()[0].contentView.children.find( + (child) => + child instanceof WebContentsView && child.webContents.getURL().endsWith('/page') + ) + return view?.getVisible() ? view.getBounds() : null + }) + // The bridge round trip observes main-process geometry after the queued bounds messages. + const settleBounds = (scope: string) => + page.evaluate( + (scope) => + (globalThis as DesktopBridge).simDesktop.browserAgent.capturePanelSnapshot(scope), + scope + ) + + const before = + await test.step('cancelling before the first animation frame restores native browser bounds', async () => { await page.getByRole('button', { name: 'pending:native', exact: true }).click() await expectWidth(720) await dragTo(698) - await shell.evaluate(({ app, BrowserWindow }) => { - app.focus({ steal: true }) - BrowserWindow.getAllWindows()[0].focus() - }) - await expect - .poll(() => - shell.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].isFocused()) - ) - .toBe(true) + await focusShell() await page.getByRole('button', { name: 'Start browser', exact: true }).click() - const nativeBounds = () => - shell.evaluate(({ BrowserWindow, WebContentsView }) => { - const view = BrowserWindow.getAllWindows()[0].contentView.children.find( - (child) => - child instanceof WebContentsView && child.webContents.getURL().endsWith('/page') - ) - return view?.getVisible() ? view.getBounds() : null - }) await expect.poll(nativeBounds).not.toBeNull() - const before = await nativeBounds() + const bounds = await nativeBounds() + if (!bounds) throw new Error('Missing native browser bounds') await beginDrag() await divider.evaluate((element) => { const rect = element.getBoundingClientRect() @@ -433,61 +334,37 @@ test('chat panel sizes survive navigation, chat switches, collapse, and layout c ) element.dispatchEvent(new PointerEvent('pointercancel', { pointerId: 1, bubbles: true })) }) - // The bridge round trip observes main-process geometry after the queued bounds messages. - await page.evaluate(() => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.browserAgent.capturePanelSnapshot('pending:native') - ) + await settleBounds('pending:native') await page.mouse.up() await expectWidth(698) - expect(await nativeBounds()).toEqual(before) + expect(await nativeBounds()).toEqual(bounds) + return bounds + }) - await check('native predictions follow a chat ID assigned during a drag', async () => { - if (!before) throw new Error('Missing native browser bounds') - await beginDrag() - await page - .getByRole('button', { name: 'Assign chat ID', exact: true }) - .evaluate((element: HTMLButtonElement) => element.click()) - await expect( - page.getByRole('button', { name: 'Assign chat ID', exact: true }) - ).toBeDisabled() - expect(await divider.evaluate((element) => element.hasPointerCapture(1))).toBe(true) - await divider.evaluate((element) => { - const rect = element.getBoundingClientRect() - element.dispatchEvent( - new PointerEvent('pointermove', { - pointerId: 1, - clientX: rect.x + 104, - bubbles: true, - }) - ) - }) - await page.evaluate(() => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.browserAgent.capturePanelSnapshot('assigned-chat') - ) - expect(await nativeBounds()).toEqual({ - ...before, - x: before.x + 50, - width: before.width - 50, - }) - await page.mouse.up() - await expectWidth(598) - }) - } - ) + await test.step('native predictions follow a chat ID assigned during a drag', async () => { + await beginDrag() + await page + .getByRole('button', { name: 'Assign chat ID', exact: true }) + .evaluate((element: HTMLButtonElement) => element.click()) + await expect(page.getByRole('button', { name: 'Assign chat ID', exact: true })).toBeDisabled() + expect(await divider.evaluate((element) => element.hasPointerCapture(1))).toBe(true) + await divider.evaluate((element) => { + const rect = element.getBoundingClientRect() + element.dispatchEvent( + new PointerEvent('pointermove', { pointerId: 1, clientX: rect.x + 104, bubbles: true }) + ) + }) + await settleBounds('assigned-chat') + expect(await nativeBounds()).toEqual({ + ...before, + x: before.x + 50, + width: before.width - 50, + }) + await page.mouse.up() + await expectWidth(598) + }) expect(errors).toEqual([]) - passed = true } finally { - mkdirSync(dirname(reportPath), { recursive: true }) - writeFileSync( - reportPath, - JSON.stringify({ passed, checks, errors, desktopExit, rendererCrashed }, null, 2) - ) - await app?.close() - await new Promise((resolve) => server.close(() => resolve())) - rmSync(userData, { recursive: true, force: true }) + await fixture.close() } }) diff --git a/apps/desktop/e2e/check-report.spec.ts b/apps/desktop/e2e/check-report.spec.ts deleted file mode 100644 index dc2a6378255..00000000000 --- a/apps/desktop/e2e/check-report.spec.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { spawnSync } from 'node:child_process' -import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs' -import { createRequire } from 'node:module' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { expect, test } from '@playwright/test' -import { omit } from '@sim/utils/object' -import type { ReportCheck } from './check-report' - -/** - * The suites' JSON reports against a real worker restart: a nested Playwright run of a fixture - * whose first test fails, so the second runs in a fresh worker with fresh module state. The report - * must keep the failure, and must not carry checks from an earlier run. - */ -const CLI = createRequire(import.meta.url).resolve('@playwright/test/cli') -const CONFIG = fileURLToPath(new URL('./fixtures/worker-restart.config.ts', import.meta.url)) - -test('a check that failed before the worker restarted stays in the report', () => { - const reportPath = join(mkdtempSync(join(tmpdir(), 'sim-check-report-')), 'report.json') - writeFileSync( - reportPath, - JSON.stringify({ - suite: 'worker-restart', - run: -1, - checks: [{ name: 'left by an earlier run', status: 'passed', durationMs: 0 }], - }) - ) - // The outer run's worker variables would make the nested runner think it is a worker. - const env = omit( - process.env, - Object.keys(process.env).filter((key) => /^(TEST_|PW_)/.test(key)) - ) - - const run = spawnSync(process.execPath, [CLI, 'test', '--config', CONFIG], { - env: { ...env, WORKER_RESTART_REPORT_PATH: reportPath }, - encoding: 'utf8', - timeout: 60_000, - }) - - expect(run.status, run.stdout + run.stderr).toBe(1) - const checks = (JSON.parse(readFileSync(reportPath, 'utf8')) as { checks: ReportCheck[] }).checks - expect(checks.map(({ name, status }) => ({ name, status }))).toEqual([ - { name: 'fails first', status: 'failed' }, - { name: 'passes after the worker restarts', status: 'passed' }, - ]) - // Proof the second check ran in a replacement worker, not the one that failed. - expect(checks[0]?.error).not.toBe(checks[1]?.error) -}) diff --git a/apps/desktop/e2e/check-report.ts b/apps/desktop/e2e/check-report.ts deleted file mode 100644 index 5fd3692f70c..00000000000 --- a/apps/desktop/e2e/check-report.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { readFileSync, writeFileSync } from 'node:fs' - -/** One check's outcome in a suite's JSON report. */ -export interface ReportCheck { - name: string - status: string - durationMs: number - error?: string - retry?: number -} - -interface Report { - suite: string - /** The Playwright run that wrote it: its workers' parent process. */ - run: number - checks: ReportCheck[] -} - -/** - * Adds a check to the suite's report at `reportPath` as soon as its outcome is known, keeping the - * checks already there from the same run. - * - * Playwright replaces a worker after a failure, and the new one starts with empty module state, so - * a report kept in memory and written at the end would drop everything before the failure, the - * failure included, and could read green. The file holds it instead. Every worker of one run is a - * child of the same runner, so a report left by an earlier run is replaced rather than added to. - */ -export function recordCheck( - reportPath: string | undefined, - suite: string, - check: ReportCheck -): void { - if (!reportPath) return - const run = process.ppid - let checks: ReportCheck[] = [] - try { - const existing = JSON.parse(readFileSync(reportPath, 'utf8')) as Report - if (existing.suite === suite && existing.run === run) checks = existing.checks - } catch { - // No report yet from this run. - } - const report: Report = { suite, run, checks: [...checks, check] } - writeFileSync(reportPath, JSON.stringify(report, null, 2)) -} diff --git a/apps/desktop/e2e/computer-use.spec.ts b/apps/desktop/e2e/computer-use.spec.ts index d171febdf3d..4c68e863b36 100644 --- a/apps/desktop/e2e/computer-use.spec.ts +++ b/apps/desktop/e2e/computer-use.spec.ts @@ -1,20 +1,27 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { createServer, type Server } from 'node:http' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { type ElectronApplication, _electron as electron, expect, test } from '@playwright/test' -import type { SimDesktopApi } from '@sim/desktop-bridge' +import type { Page } from '@playwright/test' +import { type DesktopBridge, expect, test } from './harness' +import { serveSignedIn } from './session-fixture' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) +/** Runs a computer tool call from the page; resolves 'rejected' when the desktop refuses it. */ +function runTool(window: Page, toolCallId: string): Promise { + return window.evaluate(async (toolCallId) => { + const api = (globalThis as DesktopBridge).simDesktop + try { + await api.computerUse?.executeTool(toolCallId, { action: 'status' }) + return 'unexpected success' + } catch { + return 'rejected' + } + }, toolCallId) +} -test('computer use reaches the actual helper only with canonical one-shot authorization', async () => { +test('computer use reaches the actual helper only with canonical one-shot authorization', async ({ + desktop, +}) => { test.skip(process.platform !== 'darwin', 'The native helper is macOS-only.') - const root = mkdtempSync(join(tmpdir(), 'sim-computer-use-e2e-')) - let server: Server | undefined - let app: ElectronApplication | undefined let claimed = false - let authorizationCount = 0 + /** The body of every authorization request, checked in the test rather than the handler. */ + const authorizationBodies: unknown[] = [] let releaseAuthorization: () => void = () => {} let markAuthorizationStarted: () => void = () => {} const authorizationStarted = new Promise((resolve) => { @@ -23,128 +30,82 @@ test('computer use reaches the actual helper only with canonical one-shot author const authorizationReleased = new Promise((resolve) => { releaseAuthorization = resolve }) - try { - server = createServer(async (request, response) => { - const path = new URL(request.url ?? '/', 'http://127.0.0.1').pathname - if (path === '/api/auth/get-session') { - response.writeHead(200, { 'Content-Type': 'application/json' }).end( - JSON.stringify({ - user: { id: 'computer-test' }, - session: { id: 'computer-test-session' }, - }) - ) - return + const fixture = await serveSignedIn({ + page: `Computer Use fixture

Computer Use

`, + handle: async (request, response, url) => { + if (url.pathname !== '/api/desktop/computer/authorize') return false + let body = '' + for await (const chunk of request) body += chunk.toString() + const input = JSON.parse(body) + authorizationBodies.push(input) + if (Object.keys(input).join() !== 'toolCallId') { + response.writeHead(400, { 'Content-Type': 'application/json' }).end('{}') + return true } - if (path === '/api/desktop/computer/authorize') { - authorizationCount += 1 - let body = '' - for await (const chunk of request) body += chunk.toString() - const input = JSON.parse(body) - expect(Object.keys(input)).toEqual(['toolCallId']) - if (input.toolCallId === 'delayed') { - markAuthorizationStarted() - await authorizationReleased - } else if (input.toolCallId !== 'status-once' || claimed) { - response.writeHead(403, { 'Content-Type': 'application/json' }).end('{}') - return - } - claimed = true - response.writeHead(200, { 'Content-Type': 'application/json' }).end( - JSON.stringify({ - chatId: 'computer-chat', - toolName: 'computer', - args: { action: 'status' }, - }) - ) - return + if (input.toolCallId === 'delayed') { + markAuthorizationStarted() + await authorizationReleased + } else if (input.toolCallId !== 'status-once' || claimed) { + response.writeHead(403, { 'Content-Type': 'application/json' }).end('{}') + return true } - response - .writeHead(200, { - 'Content-Type': 'text/html', - 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; SameSite=Lax; Path=/', + claimed = true + response.writeHead(200, { 'Content-Type': 'application/json' }).end( + JSON.stringify({ + chatId: 'computer-chat', + toolName: 'computer', + args: { action: 'status' }, }) - .end( - `Computer Use fixture

Computer Use

` - ) - }) - await new Promise((resolve) => server?.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing local fixture port') - const profile = join(root, 'profile') - mkdirSync(profile) - writeFileSync( - join(profile, 'settings.json'), - JSON.stringify({ origin: `http://127.0.0.1:${address.port}`, computerUseEnabled: true }) - ) - app = await electron.launch({ - args: ['.'], - cwd: DESKTOP_DIR, - env: { - ...process.env, - SIM_DESKTOP_ORIGIN: `http://127.0.0.1:${address.port}`, - SIM_DESKTOP_USER_DATA: profile, - }, + ) + return true + }, + }) + try { + const { app } = await desktop.launch({ + origin: fixture.origin, + settings: { origin: fixture.origin, computerUseEnabled: true }, }) const window = await app.firstWindow() await expect(window.getByRole('heading')).toHaveText('Computer Use') - const status = await window.evaluate(async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - return api.computerUse?.getStatus() - }) - expect(status).toMatchObject({ supported: true, enabled: true, activeAction: null }) - const result = await window.evaluate(async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - return api.computerUse?.executeTool('status-once', { - action: 'get_app_state', - bundleId: 'com.apple.systempreferences', - }) - }) - expect(result).toMatchObject({ kind: 'status', platform: 'darwin' }) - const replay = await window.evaluate(async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - try { - await api.computerUse?.executeTool('status-once', { action: 'status' }) - return 'unexpected success' - } catch { - return 'rejected' - } - }) - expect(replay).toBe('rejected') - expect(authorizationCount).toBe(2) - const delayed = window.evaluate(async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - try { - await api.computerUse?.executeTool('delayed', { action: 'status' }) - return 'unexpected success' - } catch { - return 'stopped' - } + + await test.step('an authorized call reaches the helper once and a replay is refused', async () => { + const status = await window.evaluate(() => + (globalThis as DesktopBridge).simDesktop.computerUse?.getStatus() + ) + expect(status).toMatchObject({ supported: true, enabled: true, activeAction: null }) + const result = await window.evaluate(() => + (globalThis as DesktopBridge).simDesktop.computerUse?.executeTool('status-once', { + action: 'get_app_state', + bundleId: 'com.apple.systempreferences', + }) + ) + expect(result).toMatchObject({ kind: 'status', platform: 'darwin' }) + expect(await runTool(window, 'status-once')).toBe('rejected') + expect(authorizationBodies).toEqual([ + { toolCallId: 'status-once' }, + { toolCallId: 'status-once' }, + ]) }) - await authorizationStarted - await window.evaluate(async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - await api.computerUse?.cancel('delayed') + + await test.step('cancelling while authorization is pending stops the call', async () => { + const delayed = runTool(window, 'delayed') + await authorizationStarted + await window.evaluate(() => + (globalThis as DesktopBridge).simDesktop.computerUse?.cancel('delayed') + ) + releaseAuthorization() + expect(await delayed).toBe('rejected') + expect(authorizationBodies).toHaveLength(3) }) - releaseAuthorization() - expect(await delayed).toBe('stopped') - expect(authorizationCount).toBe(3) - await window.getByRole('button', { name: 'Disable Computer Use' }).click() - await expect(window.locator('#status')).toHaveText('false') - const disabled = await window.evaluate(async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - try { - await api.computerUse?.executeTool('disabled', { action: 'status' }) - return 'unexpected success' - } catch { - return 'rejected' - } + + await test.step('turning computer use off refuses calls before asking Sim', async () => { + await window.getByRole('button', { name: 'Disable Computer Use' }).click() + await expect(window.locator('#status')).toHaveText('false') + expect(await runTool(window, 'disabled')).toBe('rejected') + expect(authorizationBodies).toHaveLength(3) }) - expect(disabled).toBe('rejected') - expect(authorizationCount).toBe(3) } finally { releaseAuthorization() - await app?.close() - await new Promise((resolve) => (server ? server.close(() => resolve()) : resolve())) - rmSync(root, { recursive: true, force: true }) + await fixture.close() } }) diff --git a/apps/desktop/e2e/continue-sign-in.spec.ts b/apps/desktop/e2e/continue-sign-in.spec.ts index c1954da5736..0a157a8535d 100644 --- a/apps/desktop/e2e/continue-sign-in.spec.ts +++ b/apps/desktop/e2e/continue-sign-in.spec.ts @@ -1,13 +1,7 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { createServer, type Server } from 'node:http' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { type ElectronApplication, _electron as electron, expect, test } from '@playwright/test' -import type { SimDesktopApi } from '@sim/desktop-bridge' -import { recordCheck } from './check-report' +import type { ElectronApplication, Page } from '@playwright/test' +import { type DesktopBridge, expect, type FixtureServer, test } from './harness' +import { serveSignedIn } from './session-fixture' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) const SCOPE = 'continue-sign-in-fixture' /** @@ -20,38 +14,13 @@ const SCOPE = 'continue-sign-in-fixture' * covered by the importer's fixture-database tests instead. */ test.describe('continue a sign-in in another browser', () => { - let server: Server - let origin: string - let site: string - let home: string - let userData: string - let app: ElectronApplication | undefined + let fixture: FixtureServer + let app: ElectronApplication + let page: Page test.beforeAll(async () => { - server = createServer((request, response) => { - const path = new URL(request.url ?? '/', 'http://localhost').pathname - if (path === '/api/auth/get-session') { - response.writeHead(200, { 'Content-Type': 'application/json' }) - response.end( - JSON.stringify({ user: { id: 'fixture-user' }, session: { id: 'fixture-session' } }) - ) - return - } - if (path.startsWith('/api/')) { - response.writeHead(200, { 'Content-Type': 'application/json' }) - response.end('{}') - return - } - if (request.headers.host?.startsWith('localhost')) { - response.writeHead(200, { 'Content-Type': 'text/html' }) - response.end('Sign in

Sign in

') - return - } - response.writeHead(200, { - 'Content-Type': 'text/html', - 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; SameSite=Lax; Path=/', - }) - response.end(`Sim fixture

Continue fixture

+ fixture = await serveSignedIn({ + page: `Sim fixture

Continue fixture

`) +`, + handle: (request, response, url) => { + if (url.pathname.startsWith('/api/') || !request.headers.host?.startsWith('localhost')) { + return false + } + response.writeHead(200, { 'Content-Type': 'text/html' }) + response.end('Sign in

Sign in

') + return true + }, }) - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - origin = `http://127.0.0.1:${address.port}` - site = `http://localhost:${address.port}` }) - test.beforeEach(async () => { - home = mkdtempSync(join(tmpdir(), 'sim-continue-home-')) - userData = mkdtempSync(join(tmpdir(), 'sim-continue-e2e-')) - app = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { - ...process.env, - HOME: home, - SIM_DESKTOP_ORIGIN: origin, - SIM_DESKTOP_USER_DATA: userData, - }, - }) - const page = await app.firstWindow() + test.afterAll(async () => { + await fixture.close() + }) + + test.beforeEach(async ({ desktop }) => { + ;({ app } = await desktop.launch({ + origin: fixture.origin, + env: { HOME: desktop.tempDir('sim-continue-home-') }, + })) + page = await app.firstWindow() await expect(page.getByRole('heading')).toHaveText('Continue fixture') await page.evaluate(async (scope) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop + const api = (globalThis as DesktopBridge).simDesktop await api.browserAgent.activateScope(scope) api.browserAgent.setPanelBounds({ x: 0, y: 120, width: 800, height: 400 }, null, scope) }, SCOPE) }) - test.afterEach(async () => { - const testInfo = test.info() - recordCheck(process.env.CONTINUE_SIGN_IN_REPORT_PATH, 'continue-sign-in', { - name: testInfo.title, - status: testInfo.status ?? 'unknown', - durationMs: testInfo.duration, - retry: testInfo.retry, - }) - await app?.close() - app = undefined - rmSync(userData, { recursive: true, force: true }) - rmSync(home, { recursive: true, force: true }) - }) - - test.afterAll(async () => { - await new Promise((resolve, reject) => - server.close((error) => (error ? reject(error) : resolve())) - ) - }) - - test('advertises the capability, but offers no browser when none is installed', async () => { - const page = await app?.firstWindow() - const surface = await page?.evaluate(async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop + test('advertises the capability without a browser to offer, and refuses calls without the user', async () => { + const surface = await page.evaluate(async (scope) => { + const api = (globalThis as DesktopBridge).simDesktop return { continueSignIn: typeof api.browserImport?.continueSignIn, bringSignInBack: typeof api.browserImport?.bringSignInBack, - pending: await api.browserImport?.getPendingSignIn?.('continue-sign-in-fixture'), + pending: await api.browserImport?.getPendingSignIn?.(scope), profiles: await api.browserImport?.listChromeProfiles(), + // Page script calling straight in, with no user gesture behind it. + continued: await api.browserImport?.continueSignIn?.('chrome:Default', scope), + broughtBack: await api.browserImport?.bringSignInBack?.(scope), } - }) + }, SCOPE) expect(surface).toEqual({ continueSignIn: 'function', bringSignInBack: 'function', pending: null, profiles: [], - }) - }) - - test('refuses page script that acts without the user', async () => { - const page = await app?.firstWindow() - const results = await page?.evaluate(async (scope) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - return { - continued: await api.browserImport?.continueSignIn?.('chrome:Default', scope), - broughtBack: await api.browserImport?.bringSignInBack?.(scope), - } - }, SCOPE) - - expect(results).toEqual({ continued: { error: 'unknown' }, broughtBack: { cookiesImported: 0, cookiesSkipped: 0, error: 'unknown' }, }) }) test('reads the page from the tab itself and hands over only https', async () => { - const page = await app?.firstWindow() - if (!page || !app) throw new Error('App did not launch') const read = (key: string) => page.evaluate((name) => Reflect.get(globalThis, name), key) await page.locator('#open').click() await expect.poll(() => read('opened')).toMatchObject({ activeTabId: expect.any(String) }) await expect .poll(() => - app?.evaluate( + app.evaluate( ({ webContents }, target) => webContents.getAllWebContents().some((contents) => contents.getURL() === target), - `${site}/login` + `${fixture.site}/login` ) ) .toBe(true) diff --git a/apps/desktop/e2e/desktop-tools-live-sim.spec.ts b/apps/desktop/e2e/desktop-tools-live-sim.spec.ts index c396d8104a4..01cf40f3098 100644 --- a/apps/desktop/e2e/desktop-tools-live-sim.spec.ts +++ b/apps/desktop/e2e/desktop-tools-live-sim.spec.ts @@ -1,18 +1,9 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' +import { mkdirSync, writeFileSync } from 'node:fs' import { dirname, join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { - type ElectronApplication, - _electron as electron, - expect, - type Locator, - type Page, - test, -} from '@playwright/test' -import type { SimDesktopApi } from '@sim/desktop-bridge' +import type { Locator, Page } from '@playwright/test' import { sleep } from '@sim/utils/helpers' import { generateId } from '@sim/utils/id' +import { answerShellDialog } from './executor-sim' import { type LiveSimConfig, liveSimConfig, @@ -22,6 +13,7 @@ import { SimDatabase, SimProxy, } from './fixtures/live-sim' +import { type DesktopApp, type DesktopBridge, type DesktopFixture, expect, test } from './harness' /** * Desktop tools in the real Electron app against a real local Sim: the renderer is Sim's own chat @@ -37,7 +29,6 @@ import { * The tests marked as running in the background let Sim's own answer through. */ -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) const config = liveSimConfig() const PICKUP_GRACE_MS = 15_000 /** Longer than the default tool budget (60 s) plus the resume grace (30 s). */ @@ -48,15 +39,17 @@ const LEASE_MS = 60_000 const ARRIVAL_MS = 60_000 /** First requests to a route compile it, which takes minutes on a cold dev app. */ const COMPILE_MS = 300_000 +/** The warm-up's budget: every route it reaches may compile from cold. */ +const WARM_UP_MS = 1_500_000 const REGISTRATION_PATH = '/api/desktop/devices' const DESKTOP_COMPLETION_PATH = '/api/desktop/tool/complete' +/** The title of the shell dialog asking to allow a folder. */ +const FOLDER_CONSENT_TITLE = 'Allow access to this folder?' /** Sim's answer to registration on an install that cannot run the background executor. */ const executorUnavailable = (answer: Record) => { answer.enabled = false } -type DesktopWindow = typeof globalThis & { simDesktop: SimDesktopApi } - test.describe('desktop tools against a live Sim', () => { test.skip(typeof config === 'string', typeof config === 'string' ? config : '') test.describe.configure({ timeout: 360_000 }) @@ -65,14 +58,14 @@ test.describe('desktop tools against a live Sim', () => { let proxy: SimProxy let agent: ScriptedAgent let db: SimDatabase - let app: ElectronApplication | undefined + let launched: DesktopApp | undefined + let warmedUp = process.env.SIM_DESKTOP_E2E_APP_SERVER === 'start' let scratch: string /** Errors the current window reported, shown when a click is blocked. */ let pageErrors: string[] = [] let testStartedAt = 0 test.beforeAll(async () => { - test.setTimeout(1_500_000) if (typeof config === 'string') throw new Error(config) sim = config proxy = new SimProxy(sim) @@ -80,23 +73,29 @@ test.describe('desktop tools against a live Sim', () => { db = new SimDatabase(sim) await Promise.all([proxy.start(), agent.start()]) proxy.rewriteAnswer(REGISTRATION_PATH, executorUnavailable) - if (process.env.SIM_DESKTOP_E2E_APP_SERVER !== 'start') - await test.step('warm up the routes the tests use', warmUp) }) test.afterAll(async () => { await Promise.all([proxy?.stop(), agent?.stop(), db?.close()]) }) - test.beforeEach(() => { + // The warm-up launches the app, which only a test's fixtures can do, so the first test runs it + // with the time it takes added to its own. + test.beforeEach(async ({ desktop }) => { + if (!warmedUp) { + // Once per worker even if it fails: the failure is this test's, not every test's. + warmedUp = true + test.setTimeout(test.info().timeout + WARM_UP_MS) + await test.step('warm up the routes the tests use', () => warmUp(desktop)) + } testStartedAt = Date.now() - scratch = mkdtempSync(join(tmpdir(), 'sim-desktop-tools-live-')) + scratch = desktop.tempDir('sim-desktop-tools-live-') }) test.afterEach(async () => { const testInfo = test.info() if (testInfo.status !== testInfo.expectedStatus) { - const page = app?.windows()[0] + const page = launched?.app.windows()[0] await page?.screenshot({ path: testInfo.outputPath('failure.png') }).catch(() => {}) writeFileSync( testInfo.outputPath('diagnostics.json'), @@ -120,11 +119,9 @@ test.describe('desktop tools against a live Sim', () => { } proxy.clearHolds() proxy.restoreNetwork() - await app?.close().catch(() => {}) - app = undefined + launched = undefined proxy.rewriteAnswer(REGISTRATION_PATH, executorUnavailable) proxy.rewriteAnswer(DESKTOP_COMPLETION_PATH, undefined) - rmSync(scratch, { recursive: true, force: true }) }) /** @@ -135,8 +132,8 @@ test.describe('desktop tools against a live Sim', () => { * so no route the tests reach is left to compile. It ends with a marker request * (`/api/health?e2e=warm-up-done`) so the dev server's log shows anything compiled after it. */ - async function warmUp(): Promise { - scratch = mkdtempSync(join(tmpdir(), 'sim-desktop-tools-warm-')) + async function warmUp(desktop: DesktopFixture): Promise { + scratch = desktop.tempDir('sim-desktop-tools-warm-') try { const user = await db.seedUser(['Warm chat', 'Warm other chat']) const headers = { @@ -208,7 +205,7 @@ test.describe('desktop tools against a live Sim', () => { // The leg stays open until Stop ends it. await turn.closed }) - const page = await openApp(user, 'Warm chat', COMPILE_MS) + const page = await openApp(desktop, user, 'Warm chat', COMPILE_MS) await send(page, '[warm-up] read and import', COMPILE_MS) await expect(page.getByText('Warming up.')).toBeVisible({ timeout: COMPILE_MS }) // Leaving and reopening a chat while its turn runs re-attaches to the turn's stream. @@ -225,33 +222,45 @@ test.describe('desktop tools against a live Sim', () => { await proxy.settled(COMPILE_MS) await compile('/api/health?e2e=warm-up-done') } finally { - await app?.close().catch(() => {}) - app = undefined - rmSync(scratch, { recursive: true, force: true }) + if (launched) await desktop.close(launched) + launched = undefined } } const chatPath = (user: SeededUser, title: string) => `/workspace/${user.workspaceId}/chat/${user.chats[title]}` + /** + * Allows the folder when `window` is the folder consent dialog, as the user would; any other + * window is left alone. + */ + async function allowFolderConsent(window: Page): Promise { + await window.waitForLoadState('domcontentloaded') + if (!window.url().endsWith('/dialog.html')) return + // The dialog takes its title before it renders. + await window.getByRole('dialog').waitFor() + if ((await window.title()) !== FOLDER_CONSENT_TITLE) return + await answerShellDialog(window, 'Allow folder') + } + /** Launches the app signed in as `user`, showing the chat titled `title`. */ - async function openApp(user: SeededUser, title: string, timeout = 120_000): Promise { - app = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { - ...process.env, - SIM_DESKTOP_ORIGIN: proxy.origin, - SIM_DESKTOP_USER_DATA: join(scratch, 'profile'), - }, + async function openApp( + desktop: DesktopFixture, + user: SeededUser, + title: string, + timeout = 120_000 + ): Promise { + launched = await desktop.launch({ + origin: proxy.origin, }) + const { app } = launched const page = await app.firstWindow({ timeout }) pageErrors = [] - app.on('window', (permission) => { - void permission - .getByRole('button', { name: 'Allow folder', exact: true }) - .click({ timeout: 10_000 }) - .catch((error) => pageErrors.push(`Folder approval failed: ${String(error)}`)) + app.on('window', (window) => { + void allowFolderConsent(window).catch((error: unknown) => { + // A dialog the app closes itself, such as on Stop, is not a failed approval. + if (!window.isClosed()) pageErrors.push(`Folder approval failed: ${String(error)}`) + }) }) page.on('pageerror', (error) => pageErrors.push(error.message)) page.on('console', (message) => { @@ -392,7 +401,9 @@ test.describe('desktop tools against a live Sim', () => { const isToolReport = (method: string, path: string) => method === 'POST' && path === '/api/copilot/confirm' - test('a browser call issued after the user switched chats fails as not started after the pickup grace', async () => { + test('a browser call issued after the user switched chats fails as not started after the pickup grace', async ({ + desktop, + }) => { const user = await db.seedUser(['Browser chat', 'Other chat']) let issue!: () => void const issued = new Promise((resolve) => { @@ -407,7 +418,7 @@ test.describe('desktop tools against a live Sim', () => { issuedAt = Date.now() turn.pause() }) - const page = await openApp(user, 'Browser chat') + const page = await openApp(desktop, user, 'Browser chat') await send(page, '[pickup-grace] which tabs are open?') await expect(page.getByText('Checking your browser tabs.')).toBeVisible({ timeout: 60_000 }) await openChat(page, user, 'Other chat') @@ -424,7 +435,7 @@ test.describe('desktop tools against a live Sim', () => { expect(call).toMatchObject({ toolName: 'browser_list_tabs', status: 'failed', claimedBy: null }) }) - test('leaving the chat does not end a local file read already under way', async () => { + test('leaving the chat does not end a local file read already under way', async ({ desktop }) => { const user = await db.seedUser(['Read chat', 'Other chat']) const marker = generateId() const file = writeFile(join(scratch, 'notes.txt'), `notes from disk ${marker}`) @@ -433,7 +444,7 @@ test.describe('desktop tools against a live Sim', () => { callId = turn.toolCall({ toolName: 'read_local_file', args: { path: file } }) turn.pause() }) - const page = await openApp(user, 'Read chat') + const page = await openApp(desktop, user, 'Read chat') // Visit the other chat once, so leaving for it later is a quick client-side switch. await openChat(page, user, 'Other chat') await openChat(page, user, 'Read chat') @@ -458,7 +469,9 @@ test.describe('desktop tools against a live Sim', () => { expect(call).toMatchObject({ toolName: 'read_local_file', status: 'completed' }) }) - test('an import keeps running across chat switches, and Stop from the reopened chat ends it', async () => { + test('an import keeps running across chat switches, and Stop from the reopened chat ends it', async ({ + desktop, + }) => { const user = await db.seedUser(['Import chat', 'Other chat']) const chatId = user.chats['Import chat'] const source = importSource() @@ -469,7 +482,7 @@ test.describe('desktop tools against a live Sim', () => { }) turn.pause() }) - const page = await openApp(user, 'Import chat') + const page = await openApp(desktop, user, 'Import chat') const firstUpload = proxy.hold(isUploadStart) await send(page, '[stop-import] import my reports') await firstUpload.arrival(ARRIVAL_MS, 'The first upload') @@ -505,7 +518,12 @@ test.describe('desktop tools against a live Sim', () => { }) /** An import whose first upload the proxy holds until released, as a large file's would take. */ - async function slowImport(user: SeededUser, title: string, marker: string) { + async function slowImport( + desktop: DesktopFixture, + user: SeededUser, + title: string, + marker: string + ) { const source = importSource() let callId = '' agent.script(marker, (turn) => { @@ -515,18 +533,21 @@ test.describe('desktop tools against a live Sim', () => { }) turn.pause() }) - const page = await openApp(user, title) + const page = await openApp(desktop, user, title) const firstUpload = proxy.hold(isUploadStart) await send(page, `${marker} import my reports`) await firstUpload.arrival(ARRIVAL_MS, 'The first upload') return { page, firstUpload, callId: () => callId } } - test('an import that runs longer than the default tool budget still completes', async () => { + test('an import that runs longer than the default tool budget still completes', async ({ + desktop, + }) => { test.setTimeout(420_000) const user = await db.seedUser(['Long import chat', 'Other chat']) const chatId = user.chats['Long import chat'] const { page, firstUpload, callId } = await slowImport( + desktop, user, 'Long import chat', '[long-import]' @@ -548,16 +569,18 @@ test.describe('desktop tools against a live Sim', () => { expect(await callState(chatId)).toMatch(/^completed/) }) - test('a long import whose window crashed settles as outcome unknown about one lease later @lease-lapse', async () => { + test('a long import whose window crashed settles as outcome unknown about one lease later @lease-lapse', async ({ + desktop, + }) => { test.setTimeout(420_000) const user = await db.seedUser(['Crashing import chat']) - const { callId } = await slowImport(user, 'Crashing import chat', '[crash-import]') + const { callId } = await slowImport(desktop, user, 'Crashing import chat', '[crash-import]') await sleep(LONG_IMPORT_MS) expect(agent.resultFor(callId())).toBeUndefined() // A crash reports nothing on its way out, unlike a closed window: only the lapse of the // lease the page was renewing tells Sim the import is gone. const crashedAt = Date.now() - await app?.evaluate(({ webContents }) => { + await launched?.app.evaluate(({ webContents }) => { for (const contents of webContents.getAllWebContents()) if (contents.getURL().includes('/workspace/')) contents.forcefullyCrashRenderer() }) @@ -567,7 +590,7 @@ test.describe('desktop tools against a live Sim', () => { expect((result?.at ?? 0) - crashedAt).toBeLessThan(LEASE_MS + 20_000) }) - test('signing out ends a desktop tool still running', async () => { + test('signing out ends a desktop tool still running', async ({ desktop }) => { const user = await db.seedUser(['Import chat']) const chatId = user.chats['Import chat'] const source = importSource() @@ -578,7 +601,7 @@ test.describe('desktop tools against a live Sim', () => { }) turn.pause() }) - const page = await openApp(user, 'Import chat') + const page = await openApp(desktop, user, 'Import chat') const firstUpload = proxy.hold(isUploadStart) await send(page, '[sign-out-import] import my reports') await firstUpload.arrival(ARRIVAL_MS, 'The first upload') @@ -625,73 +648,75 @@ test.describe('desktop tools against a live Sim', () => { return call } - test("a local read awaiting the user's approval cannot be claimed", async () => { - const user = await db.seedUser(['Approval chat']) - const secret = generateId() - const file = writeFile(join(scratch, 'secret.txt'), `private ${secret}`) - agent.script('[unapproved-read]', (turn) => { - turn.toolCall({ - toolName: 'read_local_file', - args: { path: file }, - status: 'awaiting_approval', + test("a local read or terminal command awaiting the user's approval cannot be claimed", async ({ + desktop, + }) => { + const user = await db.seedUser(['Read approval chat', 'Run approval chat']) + const page = await openApp(desktop, user, 'Read approval chat') + + await test.step('a local read', async () => { + const secret = generateId() + const file = writeFile(join(scratch, 'secret.txt'), `private ${secret}`) + agent.script('[unapproved-read]', (turn) => { + turn.toolCall({ + toolName: 'read_local_file', + args: { path: file }, + status: 'awaiting_approval', + }) + turn.pause() }) - turn.pause() + const chatId = user.chats['Read approval chat'] + const read = await gatedCall( + page, + chatId, + '[unapproved-read] read my secret', + 'read_local_file' + ) + // A renderer acting on a call the user has not allowed (a replayed event) is refused. + const response = await page.evaluate( + (toolCallId) => + (globalThis as DesktopBridge).simDesktop.localFiles?.({ operation: 'read', toolCallId }), + read.toolCallId + ) + expect(response?.ok).toBe(false) + expect(JSON.stringify(response)).not.toContain(secret) + const [after] = await db.toolCalls(chatId) + expect(after).toMatchObject({ status: 'pending', claimedBy: null }) }) - const page = await openApp(user, 'Approval chat') - const chatId = user.chats['Approval chat'] - const read = await gatedCall( - page, - chatId, - '[unapproved-read] read my secret', - 'read_local_file' - ) - - // A renderer acting on a call the user has not allowed (a replayed event) is refused. - const response = await page.evaluate( - (toolCallId) => - (globalThis as DesktopWindow).simDesktop.localFiles?.({ operation: 'read', toolCallId }), - read.toolCallId - ) - expect(response?.ok).toBe(false) - expect(JSON.stringify(response)).not.toContain(secret) - const [after] = await db.toolCalls(chatId) - expect(after).toMatchObject({ status: 'pending', claimedBy: null }) - }) - test("a terminal command awaiting the user's approval cannot be claimed", async () => { - const user = await db.seedUser(['Approval chat']) - const command = `touch '${join(scratch, 'terminal-ran')}'` - agent.script('[unapproved-run]', (turn) => { - turn.toolCall({ toolName: 'terminal', args: { operation: 'run', command } }) - turn.pause() + await test.step('a terminal command', async () => { + const command = `touch '${join(scratch, 'terminal-ran')}'` + agent.script('[unapproved-run]', (turn) => { + turn.toolCall({ toolName: 'terminal', args: { operation: 'run', command } }) + turn.pause() + }) + await openChat(page, user, 'Run approval chat') + const chatId = user.chats['Run approval chat'] + const run = await gatedCall(page, chatId, '[unapproved-run] run a command', 'terminal') + // The guard is the claim: Sim must not hand an unapproved command to the desktop, so the + // call stays pending and unclaimed. Whether a handed-over command then runs depends on a + // terminal being open for the chat, which this test does not set up, so it checks the claim. + const response = await page.evaluate( + ({ toolCallId, command }) => + (globalThis as DesktopBridge).simDesktop.terminal + .executeTool(toolCallId, 'run', { command }, 'unapproved-e2e') + .catch((error: unknown) => ({ ok: false, error: String(error) })), + { toolCallId: run.toolCallId, command } + ) + expect(response).toMatchObject({ ok: false }) + const [after] = await db.toolCalls(chatId) + expect(after).toMatchObject({ status: 'pending', claimedBy: null }) }) - const page = await openApp(user, 'Approval chat') - const chatId = user.chats['Approval chat'] - const run = await gatedCall(page, chatId, '[unapproved-run] run a command', 'terminal') - - // The guard is the claim: Sim must not hand an unapproved command to the desktop, so the call - // stays pending and unclaimed. Whether a handed-over command then runs depends on a terminal - // being open for the chat, which this test does not set up, so it checks the claim only. - const response = await page.evaluate( - ({ toolCallId, command }) => - (globalThis as DesktopWindow).simDesktop.terminal - .executeTool(toolCallId, 'run', { command }, 'unapproved-e2e') - .catch((error: unknown) => ({ ok: false, error: String(error) })), - { toolCallId: run.toolCallId, command } - ) - expect(response).toMatchObject({ ok: false }) - const [after] = await db.toolCalls(chatId) - expect(after).toMatchObject({ status: 'pending', claimedBy: null }) }) - test('a claim that reaches Sim after the user pressed Stop is refused', async () => { + test('a claim that reaches Sim after the user pressed Stop is refused', async ({ desktop }) => { const user = await db.seedUser(['Stop chat']) const file = writeFile(join(scratch, 'notes.txt'), 'notes') agent.script('[stopped-claim]', (turn) => { turn.toolCall({ toolName: 'read_local_file', args: { path: file } }) turn.pause() }) - const page = await openApp(user, 'Stop chat') + const page = await openApp(desktop, user, 'Stop chat') const chatId = user.chats['Stop chat'] // Delivered to Sim on release even should Electron have given up on it meanwhile. const lateClaim = proxy.hold(isDesktopClaim, { deliverIfAbandoned: true }) @@ -706,7 +731,7 @@ test.describe('desktop tools against a live Sim', () => { const [call] = await db.toolCalls(chatId) const replay = await page.evaluate( (toolCallId) => - (globalThis as DesktopWindow).simDesktop.localFiles?.({ operation: 'read', toolCallId }), + (globalThis as DesktopBridge).simDesktop.localFiles?.({ operation: 'read', toolCallId }), call.toolCallId ) expect(replay?.ok).toBe(false) @@ -718,7 +743,9 @@ test.describe('desktop tools against a live Sim', () => { expect(after).toMatchObject({ status: 'cancelled', claimedBy: null }) }) - test('where Sim cannot run the background executor, the app stays dormant and a desktop round trip runs in the chat view', async () => { + test('where Sim cannot run the background executor, the app stays dormant and a desktop round trip runs in the chat view', async ({ + desktop, + }) => { const user = await db.seedUser(['Round trip']) const marker = generateId() const file = writeFile(join(scratch, 'plan.txt'), `plan ${marker}`) @@ -741,7 +768,7 @@ test.describe('desktop tools against a live Sim', () => { } ) const since = Date.now() - const page = await openApp(user, 'Round trip') + const page = await openApp(desktop, user, 'Round trip') await send(page, '[round-trip] what does my plan say?') // Each layer is checked on its own (soft), so a regression shows every layer it reaches: // the round trip, the turn's binding, the routes the app calls, and the doorbell. @@ -787,7 +814,9 @@ test.describe('desktop tools against a live Sim', () => { } }) - test('in the background, a call issued after the user switched chats runs on the desktop', async () => { + test('in the background, a call issued after the user switched chats runs on the desktop', async ({ + desktop, + }) => { proxy.rewriteAnswer(REGISTRATION_PATH, undefined) const user = await db.seedUser(['Background chat', 'Other chat']) const marker = generateId() @@ -805,7 +834,7 @@ test.describe('desktop tools against a live Sim', () => { issuedAt = Date.now() turn.pause() }) - const page = await openApp(user, 'Background chat') + const page = await openApp(desktop, user, 'Background chat') await send(page, '[background-read] read my notes') await expect(page.getByText('Reading your notes.')).toBeVisible({ timeout: 60_000 }) await openChat(page, user, 'Other chat') @@ -825,7 +854,9 @@ test.describe('desktop tools against a live Sim', () => { expect(proxy.seen(issuedAt, '/api/desktop/tool/authorize')).toEqual([]) }) - test('in the background, a result reported across a network cut reaches the agent exactly once', async () => { + test('in the background, a result reported across a network cut reaches the agent exactly once', async ({ + desktop, + }) => { proxy.rewriteAnswer(REGISTRATION_PATH, undefined) const user = await db.seedUser(['Cut chat']) const chatId = user.chats['Cut chat'] @@ -836,7 +867,7 @@ test.describe('desktop tools against a live Sim', () => { callId = turn.toolCall({ toolName: 'read_local_file', args: { path: file } }) turn.pause() }) - const page = await openApp(user, 'Cut chat') + const page = await openApp(desktop, user, 'Cut chat') // Reaches Sim on release although the cut made the app give up on it, as a report already on // the wire would: the app cannot know it landed, so it reports again once back online. const completion = proxy.hold(isDesktopCompletion, { deliverIfAbandoned: true }) diff --git a/apps/desktop/e2e/executor-sim.ts b/apps/desktop/e2e/executor-sim.ts index fbb462b98aa..92b78d8790c 100644 --- a/apps/desktop/e2e/executor-sim.ts +++ b/apps/desktop/e2e/executor-sim.ts @@ -1,18 +1,11 @@ import { execFileSync } from 'node:child_process' import { createHash } from 'node:crypto' -import { mkdtempSync, readFileSync } from 'node:fs' +import { readFileSync } from 'node:fs' import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http' import type { Socket } from 'node:net' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { - type ElectronApplication, - _electron as electron, - expect, - type Page, -} from '@playwright/test' +import type { ElectronApplication, Page } from '@playwright/test' import { getErrorMessage } from '@sim/utils/errors' +import { type DesktopApp, type DesktopFixture, expect } from './harness' /** * A fixture Sim that speaks the background executor's device protocol (register, inbox, @@ -20,10 +13,9 @@ import { getErrorMessage } from '@sim/utils/errors' * executor's Electron suites share. */ -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) export const WORKSPACE = 'ws-e2e' const LEASE_RENEW_MS = 1_000 -export const RECONCILE_MS = 2_000 +const RECONCILE_MS = 2_000 type CallStatus = 'pending' | 'awaiting_approval' | 'running' | 'completed' | 'failed' | 'cancelled' @@ -45,7 +37,10 @@ export interface FixtureCall { issuedAt: number claimedAt?: number token?: string + /** Successful claims. */ claims: number + /** Every claim request for this call, refused ones included. */ + claimAttempts: number renewals: number completions: Completion[] acknowledged: boolean @@ -72,6 +67,8 @@ export class FixtureSim { readonly streams = new Map>() readonly imported: ImportedEntry[] = [] enabled = true + /** How often a registered device reads its inbox without a ring. */ + reconcileMs = RECONCILE_MS /** Connections reset while the network was cut. */ droppedWhileOffline = 0 private offline = false @@ -125,6 +122,7 @@ export class FixtureSim { this.hits.clear() this.imported.length = 0 this.enabled = true + this.reconcileMs = RECONCILE_MS this.offline = false this.droppedWhileOffline = 0 } @@ -147,6 +145,7 @@ export class FixtureSim { status, issuedAt: Date.now(), claims: 0, + claimAttempts: 0, renewals: 0, completions: [], acknowledged: false, @@ -279,7 +278,7 @@ export class FixtureSim { protocolVersion: 1, leaseMs: 60_000, leaseRenewMs: LEASE_RENEW_MS, - reconcileMs: RECONCILE_MS, + reconcileMs: this.reconcileMs, }) return } @@ -347,6 +346,7 @@ export class FixtureSim { return } if (path === '/api/desktop/tool/claim') { + call.claimAttempts += 1 if (call.status !== 'pending' || call.token) { this.json(response, 404, { error: 'This call is no longer waiting for this device' }) return @@ -434,37 +434,47 @@ export class FixtureSim { } } +export interface ExecutorApp extends DesktopApp { + window: Page +} + /** - * Launches the app against the fixture Sim. Its shells are zsh with an empty config directory, so - * what they do is the app's and not this machine's: a developer's `.zshrc` can stop at a question - * (oh-my-zsh asks before updating) and hold the first prompt for as long as nobody answers it. - * The terminal's handling of slow and stalled startup files has its own tests. + * Launches the app against the fixture Sim and waits for its window to load Sim. Its shells are + * zsh with an empty config directory, so what they do is the app's and not this machine's: a + * developer's `.zshrc` can stop at a question (oh-my-zsh asks before updating) and hold the first + * prompt for as long as nobody answers it. Pass `userData` to relaunch on an earlier profile. */ -export async function launch( +export async function launchAgainst( + desktop: DesktopFixture, sim: FixtureSim, - userData: string, - env: Record = {} -): Promise<{ app: ElectronApplication; window: Page }> { - const app = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { - ...process.env, - SHELL: '/bin/zsh', - ZDOTDIR: mkdtempSync(join(tmpdir(), 'sim-e2e-zdotdir-')), - SIM_DESKTOP_ORIGIN: sim.origin, - SIM_DESKTOP_USER_DATA: userData, - ...env, - }, + options: { userData?: string; env?: Record } = {} +): Promise { + const launched = await desktop.launch({ + origin: sim.origin, + userData: options.userData, + leaveDialogsToDesktop: true, + env: { SHELL: '/bin/zsh', ZDOTDIR: desktop.tempDir('sim-e2e-zdotdir-'), ...options.env }, }) - // A dialog listener stops Playwright auto-dismissing page dialogs, so the desktop's own handling - // decides their outcome exactly as it does in production. - const leaveDialogsToDesktop = (page: Page) => page.on('dialog', () => {}) - app.context().pages().forEach(leaveDialogsToDesktop) - app.context().on('page', leaveDialogsToDesktop) - const window = await app.firstWindow() + const window = await launched.app.firstWindow() await window.waitForURL((url) => url.origin === sim.origin, { waitUntil: 'load' }) - return { app, window } + return { ...launched, window } +} + +/** + * Where the executor's encrypted journal has a call: `started`, `result` once its result is kept + * for delivery, undefined once the call is forgotten (or before it was recorded). + */ +export function journalState(app: ElectronApplication, toolCallId: string): Promise { + return app.evaluate(({ safeStorage }, toolCallId) => { + const fs = process.getBuiltinModule('node:fs') + const path = `${process.env.SIM_DESKTOP_USER_DATA}/desktop-executor-journal.json` + if (!fs.existsSync(path)) return undefined + const envelope = JSON.parse(fs.readFileSync(path, 'utf8')) + const journal = JSON.parse( + safeStorage.decryptString(Buffer.from(envelope.ciphertext, 'base64')) + ) as { entries: { toolCallId: string; state: string }[] } + return journal.entries.find((entry) => entry.toolCallId === toolCallId)?.state + }, toolCallId) } /** The device this app registered, once it has opened its doorbell. */ diff --git a/apps/desktop/e2e/fixtures/worker-restart.config.ts b/apps/desktop/e2e/fixtures/worker-restart.config.ts deleted file mode 100644 index d0f0e3a8b2d..00000000000 --- a/apps/desktop/e2e/fixtures/worker-restart.config.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { defineConfig } from '@playwright/test' - -/** Runs only the worker-restart fixture, for `check-report.spec.ts`. */ -export default defineConfig({ - testDir: '.', - testMatch: 'worker-restart.ts', - workers: 1, - retries: 0, - reporter: [['line']], -}) diff --git a/apps/desktop/e2e/fixtures/worker-restart.ts b/apps/desktop/e2e/fixtures/worker-restart.ts deleted file mode 100644 index 8a8c3921787..00000000000 --- a/apps/desktop/e2e/fixtures/worker-restart.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { expect, test } from '@playwright/test' -import { recordCheck } from '../check-report' - -/** - * Two checks in one file, the first failing, run by `check-report.spec.ts` in a Playwright run of - * its own. The failure makes Playwright start a new worker for the second, as it does mid-suite. - */ -const reportPath = process.env.WORKER_RESTART_REPORT_PATH - -function record(name: string, status: string): void { - recordCheck(reportPath, 'worker-restart', { - name, - status, - durationMs: 0, - error: `worker ${test.info().workerIndex}`, - }) -} - -test('fails first', () => { - record('fails first', 'failed') - expect('failed').toBe('passed') -}) - -test('passes after the worker restarts', () => { - record('passes after the worker restarts', 'passed') -}) diff --git a/apps/desktop/e2e/harness.ts b/apps/desktop/e2e/harness.ts new file mode 100644 index 00000000000..03d366a8c59 --- /dev/null +++ b/apps/desktop/e2e/harness.ts @@ -0,0 +1,515 @@ +/** + * Shared launch and teardown for the Electron E2E suite. + * + * Every spec launches the app through the `desktop` fixture, which tracks each app and temp + * directory a test creates and tears all of them down, even when the test fails midway. Closing is + * bounded: `ElectronApplication.close()` asks the app to quit and then waits for the process with + * no deadline, so a quit that a dialog or a cancelled `before-quit` blocks used to hang a test to + * its timeout and then hang the worker's own teardown. A quit that misses its deadline is a real + * bug (it is the same path as Cmd+Q), so the fixture records what the app was doing, kills it, and + * fails the test rather than hiding the stall. + */ +import { type ChildProcess, execFileSync } from 'node:child_process' +import { once } from 'node:events' +import { mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs' +import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { + test as base, + type ElectronApplication, + _electron as electron, + expect, + type Page, + type TestInfo, +} from '@playwright/test' +import type { BrowserToolName } from '@sim/browser-protocol' +import type { SimDesktopApi } from '@sim/desktop-bridge' +import { type BuildOptions, build } from 'esbuild' +import postcss from 'postcss' +import loadPostcssConfig from 'postcss-load-config' + +export { expect } + +export const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) +export const SIM_DIR = fileURLToPath(new URL('../../sim/', import.meta.url)) + +/** Above the 5s an account teardown may legitimately hold `before-quit`. */ +const QUIT_DEADLINE_MS = 15_000 +const OUTPUT_TAIL_BYTES = 64 * 1024 + +export type DesktopBridge = typeof globalThis & { simDesktop: SimDesktopApi } + +type PanelHeartbeats = typeof globalThis & { simE2ePanelHeartbeats?: Record } + +/** Below the main process's 2.5s panel-bounds lease, which hides the panel once it lapses. */ +const PANEL_HEARTBEAT_MS = 500 + +export interface LaunchOptions { + origin: string + /** A profile to reuse, e.g. to relaunch on the same one. Defaults to a fresh temp profile. */ + userData?: string + /** Written to the profile's `settings.json` before launch; a string is written verbatim. */ + settings?: unknown + env?: Record + /** The app directory or main script. */ + main?: string + args?: string[] + /** + * Keeps Playwright from auto-dismissing page dialogs, so the desktop's own dialog handling + * decides them as it does in production. + */ + leaveDialogsToDesktop?: boolean +} + +export interface DesktopApp { + app: ElectronApplication + /** Captured at launch: `app.process()` throws once the app has quit or crashed. */ + child: ChildProcess + userData: string + /** The tail of the main process's stdout and stderr. */ + output(): string +} + +export interface DesktopFixture { + launch(options: LaunchOptions): Promise + /** Quits an app mid-test, under the same deadline as teardown. */ + close(desktop: DesktopApp): Promise + /** A temp directory removed after the test. */ + tempDir(prefix: string): string +} + +function hasExited(child: ChildProcess): boolean { + return child.exitCode !== null || child.signalCode !== null +} + +function captureOutput(child: ChildProcess): () => string { + let tail = '' + const append = (chunk: Buffer) => { + tail = (tail + chunk.toString('utf8')).slice(-OUTPUT_TAIL_BYTES) + } + child.stdout?.on('data', append) + child.stderr?.on('data', append) + return () => tail +} + +/** Everything that says why an app did not quit, gathered before it is killed. */ +async function quitStallDiagnostics(desktop: DesktopApp): Promise { + const pid = desktop.child.pid + const sections: string[] = [] + const windows = await Promise.race([ + desktop.app + .evaluate(({ BrowserWindow }) => + BrowserWindow.getAllWindows().map((win) => ({ + title: win.getTitle(), + url: win.webContents.getURL(), + visible: win.isVisible(), + })) + ) + .then((list) => JSON.stringify(list, null, 2)), + new Promise((resolve) => + setTimeout( + () => resolve('main process did not answer within 2s (its thread is blocked)'), + 2_000 + ) + ), + ]).catch((error: unknown) => `could not list windows: ${String(error)}`) + sections.push(`## Windows\n${windows}`) + if (process.platform === 'darwin' && pid !== undefined) { + try { + const stack = execFileSync('sample', [String(pid), '2'], { + encoding: 'utf8', + timeout: 15_000, + }) + sections.push(`## Main process sample\n${stack}`) + } catch (error) { + sections.push(`## Main process sample\nunavailable: ${String(error)}`) + } + } + sections.push(`## Main process output (tail)\n${desktop.output()}`) + try { + const log = readFileSync(join(desktop.userData, 'logs', 'desktop-events.log'), 'utf8') + sections.push(`## desktop-events.log (tail)\n${log.slice(-OUTPUT_TAIL_BYTES)}`) + } catch { + sections.push('## desktop-events.log\nnone') + } + return sections.join('\n\n') +} + +/** + * The processes that can still write a profile: Chromium's helpers stay in the app's process group + * (Playwright spawns it detached, so the group is its own), while Crashpad's handler starts its own + * session but names the profile on its command line. + */ +function profileWriters(appGroup: number, profilePaths: readonly string[]): number[] { + return execFileSync('ps', ['-axww', '-o', 'pid=,pgid=,command='], { encoding: 'utf8' }) + .split('\n') + .flatMap((line) => { + const match = /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line) + if (!match) return [] + const [, pid, group, command] = match + return Number(group) === appGroup || profilePaths.some((path) => command.includes(path)) + ? [Number(pid)] + : [] + }) +} + +/** + * Kills whatever is left of an app and removes its profile once nothing can write to it: a helper + * or Crashpad's handler creating a file mid-removal fails it with ENOTEMPTY. + */ +export async function stopAndRemoveProfile(child: ChildProcess, userData: string): Promise { + if (!hasExited(child)) { + const exited = once(child, 'exit') + child.kill('SIGKILL') + await exited + } + if (child.pid !== undefined) { + const appGroup = child.pid + let profilePaths = [userData] + try { + profilePaths = [userData, realpathSync(userData)] + } catch {} + await expect + .poll(() => { + const writers = profileWriters(appGroup, profilePaths) + for (const pid of writers) { + try { + process.kill(pid, 'SIGKILL') + } catch {} + } + return writers + }) + .toEqual([]) + } + rmSync(userData, { recursive: true, force: true }) +} + +/** Launches the app against `options.origin` on `userData`, capturing its output. */ +async function launchDesktop(options: LaunchOptions & { userData: string }): Promise { + if (options.settings !== undefined) { + writeFileSync( + join(options.userData, 'settings.json'), + typeof options.settings === 'string' ? options.settings : JSON.stringify(options.settings) + ) + } + const app = await electron.launch({ + args: [options.main ?? '.', ...(options.args ?? [])], + cwd: DESKTOP_DIR, + env: { + ...process.env, + SIM_DESKTOP_ORIGIN: options.origin, + SIM_DESKTOP_USER_DATA: options.userData, + ...options.env, + }, + }) + const child = app.process() + const desktop: DesktopApp = { + app, + child, + userData: options.userData, + output: captureOutput(child), + } + if (options.leaveDialogsToDesktop) { + const leave = (page: Page) => page.on('dialog', () => {}) + app.context().pages().forEach(leave) + app.context().on('page', leave) + } + return desktop +} + +/** + * Quits an app through Playwright (the same `app.quit()` path as Cmd+Q). If it has not exited by + * the deadline, hands what it was doing to `report`, kills it, and throws. + */ +async function quitDesktop( + desktop: DesktopApp, + report: (diagnostics: string) => Promise | void +): Promise { + const { child } = desktop + if (hasExited(child)) return + const exited = once(child, 'exit') + // The exit event is the outcome; close() itself rejects once the process is gone. + void desktop.app.close().catch(() => {}) + let timer: NodeJS.Timeout | undefined + const quit = await Promise.race([ + exited.then(() => true), + new Promise((resolve) => { + timer = setTimeout(() => resolve(false), QUIT_DEADLINE_MS) + }), + ]) + clearTimeout(timer) + if (quit) return + try { + await report(await quitStallDiagnostics(desktop)) + } finally { + if (!hasExited(child) && child.pid !== undefined) { + try { + process.kill(-child.pid, 'SIGKILL') + } catch { + child.kill('SIGKILL') + } + await exited + } + } + throw new Error( + `Electron did not quit within ${QUIT_DEADLINE_MS / 1_000}s; see the electron-quit-stall diagnostics` + ) +} + +function closeDesktop(desktop: DesktopApp, testInfo: TestInfo): Promise { + return quitDesktop(desktop, (diagnostics) => + testInfo.attach('electron-quit-stall', { body: diagnostics, contentType: 'text/plain' }) + ) +} + +export const test = base.extend<{ desktop: DesktopFixture }>({ + desktop: [ + // biome-ignore lint/correctness/noEmptyPattern: Playwright reads a fixture's dependencies from this destructuring, and this one has none. + async ({}, use, testInfo) => { + const launched: DesktopApp[] = [] + const tempDirs: string[] = [] + const tempDir = (prefix: string) => { + const dir = mkdtempSync(join(tmpdir(), prefix)) + tempDirs.push(dir) + return dir + } + await use({ + tempDir, + async launch(options) { + const desktop = await launchDesktop({ + ...options, + userData: options.userData ?? tempDir('sim-desktop-e2e-profile-'), + }) + launched.push(desktop) + return desktop + }, + close: (desktop) => closeDesktop(desktop, testInfo), + }) + // Every app is closed and every directory removed even if an earlier one fails; the first + // failure is reported once the rest are cleaned up. + // Quit in parallel so several stalled apps still fit the teardown budget. + const failures: unknown[] = [] + for (const outcome of await Promise.allSettled( + launched.map((desktop) => closeDesktop(desktop, testInfo)) + )) { + if (outcome.status === 'rejected') failures.push(outcome.reason) + } + for (const desktop of launched) { + try { + await stopAndRemoveProfile(desktop.child, desktop.userData) + } catch (error) { + failures.push(error) + } + } + for (const dir of tempDirs) rmSync(dir, { recursive: true, force: true }) + if (failures.length > 0) throw failures[0] + }, + // Teardown has its own budget, so a test that used up its time still gets cleaned up. + { timeout: 2 * QUIT_DEADLINE_MS + 30_000 }, + ], +}) + +export type FixtureHandler = ( + request: IncomingMessage, + response: ServerResponse, + url: URL +) => void | Promise + +export interface FixtureServer { + server: Server + /** `http://127.0.0.1:`. */ + origin: string + /** The same server as `http://localhost:`, a different site for cross-site checks. */ + site: string + close(): Promise +} + +/** An HTTP fixture on loopback only, closed with its open connections. */ +export async function serve(handler: FixtureHandler): Promise { + const server = createServer((request, response) => { + const url = new URL(request.url ?? '/', 'http://127.0.0.1') + // Through then(), so a handler that throws synchronously also answers 500. + Promise.resolve() + .then(() => handler(request, response, url)) + .catch((error: unknown) => { + if (!response.headersSent) response.writeHead(500) + response.end(String(error)) + }) + }) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + const address = server.address() + const port = typeof address === 'object' && address ? address.port : 0 + return { + server, + origin: `http://127.0.0.1:${port}`, + site: `http://localhost:${port}`, + close: () => + new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())) + server.closeAllConnections() + }), + } +} + +/** Brings the app's first window to the front and waits until the OS reports it focused. */ +export async function focusFirstWindow(app: ElectronApplication): Promise { + await app.evaluate(({ app, BrowserWindow }) => { + const host = BrowserWindow.getAllWindows()[0] + host.webContents.setBackgroundThrottling(false) + app.focus({ steal: true }) + host.focus() + }) + await expect + .poll(() => app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].isFocused())) + .toBe(true) +} + +/** + * Activates a browser scope in the shell page and keeps the native browser panel below a `top` + * inset. The main process treats panel bounds as a lease that lapses after 2.5s, so the bounds are + * renewed on a heartbeat, the way Sim's panel renews them. Resolves once they reached main. + */ +export async function attachBrowserPanel(shell: Page, scope: string, top = 80): Promise { + await shell.evaluate( + async ({ scope, top, heartbeatMs }) => { + const api = (globalThis as DesktopBridge).simDesktop + const heartbeats = ((globalThis as PanelHeartbeats).simE2ePanelHeartbeats ??= {}) + clearInterval(heartbeats[scope]) + await api.browserAgent.activateScope(scope) + const updateBounds = () => + api.browserAgent.setPanelBounds( + { x: 0, y: top, width: innerWidth, height: innerHeight - top }, + null, + scope + ) + updateBounds() + heartbeats[scope] = window.setInterval(updateBounds, heartbeatMs) + // One renderer's IPC is handled in order, so this round trip lands after the bounds. + await api.browserAgent.activateScope(scope) + }, + { scope, top, heartbeatMs: PANEL_HEARTBEAT_MS } + ) +} + +/** Stops renewing a scope's panel bounds and takes the panel off screen, as Sim does on hide. */ +export async function hideBrowserPanel(shell: Page, scope: string): Promise { + await shell.evaluate(async (scope) => { + const api = (globalThis as DesktopBridge).simDesktop + clearInterval((globalThis as PanelHeartbeats).simE2ePanelHeartbeats?.[scope]) + api.browserAgent.setPanelBounds(null, null, scope) + await api.browserAgent.activateScope(scope) + }, scope) +} + +export interface SimFixtureBundle { + js: string + css: string +} + +/** + * Bundles a browser fixture built from apps/sim source, with apps/sim's stylesheet, so a spec can + * serve real Sim UI from its fixture server. `entry` is either a file or inline TSX resolved from + * apps/sim. + */ +export async function bundleSimFixture( + entry: { file: string } | { source: string }, + options: Pick & { + /** More files whose utility classes the stylesheet must include; a `file` entry is added. */ + sources?: string[] + } = {} +): Promise { + const bundle = await build({ + ...('file' in entry + ? { entryPoints: [entry.file] } + : { stdin: { contents: entry.source, resolveDir: SIM_DIR, loader: 'tsx' } }), + bundle: true, + write: false, + outdir: 'out', + jsx: 'automatic', + external: ['node:async_hooks', ...(options.external ?? [])], + inject: options.inject, + banner: { js: 'var process={env:{NODE_ENV:"development"},browser:true};' }, + format: 'iife', + platform: 'browser', + tsconfig: join(SIM_DIR, 'tsconfig.json'), + define: { 'process.env.NODE_ENV': '"development"' }, + }) + const js = bundle.outputFiles.find((file) => file.path.endsWith('.js'))?.text + if (js === undefined) throw new Error('The fixture bundle produced no JavaScript') + // Stylesheets the fixture imports (e.g. a package's own CSS) come out of esbuild separately. + const importedCss = bundle.outputFiles + .filter((file) => file.path.endsWith('.css')) + .map((file) => file.text) + .join('\n') + const config = await loadPostcssConfig({}, SIM_DIR) + const stylesheet = join(SIM_DIR, 'app/_styles/globals.css') + // A fixture's own utility classes are generated too, not only the ones Sim's sources use. + const scanFixture = [...('file' in entry ? [entry.file] : []), ...(options.sources ?? [])] + .map((source) => `\n@source ${JSON.stringify(source)};`) + .join('') + const css = await postcss(config.plugins).process( + `${readFileSync(stylesheet, 'utf8')}${scanFixture}`, + { from: stylesheet } + ) + return { js, css: `${css.css}\n${importedCss}` } +} + +export interface ToolCallAuthorization { + chatId: string + toolName: string + args: unknown +} + +/** + * Stands in for Sim's `/api/desktop/tool/authorize`: the desktop asks it before running a tool + * call, and it authorizes exactly the calls a test issued. + */ +export class ToolAuthorizer { + readonly calls = new Map() + private count = 0 + + constructor(private readonly prefix: string) {} + + /** Handles the authorize route; returns false for any other path. */ + async handle(request: IncomingMessage, response: ServerResponse, url: URL): Promise { + if (url.pathname !== '/api/desktop/tool/authorize') return false + let body = '' + for await (const chunk of request) body += chunk.toString() + const authorization = this.calls.get(JSON.parse(body).toolCallId) + response.writeHead(authorization ? 200 : 403, { 'Content-Type': 'application/json' }) + response.end(JSON.stringify(authorization ?? {})) + return true + } + + /** Authorizes a new browser tool call and returns its id. */ + issue(scope: string, toolName: BrowserToolName, args: unknown): string { + const callId = `${this.prefix}-${++this.count}` + this.calls.set(callId, { chatId: scope, toolName, args }) + return callId + } + + /** Runs a browser tool from the shell page and returns its result, failing on a tool error. */ + async execute( + shell: Page, + scope: string, + toolName: BrowserToolName, + args: Record + ): Promise { + const callId = this.issue(scope, toolName, args) + const result = await shell.evaluate( + ({ callId, toolName, args, scope }) => + (globalThis as DesktopBridge).simDesktop.browserAgent.executeTool( + callId, + toolName, + args, + scope + ), + { callId, toolName, args, scope } + ) + expect(result.ok, result.error).toBe(true) + return result.result + } +} diff --git a/apps/desktop/e2e/local-files.spec.ts b/apps/desktop/e2e/local-files.spec.ts index a00fe40cf40..43e9a3e4fc9 100644 --- a/apps/desktop/e2e/local-files.spec.ts +++ b/apps/desktop/e2e/local-files.spec.ts @@ -1,6 +1,5 @@ import { mkdirSync, - mkdtempSync, readFileSync, realpathSync, renameSync, @@ -8,121 +7,156 @@ import { symlinkSync, writeFileSync, } from 'node:fs' -import { createServer, type Server } from 'node:http' -import { tmpdir } from 'node:os' import { join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { type ElectronApplication, _electron as electron, expect, test } from '@playwright/test' -import type { DesktopLocalFileRequest, SimDesktopApi } from '@sim/desktop-bridge' -import { build } from 'esbuild' -import postcss from 'postcss' -import loadPostcssConfig from 'postcss-load-config' +import type { ElectronApplication, Locator, Page } from '@playwright/test' +import type { + DesktopLocalFileRequest, + DesktopPreferences, + SimDesktopApi, +} from '@sim/desktop-bridge' +import { answerShellDialog } from './executor-sim' +import { + test as base, + type DesktopApp, + type DesktopBridge, + expect, + focusFirstWindow, + serve, +} from './harness' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) -const SIM_DIR = fileURLToPath(new URL('../../sim/', import.meta.url)) +const PNG = + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9Zl1sAAAAASUVORK5CYII=' -test('native file tools remember folder consent across chats and restarts until revoked', async () => { - test.setTimeout(180_000) - const root = mkdtempSync(join(tmpdir(), 'sim-native-files-e2e-')) - const source = join(root, 'Reports') - const outside = join(root, 'Reports-other') - mkdirSync(outside) - writeFileSync(join(outside, 'private.txt'), 'outside contents') - mkdirSync(join(source, 'empty'), { recursive: true }) - writeFileSync(join(source, 'report.txt'), 'native file contents') - const png = - 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9Zl1sAAAAASUVORK5CYII=' - writeFileSync(join(source, 'image.png'), Buffer.from(png, 'base64')) - const claimed = new Set() - const expireAfterAuthorization = new Set() - let signedIn = true - const calls: Record< - string, - { toolName: string; args: Record; chatId?: string } | undefined - > = { - directory: { toolName: 'read_local_file', args: { path: source } }, - text: { toolName: 'read_local_file', args: { path: join(source, 'report.txt') } }, - otherChat: { - toolName: 'read_local_file', - args: { path: join(source, 'report.txt') }, - chatId: 'other-chat', - }, - image: { toolName: 'read_local_file', args: { path: join(source, 'image.png') } }, - import: { - toolName: 'import_local_files', - args: { path: source, targetWorkspaceId: 'target-workspace' }, - }, +/** + * The app's own page stands in for Sim: a Forget button and a Full file access switch that drive + * the same bridge calls Sim's Desktop settings make (a real click supplies the user activation the + * setter requires), and the switch shows whatever the desktop last reported. + */ +const FIXTURE_PAGE = `Local file fixture

Local files

+ + + +` + +type LocalFileResponse = Awaited>> + +interface ToolCall { + toolName: 'read_local_file' | 'import_local_files' + args: Record + chatId?: string +} + +interface Session { + desktop: DesktopApp + app: ElectronApplication + window: Page + fullAccess: Locator + invoke(request: DesktopLocalFileRequest): Promise + /** Starts a request and resolves once its folder prompt is up. */ + requestPermission( + request: DesktopLocalFileRequest + ): Promise<{ prompt: Page; result: Promise }> + preferences(): Promise +} + +interface LocalFilesFixture { + root: string + /** `Reports`: report.txt, image.png, and an empty subfolder. */ + source: string + /** `Reports-other`, a sibling holding private.txt that no call is meant to reach. */ + outside: string + /** The calls the fixture Sim authorizes, by tool call id; any other id is refused. */ + calls: Record + /** Calls Sim refuses after their first authorization, as it does once a call has ended. */ + expireAfterAuthorization: Set + origin: string + signIn(): void + /** Launches the app, on `userData` when relaunching the same profile. */ + open(userData?: string): Promise + close(session: Session): Promise +} + +type FsPatchRuntime = typeof globalThis & { + e2eFsPatch?: { fired: string[]; restore(): void | Promise } +} + +/** Undoes a step's fs/promises patch in the main process and returns the race actions that ran. */ +async function restoreFsPatch(app: ElectronApplication): Promise { + return app.evaluate(async () => { + const runtime = globalThis as FsPatchRuntime + const patch = runtime.e2eFsPatch + runtime.e2eFsPatch = undefined + await patch?.restore() + return patch?.fired ?? [] + }) +} + +const test = base.extend<{ localFiles: LocalFilesFixture }>({ + localFiles: async ({ desktop }, use) => { + const root = desktop.tempDir('sim-native-files-e2e-') + const source = join(root, 'Reports') + const outside = join(root, 'Reports-other') + mkdirSync(outside) + writeFileSync(join(outside, 'private.txt'), 'outside contents') + mkdirSync(join(source, 'empty'), { recursive: true }) + writeFileSync(join(source, 'report.txt'), 'native file contents') + writeFileSync(join(source, 'image.png'), Buffer.from(PNG, 'base64')) + const claimed = new Set() + const expireAfterAuthorization = new Set() + let signedIn = true + const calls: Record = { + directory: { toolName: 'read_local_file', args: { path: source } }, + text: { toolName: 'read_local_file', args: { path: join(source, 'report.txt') } }, + otherChat: { + toolName: 'read_local_file', + args: { path: join(source, 'report.txt') }, + chatId: 'other-chat', + }, + image: { toolName: 'read_local_file', args: { path: join(source, 'image.png') } }, + import: { + toolName: 'import_local_files', + args: { path: source, targetWorkspaceId: 'target-workspace' }, + }, + } + const server = await serve(async (request, response, url) => { + if (url.pathname === '/api/auth/get-session') { + response + .writeHead(200, { 'Content-Type': 'application/json' }) + .end( + JSON.stringify( + signedIn + ? { user: { id: 'local-file-user' }, session: { id: 'local-file-session' } } + : null + ) ) - ) return } - if (path === '/api/auth/sign-out') { + if (url.pathname === '/api/auth/sign-out') { signedIn = false response .writeHead(200, { @@ -132,7 +166,7 @@ createRoot(document.getElementById('settings')).render( .end('{}') return } - if (path === '/api/desktop/tool/authorize') { + if (url.pathname === '/api/desktop/tool/authorize') { let body = '' for await (const chunk of request) body += chunk.toString() const input = JSON.parse(body) @@ -158,867 +192,833 @@ createRoot(document.getElementById('settings')).render( ? { 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; SameSite=Lax; Path=/' } : {}), }) - .end(`Local file fixture

Local files

- -
`) + .end(FIXTURE_PAGE) }) - await new Promise((resolve) => server?.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - const launch = () => - electron.launch({ - args: ['.', '--use-mock-keychain'], - cwd: DESKTOP_DIR, - env: { - ...process.env, - SIM_DESKTOP_ORIGIN: `http://127.0.0.1:${address.port}`, - SIM_DESKTOP_USER_DATA: join(root, 'profile'), - }, + const sessions: Session[] = [] + + const open = async (userData?: string): Promise => { + const launched = await desktop.launch({ + origin: server.origin, + userData, + args: ['--use-mock-keychain'], }) - app = await launch() - let window = await app.firstWindow() - await app.evaluate(({ app, BrowserWindow }) => { - const host = BrowserWindow.getAllWindows()[0] - if (!host) throw new Error('Missing host window') - host.webContents.setBackgroundThrottling(false) - app.focus({ steal: true }) - host.focus() - }) - await expect(window.getByRole('heading', { name: 'Local files', exact: true })).toHaveText( - 'Local files' - ) - const invoke = (input: DesktopLocalFileRequest) => - window.evaluate(async (request) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - if (!api.localFiles) throw new Error('Native file bridge missing') - return api.localFiles(request) - }, input) - await expect - .poll(() => - window.evaluate(async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - return (await api.localFilesystem?.({ operation: 'list_mounts' }))?.ok + const { app } = launched + const window = await app.firstWindow() + await focusFirstWindow(app) + await expect(window.getByRole('heading', { name: 'Local files', exact: true })).toBeVisible() + const invoke = (request: DesktopLocalFileRequest) => + window.evaluate(async (input) => { + const api = (globalThis as DesktopBridge).simDesktop + if (!api.localFiles) throw new Error('Native file bridge missing') + return api.localFiles(input) + }, request) + await expect + .poll(() => + window.evaluate( + async () => + ( + await (globalThis as DesktopBridge).simDesktop.localFilesystem?.({ + operation: 'list_mounts', + }) + )?.ok + ) + ) + .toBe(true) + if (userData === undefined) { + await window.evaluate(async () => { + const settings = (globalThis as DesktopBridge).simDesktop.settings + await settings.setPreference('browserEnabled', false) + await settings.setPreference('terminalEnabled', false) }) - ) - .toBe(true) - await window.evaluate(async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - await api.settings.setPreference('browserEnabled', false) - await api.settings.setPreference('terminalEnabled', false) + } + const session: Session = { + desktop: launched, + app, + window, + fullAccess: window.getByRole('switch', { name: 'Full file access', exact: true }), + invoke, + async requestPermission(request) { + const shown = app.waitForEvent('window', { timeout: 10_000 }) + const result = invoke(request) + void result.catch(() => {}) + const prompt = await shown + await expect( + prompt.getByRole('button', { name: "Don't allow", exact: true }) + ).toBeVisible() + return { prompt, result } + }, + preferences: () => + window.evaluate(() => (globalThis as DesktopBridge).simDesktop.settings.getPreferences()), + } + sessions.push(session) + return session + } + + await use({ + root, + source, + outside, + calls, + expireAfterAuthorization, + origin: server.origin, + signIn: () => { + signedIn = true + }, + open, + close: (session) => desktop.close(session.desktop), }) - const deniedPrompt = app.waitForEvent('window', { timeout: 10_000 }) - const deniedReads = ['text', 'otherChat'].map((toolCallId) => + // The apps quit while their server still answers, as they would against a live Sim. + try { + for (const session of sessions) await desktop.close(session.desktop) + } finally { + await server.close() + } + }, +}) + +test('folder consent is asked once per folder, shared across chats, and bound to the authorized call', async ({ + localFiles, +}) => { + const { root, source, outside, calls, expireAfterAuthorization } = localFiles + const { app, window, invoke, requestPermission } = await localFiles.open() + + await test.step('declining consent fails every read waiting on that folder', async () => { + const shown = app.waitForEvent('window', { timeout: 10_000 }) + const reads = ['text', 'otherChat'].map((toolCallId) => invoke({ operation: 'read', toolCallId }) ) - const deniedResults: unknown[] = [] - for (const read of deniedReads) - void read.then((result) => deniedResults.push(result)).catch(() => {}) - const denial = await deniedPrompt + for (const read of reads) void read.catch(() => {}) + const denial = await shown await expect(denial.getByRole('button', { name: "Don't allow", exact: true })).toBeFocused() - await denial.screenshot({ - path: - process.env.DESKTOP_LOCAL_FILES_REPORT_PATH ?? - test.info().outputPath('local-file-consent.png'), - }) - await denial - .getByRole('button', { name: "Don't allow", exact: true }) - .click({ noWaitAfter: true }) - await expect.poll(() => deniedResults.length).toBe(2) - expect(deniedResults).toEqual([ + await answerShellDialog(denial, "Don't allow") + expect(await Promise.all(reads)).toEqual([ { ok: false, error: expect.any(String) }, { ok: false, error: expect.any(String) }, ]) + }) - const folderPrompt = app.waitForEvent('window') + await test.step('an allowed folder serves the queued read, the authorized path, and images', async () => { + const shown = app.waitForEvent('window') const folderRead = invoke({ operation: 'read', toolCallId: 'directory' }) void folderRead.catch(() => {}) - const folderConsent = await folderPrompt + const consent = await shown const queuedRead = invoke({ operation: 'read', toolCallId: 'text' }) void queuedRead.catch(() => {}) - await expect( - folderConsent.getByRole('button', { name: 'Allow folder', exact: true }) - ).toBeVisible() + await expect(consent.getByRole('button', { name: 'Allow folder', exact: true })).toBeVisible() expect( - await folderConsent.evaluate(() => typeof (globalThis as { simDesktop?: unknown }).simDesktop) + await consent.evaluate(() => typeof (globalThis as { simDesktop?: unknown }).simDesktop) ).toBe('undefined') - await folderConsent - .getByRole('button', { name: 'Allow folder', exact: true }) - .click({ noWaitAfter: true }) + await answerShellDialog(consent, 'Allow folder') expect(await folderRead).toMatchObject({ ok: true, data: { representation: 'directory' } }) expect(await queuedRead).toMatchObject({ ok: true, data: { text: 'native file contents' } }) - const canonicalRequest = { + // The renderer's path is ignored: Sim's authorized arguments decide what is read. + const redirected = { operation: 'read' as const, toolCallId: 'text', path: join(outside, 'private.txt'), } - expect(await invoke(canonicalRequest)).toMatchObject({ + expect(await invoke(redirected)).toMatchObject({ ok: true, data: { representation: 'text', text: 'native file contents' }, }) expect(await invoke({ operation: 'read', toolCallId: 'image' })).toMatchObject({ ok: true, - data: { observations: [{ mediaType: 'image/png', data: png }] }, + data: { observations: [{ mediaType: 'image/png', data: PNG }] }, }) - const requestPermission = async (request: DesktopLocalFileRequest) => { - if (!app) throw new Error('Desktop app is not running') - const shown = app.waitForEvent('window', { timeout: 10_000 }) - const result = invoke(request) - void result.catch(() => {}) - const prompt = await shown - await expect(prompt.getByRole('button', { name: "Don't allow", exact: true })).toBeVisible() - return { prompt, result } + }) + + await test.step('a folder grant works in another chat but does not permit symlink escapes', async () => { + expect(await invoke({ operation: 'read', toolCallId: 'otherChat' })).toMatchObject({ + ok: true, + data: { text: 'native file contents' }, + }) + writeFileSync(join(source, 'empty', 'new.txt'), 'new file in a subfolder') + calls.nested = { + toolName: 'read_local_file', + args: { path: join(source, 'empty', 'new.txt') }, + chatId: 'another-chat', } - await test.step('File → Folder Access opens over a focused utility window', async () => { - if (!app) throw new Error('Desktop app is not running') - const serverShown = app.waitForEvent('window', { timeout: 10_000 }) - await app.evaluate(({ Menu }) => { - const item = Menu.getApplicationMenu() - ?.items.flatMap((entry) => entry.submenu?.items ?? []) - .find((entry) => entry.label === 'Server…') - if (!item) throw new Error('Server menu item missing') - item.click() - }) - await expect(await serverShown).toHaveTitle('Sim - Server') - await expect - .poll(() => - app?.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().some( - (win) => win.webContents.getURL().endsWith('server.html') && win.isVisible() - ) - ) - ) - .toBe(true) - const accessMenu = await app.evaluate(({ BrowserWindow, Menu }) => { - const utility = BrowserWindow.getAllWindows().find((win) => - win.webContents.getURL().endsWith('server.html') - ) - if (!utility) throw new Error('Server window missing') - const item = Menu.getApplicationMenu() - ?.items.flatMap((entry) => entry.submenu?.items ?? []) - .find((entry) => entry.label === 'Folder Access…') - if (!item) throw new Error('Folder Access menu item missing') - const popup = Menu.prototype.popup - let shown: { anchoredToUtility: boolean; items: string[] } | undefined - Menu.prototype.popup = function (this: Electron.Menu, options) { - shown = { - anchoredToUtility: options?.window === utility, - items: this.items.map((entry) => entry.label), - } - } - try { - item.click(undefined, utility) - } finally { - Menu.prototype.popup = popup - } - utility.close() - return shown - }) - expect(accessMenu?.anchoredToUtility).toBe(true) - expect(accessMenu?.items).toContain('Add Folder…') + expect(await invoke({ operation: 'read', toolCallId: 'nested' })).toMatchObject({ + ok: true, + data: { text: 'new file in a subfolder' }, }) + rmSync(join(source, 'empty', 'new.txt')) + symlinkSync(join(outside, 'private.txt'), join(source, 'linked.txt')) + calls.escape = { toolName: 'read_local_file', args: { path: join(source, 'linked.txt') } } + const escaped = await requestPermission({ operation: 'read', toolCallId: 'escape' }) + await expect(escaped.prompt.getByRole('dialog')).toContainText( + JSON.stringify(realpathSync(outside)) + ) + await answerShellDialog(escaped.prompt, "Don't allow") + expect(await escaped.result).toMatchObject({ ok: false }) + rmSync(join(source, 'linked.txt')) + }) - await test.step('Stop cancels only its own request while chats share a folder prompt', async () => { - const sharedFolder = join(root, 'Shared') - mkdirSync(sharedFolder) - writeFileSync(join(sharedFolder, 'shared.txt'), 'shared contents') - for (const toolCallId of ['sharedLeader', 'sharedFollower', 'sharedSurvivor']) { - calls[toolCallId] = { - toolName: 'read_local_file', - args: { path: join(sharedFolder, 'shared.txt') }, - chatId: toolCallId, - } + await test.step('cancelled calls and changed arguments cannot acquire a grant', async () => { + for (const changed of [false, true]) { + calls.stale = { toolName: 'read_local_file', args: { path: join(outside, 'private.txt') } } + const stale = await requestPermission({ operation: 'read', toolCallId: 'stale' }) + if (changed) calls.stale.args.path = join(source, 'report.txt') + else calls.stale = undefined + await answerShellDialog(stale.prompt, 'Allow folder') + expect(await stale.result).toMatchObject({ ok: false }) + } + }) + + await test.step('Stop cancels only its own request while chats share a folder prompt', async () => { + const sharedFolder = join(root, 'Shared') + mkdirSync(sharedFolder) + writeFileSync(join(sharedFolder, 'shared.txt'), 'shared contents') + for (const toolCallId of ['sharedLeader', 'sharedFollower', 'sharedSurvivor']) { + calls[toolCallId] = { + toolName: 'read_local_file', + args: { path: join(sharedFolder, 'shared.txt') }, + chatId: toolCallId, } - const leader = await requestPermission({ operation: 'read', toolCallId: 'sharedLeader' }) - let followerResult: unknown - const follower = invoke({ operation: 'read', toolCallId: 'sharedFollower' }).then( - (result) => { - followerResult = result + } + // A request joins the pending prompt in the same turn its stat of the file settles, so the + // count of those stats says how many requests share the prompt. Sim's authorization lands + // before that, which is why it cannot stand in for the join. + await app.evaluate( + (_electron, file) => { + const fs = process.getBuiltinModule('node:fs/promises') as typeof import('node:fs/promises') + const original = fs.stat + const fired: string[] = [] + ;(globalThis as FsPatchRuntime).e2eFsPatch = { + fired, + restore: () => { + fs.stat = original + }, } - ) + fs.stat = (async (...args: Parameters) => { + const result = await original(...args) + if (args[0] === file) fired.push('joined') + return result + }) as typeof fs.stat + }, + realpathSync(join(sharedFolder, 'shared.txt')) + ) + const joined = () => + app.evaluate(() => (globalThis as FsPatchRuntime).e2eFsPatch?.fired.length ?? 0) + try { + const leader = await requestPermission({ operation: 'read', toolCallId: 'sharedLeader' }) + expect(await joined()).toBe(1) + const follower = invoke({ operation: 'read', toolCallId: 'sharedFollower' }) void follower.catch(() => {}) - await expect.poll(() => claimed.has('sharedFollower')).toBe(true) - await leader.prompt.getByRole('dialog').hover() + await expect.poll(joined).toBe(2) await invoke({ operation: 'cancel', toolCallId: 'sharedFollower' }) - await expect.poll(() => followerResult).toMatchObject({ ok: false }) - await follower - await expect(leader.prompt.getByRole('dialog')).toBeVisible() + expect(await follower).toMatchObject({ ok: false }) const survivor = invoke({ operation: 'read', toolCallId: 'sharedSurvivor' }) void survivor.catch(() => {}) - await expect.poll(() => claimed.has('sharedSurvivor')).toBe(true) - await leader.prompt.getByRole('dialog').hover() + await expect.poll(joined).toBe(3) await invoke({ operation: 'cancel', toolCallId: 'sharedLeader' }) expect(await leader.result).toMatchObject({ ok: false }) - await expect(leader.prompt.getByRole('dialog')).toBeVisible() - await leader.prompt - .getByRole('button', { name: 'Allow folder', exact: true }) - .click({ noWaitAfter: true }) + // The leader's own prompt is still the one to answer: neither cancel closed it. + await answerShellDialog(leader.prompt, 'Allow folder') expect(await survivor).toMatchObject({ ok: true, data: { text: 'shared contents' } }) + } finally { + await restoreFsPatch(app) + } + }) + + await test.step('cancelling in the renderer closes consent without remembering access', async () => { + calls.cancelled = { toolName: 'read_local_file', args: { path: join(outside, 'private.txt') } } + const cancelled = await requestPermission({ operation: 'read', toolCallId: 'cancelled' }) + const closed = cancelled.prompt.waitForEvent('close') + await invoke({ operation: 'cancel', toolCallId: 'cancelled' }) + await closed + expect(await cancelled.result).toMatchObject({ ok: false }) + const again = await requestPermission({ operation: 'read', toolCallId: 'cancelled' }) + await answerShellDialog(again.prompt, "Don't allow") + expect(await again.result).toMatchObject({ ok: false }) + }) + + await test.step('consent escapes direction controls in folder names', async () => { + const folder = join(root, 'Bidi؜‎‏') + mkdirSync(folder) + calls.bidi = { toolName: 'read_local_file', args: { path: folder } } + const bidi = await requestPermission({ operation: 'read', toolCallId: 'bidi' }) + await expect(bidi.prompt.getByRole('dialog')).toContainText('Bidi\\u061c\\u200e\\u200f') + await answerShellDialog(bidi.prompt, "Don't allow") + expect(await bidi.result).toMatchObject({ ok: false }) + }) + + await test.step('an unanswered prompt does not block approved folders', async () => { + calls.blocker = { toolName: 'read_local_file', args: { path: join(outside, 'private.txt') } } + const blocker = await requestPermission({ operation: 'read', toolCallId: 'blocker' }) + expect(await invoke({ operation: 'read', toolCallId: 'text' })).toMatchObject({ ok: true }) + await answerShellDialog(blocker.prompt, "Don't allow") + expect(await blocker.result).toMatchObject({ ok: false }) + }) + + await test.step('a call that ended after authorization cannot use an approved folder', async () => { + calls.expired = { toolName: 'read_local_file', args: { path: join(source, 'report.txt') } } + expireAfterAuthorization.add('expired') + expect(await invoke({ operation: 'read', toolCallId: 'expired' })).toMatchObject({ ok: false }) + }) + + await test.step('replacing the proposed folder during consent does not expose its new target', async () => { + const proposed = join(root, 'Proposed') + mkdirSync(proposed) + calls.retargeted = { toolName: 'read_local_file', args: { path: proposed } } + const retargeted = await requestPermission({ operation: 'read', toolCallId: 'retargeted' }) + renameSync(proposed, join(root, 'Original')) + mkdirSync(proposed) + writeFileSync(join(proposed, 'unapproved.txt'), 'replacement folder contents') + await answerShellDialog(retargeted.prompt, 'Allow folder') + expect(await retargeted.result).toMatchObject({ ok: false }) + }) + + await test.step('an approved folder imports once per call and to any destination without prompting', async () => { + const manifest = await invoke({ operation: 'manifest', toolCallId: 'import' }) + if (!manifest.ok || manifest.data.kind !== 'manifest') throw new Error(JSON.stringify(manifest)) + expect(manifest.data.targetWorkspaceId).toBe('target-workspace') + expect(manifest.data.entries.map((entry) => entry.relativePath)).toEqual([ + '', + 'empty', + 'image.png', + 'report.txt', + ]) + const file = manifest.data.entries.find((entry) => entry.relativePath === 'report.txt') + if (!file) throw new Error('Missing import file') + const chunkRequest = { + operation: 'chunk' as const, + toolCallId: 'import', + relativePath: file.relativePath, + revision: file.revision, + offset: 0, + } + const chunk = await invoke(chunkRequest) + if (!chunk.ok || chunk.data.kind !== 'chunk') throw new Error(JSON.stringify(chunk)) + expect(Object.values(chunk.data.bytes)).toEqual([...Buffer.from('native file contents')]) + expect(chunk.data.eof).toBe(true) + // The bytes cross the bridge in a form the renderer can upload as a File. + expect( + await window.evaluate(async (input) => { + const response = await (globalThis as DesktopBridge).simDesktop.localFiles?.(input) + if (!response?.ok || response.data.kind !== 'chunk') throw new Error('Missing native chunk') + return new File([new Uint8Array(response.data.bytes)], 'report.txt').text() + }, chunkRequest) + ).toBe('native file contents') + expect(await invoke({ operation: 'manifest', toolCallId: 'import' })).toMatchObject({ + ok: false, + code: 'ALREADY_STARTED', }) - await test.step('expired requests cannot enable Full file access from a confirmation', async () => { - if (!app) throw new Error('Desktop app is not running') - calls.expiringFullAccess = { - toolName: 'read_local_file', - args: { path: join(outside, 'private.txt') }, - } - const permission = await requestPermission({ - operation: 'read', - toolCallId: 'expiringFullAccess', - }) - const shown = app.waitForEvent('window') - await permission.prompt - .getByRole('button', { name: 'Full file access', exact: true }) - .click({ noWaitAfter: true }) - const confirmation = await shown - calls.expiringFullAccess = undefined - await confirmation - .getByRole('button', { name: 'Enable', exact: true }) - .click({ noWaitAfter: true }) - expect(await permission.result).toMatchObject({ ok: false }) - expect( - await window.evaluate(async () => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.settings.getPreferences() - ) - ).toMatchObject({ fullFileAccess: false }) + calls.otherImport = { + toolName: 'import_local_files', + args: { path: source, targetWorkspaceId: 'other-workspace' }, + } + expect(await invoke({ operation: 'manifest', toolCallId: 'otherImport' })).toMatchObject({ + ok: true, }) - await test.step('Full file access is opt-in, survives restart, and stops granting access when disabled', async () => { - if (!app) throw new Error('Desktop app is not running') - const fullFolder = join(root, 'Full access') - mkdirSync(fullFolder) - writeFileSync(join(fullFolder, 'file.txt'), 'full access contents') - calls.fullAccess = { - toolName: 'read_local_file', - args: { path: join(fullFolder, 'file.txt') }, - } - await expect( - window.getByRole('switch', { name: 'Full file access', exact: true }) - ).not.toBeChecked() - const permission = await requestPermission({ operation: 'read', toolCallId: 'fullAccess' }) - const confirmationShown = app.waitForEvent('window') - await permission.prompt - .getByRole('button', { name: 'Full file access', exact: true }) - .click({ noWaitAfter: true }) - const confirmation = await confirmationShown - await expect(confirmation.getByRole('button', { name: 'Cancel', exact: true })).toBeFocused() - const returnedPrompt = app.waitForEvent('window') - await confirmation - .getByRole('button', { name: 'Cancel', exact: true }) - .click({ noWaitAfter: true }) - const folderPrompt = await returnedPrompt - expect( - await window.evaluate(async () => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.settings.getPreferences() - ) - ).toMatchObject({ fullFileAccess: false }) - const acceptedConfirmation = app.waitForEvent('window') - await folderPrompt - .getByRole('button', { name: 'Full file access', exact: true }) - .click({ noWaitAfter: true }) - const allowAll = await acceptedConfirmation - await allowAll.screenshot({ - path: test.info().outputPath('full-file-access-confirmation.png'), - }) - await allowAll - .getByRole('button', { name: 'Enable', exact: true }) - .click({ noWaitAfter: true }) - expect(await permission.result).toMatchObject({ - ok: true, - data: { text: 'full access contents' }, - }) - await expect( - window.getByRole('switch', { name: 'Full file access', exact: true }) - ).toBeChecked() - expect(await invoke({ operation: 'read', toolCallId: 'fullAccess' })).toMatchObject({ - ok: true, - data: { text: 'full access contents' }, - }) - calls.fullImport = { - toolName: 'import_local_files', - args: { path: fullFolder, targetWorkspaceId: 'target-workspace' }, - } - const manifest = await invoke({ operation: 'manifest', toolCallId: 'fullImport' }) - if (!manifest.ok || manifest.data.kind !== 'manifest') - throw new Error('Missing full-access manifest') - const imported = manifest.data.entries.find((entry) => entry.relativePath === 'file.txt') - if (!imported) throw new Error('Missing full-access file') - const chunk = await invoke({ - operation: 'chunk', - toolCallId: 'fullImport', - relativePath: imported.relativePath, - revision: imported.revision, - offset: 0, - }) - if (!chunk.ok || chunk.data.kind !== 'chunk') throw new Error('Missing full-access contents') - expect(Object.values(chunk.data.bytes)).toEqual([...Buffer.from('full access contents')]) - await expect( - window.getByRole('switch', { name: 'Full file access', exact: true }) - ).toBeChecked() - await expect( - window.getByRole('switch', { name: 'Full file access', exact: true }) - ).toBeEnabled() - await window.screenshot({ - path: test.info().outputPath('desktop-settings-full-access.png'), - animations: 'disabled', - }) - await window.evaluate(() => document.documentElement.classList.add('dark')) - await window.screenshot({ - path: test.info().outputPath('desktop-settings-full-access-dark.png'), - animations: 'disabled', - }) - await window.evaluate(() => document.documentElement.classList.remove('dark')) - expect(await invoke({ operation: 'read', toolCallId: 'notAuthorized' })).toMatchObject({ - ok: false, - }) - await app?.close() - app = await launch() - window = await app.firstWindow() - await expect(window.getByRole('heading', { name: 'Local files', exact: true })).toHaveText( - 'Local files' - ) - await expect - .poll(() => - window.evaluate(async () => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.settings.getPreferences() + }) + + await test.step('File → Folder Access opens over a focused utility window', async () => { + const serverShown = app.waitForEvent('window', { timeout: 10_000 }) + await app.evaluate(({ Menu }) => { + const item = Menu.getApplicationMenu() + ?.items.flatMap((entry) => entry.submenu?.items ?? []) + .find((entry) => entry.label === 'Server…') + if (!item) throw new Error('Server menu item missing') + item.click() + }) + await expect(await serverShown).toHaveTitle('Sim - Server') + await expect + .poll(() => + app.evaluate(({ BrowserWindow }) => + BrowserWindow.getAllWindows().some( + (win) => win.webContents.getURL().endsWith('server.html') && win.isVisible() ) ) - .toMatchObject({ fullFileAccess: true }) - expect(await invoke({ operation: 'read', toolCallId: 'fullAccess' })).toMatchObject({ - ok: true, - data: { text: 'full access contents' }, - }) - await window.getByRole('switch', { name: 'Full file access', exact: true }).click() - await expect( - window.getByRole('switch', { name: 'Full file access', exact: true }) - ).not.toBeChecked() - const revoked = await requestPermission({ operation: 'read', toolCallId: 'fullAccess' }) - await revoked.prompt - .getByRole('button', { name: "Don't allow", exact: true }) - .click({ noWaitAfter: true }) - expect(await revoked.result).toMatchObject({ ok: false }) - }) - await test.step('a folder grant works in another chat but does not permit symlink escapes', async () => { - expect(await invoke({ operation: 'read', toolCallId: 'otherChat' })).toMatchObject({ - ok: true, - data: { text: 'native file contents' }, - }) - writeFileSync(join(source, 'empty', 'new.txt'), 'new file in a subfolder') - calls.nested = { - toolName: 'read_local_file', - args: { path: join(source, 'empty', 'new.txt') }, - chatId: 'another-chat', - } - expect(await invoke({ operation: 'read', toolCallId: 'nested' })).toMatchObject({ - ok: true, - data: { text: 'new file in a subfolder' }, - }) - rmSync(join(source, 'empty', 'new.txt')) - symlinkSync(join(outside, 'private.txt'), join(source, 'linked.txt')) - calls.escape = { toolName: 'read_local_file', args: { path: join(source, 'linked.txt') } } - const escapedRead = await requestPermission({ operation: 'read', toolCallId: 'escape' }) - await expect(escapedRead.prompt.getByRole('dialog')).toContainText( - JSON.stringify(realpathSync(outside)) ) - await escapedRead.prompt - .getByRole('button', { name: "Don't allow", exact: true }) - .click({ noWaitAfter: true }) - expect(await escapedRead.result).toMatchObject({ ok: false }) - rmSync(join(source, 'linked.txt')) - }) - await test.step('cancelled calls and changed arguments cannot acquire a grant', async () => { - for (const changed of [false, true]) { - calls.stale = { toolName: 'read_local_file', args: { path: join(outside, 'private.txt') } } - const stale = await requestPermission({ operation: 'read', toolCallId: 'stale' }) - if (changed) calls.stale.args.path = join(source, 'report.txt') - else calls.stale = undefined - await stale.prompt - .getByRole('button', { name: 'Allow folder', exact: true }) - .click({ noWaitAfter: true }) - expect(await stale.result).toMatchObject({ ok: false }) + .toBe(true) + const accessMenu = await app.evaluate(({ BrowserWindow, Menu }) => { + const utility = BrowserWindow.getAllWindows().find((win) => + win.webContents.getURL().endsWith('server.html') + ) + if (!utility) throw new Error('Server window missing') + const item = Menu.getApplicationMenu() + ?.items.flatMap((entry) => entry.submenu?.items ?? []) + .find((entry) => entry.label === 'Folder Access…') + if (!item) throw new Error('Folder Access menu item missing') + const popup = Menu.prototype.popup + let shown: { anchoredToUtility: boolean; items: string[] } | undefined + Menu.prototype.popup = function (this: Electron.Menu, options) { + shown = { + anchoredToUtility: options?.window === utility, + items: this.items.map((entry) => entry.label), + } } - }) - await test.step('native traversal rejects redirected ancestors and replaced grant identities', async () => { - const parent = join(realpathSync(source), 'native-parent') - mkdirSync(parent) - writeFileSync(join(parent, 'inside.txt'), 'inside') - const linked = join(realpathSync(source), 'native-link') - symlinkSync(outside, linked) try { - const result = await app?.evaluate( - async ({ app }, paths) => { - const { createRequire } = process.getBuiltinModule('node:module') - const { stat } = process.getBuiltinModule('node:fs/promises') - const fs = process.getBuiltinModule('node:fs') - const native = createRequire(`${app.getAppPath()}/package.json`)( - './dist/native/directory.node' - ) as { - openApproved( - root: string, - relative: string, - dev: bigint, - ino: bigint, - directory: boolean - ): Promise - } - const root = await stat(paths.source, { bigint: true }) - const denied = async (path: string, ino = root.ino) => { - try { - const fd = await native.openApproved(paths.source, path, root.dev, ino, false) - fs.closeSync(fd) - return false - } catch { - return true - } - } - const valid = await native.openApproved( - paths.source, - 'native-parent/inside.txt', - root.dev, - root.ino, - false - ) - const text = fs.readFileSync(valid, 'utf8') - fs.closeSync(valid) - return { - text, - ancestor: await denied('native-link/private.txt'), - traversal: await denied('../Reports-other/private.txt'), - replaced: await denied('native-parent/inside.txt', root.ino + 1n), - overflow: await denied('native-parent/inside.txt', root.ino + (1n << 64n)), - } - }, - { source: realpathSync(source) } - ) - expect(result).toEqual({ - text: 'inside', - ancestor: true, - traversal: true, - replaced: true, - overflow: true, - }) + item.click(undefined, utility) } finally { - rmSync(linked) - rmSync(parent, { recursive: true }) + Menu.prototype.popup = popup } + utility.close() + return shown }) - await test.step('a symlink replacement cannot redirect an inspected file', async () => { - const file = realpathSync(join(source, 'report.txt')) - const backup = join(source, 'original-report.txt') - const other = join(source, 'other.txt') - writeFileSync(other, 'different file contents') - await app?.evaluate( - (_electron, paths) => { - const fs = process.getBuiltinModule( - 'node:fs/promises' - ) as typeof import('node:fs/promises') - const original = fs.stat - fs.stat = (async (...args: Parameters) => { - const result = await original(...args) - if (args[0] === paths.file) { - fs.stat = original - await fs.rename(paths.file, paths.backup) - await fs.symlink(paths.other, paths.file) - } - return result - }) as typeof fs.stat - }, - { file, backup, other } - ) - try { - expect(await invoke({ operation: 'read', toolCallId: 'text' })).toMatchObject({ ok: false }) - } finally { - rmSync(file) - renameSync(backup, file) - rmSync(other) - } + expect(accessMenu?.anchoredToUtility).toBe(true) + expect(accessMenu?.items).toContain('Add Folder…') + }) +}) + +test('Full file access is opt-in, survives restart, turns off cleanly, and fails closed when it cannot be saved', async ({ + localFiles, +}) => { + const { root, outside, calls } = localFiles + let session = await localFiles.open() + const fullFolder = join(root, 'Full access') + mkdirSync(fullFolder) + writeFileSync(join(fullFolder, 'file.txt'), 'full access contents') + calls.fullAccess = { toolName: 'read_local_file', args: { path: join(fullFolder, 'file.txt') } } + + await test.step('a request that ended cannot enable Full file access from its confirmation', async () => { + calls.expiringFullAccess = { + toolName: 'read_local_file', + args: { path: join(outside, 'private.txt') }, + } + const permission = await session.requestPermission({ + operation: 'read', + toolCallId: 'expiringFullAccess', }) - await test.step('swapping an ancestor cannot redirect directory enumeration', async () => { - const parent = join(realpathSync(source), 'parent') - const child = join(parent, 'child') - const backup = join(realpathSync(source), 'parent-backup') - const otherParent = join(outside, 'parent') - mkdirSync(child, { recursive: true }) - mkdirSync(join(otherParent, 'child'), { recursive: true }) - writeFileSync(join(child, 'allowed.txt'), 'allowed') - writeFileSync(join(otherParent, 'child', 'private.txt'), 'outside') - calls.ancestorRace = { toolName: 'read_local_file', args: { path: child } } - await app?.evaluate( - (_electron, paths) => { - const fs = process.getBuiltinModule( - 'node:fs/promises' - ) as typeof import('node:fs/promises') - const originalStat = fs.lstat - const originalRealpath = fs.realpath - let swapped = false - const restore = async () => { - fs.lstat = originalStat - fs.realpath = originalRealpath - if (swapped) { - await fs.rm(paths.parent) - await fs.rename(paths.backup, paths.parent) - swapped = false - } - } - ;( - globalThis as typeof globalThis & { restoreLocalFileRace?: () => Promise } - ).restoreLocalFileRace = restore - fs.lstat = (async (...args: Parameters) => { - const result = await originalStat(...args) - if (args[0] === paths.child) { - fs.lstat = originalStat - await fs.rename(paths.parent, paths.backup) - await fs.symlink(paths.otherParent, paths.parent) - swapped = true - } - return result - }) as typeof fs.lstat - fs.realpath = (async (...args: Parameters) => { - if (swapped && args[0] === paths.child) await restore() - return originalRealpath(...args) - }) as typeof fs.realpath - }, - { parent, child, backup, otherParent } - ) - try { - expect(await invoke({ operation: 'read', toolCallId: 'ancestorRace' })).toMatchObject({ - ok: true, - data: { entries: [{ name: 'allowed.txt', kind: 'file' }] }, - }) - } finally { - await app?.evaluate(async () => { - const runtime = globalThis as typeof globalThis & { - restoreLocalFileRace?: () => Promise - } - await runtime.restoreLocalFileRace?.() - runtime.restoreLocalFileRace = undefined - }) - rmSync(parent, { recursive: true, force: true }) - rmSync(otherParent, { recursive: true, force: true }) - } + const shown = session.app.waitForEvent('window') + await answerShellDialog(permission.prompt, 'Full file access') + const confirmation = await shown + calls.expiringFullAccess = undefined + await answerShellDialog(confirmation, 'Enable') + expect(await permission.result).toMatchObject({ ok: false }) + expect(await session.preferences()).toMatchObject({ fullFileAccess: false }) + }) + + await test.step('Cancel on the confirmation returns to the folder prompt, and Enable reaches every folder', async () => { + const { app, invoke, fullAccess } = session + await expect(fullAccess).not.toBeChecked() + const permission = await session.requestPermission({ + operation: 'read', + toolCallId: 'fullAccess', }) - await test.step('a replaced directory cannot return a listing for its old contents', async () => { - const directory = join(realpathSync(source), 'replace-during-read') - const backup = join(realpathSync(source), 'previous-directory') - mkdirSync(directory) - writeFileSync(join(directory, 'old.txt'), 'old contents') - calls.directoryReplaced = { toolName: 'read_local_file', args: { path: directory } } - await app?.evaluate( - (_electron, paths) => { - const fs = process.getBuiltinModule( - 'node:fs/promises' - ) as typeof import('node:fs/promises') - const original = fs.lstat - fs.lstat = (async (...args: Parameters) => { - if (args[0] === paths.directory) { - fs.lstat = original - await fs.rename(paths.directory, paths.backup) - await fs.mkdir(paths.directory) - await fs.writeFile(`${paths.directory}/new.txt`, 'new contents') - } - return original(...args) - }) as typeof fs.lstat - }, - { directory, backup } - ) + const confirmationShown = app.waitForEvent('window') + await answerShellDialog(permission.prompt, 'Full file access') + const confirmation = await confirmationShown + await expect(confirmation.getByRole('button', { name: 'Cancel', exact: true })).toBeFocused() + const returnedPrompt = app.waitForEvent('window') + await answerShellDialog(confirmation, 'Cancel') + const folderPrompt = await returnedPrompt + expect(await session.preferences()).toMatchObject({ fullFileAccess: false }) + const acceptedConfirmation = app.waitForEvent('window') + await answerShellDialog(folderPrompt, 'Full file access') + await answerShellDialog(await acceptedConfirmation, 'Enable') + expect(await permission.result).toMatchObject({ + ok: true, + data: { text: 'full access contents' }, + }) + // The desktop pushes the change to open settings pages. + await expect(fullAccess).toBeChecked() + expect(await invoke({ operation: 'read', toolCallId: 'fullAccess' })).toMatchObject({ + ok: true, + data: { text: 'full access contents' }, + }) + calls.fullImport = { + toolName: 'import_local_files', + args: { path: fullFolder, targetWorkspaceId: 'target-workspace' }, + } + const manifest = await invoke({ operation: 'manifest', toolCallId: 'fullImport' }) + if (!manifest.ok || manifest.data.kind !== 'manifest') + throw new Error('Missing full-access manifest') + const imported = manifest.data.entries.find((entry) => entry.relativePath === 'file.txt') + if (!imported) throw new Error('Missing full-access file') + const chunk = await invoke({ + operation: 'chunk', + toolCallId: 'fullImport', + relativePath: imported.relativePath, + revision: imported.revision, + offset: 0, + }) + if (!chunk.ok || chunk.data.kind !== 'chunk') throw new Error('Missing full-access contents') + expect(Object.values(chunk.data.bytes)).toEqual([...Buffer.from('full access contents')]) + expect(await invoke({ operation: 'read', toolCallId: 'notAuthorized' })).toMatchObject({ + ok: false, + }) + }) + + await test.step('Full file access survives restart, and turning it off brings folder prompts back', async () => { + await localFiles.close(session) + session = await localFiles.open(session.desktop.userData) + expect(await session.preferences()).toMatchObject({ fullFileAccess: true }) + expect(await session.invoke({ operation: 'read', toolCallId: 'fullAccess' })).toMatchObject({ + ok: true, + data: { text: 'full access contents' }, + }) + await expect(session.fullAccess).toBeChecked() + await session.fullAccess.click() + await expect(session.fullAccess).not.toBeChecked() + const revoked = await session.requestPermission({ operation: 'read', toolCallId: 'fullAccess' }) + await answerShellDialog(revoked.prompt, "Don't allow") + expect(await revoked.result).toMatchObject({ ok: false }) + }) + + await test.step('a failed settings write leaves Full file access off and local files denied', async () => { + const userData = session.desktop.userData + const settingsPath = join(userData, 'settings.json') + const backupPath = `${settingsPath}.backup` + const saved = JSON.parse(readFileSync(settingsPath, 'utf8')) + for (const previous of [false, true]) { + await localFiles.close(session) + writeFileSync(settingsPath, JSON.stringify({ ...saved, fullFileAccess: previous })) + session = await localFiles.open(userData) + await expect(session.fullAccess).toBeChecked({ checked: previous }) + // A directory where the settings file belongs makes the next write fail. + renameSync(settingsPath, backupPath) + mkdirSync(settingsPath) try { - expect(await invoke({ operation: 'read', toolCallId: 'directoryReplaced' })).toMatchObject({ + await session.fullAccess.click() + await expect(session.window.getByRole('status')).toHaveText('Not saved') + await expect(session.fullAccess).not.toBeChecked() + expect(await session.preferences()).toMatchObject({ fullFileAccess: false }) + expect(await session.invoke({ operation: 'read', toolCallId: 'text' })).toMatchObject({ ok: false, }) } finally { - rmSync(directory, { recursive: true, force: true }) - rmSync(backup, { recursive: true, force: true }) + await localFiles.close(session) + rmSync(settingsPath, { recursive: true, force: true }) + renameSync(backupPath, settingsPath) } + } + }) +}) + +test('native file access refuses paths swapped or replaced while it reads them', async ({ + localFiles, +}) => { + const { source, outside, calls } = localFiles + const { app, invoke, requestPermission } = await localFiles.open() + const granted = await requestPermission({ operation: 'read', toolCallId: 'directory' }) + await answerShellDialog(granted.prompt, 'Allow folder') + expect(await granted.result).toMatchObject({ ok: true }) + + await test.step('native traversal rejects redirected ancestors and replaced grant identities', async () => { + const parent = join(realpathSync(source), 'native-parent') + mkdirSync(parent) + writeFileSync(join(parent, 'inside.txt'), 'inside') + symlinkSync(outside, join(realpathSync(source), 'native-link')) + const result = await app.evaluate( + async ({ app }, paths) => { + const { createRequire } = process.getBuiltinModule('node:module') + const { stat } = process.getBuiltinModule('node:fs/promises') + const fs = process.getBuiltinModule('node:fs') + const native = createRequire(`${app.getAppPath()}/package.json`)( + './dist/native/directory.node' + ) as { + openApproved( + root: string, + relative: string, + dev: bigint, + ino: bigint, + directory: boolean + ): Promise + } + const root = await stat(paths.source, { bigint: true }) + const denied = async (path: string, ino = root.ino) => { + try { + const fd = await native.openApproved(paths.source, path, root.dev, ino, false) + fs.closeSync(fd) + return false + } catch { + return true + } + } + const valid = await native.openApproved( + paths.source, + 'native-parent/inside.txt', + root.dev, + root.ino, + false + ) + const text = fs.readFileSync(valid, 'utf8') + fs.closeSync(valid) + return { + text, + ancestor: await denied('native-link/private.txt'), + traversal: await denied('../Reports-other/private.txt'), + replaced: await denied('native-parent/inside.txt', root.ino + 1n), + overflow: await denied('native-parent/inside.txt', root.ino + (1n << 64n)), + } + }, + { source: realpathSync(source) } + ) + expect(result).toEqual({ + text: 'inside', + ancestor: true, + traversal: true, + replaced: true, + overflow: true, }) - await test.step('cancelling a directory read prevents its contents from returning', async () => { - const path = realpathSync(join(source, 'empty')) - calls.directoryCancel = { toolName: 'read_local_file', args: { path } } - await app?.evaluate((_electron, path) => { + }) + + await test.step('a symlink swapped in after inspection cannot redirect a file read', async () => { + const file = realpathSync(join(source, 'report.txt')) + const backup = join(source, 'original-report.txt') + const other = join(source, 'other.txt') + writeFileSync(other, 'different file contents') + await app.evaluate( + (_electron, paths) => { + const fs = process.getBuiltinModule('node:fs/promises') as typeof import('node:fs/promises') + const original = fs.stat + const fired: string[] = [] + ;(globalThis as FsPatchRuntime).e2eFsPatch = { + fired, + restore: () => { + fs.stat = original + }, + } + fs.stat = (async (...args: Parameters) => { + const result = await original(...args) + if (args[0] === paths.file) { + fs.stat = original + await fs.rename(paths.file, paths.backup) + await fs.symlink(paths.other, paths.file) + fired.push('swapped') + } + return result + }) as typeof fs.stat + }, + { file, backup, other } + ) + let fired: string[] = [] + try { + expect(await invoke({ operation: 'read', toolCallId: 'text' })).toMatchObject({ ok: false }) + } finally { + fired = await restoreFsPatch(app) + if (fired.includes('swapped')) { + rmSync(file) + renameSync(backup, file) + } + rmSync(other) + } + expect(fired).toEqual(['swapped']) + }) + + await test.step('swapping an ancestor cannot redirect directory enumeration', async () => { + const parent = join(realpathSync(source), 'parent') + const child = join(parent, 'child') + const backup = join(realpathSync(source), 'parent-backup') + const otherParent = join(outside, 'parent') + mkdirSync(child, { recursive: true }) + mkdirSync(join(otherParent, 'child'), { recursive: true }) + writeFileSync(join(child, 'allowed.txt'), 'allowed') + writeFileSync(join(otherParent, 'child', 'private.txt'), 'outside') + calls.ancestorRace = { toolName: 'read_local_file', args: { path: child } } + await app.evaluate( + (_electron, paths) => { + const fs = process.getBuiltinModule('node:fs/promises') as typeof import('node:fs/promises') + const originalLstat = fs.lstat + const originalRealpath = fs.realpath + const fired: string[] = [] + let swapped = false + const unswap = async () => { + if (!swapped) return + swapped = false + await fs.rm(paths.parent) + await fs.rename(paths.backup, paths.parent) + } + ;(globalThis as FsPatchRuntime).e2eFsPatch = { + fired, + restore: async () => { + fs.lstat = originalLstat + fs.realpath = originalRealpath + await unswap() + }, + } + fs.lstat = (async (...args: Parameters) => { + const result = await originalLstat(...args) + if (args[0] === paths.child) { + fs.lstat = originalLstat + await fs.rename(paths.parent, paths.backup) + await fs.symlink(paths.otherParent, paths.parent) + swapped = true + fired.push('swapped') + } + return result + }) as typeof fs.lstat + fs.realpath = (async (...args: Parameters) => { + if (args[0] === paths.child) await unswap() + return originalRealpath(...args) + }) as typeof fs.realpath + }, + { parent, child, backup, otherParent } + ) + let fired: string[] = [] + try { + expect(await invoke({ operation: 'read', toolCallId: 'ancestorRace' })).toMatchObject({ + ok: true, + data: { entries: [{ name: 'allowed.txt', kind: 'file' }] }, + }) + } finally { + fired = await restoreFsPatch(app) + rmSync(parent, { recursive: true, force: true }) + rmSync(otherParent, { recursive: true, force: true }) + } + expect(fired).toEqual(['swapped']) + }) + + await test.step('a replaced directory cannot return a listing for its old contents', async () => { + const directory = join(realpathSync(source), 'replace-during-read') + const backup = join(realpathSync(source), 'previous-directory') + mkdirSync(directory) + writeFileSync(join(directory, 'old.txt'), 'old contents') + calls.directoryReplaced = { toolName: 'read_local_file', args: { path: directory } } + await app.evaluate( + (_electron, paths) => { const fs = process.getBuiltinModule('node:fs/promises') as typeof import('node:fs/promises') const original = fs.lstat + const fired: string[] = [] + ;(globalThis as FsPatchRuntime).e2eFsPatch = { + fired, + restore: () => { + fs.lstat = original + }, + } fs.lstat = (async (...args: Parameters) => { - const handle = await original(...args) - if (args[0] === path) { + if (args[0] === paths.directory) { fs.lstat = original - await new Promise((resolve) => { - ;( - globalThis as typeof globalThis & { releaseLocalFileRead?: () => void } - ).releaseLocalFileRead = resolve - }) + await fs.rename(paths.directory, paths.backup) + await fs.mkdir(paths.directory) + await fs.writeFile(`${paths.directory}/new.txt`, 'new contents') + fired.push('replaced') } - return handle + return original(...args) }) as typeof fs.lstat - }, path) - const reading = invoke({ operation: 'read', toolCallId: 'directoryCancel' }) - void reading.catch(() => {}) - try { - await expect - .poll(() => - app?.evaluate( - () => - typeof (globalThis as typeof globalThis & { releaseLocalFileRead?: () => void }) - .releaseLocalFileRead === 'function' - ) - ) - .toBe(true) - await invoke({ operation: 'cancel', toolCallId: 'directoryCancel' }) - } finally { - await app?.evaluate(() => { - const runtime = globalThis as typeof globalThis & { releaseLocalFileRead?: () => void } - runtime.releaseLocalFileRead?.() - runtime.releaseLocalFileRead = undefined - }) - } - expect(await reading).toMatchObject({ ok: false }) - }) - await test.step('cancelling in the renderer closes consent without remembering access', async () => { - calls.cancelled = { - toolName: 'read_local_file', - args: { path: join(outside, 'private.txt') }, - } - const cancelled = await requestPermission({ operation: 'read', toolCallId: 'cancelled' }) - const closed = cancelled.prompt.waitForEvent('close', { timeout: 5000 }) - await window.evaluate(async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - await api.localFiles?.({ operation: 'cancel', toolCallId: 'cancelled' }) - }) - await closed - expect(await cancelled.result).toMatchObject({ ok: false }) - const again = await requestPermission({ operation: 'read', toolCallId: 'cancelled' }) - await again.prompt - .getByRole('button', { name: "Don't allow", exact: true }) - .click({ noWaitAfter: true }) - expect(await again.result).toMatchObject({ ok: false }) - }) - await test.step('consent escapes direction controls in folder names', async () => { - const folder = join(root, 'Bidi\u061c\u200e\u200f') - mkdirSync(folder) - calls.bidi = { toolName: 'read_local_file', args: { path: folder } } - const bidi = await requestPermission({ operation: 'read', toolCallId: 'bidi' }) - await expect(bidi.prompt.getByRole('dialog')).toContainText('Bidi\\u061c\\u200e\\u200f') - await bidi.prompt - .getByRole('button', { name: "Don't allow", exact: true }) - .click({ noWaitAfter: true }) - expect(await bidi.result).toMatchObject({ ok: false }) - }) - await test.step('an unanswered prompt does not block approved folders', async () => { - calls.blocker = { toolName: 'read_local_file', args: { path: join(outside, 'private.txt') } } - const blocker = await requestPermission({ operation: 'read', toolCallId: 'blocker' }) - expect(await invoke({ operation: 'read', toolCallId: 'text' })).toMatchObject({ ok: true }) - await blocker.prompt - .getByRole('button', { name: "Don't allow", exact: true }) - .click({ noWaitAfter: true }) - expect(await blocker.result).toMatchObject({ ok: false }) - }) - await test.step('cancelled calls cannot reuse an approved folder', async () => { - calls.expired = { toolName: 'read_local_file', args: { path: join(source, 'report.txt') } } - expireAfterAuthorization.add('expired') - expect(await invoke({ operation: 'read', toolCallId: 'expired' })).toMatchObject({ + }, + { directory, backup } + ) + let fired: string[] = [] + try { + expect(await invoke({ operation: 'read', toolCallId: 'directoryReplaced' })).toMatchObject({ ok: false, }) - }) - await test.step('replacing the proposed folder during consent does not expose its new target', async () => { - const proposed = join(root, 'Proposed') - mkdirSync(proposed) - calls.retargeted = { toolName: 'read_local_file', args: { path: proposed } } - const retargeted = await requestPermission({ operation: 'read', toolCallId: 'retargeted' }) - renameSync(proposed, join(root, 'Original')) - mkdirSync(proposed) - writeFileSync(join(proposed, 'unapproved.txt'), 'replacement folder contents') - await retargeted.prompt - .getByRole('button', { name: 'Allow folder', exact: true }) - .click({ noWaitAfter: true }) - expect(await retargeted.result).toMatchObject({ ok: false }) - }) - const result = await invoke({ operation: 'manifest', toolCallId: 'import' }) - if (!result.ok || result.data.kind !== 'manifest') throw new Error(JSON.stringify(result)) - expect(result.data.targetWorkspaceId).toBe('target-workspace') - expect(result.data.entries.map((entry) => entry.relativePath)).toEqual([ - '', - 'empty', - 'image.png', - 'report.txt', - ]) - const file = result.data.entries.find((entry) => entry.relativePath === 'report.txt') - if (!file) throw new Error('Missing import file') - const chunk = await invoke({ - operation: 'chunk', - toolCallId: 'import', - relativePath: file.relativePath, - revision: file.revision, - offset: 0, - }) - if (!chunk.ok || chunk.data.kind !== 'chunk') throw new Error(JSON.stringify(chunk)) - expect(Object.values(chunk.data.bytes)).toEqual([...Buffer.from('native file contents')]) - expect(chunk.data.eof).toBe(true) - expect( - await window.evaluate( - async (input) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - const response = await api.localFiles?.(input) - if (!response?.ok || response.data.kind !== 'chunk') - throw new Error('Missing native chunk') - const file = new File([new Uint8Array(response.data.bytes)], 'report.txt') - return file.text() - }, - { - operation: 'chunk' as const, - toolCallId: 'import', - relativePath: file.relativePath, - revision: file.revision, - offset: 0, - } - ) - ).toBe('native file contents') - expect(await invoke({ operation: 'manifest', toolCallId: 'import' })).toMatchObject({ - ok: false, - code: 'ALREADY_STARTED', - }) - await test.step('an approved folder permits imports without repeated destination prompts', async () => { - calls.otherImport = { - toolName: 'import_local_files', - args: { path: source, targetWorkspaceId: 'other-workspace' }, - } - expect(await invoke({ operation: 'manifest', toolCallId: 'otherImport' })).toMatchObject({ - ok: true, - }) - }) - await test.step('folder permissions survive restarting the desktop app', async () => { - await app?.close() - app = await launch() - window = await app.firstWindow() - await expect(window.getByRole('heading', { name: 'Local files', exact: true })).toHaveText( - 'Local files' - ) - expect(await invoke({ operation: 'read', toolCallId: 'text' })).toMatchObject({ ok: true }) - }) - await test.step('forgetting a folder revokes native reads and survives restart', async () => { - await window.getByRole('button', { name: 'Forget folders', exact: true }).click() - await expect(window.getByRole('button', { name: 'Forgotten', exact: true })).toBeVisible() - await app?.close() - app = await launch() - window = await app.firstWindow() - await expect(window.getByRole('heading', { name: 'Local files', exact: true })).toHaveText( - 'Local files' - ) - const revoked = await requestPermission({ operation: 'read', toolCallId: 'text' }) - await revoked.prompt - .getByRole('button', { name: 'Allow folder', exact: true }) - .click({ noWaitAfter: true }) - expect(await revoked.result).toMatchObject({ ok: true }) - }) - - await test.step('a remembered grant does not follow a replaced folder after restart', async () => { - await app?.close() - renameSync(source, join(root, 'Original-reports')) - mkdirSync(source) - writeFileSync(join(source, 'report.txt'), 'replacement contents') - app = await launch() - window = await app.firstWindow() - await expect(window.getByRole('heading', { name: 'Local files', exact: true })).toHaveText( - 'Local files' - ) - const replaced = await requestPermission({ operation: 'read', toolCallId: 'text' }) - await replaced.prompt - .getByRole('button', { name: "Don't allow", exact: true }) - .click({ noWaitAfter: true }) - expect(await replaced.result).toMatchObject({ ok: false }) - rmSync(source, { recursive: true }) - renameSync(join(root, 'Original-reports'), source) - const restored = await requestPermission({ operation: 'read', toolCallId: 'text' }) - await restored.prompt - .getByRole('button', { name: 'Allow folder', exact: true }) - .click({ noWaitAfter: true }) - expect(await restored.result).toMatchObject({ ok: true }) - }) + } finally { + fired = await restoreFsPatch(app) + rmSync(directory, { recursive: true, force: true }) + rmSync(backup, { recursive: true, force: true }) + } + expect(fired).toEqual(['replaced']) + }) - await test.step('sign-out revokes remembered grants and Full file access before the next account session', async () => { - await window.getByRole('switch', { name: 'Full file access', exact: true }).click() - await expect( - window.getByRole('switch', { name: 'Full file access', exact: true }) - ).toBeChecked() - await app?.evaluate(({ Menu }) => { - const item = Menu.getApplicationMenu() - ?.items.flatMap((entry) => entry.submenu?.items ?? []) - .find((entry) => entry.label === 'Sign Out') - if (!item) throw new Error('Sign Out menu item missing') - item.click() + await test.step('cancelling a directory read prevents its contents from returning', async () => { + const path = realpathSync(join(source, 'empty')) + calls.directoryCancel = { toolName: 'read_local_file', args: { path } } + await app.evaluate((_electron, path) => { + const fs = process.getBuiltinModule('node:fs/promises') as typeof import('node:fs/promises') + const original = fs.lstat + const fired: string[] = [] + let release = () => {} + const held = new Promise((resolve) => { + release = resolve }) - await expect(window).toHaveURL(`http://127.0.0.1:${address.port}/login`) - signedIn = true - await window.goto(`http://127.0.0.1:${address.port}/`) + ;(globalThis as FsPatchRuntime).e2eFsPatch = { + fired, + restore: () => { + fs.lstat = original + release() + }, + } + fs.lstat = (async (...args: Parameters) => { + const result = await original(...args) + if (args[0] === path) { + fs.lstat = original + fired.push('held') + await held + } + return result + }) as typeof fs.lstat + }, path) + const reading = invoke({ operation: 'read', toolCallId: 'directoryCancel' }) + void reading.catch(() => {}) + try { await expect .poll(() => - window.evaluate(async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - return (await api.localFilesystem?.({ operation: 'list_mounts' }))?.ok - }) + app.evaluate(() => (globalThis as FsPatchRuntime).e2eFsPatch?.fired.includes('held')) ) .toBe(true) - await expect - .poll(() => - window.evaluate(async () => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.settings.getPreferences() - ) - ) - .toMatchObject({ fullFileAccess: false }) - const revoked = await requestPermission({ operation: 'read', toolCallId: 'text' }) - await revoked.prompt - .getByRole('button', { name: "Don't allow", exact: true }) - .click({ noWaitAfter: true }) - expect(await revoked.result).toMatchObject({ ok: false }) + await invoke({ operation: 'cancel', toolCallId: 'directoryCancel' }) + } finally { + await restoreFsPatch(app) + } + expect(await reading).toMatchObject({ ok: false }) + }) +}) + +test('remembered folder grants survive restart until forgotten, replaced, or signed out', async ({ + localFiles, +}) => { + const { root, source } = localFiles + let session = await localFiles.open() + const restart = async () => { + await localFiles.close(session) + session = await localFiles.open(session.desktop.userData) + } + const answerTextRead = async (button: 'Allow folder' | "Don't allow") => { + const permission = await session.requestPermission({ operation: 'read', toolCallId: 'text' }) + await answerShellDialog(permission.prompt, button) + return permission.result + } + expect(await answerTextRead('Allow folder')).toMatchObject({ ok: true }) + + await test.step('a folder grant survives restarting the app', async () => { + await restart() + expect(await session.invoke({ operation: 'read', toolCallId: 'text' })).toMatchObject({ + ok: true, }) - await test.step('a failed settings write reports the error and leaves Full file access disabled', async () => { - const settingsPath = join(root, 'profile', 'settings.json') - const saved = JSON.parse(readFileSync(settingsPath, 'utf8')) - for (const previous of [false, true]) { - await app?.close() - rmSync(settingsPath, { recursive: true, force: true }) - writeFileSync(settingsPath, JSON.stringify({ ...saved, fullFileAccess: previous })) - app = await launch() - window = await app.firstWindow() - const toggle = window.getByRole('switch', { name: 'Full file access', exact: true }) - await expect(toggle).toBeChecked({ checked: previous }) - renameSync(settingsPath, `${settingsPath}.backup`) - mkdirSync(settingsPath) - try { - await toggle.click() - await expect( - window.getByText( - 'Could not save file access settings. Your previous setting may return after restarting Sim.', - { exact: true } - ) - ).toBeVisible() - await expect(toggle).not.toBeChecked() - expect( - await window.evaluate(async () => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.settings.getPreferences() - ) - ).toMatchObject({ fullFileAccess: false }) - expect(await invoke({ operation: 'read', toolCallId: 'text' })).toMatchObject({ - ok: false, - }) - } finally { - await app.close() - app = undefined - rmSync(settingsPath, { recursive: true, force: true }) - renameSync(`${settingsPath}.backup`, settingsPath) - } - } + }) + + await test.step('forgetting a folder revokes native reads and survives restart', async () => { + await session.window.getByRole('button', { name: 'Forget folders', exact: true }).click() + await expect( + session.window.getByRole('button', { name: 'Forgotten', exact: true }) + ).toBeVisible() + await restart() + expect(await answerTextRead('Allow folder')).toMatchObject({ ok: true }) + }) + + await test.step('a remembered grant does not follow a replaced folder after restart', async () => { + await localFiles.close(session) + renameSync(source, join(root, 'Original-reports')) + mkdirSync(source) + writeFileSync(join(source, 'report.txt'), 'replacement contents') + session = await localFiles.open(session.desktop.userData) + expect(await answerTextRead("Don't allow")).toMatchObject({ ok: false }) + rmSync(source, { recursive: true }) + renameSync(join(root, 'Original-reports'), source) + expect(await answerTextRead('Allow folder')).toMatchObject({ ok: true }) + }) + + await test.step('sign-out revokes remembered grants and Full file access before the next account session', async () => { + const { app, window, fullAccess } = session + await fullAccess.click() + await expect(fullAccess).toBeChecked() + await app.evaluate(({ Menu }) => { + const item = Menu.getApplicationMenu() + ?.items.flatMap((entry) => entry.submenu?.items ?? []) + .find((entry) => entry.label === 'Sign Out') + if (!item) throw new Error('Sign Out menu item missing') + item.click() }) - } finally { - await app?.close() - server?.close() - rmSync(root, { recursive: true, force: true }) - } + await expect(window).toHaveURL(`${localFiles.origin}/login`) + localFiles.signIn() + await window.goto(`${localFiles.origin}/`) + await expect + .poll(() => + window.evaluate( + async () => + ( + await (globalThis as DesktopBridge).simDesktop.localFilesystem?.({ + operation: 'list_mounts', + }) + )?.ok + ) + ) + .toBe(true) + await expect.poll(() => session.preferences()).toMatchObject({ fullFileAccess: false }) + expect(await answerTextRead("Don't allow")).toMatchObject({ ok: false }) + }) }) diff --git a/apps/desktop/e2e/packaged-smoke.spec.ts b/apps/desktop/e2e/packaged-smoke.spec.ts index 559db75d3ea..c2be201f8d7 100644 --- a/apps/desktop/e2e/packaged-smoke.spec.ts +++ b/apps/desktop/e2e/packaged-smoke.spec.ts @@ -1,10 +1,10 @@ -import { type ChildProcess, execFileSync, spawn } from 'node:child_process' -import { once } from 'node:events' -import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs' +import { spawn } from 'node:child_process' +import { existsSync, mkdtempSync, readFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { FuseV1Options, FuseVersion, getCurrentFuseWire } from '@electron/fuses' -import { type Browser, chromium, expect, test } from '@playwright/test' +import { type Browser, chromium } from '@playwright/test' +import { expect, stopAndRemoveProfile, test } from './harness' const FUSE_DISABLED = '0'.charCodeAt(0) const FUSE_ENABLED = '1'.charCodeAt(0) @@ -27,53 +27,6 @@ test.skip( 'Packaged smoke runs only after the desktop executable has been built' ) -/** - * The processes of a packaged run that can still write its profile. Chromium's helpers stay in the - * app's process group (it is spawned detached, so the group is its own), while Crashpad's handler - * starts its own session but names the profile's Crashpad database on its command line. - */ -function profileWriters(appGroup: number, profilePaths: readonly string[]): number[] { - return execFileSync('ps', ['-axww', '-o', 'pid=,pgid=,command='], { encoding: 'utf8' }) - .split('\n') - .flatMap((line) => { - const match = /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line) - if (!match) return [] - const [, pid, group, command] = match - return Number(group) === appGroup || profilePaths.some((path) => command.includes(path)) - ? [Number(pid)] - : [] - }) -} - -/** - * Removes a profile only once nothing can write into it. Killing the main process leaves its - * helpers and Crashpad's handler running for a moment, and a file one of them creates while the - * directory is being removed fails the removal with ENOTEMPTY. - */ -async function stopAndRemoveProfile(child: ChildProcess, userDataPath: string): Promise { - if (child.exitCode === null && child.signalCode === null) { - const exited = once(child, 'exit') - child.kill('SIGKILL') - await exited - } - const appGroup = child.pid - if (appGroup !== undefined) { - const profilePaths = [userDataPath, realpathSync(userDataPath)] - await expect - .poll(() => { - const writers = profileWriters(appGroup, profilePaths) - for (const pid of writers) { - try { - process.kill(pid, 'SIGKILL') - } catch {} - } - return writers - }) - .toEqual([]) - } - rmSync(userDataPath, { recursive: true, force: true }) -} - test('packaged Electron binary has the production fuse policy', async () => { const executablePath = process.env.SIM_DESKTOP_EXECUTABLE if (!executablePath) throw new Error('SIM_DESKTOP_EXECUTABLE is required') @@ -90,48 +43,12 @@ test('packaged Electron binary has the production fuse policy', async () => { } }) -test('packaged main process starts and records launch telemetry', async () => { - const executablePath = process.env.SIM_DESKTOP_EXECUTABLE - if (!executablePath) throw new Error('SIM_DESKTOP_EXECUTABLE is required') - const userDataPath = mkdtempSync(join(tmpdir(), 'sim-desktop-packaged-e2e-')) - const child = spawn(executablePath, [], { - detached: true, - env: { - ...process.env, - SIM_DESKTOP_ORIGIN: 'http://127.0.0.1:1', - SIM_DESKTOP_USER_DATA: userDataPath, - }, - stdio: 'ignore', - }) - const eventLogPath = join(userDataPath, 'logs', 'desktop-events.log') - - try { - await expect - .poll( - () => { - if (child.exitCode !== null || child.signalCode !== null) { - throw new Error( - `Packaged app exited with ${child.exitCode ?? child.signalCode ?? 'unknown status'}` - ) - } - return ( - existsSync(eventLogPath) && readFileSync(eventLogPath, 'utf8').includes('app_launch') - ) - }, - { timeout: 10_000 } - ) - .toBe(true) - } finally { - await stopAndRemoveProfile(child, userDataPath) - } -}) - // The unpackaged suite cannot see this: the bundled pages live inside app.asar // only once packaged, and the file-protocol fuse is only off once packaged. // v0.8.13 through v0.8.19 shipped both pages blank because nothing loaded them // in that configuration. Chromium's remote-debugging switch is honoured by the // fused binary, which is what lets the test read the rendered page. -test('packaged shell renders the bundled offline page', async () => { +test('packaged shell records its launch and renders the bundled offline page', async () => { const executablePath = process.env.SIM_DESKTOP_EXECUTABLE if (!executablePath) throw new Error('SIM_DESKTOP_EXECUTABLE is required') const userDataPath = mkdtempSync(join(tmpdir(), 'sim-desktop-packaged-e2e-')) @@ -179,6 +96,10 @@ test('packaged shell renders the bundled offline page', async () => { if (!offline) throw new Error('offline page disappeared') await expect(offline.locator('#title')).toHaveText('Can’t connect to Sim') await expect(offline.locator('#server')).toBeVisible() + const eventLog = join(userDataPath, 'logs', 'desktop-events.log') + await expect + .poll(() => existsSync(eventLog) && readFileSync(eventLog, 'utf8').includes('app_launch')) + .toBe(true) // The picker is the recovery path from here. Opening it and reading the // pre-filled value crosses the local-page IPC gate twice, which packaged diff --git a/apps/desktop/e2e/password-autofill.spec.ts b/apps/desktop/e2e/password-autofill.spec.ts index 8a00ba9bbd3..a2a796dd177 100644 --- a/apps/desktop/e2e/password-autofill.spec.ts +++ b/apps/desktop/e2e/password-autofill.spec.ts @@ -1,125 +1,57 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { createServer, type Server } from 'node:http' -import { tmpdir } from 'node:os' +import { writeFileSync } from 'node:fs' import { join } from 'node:path' -import { fileURLToPath } from 'node:url' +import type { ElectronApplication, Locator, Page } from '@playwright/test' +import { getErrorMessage } from '@sim/utils/errors' import { - type ElectronApplication, - _electron as electron, + attachBrowserPanel, + type DesktopBridge, expect, - type Page, + type FixtureServer, + focusFirstWindow, + hideBrowserPanel, + ToolAuthorizer, test, -} from '@playwright/test' -import type { SimDesktopApi } from '@sim/desktop-bridge' +} from './harness' +import { serveSignedIn } from './session-fixture' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) const SCOPE = 'password-fixture' -const SCREENSHOTS = process.env.SIM_PASSWORD_SCREENSHOTS +const PICKER_PAGE = 'credential-picker.html' const LOGIN = `Account sign in

Sign in to your account

` test.describe('saved password autofill', () => { - let server: Server - let origin: string - let site: string + let fixture: FixtureServer let app: ElectronApplication let host: Page let userData: string - const calls = new Map< - string, - { chatId: string; toolName: string; args: Record } - >() - let serial = 0 + const authorizer = new ToolAuthorizer('fixture') test.beforeAll(async () => { - server = createServer(async (request, response) => { - const path = new URL(request.url ?? '/', 'http://localhost').pathname - if (path === '/api/auth/get-session') { - response.writeHead(200, { 'Content-Type': 'application/json' }) - response.end( - JSON.stringify({ user: { id: 'fixture-user' }, session: { id: 'fixture-session' } }) - ) - return - } - if (path === '/api/desktop/tool/authorize') { - let body = '' - for await (const chunk of request) body += chunk.toString() - const call = calls.get(JSON.parse(body).toolCallId) - response.writeHead(call ? 200 : 403, { 'Content-Type': 'application/json' }) - response.end(JSON.stringify(call ?? {})) - return - } - if (path.startsWith('/api/')) { - response.writeHead(200, { 'Content-Type': 'application/json' }) - response.end('{}') - return - } - response.writeHead(200, { - 'Content-Type': 'text/html', - 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; SameSite=Lax; Path=/', - }) - response.end( - path === '/login' - ? LOGIN - : 'Sim fixture

Password fixture

' - ) + fixture = await serveSignedIn({ + page: 'Sim fixture

Password fixture

', + handle: async (request, response, url) => { + if (await authorizer.handle(request, response, url)) return true + if (url.pathname !== '/login') return false + response.writeHead(200, { 'Content-Type': 'text/html' }).end(LOGIN) + return true + }, }) - await new Promise((resolve) => server.listen(0, resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - origin = `http://127.0.0.1:${address.port}` - site = `http://localhost:${address.port}` }) - test.beforeEach(async () => { - userData = mkdtempSync(join(tmpdir(), 'sim-password-e2e-')) - app = await electron.launch({ - args: ['.'], - cwd: DESKTOP_DIR, - env: { ...process.env, SIM_DESKTOP_ORIGIN: origin, SIM_DESKTOP_USER_DATA: userData }, - }) + test.afterAll(async () => { + await fixture.close() + }) + + test.beforeEach(async ({ desktop }) => { + ;({ app, userData } = await desktop.launch({ origin: fixture.origin })) host = await app.firstWindow() await expect(host.getByRole('heading')).toHaveText('Password fixture') - await app.evaluate(({ app, BrowserWindow }) => { - app.focus({ steal: true }) - BrowserWindow.getAllWindows()[0].focus() - }) - await expect - .poll(() => app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].isFocused())) - .toBe(true) - await host.evaluate(async (scope) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - await api.browserAgent.activateScope(scope) - api.browserAgent.setPanelBounds( - { x: 0, y: 130, width: innerWidth, height: innerHeight - 130 }, - null, - scope - ) - setInterval( - () => - api.browserAgent.setPanelBounds( - { x: 0, y: 130, width: innerWidth, height: innerHeight - 130 }, - null, - scope - ), - 200 - ) - }, SCOPE) + await focusFirstWindow(app) + await attachBrowserPanel(host, SCOPE, 130) await seed(3) - await navigate(`${site}/login`) - }) - - test.afterEach(async () => { - await app?.close() - rmSync(userData, { recursive: true, force: true }) - calls.clear() - }) - test.afterAll(async () => { - await new Promise((resolve, reject) => - server.close((error) => (error ? reject(error) : resolve())) - ) + await navigate(`${fixture.site}/login`) }) async function seed(count: number, prefix = 'account') { @@ -136,7 +68,7 @@ test.describe('saved password autofill', () => { })) return safeStorage.encryptString(JSON.stringify(records)).toString('base64') }, - { site, count, prefix } + { site: fixture.site, count, prefix } ) writeFileSync( join(userData, 'browser-credentials.json'), @@ -146,16 +78,7 @@ test.describe('saved password autofill', () => { } async function navigate(url: string) { - const id = `fixture-${++serial}` - calls.set(id, { chatId: SCOPE, toolName: 'browser_open_url', args: { url } }) - const result = await host.evaluate( - async ({ id, url, scope }) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - return api.browserAgent.executeTool(id, 'browser_open_url', { url }, scope) - }, - { id, url, scope: SCOPE } - ) - expect(result.ok, result.error).toBe(true) + await authorizer.execute(host, SCOPE, 'browser_open_url', { url }) } async function pageScript(script: string): Promise { @@ -167,16 +90,18 @@ test.describe('saved password autofill', () => { if (!page) throw new Error('Missing fixture page') return page.executeJavaScript(script) }, - { site, script } + { site: fixture.site, script } ) } + /** Clicks a login field with native input, as a user would. */ async function clickField(id = 'user') { await app.evaluate( async ({ webContents }, { site, id }) => { const page = webContents .getAllWebContents() - .find((contents) => contents.getURL().startsWith(`${site}/login`))! + .find((contents) => contents.getURL().startsWith(`${site}/login`)) + if (!page) throw new Error('Missing fixture page') const point = await page.executeJavaScript( `(() => {const r=document.getElementById(${JSON.stringify(id)}).getBoundingClientRect();return {x:Math.round(r.x+12),y:Math.round(r.y+12)}})()` ) @@ -184,29 +109,98 @@ test.describe('saved password autofill', () => { page.sendInputEvent({ type: 'mouseDown', button: 'left', clickCount: 1, ...point }) page.sendInputEvent({ type: 'mouseUp', button: 'left', clickCount: 1, ...point }) }, - { site, id } + { site: fixture.site, id } ) } - async function picker() { - await expect - .poll(() => app.windows().some((page) => page.url().includes('credential-picker.html'))) - .toBe(true) - const page = app.windows().find((page) => page.url().includes('credential-picker.html'))! + /** Sends a key to the login page with native input. */ + async function loginKey(keyCode: string) { + await app.evaluate( + ({ webContents }, { site, keyCode }) => { + const page = webContents + .getAllWebContents() + .find((contents) => contents.getURL().startsWith(`${site}/login`)) + if (!page) throw new Error('Missing fixture page') + page.sendInputEvent({ type: 'keyDown', keyCode }) + page.sendInputEvent({ type: 'keyUp', keyCode }) + }, + { site: fixture.site, keyCode } + ) + } + + const pickerPage = () => app.windows().find((page) => page.url().includes(PICKER_PAGE)) + const pickerOpen = () => pickerPage() !== undefined + + async function picker(): Promise { + await expect.poll(pickerOpen).toBe(true) + const page = pickerPage() + if (!page) throw new Error('The picker closed before it could be read') await expect(page.getByRole('menu')).toBeVisible() return page } + const pickerFocused = () => + app.evaluate( + ({ BrowserWindow }, pickerUrl) => + BrowserWindow.getFocusedWindow()?.webContents.getURL().includes(pickerUrl), + PICKER_PAGE + ) + async function pickerKey(keyCode: string) { - await app.evaluate(({ BrowserWindow }, keyCode) => { - const contents = BrowserWindow.getAllWindows().find((window) => - window.webContents.getURL().includes('credential-picker.html') - )!.webContents - contents.sendInputEvent({ type: 'keyDown', keyCode }) - contents.sendInputEvent({ type: 'keyUp', keyCode }) - }, keyCode) + await app.evaluate( + ({ BrowserWindow }, { keyCode, pickerUrl }) => { + const picker = BrowserWindow.getAllWindows().find((window) => + window.webContents.getURL().includes(pickerUrl) + ) + if (!picker) throw new Error('The picker is not open') + picker.webContents.sendInputEvent({ type: 'keyDown', keyCode }) + picker.webContents.sendInputEvent({ type: 'keyUp', keyCode }) + }, + { keyCode, pickerUrl: PICKER_PAGE } + ) + } + + /** Chooses an account; the picker closes under the click, the only error tolerated. */ + async function choose(menu: Page, item: Locator) { + const closed = menu.waitForEvent('close') + await item.click().catch((error: unknown) => { + if (!getErrorMessage(error).includes('Target page, context or browser has been closed')) { + throw error + } + }) + await closed } + /** Whether the picker sits flush with the username field, below it or above it. */ + const placement = () => + app.evaluate(async ({ BrowserWindow, WebContentsView }, pickerUrl) => { + const picker = BrowserWindow.getAllWindows().find((window) => + window.webContents.getURL().includes(pickerUrl) + ) + const parent = picker?.getParentWindow() + const view = parent?.contentView.children.find( + (child): child is InstanceType => + child instanceof WebContentsView && child.webContents.getURL().includes('/login') + ) + if (!picker || !parent || !view) return null + const field = await view.webContents.executeJavaScript( + '(() => { const r=document.getElementById("user").getBoundingClientRect(); return {x:r.x,y:r.y,height:r.height} })()' + ) + const bounds = picker.getBounds() + const zoom = view.webContents.getZoomFactor() + const fieldX = parent.getContentBounds().x + view.getBounds().x + field.x * zoom + const fieldY = parent.getContentBounds().y + view.getBounds().y + field.y * zoom + const fieldHeight = field.height * zoom + return { + alignedX: Math.abs(bounds.x - fieldX) <= 1, + adjacentY: + Math.min( + Math.abs(bounds.y - fieldY - fieldHeight - 4), + Math.abs(bounds.y + bounds.height + 4 - fieldY) + ) <= 1, + } + }, PICKER_PAGE) + test('uses shared emcn styling, fills a selected account, and never submits', async () => { await clickField() const menu = await picker() @@ -219,35 +213,7 @@ test.describe('saved password autofill', () => { }) expect(denied).toBe('failed') expect(await pageScript('document.getElementById("pass").value')).toBe('') - const placement = await app.evaluate(async ({ BrowserWindow, WebContentsView }) => { - const picker = BrowserWindow.getAllWindows().find((window) => - window.webContents.getURL().includes('credential-picker.html') - )! - const parent = picker.getParentWindow()! - const view = parent.contentView.children.find( - (view) => view instanceof WebContentsView && view.webContents.getURL().includes('/login') - ) as InstanceType - const field = await view.webContents.executeJavaScript( - '(() => { const r=document.getElementById("user").getBoundingClientRect(); return {x:r.x,y:r.y,height:r.height} })()' - ) - const bounds = picker.getBounds() - const zoom = view.webContents.getZoomFactor() - return { - x: bounds.x, - y: bounds.y, - height: bounds.height, - fieldX: parent.getContentBounds().x + view.getBounds().x + field.x * zoom, - fieldY: parent.getContentBounds().y + view.getBounds().y + field.y * zoom, - fieldHeight: field.height * zoom, - } - }) - expect(Math.abs(placement.x - placement.fieldX)).toBeLessThanOrEqual(1) - expect( - Math.min( - Math.abs(placement.y - placement.fieldY - placement.fieldHeight - 4), - Math.abs(placement.y + placement.height + 4 - placement.fieldY) - ) - ).toBeLessThanOrEqual(1) + await expect.poll(placement).toEqual({ alignedX: true, adjacentY: true }) await menu.evaluate(async () => { await document.fonts.ready await new Promise(requestAnimationFrame) @@ -262,18 +228,7 @@ test.describe('saved password autofill', () => { })) expect(geometry).toMatchObject({ x: 0, width: 320, overflow: false, weight: '400' }) expect(geometry.font).toContain('Season Sans') - if (SCREENSHOTS) { - mkdirSync(SCREENSHOTS, { recursive: true }) - for (const theme of ['light', 'dark']) { - await host.evaluate((theme) => { - document.documentElement.className = theme - document.documentElement.style.colorScheme = theme - }, theme) - await expect(menu.locator('html')).toHaveClass(theme) - await menu.screenshot({ path: join(SCREENSHOTS, `password-picker-${theme}.png`) }) - } - } - await menu.getByRole('menuitem', { name: 'account2@example.test', exact: true }).click() + await choose(menu, menu.getByRole('menuitem', { name: 'account2@example.test', exact: true })) await expect .poll(() => pageScript( @@ -281,29 +236,14 @@ test.describe('saved password autofill', () => { ) ) .toEqual({ user: 'account2@example.test', pass: 'fixture-secret-1', submitted: null }) - await expect - .poll(() => app.windows().some((page) => page.url().includes('credential-picker.html'))) - .toBe(false) }) test('supports keyboard selection and dismissal without unnecessary scrolling', async () => { await seed(15) await clickField() const menu = await picker() - await app.evaluate(({ webContents }, site) => { - const page = webContents - .getAllWebContents() - .find((contents) => contents.getURL().startsWith(`${site}/login`))! - page.sendInputEvent({ type: 'keyDown', keyCode: 'Down' }) - page.sendInputEvent({ type: 'keyUp', keyCode: 'Down' }) - }, site) - await expect - .poll(() => - app.evaluate(({ BrowserWindow }) => - BrowserWindow.getFocusedWindow()?.webContents.getURL().includes('credential-picker.html') - ) - ) - .toBe(true) + await loginKey('Down') + await expect.poll(pickerFocused).toBe(true) await expect(menu.getByRole('menuitem')).toHaveCount(15) await pickerKey('End') await expect(menu.getByRole('menuitem').last()).toBeFocused() @@ -311,15 +251,11 @@ test.describe('saved password autofill', () => { await expect .poll(() => pageScript('document.getElementById("user").value')) .toBe('account9@example.test') - await expect - .poll(() => app.windows().some((page) => page.url().includes('credential-picker.html'))) - .toBe(false) + await expect.poll(pickerOpen).toBe(false) await clickField() await picker() await pickerKey('Escape') - await expect - .poll(() => app.windows().some((page) => page.url().includes('credential-picker.html'))) - .toBe(false) + await expect.poll(pickerOpen).toBe(false) }) for (const count of [1, 3]) { @@ -345,14 +281,11 @@ test.describe('saved password autofill', () => { }) ) .toBe(true) - if (SCREENSHOTS) { - await menu.screenshot({ path: join(SCREENSHOTS, `password-picker-long-${count}.png`) }) - } - await app.evaluate(({ BrowserWindow }) => { + await app.evaluate(({ BrowserWindow }, pickerUrl) => { BrowserWindow.getAllWindows() - .find((window) => window.webContents.getURL().includes('credential-picker.html'))! - .setContentSize(800, 600) - }) + .find((window) => window.webContents.getURL().includes(pickerUrl)) + ?.setContentSize(800, 600) + }, PICKER_PAGE) await menu .getByRole('menuitem') .first() @@ -377,40 +310,20 @@ test.describe('saved password autofill', () => { await clickField() await picker() await host.getByRole('button', { name: 'Outside the browser' }).click() - await expect - .poll(() => app.windows().some((page) => page.url().includes('credential-picker.html'))) - .toBe(false) + await expect.poll(pickerOpen).toBe(false) await expect(host.getByRole('button', { name: 'Outside the browser' })).toBeFocused() await clickField() await picker() - await host.evaluate((scope) => { - ;( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.browserAgent.setPanelBounds(null, null, scope) - }, SCOPE) - await expect - .poll(() => app.windows().some((page) => page.url().includes('credential-picker.html'))) - .toBe(false) + await hideBrowserPanel(host, SCOPE) + await expect.poll(pickerOpen).toBe(false) expect(await pageScript('document.getElementById("pass").value')).toBe('') }) test('returns keyboard focus to the login after dismissal and selection', async () => { await clickField() await picker() - await app.evaluate(({ webContents }, site) => { - const page = webContents - .getAllWebContents() - .find((contents) => contents.getURL().startsWith(`${site}/login`))! - page.sendInputEvent({ type: 'keyDown', keyCode: 'Down' }) - page.sendInputEvent({ type: 'keyUp', keyCode: 'Down' }) - }, site) - await expect - .poll(() => - app.evaluate(({ BrowserWindow }) => - BrowserWindow.getFocusedWindow()?.webContents.getURL().includes('credential-picker.html') - ) - ) - .toBe(true) + await loginKey('Down') + await expect.poll(pickerFocused).toBe(true) await pickerKey('Escape') await expect .poll(() => @@ -419,18 +332,19 @@ test.describe('saved password autofill', () => { page: webContents.getFocusedWebContents()?.getURL(), })) ) - .toEqual({ window: host.url(), page: `${site}/login` }) + .toEqual({ window: host.url(), page: `${fixture.site}/login` }) await app.evaluate(({ webContents }) => { - const page = webContents.getFocusedWebContents()! + const page = webContents.getFocusedWebContents() + if (!page) throw new Error('No focused page') page.sendInputEvent({ type: 'keyDown', keyCode: 'Tab' }) page.sendInputEvent({ type: 'keyUp', keyCode: 'Tab' }) }) await expect.poll(() => pageScript('document.activeElement.id')).toBe('pass') const menu = await picker() - await menu.getByRole('menuitem').first().click() + await choose(menu, menu.getByRole('menuitem').first()) await expect .poll(() => app.evaluate(({ webContents }) => webContents.getFocusedWebContents()?.getURL())) - .toBe(`${site}/login`) + .toBe(`${fixture.site}/login`) }) test('rejects replaced fields and excludes account creation', async () => { @@ -439,25 +353,28 @@ test.describe('saved password autofill', () => { await pageScript( 'document.querySelector("form").innerHTML = \'\'' ) - await expect - .poll(() => app.windows().some((page) => page.url().includes('credential-picker.html'))) - .toBe(false) + await expect.poll(pickerOpen).toBe(false) await clickField('pass') + // The click must have landed, or the checks below would pass without exercising anything. + await expect.poll(() => pageScript('document.activeElement.id')).toBe('pass') expect(await pageScript('document.getElementById("pass").value')).toBe('') - expect(app.windows().some((page) => page.url().includes('credential-picker.html'))).toBe(false) + expect(pickerOpen()).toBe(false) }) + test('offers a focused manual chooser with one account', async () => { await seed(1) await host.evaluate(async (scope) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop + const api = (globalThis as DesktopBridge).simDesktop await api.browserAgent.capturePanelSnapshot(scope) if (!(await api.browserAgent.setPanelOccluded(true, scope))) { throw new Error('Could not open the toolbar overlay') } }, SCOPE) await host.evaluate((scope) => { - document.getElementById('outside')!.onclick = async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop + const outside = document.getElementById('outside') + if (!outside) throw new Error('Missing outside button') + outside.onclick = async () => { + const api = (globalThis as DesktopBridge).simDesktop await api.browserAgent.setPanelOccluded(false, scope) await api.browserCredentials.showChooser({ x: 20, y: 80 }, scope) } @@ -465,14 +382,8 @@ test.describe('saved password autofill', () => { await host.getByRole('button', { name: 'Outside the browser' }).click() const menu = await picker() await expect(menu.getByRole('menuitem')).toHaveCount(1) - await expect - .poll(() => - app.evaluate(({ BrowserWindow }) => - BrowserWindow.getFocusedWindow()?.webContents.getURL().includes('credential-picker.html') - ) - ) - .toBe(true) - await menu.getByRole('menuitem').click() + await expect.poll(pickerFocused).toBe(true) + await choose(menu, menu.getByRole('menuitem')) await expect .poll(() => pageScript('document.getElementById("pass").value')) .toBe('fixture-secret-0') @@ -484,21 +395,19 @@ test.describe('saved password autofill', () => { ) await clickField() const menu = await picker() + // A failed fill keeps the picker open to show why. await menu.getByRole('menuitem').first().click() await expect(menu.getByRole('alert')).toHaveText( 'Could not fill this form. Select the field again.' ) expect(await pageScript('document.getElementById("pass").value')).toBe('') - if (SCREENSHOTS) await menu.screenshot({ path: join(SCREENSHOTS, 'password-picker-error.png') }) }) test('closes on navigation and never fills the destination', async () => { await clickField() await picker() - await navigate(`${site}/login?next=1`) - await expect - .poll(() => app.windows().some((page) => page.url().includes('credential-picker.html'))) - .toBe(false) + await navigate(`${fixture.site}/login?next=1`) + await expect.poll(pickerOpen).toBe(false) expect(await pageScript('document.getElementById("pass").value')).toBe('') }) @@ -510,16 +419,17 @@ test.describe('saved password autofill', () => { await app.evaluate(async ({ webContents }, site) => { const page = webContents .getAllWebContents() - .find((contents) => contents.getURL().startsWith(`${site}/login`))! + .find((contents) => contents.getURL().startsWith(`${site}/login`)) + if (!page) throw new Error('Missing fixture page') const point = await page.executeJavaScript( '(() => {const r=document.getElementById("shadow").shadowRoot.getElementById("pass").getBoundingClientRect();return {x:Math.round(r.x+4),y:Math.round(r.y+4)}})()' ) page.focus() page.sendInputEvent({ type: 'mouseDown', button: 'left', clickCount: 1, ...point }) page.sendInputEvent({ type: 'mouseUp', button: 'left', clickCount: 1, ...point }) - }, site) + }, fixture.site) const menu = await picker() - await menu.getByRole('menuitem').first().click() + await choose(menu, menu.getByRole('menuitem').first()) await expect .poll(() => pageScript('document.getElementById("shadow").shadowRoot.getElementById("pass").value') diff --git a/apps/desktop/e2e/quick-chat.spec.ts b/apps/desktop/e2e/quick-chat.spec.ts index 95d94ef3f4d..37e6e56f275 100644 --- a/apps/desktop/e2e/quick-chat.spec.ts +++ b/apps/desktop/e2e/quick-chat.spec.ts @@ -1,30 +1,21 @@ -import { mkdtempSync, writeFileSync } from 'node:fs' -import type { Server } from 'node:http' -import { createServer } from 'node:http' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { fileURLToPath } from 'node:url' import type { ElectronApplication, Page } from '@playwright/test' -import { _electron as electron, expect, test } from '@playwright/test' import type { DesktopPreferences, QuickChatShortcut } from '@sim/desktop-bridge' -import { getErrorMessage } from '@sim/utils/errors' -import { recordCheck } from './check-report' +import { type DesktopBridge, expect, type FixtureServer, serve, test } from './harness' /** * Drives the quick chat window in the real shell against a fixture origin: where it opens, that * it floats with no desktop bridge, that it resizes within its bounds, that "Open in Sim" hands * the chat to a full window, that the toggle hides and restores the same page, that sign-out - * destroys it, and how its shortcut setting and load failures behave. Each check lands in a JSON - * report at QUICK_CHAT_REPORT_PATH as it finishes. + * destroys it, and how its shortcut setting and load failures behave. */ -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) const WORKSPACE_ROUTE = '/workspace/ws1/home' +const QUICK_ROUTE = '/extension/ws1' const DEFAULT_SHORTCUT: QuickChatShortcut = 'Alt+Space' const PAGES: Record = { [WORKSPACE_ROUTE]: '

workspace

', - '/extension/ws1': `

quick-chat

+ [QUICK_ROUTE]: `

quick-chat

Open in Sim `, '/workspace/ws1/chat/c1': @@ -32,63 +23,6 @@ const PAGES: Record = { '/login': '

fixture-login

', } -interface FixtureServer { - server: Server - origin: string - /** Drops every connection for `path`, so its loads fail, until `failing` is turned off again. */ - setFailing: (path: string, failing: boolean) => void -} - -function startFixtureServer(): Promise { - const failing = new Set() - return new Promise((resolvePromise) => { - const server = createServer((request, response) => { - const path = new URL(request.url ?? '/', 'http://127.0.0.1').pathname - if (failing.has(path)) { - request.socket.destroy() - return - } - if (path === '/api/auth/sign-out') { - response.writeHead(200, { 'Content-Type': 'application/json' }).end('{}') - return - } - const body = PAGES[path] - if (!body) { - response.writeHead(404, { 'Content-Type': 'text/html' }).end('

not found

') - return - } - response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }).end(body) - }) - server.listen(0, '127.0.0.1', () => { - const address = server.address() - const port = typeof address === 'object' && address ? address.port : 0 - resolvePromise({ - server, - origin: `http://127.0.0.1:${port}`, - setFailing: (path, on) => { - if (on) failing.add(path) - else failing.delete(path) - }, - }) - }) - }) -} - -function launchApp(origin: string, settings: string | Record = {}) { - const userData = mkdtempSync(join(tmpdir(), 'sim-desktop-quick-chat-')) - writeFileSync( - join(userData, 'settings.json'), - typeof settings === 'string' - ? settings - : JSON.stringify({ origin, lastRoute: WORKSPACE_ROUTE, ...settings }) - ) - return electron.launch({ - args: ['.'], - cwd: DESKTOP_DIR, - env: { ...process.env, SIM_DESKTOP_ORIGIN: origin, SIM_DESKTOP_USER_DATA: userData }, - }) -} - /** Clicks an application-menu item by label, the way a user choosing it from the menu bar would. */ function clickMenu(app: ElectronApplication, label: string): Promise { return app.evaluate(({ Menu }, label) => { @@ -123,6 +57,13 @@ function windowState(app: ElectronApplication, url: string) { }, url) } +/** Whether a floating (always-on-top) window exists; full windows never float. */ +function hasFloatingWindow(app: ElectronApplication): Promise { + return app.evaluate(({ BrowserWindow }) => + BrowserWindow.getAllWindows().some((win) => !win.isDestroyed() && win.isAlwaysOnTop()) + ) +} + /** Resizes the window showing `url` the way dragging its edge would. */ function resizeWindow(app: ElectronApplication, url: string, width: number, height: number) { return app.evaluate( @@ -142,235 +83,214 @@ const hasBridge = (page: Page) => const setShortcut = (page: Page, shortcut: string | null) => page.evaluate( (value) => - ( - globalThis as unknown as { - simDesktop: { - settings: { setQuickChatShortcut(v: unknown): Promise } - } - } - ).simDesktop.settings.setQuickChatShortcut(value), + (globalThis as DesktopBridge).simDesktop.settings.setQuickChatShortcut?.( + value as QuickChatShortcut | null + ), shortcut ) const isRegistered = (app: ElectronApplication, shortcut: string) => app.evaluate(({ globalShortcut }, value) => globalShortcut.isRegistered(value), shortcut) -/** Runs one named check and records its outcome as soon as it is known. */ -async function check(name: string, body: () => Promise) { - const reportPath = process.env.QUICK_CHAT_REPORT_PATH ?? test.info().outputPath('quick-chat.json') - const started = Date.now() - const record = (status: 'passed' | 'failed', error?: unknown) => - recordCheck(reportPath, 'quick-chat', { - name, - status, - durationMs: Date.now() - started, - retry: test.info().retry, - ...(error === undefined ? {} : { error: getErrorMessage(error) }), - }) - try { - await body() - record('passed') - } catch (error) { - record('failed', error) - throw error - } -} - test.describe('quick chat window', () => { let fixture: FixtureServer - let app: ElectronApplication | undefined + /** Paths whose connections are dropped, so their loads fail. */ + const failing = new Set() test.beforeAll(async () => { - fixture = await startFixtureServer() + fixture = await serve((request, response, url) => { + if (failing.has(url.pathname)) { + request.socket.destroy() + return + } + if (url.pathname === '/api/auth/sign-out') { + response.writeHead(200, { 'Content-Type': 'application/json' }).end('{}') + return + } + const body = PAGES[url.pathname] + if (!body) { + response.writeHead(404, { 'Content-Type': 'text/html' }).end('

not found

') + return + } + response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }).end(body) + }) }) - test.afterAll(() => { - fixture.server.close() + test.afterAll(async () => { + await fixture.close() }) - test.afterEach(async () => { - await app?.close().catch(() => {}) + test.afterEach(() => { + failing.clear() }) - test('opens, resizes, hands off, toggles, and closes on sign-out', async () => { - const launched = await launchApp(fixture.origin) - app = launched - const main = await launched.firstWindow() + const settings = (extra: Record = {}) => ({ + origin: fixture.origin, + lastRoute: WORKSPACE_ROUTE, + ...extra, + }) + + test('opens, resizes, hands off, toggles, and closes on sign-out', async ({ desktop }) => { + const { app } = await desktop.launch({ origin: fixture.origin, settings: settings() }) + const main = await app.firstWindow() await expect(main.locator('#app')).toHaveText('workspace') - const quickUrl = `${fixture.origin}/extension/ws1` - let quick: Page | undefined + const quickUrl = `${fixture.origin}${QUICK_ROUTE}` - await check('opens the compact chat for the last workspace as a floating window', async () => { - const opened = launched.waitForEvent('window') - await clickMenu(launched, 'Quick Chat') - quick = await opened - await expect(quick.locator('#quick')).toHaveText('quick-chat') - expect(quick.url()).toBe(quickUrl) - await expect - .poll(() => windowState(launched, quickUrl)) - .toMatchObject({ visible: true, alwaysOnTop: true }) - }) + const quick = + await test.step('opens the compact chat for the last workspace as a floating window', async () => { + const opened = app.waitForEvent('window') + await clickMenu(app, 'Quick Chat') + const page = await opened + await expect(page.locator('#quick')).toHaveText('quick-chat') + expect(page.url()).toBe(quickUrl) + await expect + .poll(() => windowState(app, quickUrl)) + .toMatchObject({ visible: true, alwaysOnTop: true }) + return page + }) - await check('the floating page gets no desktop bridge while full windows keep it', async () => { - if (!quick) throw new Error('Quick chat did not open') + await test.step('the floating page gets no desktop bridge while full windows keep it', async () => { expect(await hasBridge(quick)).toBe(false) expect(await hasBridge(main)).toBe(true) }) - await check('resizing holds the minimum size and the page follows the window', async () => { - if (!quick) throw new Error('Quick chat did not open') - const page = quick - await resizeWindow(launched, quickUrl, 200, 200) - await expect.poll(() => windowState(launched, quickUrl)).toMatchObject({ size: [360, 420] }) + await test.step('resizing holds the minimum size and the page follows the window', async () => { + await resizeWindow(app, quickUrl, 200, 200) + await expect.poll(() => windowState(app, quickUrl)).toMatchObject({ size: [360, 420] }) // Small enough for any runner display; macOS clamps a window to the screen it is on. - await resizeWindow(launched, quickUrl, 600, 560) - await expect.poll(() => windowState(launched, quickUrl)).toMatchObject({ size: [600, 560] }) - await expect.poll(() => page.evaluate(() => window.innerWidth)).toBe(600) + await resizeWindow(app, quickUrl, 600, 560) + await expect.poll(() => windowState(app, quickUrl)).toMatchObject({ size: [600, 560] }) + await expect.poll(() => quick.evaluate(() => window.innerWidth)).toBe(600) }) - await check( - 'Open in Sim hands the chat to a full window and leaves the panel open', - async () => { - if (!quick) throw new Error('Quick chat did not open') - const handedOff = launched.waitForEvent('window') - await quick.locator('#open-in-sim').click() - const full = await handedOff - await expect(full.locator('#chat')).toHaveText('handed-off') - expect(await hasBridge(full)).toBe(true) - expect(await windowState(launched, quickUrl)).toMatchObject({ - visible: true, - alwaysOnTop: true, - }) - } - ) + await test.step('Open in Sim hands the chat to a full window and leaves the panel open', async () => { + const handedOff = app.waitForEvent('window') + await quick.locator('#open-in-sim').click() + const full = await handedOff + await expect(full.locator('#chat')).toHaveText('handed-off') + expect(await hasBridge(full)).toBe(true) + expect(await windowState(app, quickUrl)).toMatchObject({ visible: true, alwaysOnTop: true }) + }) - await check( - 'the toggle brings a background panel forward, then hides it, keeping the page', - async () => { - if (!quick) throw new Error('Quick chat did not open') - await quick.evaluate(() => { - ;(globalThis as { quickChatMarker?: string }).quickChatMarker = 'kept' - }) - // The hand-off focused the full window; the app must be active for window focus to land. - await launched.evaluate(({ app }) => app.focus({ steal: true })) - await clickMenu(launched, 'Quick Chat') - await expect - .poll(() => windowState(launched, quickUrl)) - .toMatchObject({ visible: true, focused: true }) - await clickMenu(launched, 'Quick Chat') - await expect.poll(() => windowState(launched, quickUrl)).toMatchObject({ visible: false }) - await clickMenu(launched, 'Quick Chat') - await expect.poll(() => windowState(launched, quickUrl)).toMatchObject({ visible: true }) - expect( - await quick.evaluate(() => (globalThis as { quickChatMarker?: string }).quickChatMarker) - ).toBe('kept') - } - ) + await test.step('the toggle brings a background panel forward, then hides it, keeping the page', async () => { + await quick.evaluate(() => { + ;(globalThis as { quickChatMarker?: string }).quickChatMarker = 'kept' + }) + // The hand-off focused the full window; the app must be active for window focus to land. + await app.evaluate(({ app }) => app.focus({ steal: true })) + await clickMenu(app, 'Quick Chat') + await expect + .poll(() => windowState(app, quickUrl)) + .toMatchObject({ visible: true, focused: true }) + await clickMenu(app, 'Quick Chat') + await expect.poll(() => windowState(app, quickUrl)).toMatchObject({ visible: false }) + await clickMenu(app, 'Quick Chat') + await expect.poll(() => windowState(app, quickUrl)).toMatchObject({ visible: true }) + expect( + await quick.evaluate(() => (globalThis as { quickChatMarker?: string }).quickChatMarker) + ).toBe('kept') + }) - await check('signing out destroys the panel with the account it belonged to', async () => { - await clickMenu(launched, 'Sign Out') + await test.step('signing out destroys the panel with the account it belonged to', async () => { + await clickMenu(app, 'Sign Out') // Found as the only always-on-top window, not by URL: sign-out sends full windows to /login. - await expect - .poll( - () => - launched.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().some((win) => !win.isDestroyed() && win.isAlwaysOnTop()) - ), - { timeout: 30_000 } - ) - .toBe(false) + await expect.poll(() => hasFloatingWindow(app), { timeout: 30_000 }).toBe(false) + // Windows go to /login only once the whole account teardown has finished. + await expect(main.locator('#login')).toHaveText('fixture-login', { timeout: 30_000 }) }) }) - test('the shortcut setting and a failed first load', async () => { + test('the shortcut setting and a failed first load', async ({ desktop }) => { test.skip(process.platform !== 'darwin', 'Only macOS binds a shortcut by default') - const launched = await launchApp(fixture.origin, { quickChatShortcut: 'CommandOrControl+Q' }) - app = launched - const main = await launched.firstWindow() + const { app } = await desktop.launch({ + origin: fixture.origin, + settings: settings({ quickChatShortcut: 'CommandOrControl+Q' }), + }) + const main = await app.firstWindow() await expect(main.locator('#app')).toHaveText('workspace') - await check('a stored shortcut outside the presets falls back to the default', async () => { - const preferences = await main.evaluate(() => - ( - globalThis as unknown as { - simDesktop: { settings: { getPreferences(): Promise } } - } - ).simDesktop.settings.getPreferences() + await test.step('a stored shortcut outside the presets falls back to the default', async () => { + const preferences: DesktopPreferences = await main.evaluate(() => + (globalThis as DesktopBridge).simDesktop.settings.getPreferences() ) expect(preferences).toMatchObject({ quickChatShortcut: DEFAULT_SHORTCUT, quickChatShortcutAvailable: true, }) - expect(await isRegistered(launched, DEFAULT_SHORTCUT)).toBe(true) - expect(await isRegistered(launched, 'CommandOrControl+Q')).toBe(false) + expect(await isRegistered(app, DEFAULT_SHORTCUT)).toBe(true) + expect(await isRegistered(app, 'CommandOrControl+Q')).toBe(false) }) - await check('choosing another shortcut releases the old one and binds the new', async () => { + await test.step('choosing another shortcut releases the old one and binds the new', async () => { const next: QuickChatShortcut = 'CommandOrControl+Shift+Space' expect(await setShortcut(main, next)).toMatchObject({ quickChatShortcut: next, quickChatShortcutAvailable: true, }) - expect(await isRegistered(launched, next)).toBe(true) - expect(await isRegistered(launched, DEFAULT_SHORTCUT)).toBe(false) + expect(await isRegistered(app, next)).toBe(true) + expect(await isRegistered(app, DEFAULT_SHORTCUT)).toBe(false) }) - await check( - 'turning it off releases the shortcut and refuses values off the list', - async () => { - expect(await setShortcut(main, null)).toMatchObject({ - quickChatShortcut: null, - quickChatShortcutAvailable: true, - }) - expect(await isRegistered(launched, 'CommandOrControl+Shift+Space')).toBe(false) - expect(await setShortcut(main, 'CommandOrControl+Q')).toMatchObject({ - quickChatShortcut: null, - }) - expect(await isRegistered(launched, 'CommandOrControl+Q')).toBe(false) - } - ) + await test.step('turning it off releases the shortcut and refuses values off the list', async () => { + expect(await setShortcut(main, null)).toMatchObject({ + quickChatShortcut: null, + quickChatShortcutAvailable: true, + }) + expect(await isRegistered(app, 'CommandOrControl+Shift+Space')).toBe(false) + expect(await setShortcut(main, 'CommandOrControl+Q')).toMatchObject({ + quickChatShortcut: null, + }) + expect(await isRegistered(app, 'CommandOrControl+Q')).toBe(false) + }) - await check('a failed first load reloads when the panel is shown again', async () => { - fixture.setFailing('/extension/ws1', true) - const opened = launched.waitForEvent('window') - await clickMenu(launched, 'Quick Chat') + await test.step('a failed first load reloads when the panel is shown again', async () => { + failing.add(QUICK_ROUTE) + // Listens before the panel exists: its first load can fail before Playwright sees the page. + await app.evaluate(({ app }) => { + const state = globalThis as { quickChatLoadFailed?: boolean } + app.once('browser-window-created', (_event, win) => { + win.webContents.on( + 'did-fail-load', + (_failure, _code, _description, _url, isMainFrame) => { + if (isMainFrame) state.quickChatLoadFailed = true + } + ) + }) + }) + const opened = app.waitForEvent('window') + await clickMenu(app, 'Quick Chat') const quick = await opened - await quick.waitForLoadState().catch(() => {}) - expect(await quick.locator('#quick').count()).toBe(0) - fixture.setFailing('/extension/ws1', false) - await launched.evaluate(({ app }) => app.focus({ steal: true })) - // Pressing the shortcut either hides a focused panel or shows it again; each show after the - // failure reloads, so a few presses must land on the loaded page. await expect - .poll( - async () => { - if ((await quick.locator('#quick').count()) > 0) return true - await clickMenu(launched, 'Quick Chat') - return false - }, - { intervals: [1_000], timeout: 15_000 } + .poll(() => + app.evaluate(() => (globalThis as { quickChatLoadFailed?: boolean }).quickChatLoadFailed) ) .toBe(true) + await expect(quick.locator('#quick')).toHaveCount(0) + failing.delete(QUICK_ROUTE) + + // Focus the main window so the toggle reveals the panel rather than hiding a focused one. + await app.evaluate(({ app, BrowserWindow }, route) => { + const win = BrowserWindow.getAllWindows().find((candidate) => + candidate.webContents.getURL().endsWith(route) + ) + if (!win) throw new Error('Main window is missing') + app.focus({ steal: true }) + win.focus() + }, WORKSPACE_ROUTE) + await expect + .poll(() => windowState(app, `${fixture.origin}${WORKSPACE_ROUTE}`)) + .toMatchObject({ focused: true }) + await clickMenu(app, 'Quick Chat') await expect(quick.locator('#quick')).toHaveText('quick-chat') }) }) - test('stays closed while account data cannot be stored', async () => { + test('the toggle opens nothing while account data cannot be stored', async ({ desktop }) => { // An unreadable settings file blocks persistence, which makes account data unavailable. - const launched = await launchApp(fixture.origin, '[]') - app = launched - await launched.firstWindow() - await check( - 'the shortcut opens nothing while the window could not hold an account', - async () => { - await clickMenu(launched, 'Quick Chat') - await new Promise((resolveDelay) => setTimeout(resolveDelay, 1_500)) - expect( - await launched.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().some((win) => !win.isDestroyed() && win.isAlwaysOnTop()) - ) - ).toBe(false) - } - ) + const { app } = await desktop.launch({ origin: fixture.origin, settings: '[]' }) + await app.firstWindow() + // The toggle builds the window synchronously inside the menu click. + await clickMenu(app, 'Quick Chat') + expect(await hasFloatingWindow(app)).toBe(false) }) }) diff --git a/apps/desktop/e2e/session-cookies.spec.ts b/apps/desktop/e2e/session-cookies.spec.ts index 7c85b99e63f..ac55b5c5ec9 100644 --- a/apps/desktop/e2e/session-cookies.spec.ts +++ b/apps/desktop/e2e/session-cookies.spec.ts @@ -1,12 +1,14 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { createServer, type Server } from 'node:http' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { type ElectronApplication, _electron as electron, expect, test } from '@playwright/test' -import type { SimDesktopApi } from '@sim/desktop-bridge' +import type { ElectronApplication, Page } from '@playwright/test' +import { + attachBrowserPanel, + expect, + type FixtureServer, + type LaunchOptions, + ToolAuthorizer, + test, +} from './harness' +import { serveSignedIn } from './session-fixture' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) const SCOPE = 'session-cookies-fixture' /** @@ -15,145 +17,68 @@ const SCOPE = 'session-cookies-fixture' * every restart. This drives a real quit and relaunch against one profile. */ test.describe('built-in browser session cookies', () => { - let server: Server - let origin: string - let site: string - let userData: string - let app: ElectronApplication | undefined - let serial = 0 + let fixture: FixtureServer let lastCookieHeader: string | undefined - const calls = new Map< - string, - { chatId: string; toolName: string; args: Record } - >() + const authorizer = new ToolAuthorizer('fixture') test.beforeAll(async () => { - server = createServer(async (request, response) => { - const path = new URL(request.url ?? '/', 'http://localhost').pathname - if (path === '/api/auth/get-session') { - response.writeHead(200, { 'Content-Type': 'application/json' }) - response.end( - JSON.stringify({ user: { id: 'fixture-user' }, session: { id: 'fixture-session' } }) - ) - return - } - if (path === '/api/desktop/tool/authorize') { - let body = '' - for await (const chunk of request) body += chunk.toString() - const call = calls.get(JSON.parse(body).toolCallId) - response.writeHead(call ? 200 : 403, { 'Content-Type': 'application/json' }) - response.end(JSON.stringify(call ?? {})) - return - } - if (path.startsWith('/api/')) { - response.writeHead(200, { 'Content-Type': 'application/json' }) - response.end('{}') - return - } - if (path === '/sign-in') { - // A login redirect that sets a short-lived cookie the next hop deletes. - response.writeHead(302, { - 'Set-Cookie': 'oauth_state=pending; HttpOnly; Path=/', - Location: '/signed-in', - }) - response.end() - return - } - if (path === '/signed-in') { - response.writeHead(200, { - 'Content-Type': 'text/html', - 'Set-Cookie': [ - 'oauth_state=; Path=/; Max-Age=0', - 'login=fixture; HttpOnly; SameSite=Lax; Path=/', - 'remember=1; Path=/; Max-Age=3600', - ], - }) - response.end('Signed in') - return - } - if (path === '/account') { - lastCookieHeader = request.headers.cookie ?? '' - response.writeHead(200, { 'Content-Type': 'text/html' }) - response.end('Account') - return - } - if (request.headers.host?.startsWith('localhost')) { - // Favicon and other stray site requests must not set the app session cookie on the site. - response.writeHead(404) - response.end() - return - } - response.writeHead(200, { - 'Content-Type': 'text/html', - 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; SameSite=Lax; Path=/', - }) - response.end('Sim fixture

Session cookie fixture

') + fixture = await serveSignedIn({ + page: 'Sim fixture

Session cookie fixture

', + handle: async (request, response, url) => { + if (await authorizer.handle(request, response, url)) return true + if (url.pathname === '/sign-in') { + // A login redirect that sets a short-lived cookie the next hop deletes. + response.writeHead(302, { + 'Set-Cookie': 'oauth_state=pending; HttpOnly; Path=/', + Location: '/signed-in', + }) + response.end() + return true + } + if (url.pathname === '/signed-in') { + response.writeHead(200, { + 'Content-Type': 'text/html', + 'Set-Cookie': [ + 'oauth_state=; Path=/; Max-Age=0', + 'login=fixture; HttpOnly; SameSite=Lax; Path=/', + 'remember=1; Path=/; Max-Age=3600', + ], + }) + response.end('Signed in') + return true + } + if (url.pathname === '/account') { + lastCookieHeader = request.headers.cookie ?? '' + response.writeHead(200, { 'Content-Type': 'text/html' }) + response.end('Account') + return true + } + if (request.headers.host?.startsWith('localhost')) { + // Favicon and other stray site requests must not set the app session cookie on the site. + response.writeHead(404) + response.end() + return true + } + return false + }, }) - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - origin = `http://127.0.0.1:${address.port}` - /** Pages outside the app origin browse in the built-in browser's own partition. */ - site = `http://localhost:${address.port}` - }) - - test.beforeEach(() => { - userData = mkdtempSync(join(tmpdir(), 'sim-session-cookies-e2e-')) - }) - - test.afterEach(async () => { - await app?.close() - app = undefined - rmSync(userData, { recursive: true, force: true }) - calls.clear() }) test.afterAll(async () => { - await new Promise((resolve, reject) => - server.close((error) => (error ? reject(error) : resolve())) - ) + await fixture.close() }) - async function launch(): Promise { - const launched = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { ...process.env, SIM_DESKTOP_ORIGIN: origin, SIM_DESKTOP_USER_DATA: userData }, - }) - const host = await launched.firstWindow() + async function openShell(app: ElectronApplication) { + const host = await app.firstWindow() await expect(host.getByRole('heading')).toHaveText('Session cookie fixture') - await host.evaluate(async (scope) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - await api.browserAgent.activateScope(scope) - const updateBounds = () => - api.browserAgent.setPanelBounds( - { x: 0, y: 80, width: innerWidth, height: innerHeight - 80 }, - null, - scope - ) - updateBounds() - setInterval(updateBounds, 200) - }, SCOPE) - return launched - } - - async function navigate(target: ElectronApplication, url: string) { - const id = `fixture-${++serial}` - calls.set(id, { chatId: SCOPE, toolName: 'browser_open_url', args: { url } }) - const host = await target.firstWindow() - const result = await host.evaluate( - async ({ id, url, scope }) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - return api.browserAgent.executeTool(id, 'browser_open_url', { url }, scope) - }, - { id, url, scope: SCOPE } - ) - expect(result.ok, result.error).toBe(true) + await attachBrowserPanel(host, SCOPE) + return host } - async function cookiesSentToSite(target: ElectronApplication): Promise { + /** The cookies the built-in browser sends to the site (`fixture.site`, its own partition). */ + async function cookiesSentToSite(host: Page): Promise { lastCookieHeader = undefined - await navigate(target, `${site}/account`) + await authorizer.execute(host, SCOPE, 'browser_open_url', { url: `${fixture.site}/account` }) await expect.poll(() => lastCookieHeader).not.toBeUndefined() return (lastCookieHeader ?? '') .split(';') @@ -162,17 +87,26 @@ test.describe('built-in browser session cookies', () => { .sort() } - test('keeps a session-cookie login across a restart without reviving deleted cookies', async () => { - app = await launch() - await navigate(app, `${site}/sign-in`) - expect(await cookiesSentToSite(app)).toEqual(['login=fixture', 'remember=1']) + test('keeps a session-cookie login across a restart without reviving deleted cookies', async ({ + desktop, + }) => { + const options: LaunchOptions = { + origin: fixture.origin, + } + const first = await desktop.launch(options) + const host = await openShell(first.app) + await authorizer.execute(host, SCOPE, 'browser_open_url', { url: `${fixture.site}/sign-in` }) + expect(await cookiesSentToSite(host)).toEqual(['login=fixture', 'remember=1']) - await app.evaluate(({ session }) => + await first.app.evaluate(({ session }) => session.fromPartition('persist:sim-browser-agent').cookies.flushStore() ) - await app.close() + await desktop.close(first) - app = await launch() - expect(await cookiesSentToSite(app)).toEqual(['login=fixture', 'remember=1']) + const relaunched = await desktop.launch({ ...options, userData: first.userData }) + expect(await cookiesSentToSite(await openShell(relaunched.app))).toEqual([ + 'login=fixture', + 'remember=1', + ]) }) }) diff --git a/apps/desktop/e2e/session-fixture.ts b/apps/desktop/e2e/session-fixture.ts new file mode 100644 index 00000000000..71b29c4caed --- /dev/null +++ b/apps/desktop/e2e/session-fixture.ts @@ -0,0 +1,33 @@ +import { type FixtureHandler, type FixtureServer, serve } from './harness' + +export interface SignedInOriginOptions { + /** The HTML of every app page, served with the session cookie. */ + page: string + /** Sees each request first; returns true when it answered it. */ + handle?: (...args: Parameters) => boolean | Promise +} + +/** + * A fixture Sim origin with a signed-in user: the shell treats the window as signed in only when + * the session cookie is set and `/api/auth/get-session` returns a user. Every other `/api/` route + * answers `{}`. + */ +export function serveSignedIn({ page, handle }: SignedInOriginOptions): Promise { + return serve(async (request, response, url) => { + if (handle && (await handle(request, response, url))) return + if (url.pathname.startsWith('/api/')) { + response.writeHead(200, { 'Content-Type': 'application/json' }) + response.end( + url.pathname === '/api/auth/get-session' + ? JSON.stringify({ user: { id: 'fixture-user' }, session: { id: 'fixture-session' } }) + : '{}' + ) + return + } + response.writeHead(200, { + 'Content-Type': 'text/html; charset=utf-8', + 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; SameSite=Lax; Path=/', + }) + response.end(page) + }) +} diff --git a/apps/desktop/e2e/smoke.spec.ts b/apps/desktop/e2e/smoke.spec.ts index 3d2f6e5bdb7..aca424f1d9d 100644 --- a/apps/desktop/e2e/smoke.spec.ts +++ b/apps/desktop/e2e/smoke.spec.ts @@ -1,13 +1,8 @@ -import { mkdtempSync } from 'node:fs' -import type { Server } from 'node:http' -import { createServer } from 'node:http' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { fileURLToPath } from 'node:url' -import type { ElectronApplication } from '@playwright/test' -import { _electron as electron, expect, test } from '@playwright/test' +import type { ElectronApplication, Page } from '@playwright/test' +import { getErrorMessage } from '@sim/utils/errors' +import { expect, type FixtureServer, serve, test } from './harness' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) +const OFFLINE_ORIGIN = 'http://127.0.0.1:1' const PAGES: Record = { '/home': `Sim Fixture @@ -24,76 +19,74 @@ const PAGES: Record = { /** `User-Agent` of every request the fixture origin has served, in arrival order. */ const requestUserAgents: string[] = [] -function startFixtureServer(): Promise<{ server: Server; origin: string }> { - return new Promise((resolvePromise) => { - const server = createServer((request, response) => { +/** Runs an action that closes `page`, tolerating only the error from the page closing under it. */ +async function closeWith(page: Page, action: () => Promise): Promise { + const closed = page.waitForEvent('close') + await action().catch((error: unknown) => { + if (!getErrorMessage(error).includes('Target page, context or browser has been closed')) { + throw error + } + }) + await closed +} + +/** Replaces `shell.openExternal` with a recorder, read back by `openedExternally`. */ +async function recordExternalOpens(app: ElectronApplication): Promise { + await app.evaluate(({ shell }) => { + const opened: string[] = [] + ;(globalThis as { __openedExternal?: string[] }).__openedExternal = opened + shell.openExternal = async (url: string) => { + opened.push(url) + } + }) +} + +function openedExternally(app: ElectronApplication): Promise { + return app.evaluate(() => (globalThis as { __openedExternal?: string[] }).__openedExternal) +} + +function dialogFits(page: Page): Promise { + return page + .getByRole('dialog') + .evaluate((element) => element.scrollHeight <= globalThis.innerHeight) +} + +test.describe('desktop shell smoke', () => { + let fixture: FixtureServer + + test.beforeAll(async () => { + fixture = await serve((request, response, url) => { requestUserAgents.push(request.headers['user-agent'] ?? '') - const path = new URL(request.url ?? '/', 'http://127.0.0.1').pathname const sessionCookie = request.headers.cookie ?.split(';') .map((cookie) => cookie.trim()) .includes('sim-e2e-session=shared') const body = - path === '/mcp' + url.pathname === '/mcp' ? sessionCookie ? '

oauth-popup

' : '

sign-in-required

' - : PAGES[path] + : PAGES[url.pathname] if (!body) { response.writeHead(404, { 'Content-Type': 'text/html' }).end('

not found

') return } response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }).end(body) }) - server.listen(0, '127.0.0.1', () => { - const address = server.address() - const port = typeof address === 'object' && address ? address.port : 0 - resolvePromise({ server, origin: `http://127.0.0.1:${port}` }) - }) - }) -} - -async function launchApp(origin: string): Promise { - return electron.launch({ - args: ['.'], - cwd: DESKTOP_DIR, - env: { - ...process.env, - SIM_DESKTOP_ORIGIN: origin, - SIM_DESKTOP_USER_DATA: mkdtempSync(join(tmpdir(), 'sim-desktop-e2e-')), - }, - }) -} - -test.describe('desktop shell smoke', () => { - let server: Server - let origin: string - let app: ElectronApplication - - test.beforeAll(async () => { - ;({ server, origin } = await startFixtureServer()) }) test.afterAll(async () => { - server.close() - }) - - test.afterEach(async () => { - await app?.close().catch(() => {}) - }) - - test('loads the configured origin top-level', async () => { - app = await launchApp(origin) - const window = await app.firstWindow() - await expect(window.locator('#app')).toHaveText('fixture-app') - expect(window.url()).toBe(`${origin}/home`) + await fixture.close() }) - test('presents one stock Chrome user agent on every request from the first load', async () => { + test('loads the configured origin top-level with one stock Chrome user agent on every request', async ({ + desktop, + }) => { requestUserAgents.length = 0 - app = await launchApp(origin) + const { app } = await desktop.launch({ origin: fixture.origin }) const window = await app.firstWindow() await expect(window.locator('#app')).toHaveText('fixture-app') + expect(window.url()).toBe(`${fixture.origin}/home`) await window.evaluate(() => fetch('/home').then((response) => response.text())) const pageUserAgent = await window.evaluate(() => navigator.userAgent) @@ -104,8 +97,8 @@ test.describe('desktop shell smoke', () => { expect(new Set(requestUserAgents)).toEqual(new Set([pageUserAgent])) }) - test('internal window.open creates an independent full Sim window', async () => { - app = await launchApp(origin) + test('internal window.open creates an independent full Sim window', async ({ desktop }) => { + const { app } = await desktop.launch({ origin: fixture.origin }) const window = await app.firstWindow() const newWindowPromise = app.waitForEvent('window') await window.locator('#internal-blank').click() @@ -115,30 +108,36 @@ test.describe('desktop shell smoke', () => { expect(app.windows()).toHaveLength(2) }) - test('external window.open goes to the system browser, never a new app window', async () => { - app = await launchApp(origin) + test('other origins open in the system browser, never in an app window or the app document', async ({ + desktop, + }) => { + const { app } = await desktop.launch({ origin: fixture.origin }) const window = await app.firstWindow() - await app.evaluate(({ shell }) => { - const opened: string[] = [] - ;(globalThis as { __openedExternal?: string[] }).__openedExternal = opened - shell.openExternal = async (url: string) => { - opened.push(url) - } - }) - await window.locator('#external-blank').click() - await expect - .poll(() => - app.evaluate(() => (globalThis as { __openedExternal?: string[] }).__openedExternal) - ) - .toEqual(['https://docs.sim.ai/x']) - expect(app.windows()).toHaveLength(1) await expect(window.locator('#app')).toHaveText('fixture-app') + await recordExternalOpens(app) + + await test.step('window.open to another origin', async () => { + await window.locator('#external-blank').click() + await expect.poll(() => openedExternally(app)).toEqual(['https://docs.sim.ai/x']) + expect(app.windows()).toHaveLength(1) + await expect(window.locator('#app')).toHaveText('fixture-app') + }) + + await test.step('same-window navigation to another origin', async () => { + await window.locator('#external-navigate').click({ noWaitAfter: true }) + await expect + .poll(() => openedExternally(app)) + .toEqual(['https://docs.sim.ai/x', 'https://docs.sim.ai/navigation']) + expect(window.url()).toBe(`${fixture.origin}/home`) + }) }) - test('OAuth popups share the session without inheriting the privileged preload', async () => { - app = await launchApp(origin) + test('OAuth popups share the session without inheriting the privileged preload', async ({ + desktop, + }) => { + const { app } = await desktop.launch({ origin: fixture.origin }) const window = await app.firstWindow() - await window.waitForURL(`${origin}/home`, { waitUntil: 'load' }) + await window.waitForURL(`${fixture.origin}/home`, { waitUntil: 'load' }) await window.evaluate(() => { document.cookie = 'sim-e2e-session=shared; Path=/; SameSite=Lax' }) @@ -152,31 +151,10 @@ test.describe('desktop shell smoke', () => { .toBe('undefined') }) - test('cross-origin same-window navigation opens externally and preserves the app document', async () => { - app = await launchApp(origin) + test('unreachable origin shows the bundled offline page', async ({ desktop }) => { + const { app } = await desktop.launch({ origin: OFFLINE_ORIGIN }) const window = await app.firstWindow() - await app.evaluate(({ shell }) => { - const opened: string[] = [] - ;(globalThis as { __openedExternal?: string[] }).__openedExternal = opened - shell.openExternal = async (url: string) => { - opened.push(url) - } - }) - - await window.locator('#external-navigate').click({ noWaitAfter: true }) - - await expect - .poll(() => - app.evaluate(() => (globalThis as { __openedExternal?: string[] }).__openedExternal) - ) - .toEqual(['https://docs.sim.ai/navigation']) - expect(window.url()).toBe(`${origin}/home`) - }) - - test('unreachable origin shows the bundled offline page', async () => { - app = await launchApp('http://127.0.0.1:1') - const window = await app.firstWindow() - await window.waitForSelector('#retry', { timeout: 30_000 }) + await expect(window.locator('#retry')).toBeVisible({ timeout: 30_000 }) expect(window.url()).toMatch(/^sim-shell:\/\/pages\/offline\.html\?/) const home = window.getByRole('link', { name: 'Home', exact: true }) await expect(home).toBeVisible() @@ -196,9 +174,11 @@ test.describe('desktop shell smoke', () => { await expect(window.locator('#detail')).toHaveAttribute('role', 'status') }) - test('offline title-bar geometry follows native fullscreen state across reloads', async () => { + test('offline title-bar geometry follows native fullscreen state across reloads', async ({ + desktop, + }) => { test.skip(process.platform !== 'darwin', 'The traffic-light lane is macOS-specific') - app = await launchApp('http://127.0.0.1:1') + const { app } = await desktop.launch({ origin: OFFLINE_ORIGIN }) const window = await app.firstWindow() await expect(window.locator('#server')).toBeVisible() await expect(window.locator('html')).toHaveAttribute('data-sim-desktop-title-bar', 'inset') @@ -223,8 +203,10 @@ test.describe('desktop shell smoke', () => { .toBeGreaterThanOrEqual(38) }) - test('bundled dialogs follow the app theme independently of the system theme', async () => { - app = await launchApp(origin) + test('the hang recovery dialog is an isolated, app-themed EMCN dialog that defaults to Wait', async ({ + desktop, + }) => { + const { app } = await desktop.launch({ origin: fixture.origin }) const window = await app.firstWindow() await expect(window.locator('#app')).toBeVisible() await app.evaluate(({ nativeTheme }) => { @@ -232,143 +214,114 @@ test.describe('desktop shell smoke', () => { }) await window.evaluate(() => { document.documentElement.className = 'dark' + ;(globalThis as { __sameDocument?: boolean }).__sameDocument = true }) const dialogPromise = app.waitForEvent('window') await app.evaluate(({ BrowserWindow }) => { BrowserWindow.getAllWindows()[0].webContents.emit('unresponsive') }) const prompt = await dialogPromise - await expect(prompt.getByRole('dialog')).toBeVisible() - await expect(prompt.locator('html')).toHaveClass('dark') - await expect(prompt.locator('html')).toHaveCSS('color-scheme', 'dark') - await expect(prompt.locator('#dialog-message')).toHaveCSS('-webkit-font-smoothing', 'auto') - await expect(prompt.locator('#dialog-message')).toHaveCSS('font-weight', '400') - await expect(prompt.locator('#dialog-message')).toHaveCSS('font-size', '14px') - await window.evaluate(() => { - document.documentElement.className = 'light' + + await test.step('isolated dialog with Wait focused', async () => { + await expect( + prompt.getByRole('dialog', { name: 'Sim isn’t responding', exact: true }) + ).toBeVisible() + await expect(prompt.getByRole('button', { name: 'Wait', exact: true })).toBeFocused() + await expect.poll(() => dialogFits(prompt)).toBe(true) + await expect + .poll(() => + prompt.evaluate(() => typeof (globalThis as { simDesktop?: unknown }).simDesktop) + ) + .toBe('undefined') }) - await expect(prompt.locator('html')).toHaveClass('light') - await expect(prompt.locator('html')).toHaveCSS('color-scheme', 'light') - await prompt.getByRole('button', { name: 'Wait', exact: true }).click() - }) - test('recovery messages use an isolated EMCN dialog with a safe keyboard default', async () => { - app = await launchApp('http://127.0.0.1:1') - const window = await app.firstWindow() - await expect(window.locator('#server')).toBeVisible() - const dialogPromise = app.waitForEvent('window') - await app.evaluate(({ BrowserWindow }) => { - BrowserWindow.getAllWindows()[0].webContents.emit('unresponsive') + await test.step('follows the app theme, not the system theme', async () => { + await expect(prompt.locator('html')).toHaveClass('dark') + await expect(prompt.locator('html')).toHaveCSS('color-scheme', 'dark') + await expect(prompt.locator('#dialog-message')).toHaveCSS('-webkit-font-smoothing', 'auto') + await expect(prompt.locator('#dialog-message')).toHaveCSS('font-weight', '400') + await expect(prompt.locator('#dialog-message')).toHaveCSS('font-size', '14px') + await window.evaluate(() => { + document.documentElement.className = 'light' + }) + await expect(prompt.locator('html')).toHaveClass('light') + await expect(prompt.locator('html')).toHaveCSS('color-scheme', 'light') }) - const prompt = await dialogPromise - await expect( - prompt.getByRole('dialog', { name: 'Sim isn’t responding', exact: true }) - ).toBeVisible() - await expect(prompt.getByText('Sim isn’t responding')).toBeVisible() - await expect(prompt.getByRole('button', { name: 'Wait', exact: true })).toBeFocused() - await expect - .poll(() => - prompt - .getByRole('dialog') - .evaluate((element) => element.scrollHeight <= globalThis.innerHeight) - ) - .toBe(true) - await expect - .poll(() => prompt.evaluate(() => typeof (globalThis as { simDesktop?: unknown }).simDesktop)) - .toBe('undefined') - await prompt.screenshot({ - path: test.info().outputPath('recovery-dialog.png'), - animations: 'disabled', + + await test.step('a long message keeps every button reachable', async () => { + await app.evaluate(({ BrowserWindow }) => { + const win = BrowserWindow.getAllWindows().find( + (entry) => entry.webContents.getURL() === 'sim-shell://pages/dialog.html' + ) + if (!win) throw new Error('Recovery dialog is missing') + win.webContents.ipc.removeHandler('shell:configuration') + win.webContents.ipc.handle('shell:configuration', () => ({ + title: 'Long recovery message', + text: Array.from({ length: 80 }, (_, index) => `Diagnostic detail ${index + 1}`).join( + '\n' + ), + type: 'warning', + buttons: ['Wait', 'Reload'], + defaultId: 0, + cancelId: 0, + })) + win.webContents.reload() + }) + await expect( + prompt.getByRole('dialog', { name: 'Long recovery message', exact: true }) + ).toBeVisible() + await expect(prompt.getByRole('button', { name: 'Reload', exact: true })).toBeInViewport() + await expect(prompt.getByRole('button', { name: 'Wait', exact: true })).toBeFocused() }) - await app.evaluate(({ BrowserWindow }) => { - const win = BrowserWindow.getAllWindows().find( - (entry) => entry.webContents.getURL() === 'sim-shell://pages/dialog.html' + + await test.step('Enter waits instead of reloading', async () => { + await closeWith(prompt, () => + prompt.getByRole('button', { name: 'Wait', exact: true }).press('Enter') ) - if (!win) throw new Error('Recovery dialog is missing') - win.webContents.ipc.removeHandler('shell:configuration') - win.webContents.ipc.handle('shell:configuration', () => ({ - title: 'Long recovery message', - text: Array.from({ length: 80 }, (_, index) => `Diagnostic detail ${index + 1}`).join('\n'), - type: 'warning', - buttons: ['Wait', 'Reload'], - defaultId: 0, - cancelId: 0, - })) - win.webContents.reload() + await expect(window.locator('#app')).toBeVisible() + expect( + await window.evaluate(() => (globalThis as { __sameDocument?: boolean }).__sameDocument) + ).toBe(true) }) - await expect( - prompt.getByRole('dialog', { name: 'Long recovery message', exact: true }) - ).toBeVisible() - await expect(prompt.getByRole('button', { name: 'Reload', exact: true })).toBeInViewport() - await expect(prompt.getByRole('button', { name: 'Wait', exact: true })).toBeFocused() - const closed = prompt.waitForEvent('close') - await prompt - .getByRole('button', { name: 'Wait', exact: true }) - .press('Enter') - .catch(() => {}) - await closed - await expect(window.locator('#server')).toBeVisible() }) // The picker is the only way to repoint a shell whose server is unreachable. // Its page, the pre-filled value (which crosses the local-page IPC gate) and // Escape are asserted together because the packaged build once opened it as // a blank sheet with no way out. - test('the offline server picker handles validation and dismissal', async () => { - const testInfo = test.info() - app = await launchApp('http://127.0.0.1:1') + test('the offline server picker handles validation and dismissal', async ({ desktop }) => { + const { app } = await desktop.launch({ origin: OFFLINE_ORIGIN }) const window = await app.firstWindow() - await window.waitForSelector('#server', { timeout: 30_000 }) + await expect(window.locator('#server')).toBeVisible({ timeout: 30_000 }) const pickerPromise = app.waitForEvent('window') await window.locator('#server').click() const picker = await pickerPromise + const serverUrl = picker.getByLabel('Server URL') await expect(picker).toHaveURL('sim-shell://pages/server.html') await expect(picker.getByRole('dialog', { name: 'Sim server', exact: true })).toBeVisible() - await expect(picker.getByLabel('Server URL')).toHaveValue('http://127.0.0.1:1') - await expect(picker.getByLabel('Server URL')).toBeFocused() - await expect - .poll(() => - picker - .getByRole('dialog') - .evaluate((element) => element.scrollHeight <= globalThis.innerHeight) - ) - .toBe(true) - await picker.getByLabel('Server URL').fill('http://example.com') - await picker.getByLabel('Server URL').press('Enter') + await expect(serverUrl).toHaveValue(OFFLINE_ORIGIN) + await expect(serverUrl).toBeFocused() + await expect.poll(() => dialogFits(picker)).toBe(true) + + await serverUrl.fill('http://example.com') + await serverUrl.press('Enter') await expect(picker.locator('#server-origin-errors')).toBeVisible() - await expect(picker.getByLabel('Server URL')).toHaveAccessibleDescription( - /Server URL must use HTTPS/ - ) - await expect(picker.getByLabel('Server URL')).toHaveAttribute('aria-invalid', 'true') - await picker.getByLabel('Server URL').fill('http://127.0.0.1:1') + await expect(serverUrl).toHaveAccessibleDescription(/Server URL must use HTTPS/) + await expect(serverUrl).toHaveAttribute('aria-invalid', 'true') + await serverUrl.fill(OFFLINE_ORIGIN) await expect(picker.locator('#server-origin-errors')).toHaveCount(0) - await expect(picker.getByLabel('Server URL')).not.toHaveAttribute('aria-invalid', 'true') + await expect(serverUrl).not.toHaveAttribute('aria-invalid', 'true') await picker.getByRole('button', { name: 'Connect', exact: true }).click() await expect(picker.getByRole('status')).toHaveText('Already connected to this server.') - await expect - .poll(() => - picker - .getByRole('dialog') - .evaluate((element) => element.scrollHeight <= globalThis.innerHeight) - ) - .toBe(true) - await picker.emulateMedia({ colorScheme: 'light' }) - await picker.screenshot({ - path: testInfo.outputPath('server-modal-light.png'), - animations: 'disabled', - }) + await expect.poll(() => dialogFits(picker)).toBe(true) + + // The picker follows the app's theme, not the system's. await picker.emulateMedia({ colorScheme: 'dark' }) await expect(picker.locator('[data-auth-root]')).toHaveCSS('color-scheme', 'light') - await picker.screenshot({ - path: testInfo.outputPath('server-modal-dark.png'), - animations: 'disabled', - }) - const closed = picker.waitForEvent('close') - await picker.keyboard.press('Escape').catch(() => {}) - await closed + await closeWith(picker, () => picker.keyboard.press('Escape')) expect(app.windows()).toHaveLength(1) }) }) diff --git a/apps/desktop/e2e/source-connect.spec.ts b/apps/desktop/e2e/source-connect.spec.ts index 6f5925bb3c9..d7c844fa32b 100644 --- a/apps/desktop/e2e/source-connect.spec.ts +++ b/apps/desktop/e2e/source-connect.spec.ts @@ -1,47 +1,18 @@ -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { createServer } from 'node:http' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' -import { chromium, _electron as electron, expect, test } from '@playwright/test' -import { getErrorMessage } from '@sim/utils/errors' import { sleep } from '@sim/utils/helpers' import { generateShortId } from '@sim/utils/id' -import { build } from 'esbuild' -import postcss from 'postcss' -import loadPostcssConfig from 'postcss-load-config' +import { bundleSimFixture, expect, serve, test } from './harness' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) -const SIM_DIR = fileURLToPath(new URL('../../sim/', import.meta.url)) const FIXTURE = fileURLToPath( new URL('../../sim/scripts/fixtures/desktop-source-connect.tsx', import.meta.url) ) +const BROWSER_BUFFER = fileURLToPath(new URL('./fixtures/browser-buffer.ts', import.meta.url)) /** Real renderer, preload, main process, loopback, and a separate browser cookie jar. */ -test('source authorization returns to its desktop screen and refreshes live', async () => { - const reportPath = - process.env.DESKTOP_SOURCE_CONNECT_REPORT_PATH ?? test.info().outputPath('source-connect.json') - const checks: { - name: string - status: 'passed' | 'failed' - durationMs: number - error?: string - }[] = [] - const check = async (name: string, action: () => Promise) => { - const started = Date.now() - try { - await test.step(name, action) - checks.push({ name, status: 'passed', durationMs: Date.now() - started }) - } catch (error) { - checks.push({ - name, - status: 'failed', - durationMs: Date.now() - started, - error: getErrorMessage(error), - }) - throw error - } - } +test('source authorization returns to its desktop screen and refreshes live', async ({ + desktop, + context, +}) => { const tickets = new Map() const attempts = new Map() const accountAttempts = new Map() @@ -60,14 +31,11 @@ test('source authorization returns to its desktop screen and refreshes live', as const personalAttempts = new Map() let personalInventoryFailed = false let personalInventoryFailures = 0 - let javascript = '' - let stylesheet = '' + /** The desktop state of each `/desktop/connect/complete` handoff the browser made. */ + const completedStates: string[] = [] + const bundle = await bundleSimFixture({ file: FIXTURE }, { inject: [BROWSER_BUFFER] }) let origin = '' - let app: Awaited> | undefined - let browser: Awaited> | undefined - const userData = mkdtempSync(join(tmpdir(), 'sim-source-connect-e2e-')) - const server = createServer(async (request, response) => { - const url = new URL(request.url ?? '/', origin || 'http://localhost') + const server = await serve(async (request, response, url) => { const path = url.pathname const session = request.headers.cookie?.includes('browser-fixture') ? 'browser-fixture' @@ -87,7 +55,7 @@ test('source authorization returns to its desktop screen and refreshes live', as } if (path === '/fixture.js' || path === '/fixture.css') { response.setHeader('content-type', path.endsWith('.js') ? 'text/javascript' : 'text/css') - response.end(path.endsWith('.js') ? javascript : stylesheet) + response.end(path.endsWith('.js') ? bundle.js : bundle.css) return } if (path === '/api/organizations/fixture-organization/connected-accounts') { @@ -165,6 +133,7 @@ test('source authorization returns to its desktop screen and refreshes live', as } if (path === '/api/desktop/source-connect') { const { requestId, request: sourceRequest } = await body() + // Outlives Chromium's ~5s transient user activation: opening the browser must not need it. if (startSessions.length === 0) await sleep(5_500) tickets.set(requestId, sourceRequest) json({ requestId }) @@ -361,6 +330,7 @@ test('source authorization returns to its desktop screen and refreshes live', as return } if (path === '/desktop/connect/complete') { + completedStates.push(url.searchParams.get('state') ?? '') const params = new URLSearchParams({ state: url.searchParams.get('state') ?? '' }) if (url.searchParams.has('error')) params.set('error', url.searchParams.get('error')!) if (url.searchParams.has('credentialId')) @@ -413,55 +383,22 @@ test('source authorization returns to its desktop screen and refreshes live', as '
' ) }) + origin = server.origin try { - await check('launch the production source hook and native bridge', async () => { - const config = await loadPostcssConfig({}, SIM_DIR) - const cssPath = join(SIM_DIR, 'app/_styles/globals.css') - const css = await postcss(config.plugins).process( - `${readFileSync(cssPath, 'utf8')}\n@source ${JSON.stringify(FIXTURE)};`, - { from: cssPath } - ) - const bundle = await build({ - entryPoints: [FIXTURE], - bundle: true, - write: false, - outfile: test.info().outputPath('fixture.js'), - format: 'iife', - platform: 'browser', - tsconfig: join(SIM_DIR, 'tsconfig.json'), - external: ['node:async_hooks'], - inject: [fileURLToPath(new URL('./fixtures/browser-buffer.ts', import.meta.url))], - banner: { js: 'var process={env:{NODE_ENV:"development"},browser:true};' }, - define: { 'process.env.NODE_ENV': '"development"' }, - }) - javascript = bundle.outputFiles.find((file) => file.path.endsWith('.js'))?.text ?? '' - stylesheet = `${css.css}\n${bundle.outputFiles.find((file) => file.path.endsWith('.css'))?.text ?? ''}` - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - origin = `http://127.0.0.1:${address.port}` - app = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { ...process.env, SIM_DESKTOP_ORIGIN: origin, SIM_DESKTOP_USER_DATA: userData }, - }) - await app.evaluate(({ shell }) => { - const global = globalThis as typeof globalThis & { openedUrls: string[] } - global.openedUrls = [] - shell.openExternal = async (url) => { - global.openedUrls.push(url) - } - }) - browser = await chromium.launch() + const { app: shell } = await desktop.launch({ origin }) + await shell.evaluate(({ shell }) => { + const global = globalThis as typeof globalThis & { openedUrls: string[] } + global.openedUrls = [] + shell.openExternal = async (url) => { + global.openedUrls.push(url) + } }) - if (!app || !browser) throw new Error('Missing apps') - const shell = app - const page = await app.firstWindow() + const page = await shell.firstWindow() const pageErrors: string[] = [] page.on('pageerror', (error) => pageErrors.push(error.message)) + // Reloads so errors from the first render, before the listener existed, are caught too. await page.reload() - await expect.poll(() => pageErrors).toEqual([]) - const context = await browser.newContext() + await expect(page.getByLabel('Source draft')).toBeVisible() await context.addCookies([ { name: 'better-auth.session_token', @@ -474,103 +411,97 @@ test('source authorization returns to its desktop screen and refreshes live', as const external = await context.newPage() const opened = () => shell.evaluate(() => (globalThis as typeof globalThis & { openedUrls: string[] }).openedUrls) - await check( - 'separate browser consent completes under its initiating session and refreshes desktop', - async () => { - await page.getByLabel('Source draft').fill('Preserved while connecting') - await page.getByRole('button', { name: 'Connect Slack' }).click() - await expect.poll(async () => (await opened()).length, { timeout: 15_000 }).toBe(1) - expect(page.url()).toBe(`${origin}/home`) - await expect(page.getByLabel('Connection')).toHaveText('pending') - await external.goto((await opened())[0]) - await external.getByRole('link', { name: 'Authorize', exact: true }).click() - await expect(page.getByLabel('Connection')).toHaveText('success') - await expect(page.getByLabel('Accounts')).toHaveText('1') - await expect(page.getByLabel('Source draft')).toHaveValue('Preserved while connecting') - expect(startSessions).toEqual(['browser-fixture']) - expect(callbackSessions).toEqual(['browser-fixture']) - await expect(external).toHaveURL(`${origin}/desktop/done?kind=connect`) - } - ) - await check( - 'denied authorization returns an actionable error without navigating desktop', - async () => { - await page.getByRole('button', { name: 'Connect Slack' }).click() - await expect.poll(async () => (await opened()).length, { timeout: 15_000 }).toBe(2) - await external.goto((await opened())[1]) - await external.getByRole('link', { name: 'Cancel', exact: true }).click() - await expect(page.getByLabel('Connection')).toHaveText('error') - await expect(page.getByRole('alert')).toContainText('Try connecting again') - expect(page.url()).toBe(`${origin}/home`) - await expect(page.getByLabel('Accounts')).toHaveText('1') - } - ) - await check( - 'native cancellation rejects a stale callback without disrupting the next request', - async () => { - await page.getByRole('button', { name: 'Connect Slack' }).click() - await expect.poll(async () => (await opened()).length, { timeout: 15_000 }).toBe(3) - await external.goto((await opened())[2]) - await external.getByRole('link', { name: 'Authorize', exact: true }).waitFor() - const staleCallback = await external - .getByRole('link', { name: 'Authorize', exact: true }) - .getAttribute('href') - await expect(page.getByRole('button', { name: 'Cancel', exact: true })).toHaveCount(1) - await page.getByRole('button', { name: 'Cancel', exact: true }).click() - await expect(page.getByLabel('Connection')).toHaveText('error') - const canceled = new URL((await opened())[2]) - const probe = `http://127.0.0.1:${canceled.searchParams.get('port')}/connect/callback?state=${'x'.repeat(32)}` - await expect - .poll(() => - fetch(probe).then( - () => false, - () => true - ) + await test.step('separate browser consent completes under its initiating session and refreshes desktop', async () => { + await page.getByLabel('Source draft').fill('Preserved while connecting') + await page.getByRole('button', { name: 'Connect Slack' }).click() + // The first start outlives the default timeout on purpose (see /api/desktop/source-connect). + await expect.poll(async () => (await opened()).length, { timeout: 15_000 }).toBe(1) + expect(page.url()).toBe(`${origin}/home`) + await expect(page.getByLabel('Connection')).toHaveText('pending') + await external.goto((await opened())[0]) + await external.getByRole('link', { name: 'Authorize', exact: true }).click() + await expect(page.getByLabel('Connection')).toHaveText('success') + await expect(page.getByLabel('Accounts')).toHaveText('1') + await expect(page.getByLabel('Source draft')).toHaveValue('Preserved while connecting') + expect(startSessions).toEqual(['browser-fixture']) + expect(callbackSessions).toEqual(['browser-fixture']) + await expect(external).toHaveURL(`${origin}/desktop/done?kind=connect`) + }) + await test.step('denied authorization returns an actionable error without navigating desktop', async () => { + await page.getByRole('button', { name: 'Connect Slack' }).click() + await expect.poll(async () => (await opened()).length).toBe(2) + await external.goto((await opened())[1]) + await external.getByRole('link', { name: 'Cancel', exact: true }).click() + await expect(page.getByLabel('Connection')).toHaveText('error') + await expect(page.getByRole('alert')).toContainText('Try connecting again') + expect(page.url()).toBe(`${origin}/home`) + await expect(page.getByLabel('Accounts')).toHaveText('1') + }) + await test.step('native cancellation rejects a stale callback without disrupting the next request', async () => { + await page.getByRole('button', { name: 'Connect Slack' }).click() + await expect.poll(async () => (await opened()).length).toBe(3) + await external.goto((await opened())[2]) + await external.getByRole('link', { name: 'Authorize', exact: true }).waitFor() + const staleCallback = await external + .getByRole('link', { name: 'Authorize', exact: true }) + .getAttribute('href') + await expect(page.getByRole('button', { name: 'Cancel', exact: true })).toHaveCount(1) + await page.getByRole('button', { name: 'Cancel', exact: true }).click() + await expect(page.getByLabel('Connection')).toHaveText('error') + const canceled = new URL((await opened())[2]) + const probe = `http://127.0.0.1:${canceled.searchParams.get('port')}/connect/callback?state=${'x'.repeat(32)}` + await expect + .poll(() => + fetch(probe).then( + () => false, + () => true ) - .toBe(true) - await page.getByRole('button', { name: 'Connect Slack' }).click() - await expect.poll(async () => (await opened()).length, { timeout: 15_000 }).toBe(4) - await external.goto(`${origin}${staleCallback}`) - await expect(page.getByLabel('Connection')).toHaveText('pending') - await external.goto((await opened())[3]) - await external.getByRole('link', { name: 'Authorize', exact: true }).click() - await expect(page.getByLabel('Connection')).toHaveText('success') - await expect(page.getByLabel('Source draft')).toHaveValue('Preserved while connecting') - } - ) - await check( - 'GitHub setup stays in the browser session and verifies the returned credential in desktop', - async () => { + ) + .toBe(true) + await page.getByRole('button', { name: 'Connect Slack' }).click() + await expect.poll(async () => (await opened()).length).toBe(4) + const handoffs = completedStates.length + await external.goto(`${origin}${staleCallback}`) + // The browser page hands the stale result back toward the canceled attempt's loopback. + await expect + .poll(() => completedStates.slice(handoffs)) + .toEqual([canceled.searchParams.get('state')]) + await expect(page.getByLabel('Connection')).toHaveText('pending') + await external.goto((await opened())[3]) + await external.getByRole('link', { name: 'Authorize', exact: true }).click() + await expect(page.getByLabel('Connection')).toHaveText('success') + await expect(page.getByLabel('Source draft')).toHaveValue('Preserved while connecting') + }) + await test.step('GitHub setup stays in the browser session and verifies the returned credential in desktop', async () => { + await page.getByRole('button', { name: 'Connect GitHub' }).click() + await expect.poll(async () => (await opened()).length).toBe(5) + await external.goto((await opened())[4]) + await external.getByRole('link', { name: 'Authorize GitHub' }).click() + await expect(page.getByLabel('GitHub error')).toContainText('not available') + await expect(page.getByLabel('GitHub credential')).toHaveText('') + nativeCredentialVisible = true + let releaseGithubInventory = () => {} + githubInventoryHold = new Promise((resolve) => { + releaseGithubInventory = resolve + }) + try { await page.getByRole('button', { name: 'Connect GitHub' }).click() - await expect.poll(async () => (await opened()).length).toBe(5) - await external.goto((await opened())[4]) + await expect.poll(async () => (await opened()).length).toBe(6) + await external.goto((await opened())[5]) await external.getByRole('link', { name: 'Authorize GitHub' }).click() - await expect(page.getByLabel('GitHub error')).toContainText('not available') - await expect(page.getByLabel('GitHub credential')).toHaveText('') - nativeCredentialVisible = true - let releaseGithubInventory = () => {} - githubInventoryHold = new Promise((resolve) => { - releaseGithubInventory = resolve - }) - try { - await page.getByRole('button', { name: 'Connect GitHub' }).click() - await expect.poll(async () => (await opened()).length).toBe(6) - await external.goto((await opened())[5]) - await external.getByRole('link', { name: 'Authorize GitHub' }).click() - await expect.poll(() => githubInventorySessions.length).toBe(2) - await expect(page.getByLabel('GitHub pending')).toHaveText('true') - } finally { - githubInventoryHold = undefined - releaseGithubInventory() - } - await expect(page.getByLabel('GitHub credential')).toHaveText('fixture-github-credential') - expect(githubStartSessions).toEqual(['browser-fixture', 'browser-fixture']) - expect(githubInventorySessions).toEqual(['desktop-fixture', 'desktop-fixture']) - await expect(page.getByLabel('GitHub pending')).toHaveText('false') - expect(page.url()).toBe(`${origin}/home`) + await expect.poll(() => githubInventorySessions.length).toBe(2) + await expect(page.getByLabel('GitHub pending')).toHaveText('true') + } finally { + githubInventoryHold = undefined + releaseGithubInventory() } - ) - await check('ordinary knowledge-base enrollment preserves its invitation step', async () => { + await expect(page.getByLabel('GitHub credential')).toHaveText('fixture-github-credential') + expect(githubStartSessions).toEqual(['browser-fixture', 'browser-fixture']) + expect(githubInventorySessions).toEqual(['desktop-fixture', 'desktop-fixture']) + await expect(page.getByLabel('GitHub pending')).toHaveText('false') + expect(page.url()).toBe(`${origin}/home`) + }) + await test.step('ordinary knowledge-base enrollment preserves its invitation step', async () => { await page.getByRole('button', { name: 'Connect invited source' }).click() await expect.poll(async () => (await opened()).length).toBe(7) await external.goto((await opened())[6]) @@ -579,7 +510,7 @@ test('source authorization returns to its desktop screen and refreshes live', as await expect(page.getByLabel('Enrollment error')).toHaveText('') expect(page.url()).toBe(`${origin}/home`) }) - await check('browser sign-in failures retain recovery guidance on desktop', async () => { + await test.step('browser sign-in failures retain recovery guidance on desktop', async () => { await page.getByRole('button', { name: 'Connect Slack' }).click() await expect.poll(async () => (await opened()).length).toBe(8) await external.goto((await opened())[7]) @@ -588,7 +519,7 @@ test('source authorization returns to its desktop screen and refreshes live', as await expect(page.getByRole('alert')).toContainText('Sign in to Sim in your browser') expect(page.url()).toBe(`${origin}/home`) }) - await check('managed accounts return through the desktop completion handoff', async () => { + await test.step('managed accounts return through the desktop completion handoff', async () => { await page.getByRole('button', { name: 'Connect MCP account', exact: true }).click() await expect.poll(async () => (await opened()).length).toBe(9) await external.goto((await opened())[8]) @@ -601,25 +532,22 @@ test('source authorization returns to its desktop screen and refreshes live', as const web = await context.newPage() web.on('pageerror', (error) => pageErrors.push(error.message)) await web.goto(`${origin}/o/fixture-organization/integrations?search=fixture`) - await check( - 'web authorization preserves the origin and refreshes after an isolated provider window', - async () => { - accountConnected = false - mcpAccountConnected = false - await web.reload() - await web.getByLabel('Source draft').fill('Web draft retained') - await expect(web.getByLabel('Account count')).toHaveText('0') - const popupReady = context.waitForEvent('page') - await web.getByRole('button', { name: 'Connect account', exact: true }).click() - const popup = await popupReady - await popup.getByRole('link', { name: 'Authorize account' }).click() - await expect(web.getByLabel('Account count')).toHaveText('1') - await expect(web.getByLabel('Account authorization', { exact: true })).toHaveText('success') - await expect(web.getByLabel('Source draft')).toHaveValue('Web draft retained') - expect(web.url()).toBe(`${origin}/o/fixture-organization/integrations?search=fixture`) - } - ) - await check('overlapping connect and reconnect preserve the active authorization', async () => { + await test.step('web authorization preserves the origin and refreshes after an isolated provider window', async () => { + accountConnected = false + mcpAccountConnected = false + await web.reload() + await web.getByLabel('Source draft').fill('Web draft retained') + await expect(web.getByLabel('Account count')).toHaveText('0') + const popupReady = context.waitForEvent('page') + await web.getByRole('button', { name: 'Connect account', exact: true }).click() + const popup = await popupReady + await popup.getByRole('link', { name: 'Authorize account' }).click() + await expect(web.getByLabel('Account count')).toHaveText('1') + await expect(web.getByLabel('Account authorization', { exact: true })).toHaveText('success') + await expect(web.getByLabel('Source draft')).toHaveValue('Web draft retained') + expect(web.url()).toBe(`${origin}/o/fixture-organization/integrations?search=fixture`) + }) + await test.step('overlapping connect and reconnect preserve the active authorization', async () => { const popupReady = context.waitForEvent('page') await web.getByRole('button', { name: 'Connect account', exact: true }).click() const popup = await popupReady @@ -632,7 +560,7 @@ test('source authorization returns to its desktop screen and refreshes live', as await popup.getByRole('link', { name: 'Authorize account' }).click() await expect(web.getByLabel('Account authorization', { exact: true })).toHaveText('success') }) - await check('web denial and cancellation leave the initiating page usable', async () => { + await test.step('web denial and cancellation leave the initiating page usable', async () => { const popupReady = context.waitForEvent('page') await web.getByRole('button', { name: 'Connect account', exact: true }).click() const popup = await popupReady @@ -651,7 +579,7 @@ test('source authorization returns to its desktop screen and refreshes live', as await expect(web.getByRole('button', { name: 'Connect account', exact: true })).toBeEnabled() await expect(web.getByLabel('Account count')).toHaveText('1') }) - await check('reconnect uses the same completion lifecycle', async () => { + await test.step('reconnect uses the same completion lifecycle', async () => { const popupReady = context.waitForEvent('page') await web.getByRole('button', { name: 'Reconnect account', exact: true }).click() const popup = await popupReady @@ -659,7 +587,7 @@ test('source authorization returns to its desktop screen and refreshes live', as await expect(web.getByLabel('Reconnect status')).toHaveText('success') await expect(web.getByLabel('Source draft')).toHaveValue('Web draft retained') }) - await check('blocked popups complete in the same tab and return to Integrations', async () => { + await test.step('blocked popups complete in the same tab and return to Integrations', async () => { await web.evaluate(() => { window.open = () => null }) @@ -668,7 +596,7 @@ test('source authorization returns to its desktop screen and refreshes live', as await expect(web).toHaveURL(`${origin}/o/fixture-organization/integrations`) await expect(web.getByLabel('Account count')).toHaveText('1') }) - await check('canceling Slack setup aborts the pending web HTTP request', async () => { + await test.step('canceling Slack setup aborts the pending web HTTP request', async () => { holdSlackStart = true const starts = startSessions.length try { @@ -681,65 +609,59 @@ test('source authorization returns to its desktop screen and refreshes live', as holdSlackStart = false } }) - await check( - 'desktop Search preserves pending receipts after inventory failure and allows cancellation/retry', - async () => { - const previousOpens = (await opened()).length - await page.getByRole('button', { name: 'Connect personal Search', exact: true }).click() - await expect.poll(async () => (await opened()).length).toBe(previousOpens + 1) - await external.goto((await opened())[previousOpens]) - await external.getByRole('link', { name: 'Authorize personal Search' }).waitFor() - personalInventoryFailed = true - await external.getByRole('link', { name: 'Authorize personal Search' }).click() - await expect(external).toHaveURL(`${origin}/desktop/done?kind=connect`) - await expect.poll(() => personalInventoryFailures).toBeGreaterThan(0) - await expect( - page.getByRole('button', { name: 'Connect personal Search', exact: true }) - ).toBeEnabled() - const receipt = () => - page.evaluate(() => { - const entry = Object.entries(localStorage).find(([key]) => - key.startsWith('sim.search-connection.') - ) - if (!entry) return null - const attempt: { completionId: string; status: string; credentialId?: string } = - JSON.parse(entry[1]) - return attempt - }) - const pendingReceipt = await receipt() - expect(pendingReceipt).toMatchObject({ status: 'pending' }) - await page.getByRole('button', { name: 'Connect personal Search', exact: true }).click() - expect(await receipt()).toEqual(pendingReceipt) - await page.getByRole('button', { name: 'Cancel personal Search', exact: true }).click() - await expect - .poll(receipt) - .toMatchObject({ completionId: pendingReceipt?.completionId, status: 'failed' }) - personalInventoryFailed = false - await page.getByRole('button', { name: 'Retry personal inventory', exact: true }).click() - await page.getByRole('button', { name: 'Connect personal Search', exact: true }).click() - await expect.poll(async () => (await opened()).length).toBe(previousOpens + 2) - const retryReceipt = await receipt() - expect(retryReceipt).toMatchObject({ status: 'pending' }) - expect(retryReceipt?.completionId).not.toBe(pendingReceipt?.completionId) - await external.goto((await opened())[previousOpens + 1]) - await external.getByRole('link', { name: 'Authorize personal Search' }).click() - await expect.poll(receipt).toMatchObject({ - completionId: retryReceipt?.completionId, - status: 'connected', - credentialId: 'fixture-personal-account', + await test.step('desktop Search preserves pending receipts after inventory failure and allows cancellation/retry', async () => { + const previousOpens = (await opened()).length + await page.getByRole('button', { name: 'Connect personal Search', exact: true }).click() + await expect.poll(async () => (await opened()).length).toBe(previousOpens + 1) + await external.goto((await opened())[previousOpens]) + await external.getByRole('link', { name: 'Authorize personal Search' }).waitFor() + personalInventoryFailed = true + await external.getByRole('link', { name: 'Authorize personal Search' }).click() + await expect(external).toHaveURL(`${origin}/desktop/done?kind=connect`) + await expect.poll(() => personalInventoryFailures).toBeGreaterThan(0) + await expect( + page.getByRole('button', { name: 'Connect personal Search', exact: true }) + ).toBeEnabled() + const receipt = () => + page.evaluate(() => { + const entry = Object.entries(localStorage).find(([key]) => + key.startsWith('sim.search-connection.') + ) + if (!entry) return null + const attempt: { completionId: string; status: string; credentialId?: string } = + JSON.parse(entry[1]) + return attempt }) - } - ) - await page.screenshot({ path: test.info().outputPath('source-connect-desktop.png') }) - } finally { - mkdirSync(dirname(reportPath), { recursive: true }) - writeFileSync(reportPath, JSON.stringify({ checks }, null, 2)) - await browser?.close() - await app?.close() - await new Promise((resolve) => { - server.close(() => resolve()) - server.closeAllConnections() + const pendingReceipt = await receipt() + expect(pendingReceipt).toMatchObject({ status: 'pending' }) + const connect = page.getByRole('button', { name: 'Connect personal Search', exact: true }) + await connect.click() + // Cancel lands after the second Connect, so failing the first attempt's receipt shows + // that Connect neither replaced it nor started another authorization. + await page.getByRole('button', { name: 'Cancel personal Search', exact: true }).click() + await expect + .poll(receipt) + .toMatchObject({ completionId: pendingReceipt?.completionId, status: 'failed' }) + expect(await opened()).toHaveLength(previousOpens + 1) + personalInventoryFailed = false + await page.getByRole('button', { name: 'Retry personal inventory', exact: true }).click() + // Connect stays disabled until the retried inventory offers the source again. + await expect(connect).toBeEnabled() + await connect.click() + await expect.poll(async () => (await opened()).length).toBe(previousOpens + 2) + const retryReceipt = await receipt() + expect(retryReceipt).toMatchObject({ status: 'pending' }) + expect(retryReceipt?.completionId).not.toBe(pendingReceipt?.completionId) + await external.goto((await opened())[previousOpens + 1]) + await external.getByRole('link', { name: 'Authorize personal Search' }).click() + await expect.poll(receipt).toMatchObject({ + completionId: retryReceipt?.completionId, + status: 'connected', + credentialId: 'fixture-personal-account', + }) }) - rmSync(userData, { recursive: true, force: true }) + expect(pageErrors).toEqual([]) + } finally { + await server.close() } }) diff --git a/apps/desktop/e2e/terminal-cancel.spec.ts b/apps/desktop/e2e/terminal-cancel.spec.ts index 1d639b7dacc..b030b0e3358 100644 --- a/apps/desktop/e2e/terminal-cancel.spec.ts +++ b/apps/desktop/e2e/terminal-cancel.spec.ts @@ -1,13 +1,17 @@ import { execFileSync } from 'node:child_process' -import { chmodSync, mkdtempSync, readdirSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' +import { chmodSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { join } from 'node:path' -import { type ElectronApplication, expect, type Page, test } from '@playwright/test' -import type { SimDesktopApi } from '@sim/desktop-bridge' -import { sleep } from '@sim/utils/helpers' +import type { Page } from '@playwright/test' import { randomInt } from '@sim/utils/random' -import { recordCheck } from './check-report' -import { FixtureSim, launch, processRunning, registeredDevice, settled } from './executor-sim' +import { + type ExecutorApp, + FixtureSim, + launchAgainst, + processRunning, + registeredDevice, + settled, +} from './executor-sim' +import { type DesktopBridge, type DesktopFixture, expect, test } from './harness' /** * Stopping the agent's terminal commands in the real app, with real shells and a real tmux @@ -19,8 +23,9 @@ import { FixtureSim, launch, processRunning, registeredDevice, settled } from '. * Agent commands in a plain shell ignore SIGHUP, SIGINT and SIGTERM, so closing the shell cannot * end them by accident: only Sim's own stop, which escalates to SIGKILL on the command's process * group, does. The user's commands ignore the same signals, so a stop that reached them would - * show. Each launch gets its own tmux server (TMUX_TMPDIR), which the app's shells and its tmux - * calls inherit. The tmux scenarios skip where tmux is not installed. + * show. Each test gets its own tmux server (TMUX_TMPDIR), which the app's shells and its tmux + * calls inherit. The tmux scenarios skip where tmux is not installed, except in CI, which + * installs it. */ const CHAT_PLAIN = 'chat-cancel-plain' @@ -30,8 +35,6 @@ const TMUX_SESSION = 'agent-e2e' const STUBBORN = "trap '' HUP INT TERM" const sim = new FixtureSim() -/** The app's own log output for the current test, attached when it fails. */ -const appOutput: string[] = [] /** The shells, sleeps and tmux processes running, for a failure about who started what. */ function processes(): string { @@ -71,8 +74,13 @@ function findTmux(): string | null { } } -/** One launch's own tmux server, and a way to read and reshape it as the user would. */ +function requireTmux(): void { + test.skip(!REAL_TMUX, 'tmux is not installed on this machine') +} + +/** One test's own tmux server, and a way to read and reshape it as the user would. */ class TmuxServer { + /** Short and under /tmp: the server's socket path must fit in 104 bytes. */ readonly dir = mkdtempSync('/tmp/sim-tmux-') run(args: string[]): string { @@ -102,9 +110,9 @@ class TmuxServer { } } - /** The pane an agent run opened, found by the run script it was started with. */ - runPane(): { id: string; runId: string } | undefined { - return this.panes().find((pane) => pane.command.includes('run.sh')) + /** The panes agent runs opened, found by the run script they were started with. */ + runPanes(): Array<{ id: string; runId: string }> { + return this.panes().filter((pane) => pane.command.includes('run.sh')) } hasPane(id: string): boolean { @@ -124,18 +132,19 @@ class TmuxServer { } } - kill(): void { + remove(): void { try { this.run(['kill-server']) } catch { // Already gone. } + rmSync(this.dir, { recursive: true, force: true }) } } /** A `tmux` ahead of the real one on PATH that refuses pane options, as tmux before 3.0 does. */ -function oldTmuxPath(): string { - const dir = mkdtempSync(join(tmpdir(), 'sim-old-tmux-')) +function oldTmuxPath(desktop: DesktopFixture): string { + const dir = desktop.tempDir('sim-old-tmux-') const binary = join(dir, 'tmux') writeFileSync( binary, @@ -156,8 +165,7 @@ function bridge(window: Page) { /** The user opens a terminal tab in a chat's terminal panel and starts a command in it. */ async userRuns(scope: string, command: string): Promise { const terminalId = await window.evaluate(async (scopeId) => { - const terminal = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }) - .simDesktop.terminal + const terminal = (globalThis as DesktopBridge).simDesktop.terminal await terminal.activateScope(scopeId) terminal.setVisible?.(true, scopeId) terminal.setFocused(true, scopeId) @@ -169,17 +177,14 @@ function bridge(window: Page) { await window.keyboard.press('Shift') await window.evaluate( ([id, text, scopeId]) => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.terminal.write(id, text, scopeId), + (globalThis as DesktopBridge).simDesktop.terminal.write(id, text, scopeId), [terminalId, `${command}\r`, scope] as const ) }, /** The user puts a chat away: its terminals close, though tmux runs started in them go on. */ async putAway(scope: string): Promise { return window.evaluate(async (scopeId) => { - const terminal = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }) - .simDesktop.terminal + const terminal = (globalThis as DesktopBridge).simDesktop.terminal await terminal.activateScope(scopeId) return terminal.suspendScope(scopeId) }, scope) @@ -187,9 +192,7 @@ function bridge(window: Page) { async setTerminalEnabled(enabled: boolean): Promise { await window.evaluate( (value) => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.settings.setPreference('terminalEnabled', value), + (globalThis as DesktopBridge).simDesktop.settings.setPreference('terminalEnabled', value), enabled ) }, @@ -202,14 +205,16 @@ async function agentRunsPlain(deviceId: string, seconds: number): Promise processRunning(`${slept(seconds)}`), { timeout: 30_000 }).toBe(true) + await expect.poll(() => processRunning(slept(seconds)), { timeout: 30_000 }).toBe(true) return call } -/** - * The agent's terminal attaches to tmux (the agent starts a tmux client in it), and the agent then - * runs a command, which tmux gives its own tagged pane. Resolves with the call and that pane. - */ +/** The user starts a stubborn command in a tab of their own; resolves once it is running. */ +async function userRunsPlain(window: Page, seconds: number): Promise { + await bridge(window).userRuns(CHAT_PLAIN, stubborn(seconds)) + await expect.poll(() => processRunning(slept(seconds)), { timeout: 30_000 }).toBe(true) +} + /** The agent starts a tmux client in its chat's terminal, so its runs go to tmux panes. */ async function agentAttachesTmux(deviceId: string, tmux: TmuxServer): Promise { const before = tmux.clients() @@ -218,8 +223,17 @@ async function agentAttachesTmux(deviceId: string, tmux: TmuxServer): Promise tmux.clients(), { timeout: 30_000 }).toBe(before + 1) - // The terminal's attachment is looked up again once its short cache lapses. - await sleep(3_500) + // The terminal remembers for a few seconds that it was not in tmux. Listing panes only works + // once it sees the attachment, and the run that follows then goes to tmux as well. + await expect + .poll( + async () => { + const probe = sim.issue(deviceId, CHAT_TMUX, 'terminal', { operation: 'panes', args: {} }) + return (await settled(sim, probe)).status + }, + { timeout: 30_000 } + ) + .toBe('success') } /** @@ -233,6 +247,17 @@ async function agentRunsInTmux( waitSeconds = 120 ): Promise<{ call: string; pane: { id: string; runId: string } }> { await agentAttachesTmux(deviceId, tmux) + return agentRunsInAttachedTmux(deviceId, tmux, seconds, waitSeconds) +} + +/** {@link agentRunsInTmux} in a chat terminal that is already attached. */ +async function agentRunsInAttachedTmux( + deviceId: string, + tmux: TmuxServer, + seconds: number, + waitSeconds: number +): Promise<{ call: string; pane: { id: string; runId: string } }> { + const known = new Set(tmux.runPanes().map((pane) => pane.id)) // It ignores Ctrl-C, so stopping it takes closing its pane, the step that must spare the user's. const call = sim.issue(deviceId, CHAT_TMUX, 'terminal', { operation: 'run', @@ -241,18 +266,37 @@ async function agentRunsInTmux( waitSeconds, }, }) - await expect.poll(() => processRunning(`${slept(seconds)}`), { timeout: 30_000 }).toBe(true) - await expect.poll(() => tmux.runPane(), { timeout: 10_000 }).toBeTruthy() - return { call, pane: tmux.runPane() as { id: string; runId: string } } + await expect.poll(() => processRunning(slept(seconds)), { timeout: 30_000 }).toBe(true) + const newPane = () => tmux.runPanes().find((pane) => !known.has(pane.id)) + await expect.poll(newPane, { timeout: 10_000 }).toBeTruthy() + return { call, pane: newPane() as { id: string; runId: string } } } async function claimed(call: string): Promise { await expect.poll(() => sim.requireCall(call).claims, { timeout: 30_000 }).toBe(1) } +/** The runs this app has recorded for a later process to find. */ +function recordedRuns(userData: string): string[] { + try { + return readdirSync(join(userData, 'terminal-runs')) + } catch { + return [] + } +} + +/** Where a recorded run stands: `started`, or `delivered` once the model has its pane. */ +function recordedRunState(userData: string, runId: string): unknown { + try { + return JSON.parse(readFileSync(join(userData, 'terminal-runs', `${runId}.json`), 'utf8')).state + } catch { + return undefined + } +} + test.describe('terminal cancel', () => { - let app: ElectronApplication | null = null let tmux: TmuxServer + let launched: ExecutorApp[] = [] const leftovers: string[] = [] test.beforeAll(async () => { @@ -260,17 +304,13 @@ test.describe('terminal cancel', () => { }) test.beforeEach(() => { + // CI installs tmux, so a runner without it fails instead of quietly skipping half the suite. + if (process.env.CI) expect(REAL_TMUX, 'tmux is not installed').not.toBeNull() tmux = new TmuxServer() }) - test.afterEach(async () => { + test.afterEach(async ({ desktop }) => { const testInfo = test.info() - recordCheck(process.env.TERMINAL_CANCEL_REPORT_PATH, 'terminal-cancel', { - name: testInfo.title, - status: testInfo.status ?? 'unknown', - durationMs: testInfo.duration, - retry: testInfo.retry, - }) if (testInfo.status !== testInfo.expectedStatus) { // What each call came back with, and the panes tmux held, explain most failures. const calls = [...sim.calls.values()].map((call) => ({ @@ -286,23 +326,22 @@ test.describe('terminal cancel', () => { await testInfo.attach('calls', { body: JSON.stringify({ calls, panes: tmux.panes() }, null, 2), }) - await testInfo.attach('app-output', { body: appOutput.join('').slice(-6_000) }) + for (const [index, app] of launched.entries()) { + await testInfo.attach(`app-output-${index + 1}`, { body: app.output().slice(-6_000) }) + } await testInfo.attach('processes', { body: processes() }) } - appOutput.length = 0 - // Quitting with a command still running in a tab asks first (natively, on macOS), and nobody - // is there to answer, so a close that does not finish promptly ends the app instead. - const closing = app - const closed = await Promise.race([ - closing?.close().then( - () => true, - () => true - ) ?? Promise.resolve(true), - sleep(5_000).then(() => false), - ]) - if (!closed) closing?.process().kill('SIGKILL') - app = null - tmux.kill() + // Quit while the tmux server and the fixture Sim still answer, so a stall is the app's own. + let quitFailure: unknown + for (const app of launched) { + try { + await desktop.close(app) + } catch (error) { + quitFailure ??= error + } + } + launched = [] + tmux.remove() for (const pattern of leftovers.splice(0)) { try { execFileSync('pkill', ['-9', '-f', pattern]) @@ -311,33 +350,49 @@ test.describe('terminal cancel', () => { } } sim.reset() + if (quitFailure) throw quitFailure }) test.afterAll(async () => { await sim.stop() }) + /** Launches the app on this test's tmux server, on `userData` when relaunching. */ + async function launch( + desktop: DesktopFixture, + options: { userData?: string; env?: Record } = {} + ): Promise { + const app = await launchAgainst(desktop, sim, { + userData: options.userData, + env: { TMUX_TMPDIR: tmux.dir, ...options.env }, + }) + launched.push(app) + return app + } + async function start( - name: string, + desktop: DesktopFixture, env: Record = {} - ): Promise<{ window: Page; deviceId: string; userData: string }> { - const userData = mkdtempSync(join(tmpdir(), `sim-cancel-${name}-`)) - const launched = await launch(sim, userData, { TMUX_TMPDIR: tmux.dir, ...env }) - app = launched.app - launched.app.process().stdout?.on('data', (chunk: Buffer) => appOutput.push(chunk.toString())) - launched.app.process().stderr?.on('data', (chunk: Buffer) => appOutput.push(chunk.toString())) + ): Promise { + const app = await launch(desktop, { env }) const deviceId = await registeredDevice(sim) - await launched.window.goto(`${sim.origin}/workspace/ws-e2e/chat/${CHAT_PLAIN}`) - return { window: launched.window, deviceId, userData } + await app.window.goto(`${sim.origin}/workspace/ws-e2e/chat/${CHAT_PLAIN}`) + return { ...app, deviceId } } - test('Stop ends the agent command in a plain shell and leaves the user command running', async () => { - const { window, deviceId } = await start('stop-plain') + /** The app dies without a word: its shells go with it, and its tmux runs outlive it. */ + function crash(app: ExecutorApp): void { + app.child.kill('SIGKILL') + } + + test('Stop ends the agent command in a plain shell and leaves the user command running', async ({ + desktop, + }) => { + const { window, deviceId } = await start(desktop) leftovers.push(slept(701), slept(702)) // The agent's terminal comes first; the user's own tab opens beside it. const call = await agentRunsPlain(deviceId, 701) - await bridge(window).userRuns(CHAT_PLAIN, stubborn(702)) - await expect.poll(() => processRunning(slept(702)), { timeout: 30_000 }).toBe(true) + await userRunsPlain(window, 702) sim.stopCall(call) @@ -346,9 +401,11 @@ test.describe('terminal cancel', () => { expect(processRunning(slept(702))).toBe(true) }) - test('Stop interrupts a tagged tmux run and closes only its pane, never the user pane beside it', async () => { - test.skip(!REAL_TMUX, 'tmux is not installed on this machine') - const { deviceId } = await start('stop-tmux') + test('Stop interrupts a tagged tmux run and closes only its pane, never the user pane beside it', async ({ + desktop, + }) => { + requireTmux() + const { deviceId } = await start(desktop) leftovers.push(slept(711), slept(712)) const { call, pane } = await agentRunsInTmux(deviceId, tmux, 711) expect(pane.runId).not.toBe('') @@ -363,15 +420,17 @@ test.describe('terminal cancel', () => { expect(processRunning(slept(712))).toBe(true) }) - test('signing out stops every agent command and leaves the user commands running', async () => { - const { window, deviceId } = await start('sign-out') + test('signing out stops every agent command and leaves the user commands running', async ({ + desktop, + }) => { + const { window, deviceId } = await start(desktop) leftovers.push(slept(721), slept(722), slept(723), slept(724)) const plain = await agentRunsPlain(deviceId, 721) await claimed(plain) - await bridge(window).userRuns(CHAT_PLAIN, stubborn(722)) - await expect.poll(() => processRunning(slept(722)), { timeout: 30_000 }).toBe(true) + await userRunsPlain(window, 722) const run = REAL_TMUX ? await agentRunsInTmux(deviceId, tmux, 723) : null const users = run ? tmux.split(run.pane.id, stubborn(724)) : null + if (users) await expect.poll(() => processRunning(slept(724)), { timeout: 15_000 }).toBe(true) // The web app signs out by navigating to its login page. await window.goto(`${sim.origin}/login?fromLogout=true`) @@ -386,53 +445,45 @@ test.describe('terminal cancel', () => { } }) - test('a session ended by another account signing in stops every agent command and leaves the user pane running', async () => { - const { window, deviceId } = await start('account') - leftovers.push(slept(731), slept(733), slept(734)) + // Sign-out, the session ending and Terminal off all stop through the same stop for everything; + // the sign-out test covers its tmux side, so these two prove only that their trigger reaches it. + test('a session ended by another account signing in stops the agent command and leaves the user command running', async ({ + desktop, + }) => { + const { window, deviceId } = await start(desktop) + leftovers.push(slept(731), slept(732)) await agentRunsPlain(deviceId, 731) - const run = REAL_TMUX ? await agentRunsInTmux(deviceId, tmux, 733) : null - const users = run ? tmux.split(run.pane.id, stubborn(734)) : null - if (users) await expect.poll(() => processRunning(slept(734)), { timeout: 15_000 }).toBe(true) + await userRunsPlain(window, 732) // Another account signing in replaces the session: the old session cookie goes away. await window.goto(`${sim.origin}/session-ended`) await expect.poll(() => processRunning(slept(731)), { timeout: 30_000 }).toBe(false) - if (run && users) { - await expect.poll(() => processRunning(slept(733)), { timeout: 15_000 }).toBe(false) - await expect.poll(() => tmux.hasPane(run.pane.id), { timeout: 10_000 }).toBe(false) - expect(tmux.hasPane(users)).toBe(true) - expect(processRunning(slept(734))).toBe(true) - } + expect(processRunning(slept(732))).toBe(true) }) - test('switching Terminal off stops every agent command and leaves the user commands running', async () => { - const { window, deviceId } = await start('terminal-off') - leftovers.push(slept(741), slept(743), slept(744)) + test('switching Terminal off stops the agent command and leaves the user command running', async ({ + desktop, + }) => { + const { window, deviceId } = await start(desktop) + leftovers.push(slept(741), slept(742)) await agentRunsPlain(deviceId, 741) - const run = REAL_TMUX ? await agentRunsInTmux(deviceId, tmux, 743) : null - const users = run ? tmux.split(run.pane.id, stubborn(744)) : null + await userRunsPlain(window, 742) await bridge(window).setTerminalEnabled(false) await expect.poll(() => processRunning(slept(741)), { timeout: 30_000 }).toBe(false) - if (run && users) { - await expect.poll(() => processRunning(slept(743)), { timeout: 15_000 }).toBe(false) - await expect.poll(() => tmux.hasPane(run.pane.id), { timeout: 10_000 }).toBe(false) - expect(tmux.hasPane(users)).toBe(true) - expect(processRunning(slept(744))).toBe(true) - } + expect(processRunning(slept(742))).toBe(true) }) - test('signing out stops a tmux run whose chat was put away', async () => { - test.skip(!REAL_TMUX, 'tmux is not installed on this machine') - const { window, deviceId, userData } = await start('put-away') + test('signing out stops a tmux run whose chat was put away', async ({ desktop }) => { + requireTmux() + const { window, deviceId, userData } = await start(desktop) leftovers.push(slept(801)) const { pane } = await agentRunsInTmux(deviceId, tmux, 801) // No live terminal holds the run any more; only its record does. expect(await bridge(window).putAway(CHAT_TMUX)).toBe(true) - await sleep(1_000) expect(processRunning(slept(801))).toBe(true) await window.goto(`${sim.origin}/login?fromLogout=true`) @@ -442,167 +493,127 @@ test.describe('terminal cancel', () => { await expect.poll(() => recordedRuns(userData), { timeout: 10_000 }).toEqual([]) }) - /** The app dies without a word: its shells go with it, and its tmux runs outlive it. */ - function crash(): void { - app?.process().kill('SIGKILL') - app = null - } - - /** The runs this app has recorded for a later process to find. */ - function recordedRuns(userData: string): string[] { - try { - return readdirSync(join(userData, 'terminal-runs')) - } catch { - return [] - } - } - - test('the launch after an interrupted sign-out stops the tmux run the previous app left running', async () => { - test.skip(!REAL_TMUX, 'tmux is not installed on this machine') - const { deviceId, userData } = await start('recovery') + test('the launch after an interrupted sign-out stops the tmux run the previous app left running', async ({ + desktop, + }) => { + requireTmux() + const first = await start(desktop) leftovers.push(slept(751)) - const { pane } = await agentRunsInTmux(deviceId, tmux, 751) + const { pane } = await agentRunsInTmux(first.deviceId, tmux, 751) // The app dies mid sign-out: its recovery marker is on disk and the tmux run outlives it. - crash() + crash(first) writeFileSync( - join(userData, 'account-data-teardown-required.json'), + join(first.userData, 'account-data-teardown-required.json'), JSON.stringify({ version: 2, kind: 'account', origin: sim.origin }) ) expect(processRunning(slept(751))).toBe(true) - app = (await launch(sim, userData, { TMUX_TMPDIR: tmux.dir })).app + await launch(desktop, { userData: first.userData }) await expect.poll(() => processRunning(slept(751)), { timeout: 30_000 }).toBe(false) expect(tmux.hasPane(pane.id)).toBe(false) - await expect.poll(() => recordedRuns(userData), { timeout: 10_000 }).toEqual([]) + await expect.poll(() => recordedRuns(first.userData), { timeout: 10_000 }).toEqual([]) }) - test('the launch after a crash stops the tmux run its call can no longer report', async () => { - test.skip(!REAL_TMUX, 'tmux is not installed on this machine') - const { deviceId, userData } = await start('crash-live') + test('the launch after a crash stops the tmux run its call can no longer report', async ({ + desktop, + }) => { + requireTmux() + const first = await start(desktop) leftovers.push(slept(771), slept(772)) - const { pane } = await agentRunsInTmux(deviceId, tmux, 771) + const { pane } = await agentRunsInTmux(first.deviceId, tmux, 771) const users = tmux.split(pane.id, stubborn(772)) // Same user, plain crash: the journal settles the call as outcome unknown, and nothing will // ever read what the command does. - crash() + crash(first) expect(processRunning(slept(771))).toBe(true) - app = (await launch(sim, userData, { TMUX_TMPDIR: tmux.dir })).app + await launch(desktop, { userData: first.userData }) await expect.poll(() => processRunning(slept(771)), { timeout: 30_000 }).toBe(false) expect(tmux.hasPane(pane.id)).toBe(false) expect(tmux.hasPane(users)).toBe(true) expect(processRunning(slept(772))).toBe(true) - await expect.poll(() => recordedRuns(userData), { timeout: 10_000 }).toEqual([]) + await expect.poll(() => recordedRuns(first.userData), { timeout: 10_000 }).toEqual([]) }) - test('the launch after a crash only forgets a tmux run that had already finished', async () => { - test.skip(!REAL_TMUX, 'tmux is not installed on this machine') - const { deviceId, userData } = await start('crash-finished') + test('the launch after a crash only forgets a tmux run that had already finished', async ({ + desktop, + }) => { + requireTmux() + const first = await start(desktop) leftovers.push(slept(6), slept(782)) // Handed back as still running, it then finishes on its own. - const { call, pane } = await agentRunsInTmux(deviceId, tmux, 6, 2) + const { call, pane } = await agentRunsInTmux(first.deviceId, tmux, 6, 2) await settled(sim, call) const users = tmux.split(pane.id, stubborn(782)) await expect.poll(() => tmux.hasPane(pane.id), { timeout: 20_000 }).toBe(false) - expect(recordedRuns(userData)).toHaveLength(1) + expect(recordedRuns(first.userData)).toHaveLength(1) - crash() - app = (await launch(sim, userData, { TMUX_TMPDIR: tmux.dir })).app + crash(first) + await launch(desktop, { userData: first.userData }) - await expect.poll(() => recordedRuns(userData), { timeout: 30_000 }).toEqual([]) + await expect.poll(() => recordedRuns(first.userData), { timeout: 30_000 }).toEqual([]) expect(tmux.hasPane(users)).toBe(true) expect(processRunning(slept(782))).toBe(true) }) - test('a run handed back as still going survives a quit and the relaunch, and can still be read', async () => { - test.skip(!REAL_TMUX, 'tmux is not installed on this machine') - const { deviceId, userData } = await start('collectable') - leftovers.push(slept(811)) - const { call, pane } = await agentRunsInTmux(deviceId, tmux, 811, 2) - const handedBack = await settled(sim, call) - expect(handedBack.data).toMatchObject({ status: 'running', pane: pane.id }) - - // Quitting stops no tmux run; the relaunch leaves one the model may come back to. - const quitting = app - app = null - const quit = await Promise.race([ - quitting?.close().then(() => true) ?? Promise.resolve(true), - sleep(10_000).then(() => false), - ]) - if (!quit) quitting?.process().kill('SIGKILL') + test('a run handed back as still going survives a quit and the relaunch, and can still be read', async ({ + desktop, + }) => { + requireTmux() + const first = await start(desktop) + leftovers.push(slept(811), slept(812)) + const kept = await agentRunsInTmux(first.deviceId, tmux, 811, 2) + const handedBack = await settled(sim, kept.call) + expect(handedBack.data).toMatchObject({ status: 'running', pane: kept.pane.id }) + await expect.poll(() => recordedRunState(first.userData, kept.pane.runId)).toBe('delivered') + // Still running when the app quits, so its result never reaches the model: the relaunch stops + // it, which is also how this test knows the relaunch has decided about every recorded run. + const uncollectable = await agentRunsInAttachedTmux(first.deviceId, tmux, 812, 120) + + // Quitting stops no tmux run. + await desktop.close(first) expect(processRunning(slept(811))).toBe(true) - app = (await launch(sim, userData, { TMUX_TMPDIR: tmux.dir })).app - // Same install, same device: it is back once its doorbell is open again. - const relaunched = await registeredDevice(sim) - await sleep(5_000) + expect(processRunning(slept(812))).toBe(true) + + await launch(desktop, { userData: first.userData }) + await expect.poll(() => processRunning(slept(812)), { timeout: 30_000 }).toBe(false) + await expect + .poll(() => recordedRuns(first.userData), { timeout: 10_000 }) + .toEqual([`${kept.pane.runId}.json`]) + expect(tmux.hasPane(uncollectable.pane.id)).toBe(false) expect(processRunning(slept(811))).toBe(true) - expect(tmux.hasPane(pane.id)).toBe(true) - expect(recordedRuns(userData)).toHaveLength(1) + expect(tmux.hasPane(kept.pane.id)).toBe(true) - // The model comes back to the pane it was handed. + // Same install, same device: it is back once its doorbell is open again, and the model comes + // back to the pane it was handed. + const relaunched = await registeredDevice(sim) await agentAttachesTmux(relaunched, tmux) const read = sim.issue(relaunched, CHAT_TMUX, 'terminal', { operation: 'read', - args: { pane: pane.id, lines: 50 }, + args: { pane: kept.pane.id, lines: 50 }, }) const output = await settled(sim, read) expect(output.status, output.message).toBe('success') expect(JSON.stringify(output.data)).toContain('collect-me') }) - test("never touches a pane that took a recorded run's id after tmux restarted", async () => { - test.skip(!REAL_TMUX, 'tmux is not installed on this machine') - const { deviceId, userData } = await start('stale-record') - leftovers.push(slept(791), slept(792)) - const { pane } = await agentRunsInTmux(deviceId, tmux, 791) - crash() - - // tmux restarts, ending the run with it, and the user's own pane gets the run's old id. - tmux.kill() - // The old server takes a moment to let go of its socket. - await expect - .poll( - () => { - try { - tmux.run(['-f', '/dev/null', 'new-session', '-d', '-s', 'users', stubborn(792)]) - return true - } catch { - return false - } - }, - { timeout: 10_000 } - ) - .toBe(true) - for (let panes = 0; panes < 10 && !tmux.hasPane(pane.id); panes += 1) { - tmux.split('users', stubborn(792)) - } - expect(processRunning(slept(791))).toBe(false) - - app = (await launch(sim, userData, { TMUX_TMPDIR: tmux.dir })).app - - await expect.poll(() => recordedRuns(userData), { timeout: 30_000 }).toEqual([]) - expect(tmux.hasPane(pane.id)).toBe(true) - expect(processRunning(slept(792))).toBe(true) - }) - - test('on tmux without pane options a run goes ahead untracked, and Stop and sign-out leave it alone', async () => { - test.skip(!REAL_TMUX, 'tmux is not installed on this machine') - const { window, deviceId } = await start('untracked', { PATH: oldTmuxPath() }) + test('on tmux without pane options a run goes ahead untracked, and Stop leaves it alone', async ({ + desktop, + }) => { + requireTmux() + const { deviceId } = await start(desktop, { PATH: oldTmuxPath(desktop) }) leftovers.push(slept(761)) const { call, pane } = await agentRunsInTmux(deviceId, tmux, 761) expect(pane.runId).toBe('') sim.stopCall(call) - await settled(sim, call, 20_000) - await sleep(6_000) - expect(processRunning(slept(761))).toBe(true) - expect(tmux.hasPane(pane.id)).toBe(true) - await window.goto(`${sim.origin}/login?fromLogout=true`) - await sleep(8_000) + // The call reports only once its stop has run, so whatever the stop did is done by now. + const stopped = await settled(sim, call, 20_000) + expect(stopped.status).toBe('cancelled') expect(processRunning(slept(761))).toBe(true) expect(tmux.hasPane(pane.id)).toBe(true) }) diff --git a/apps/desktop/e2e/update-notification.spec.ts b/apps/desktop/e2e/update-notification.spec.ts index b088ef4ca78..fed997f229c 100644 --- a/apps/desktop/e2e/update-notification.spec.ts +++ b/apps/desktop/e2e/update-notification.spec.ts @@ -1,112 +1,39 @@ -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { createServer } from 'node:http' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' -import { _electron as electron, expect, test } from '@playwright/test' import type { DesktopUpdateState } from '@sim/desktop-bridge' -import { getErrorMessage } from '@sim/utils/errors' -import { sleep } from '@sim/utils/helpers' -import { build } from 'esbuild' -import postcss from 'postcss' -import loadPostcssConfig from 'postcss-load-config' +import { bundleSimFixture, type DesktopBridge, expect, serve, test } from './harness' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) -const SIM_DIR = fileURLToPath(new URL('../../sim/', import.meta.url)) const FIXTURE = fileURLToPath(new URL('./fixtures/update-notification.tsx', import.meta.url)) -test('desktop update actions survive navigation without repeating dismissed or stale offers', async () => { - const reportPath = - process.env.DESKTOP_UPDATE_NOTICE_REPORT_PATH ?? test.info().outputPath('update-notice.json') - const checks: { - name: string - status: 'passed' | 'failed' - durationMs: number - error?: string - }[] = [] - const check = async (name: string, run: () => Promise) => { - const started = Date.now() - try { - await test.step(name, run) - checks.push({ name, status: 'passed', durationMs: Date.now() - started }) - } catch (error) { - checks.push({ - name, - status: 'failed', - durationMs: Date.now() - started, - error: getErrorMessage(error), - }) - throw error - } - } - const userData = mkdtempSync(join(tmpdir(), 'sim-update-notice-e2e-')) - let app: Awaited> | undefined - let passed = false - let javascript = '' - let stylesheet = '' - const server = createServer((request, response) => { - const path = new URL(request.url ?? '/', 'http://localhost').pathname - if (path === '/fixture.js' || path === '/fixture.css') { - response.setHeader('Content-Type', path.endsWith('.js') ? 'text/javascript' : 'text/css') - response.end(path.endsWith('.js') ? javascript : stylesheet) - } else if (path.startsWith('/api/')) { - response.setHeader('Content-Type', 'application/json') - response.end('{}') +test('desktop update actions survive navigation without repeating dismissed or stale offers', async ({ + desktop, +}) => { + const { js, css } = await bundleSimFixture({ + source: `import { mountUpdateNotificationFixture } from ${JSON.stringify(FIXTURE)}; +import { DesktopUpdateNotification } from '@/app/_shell/desktop-update-notification'; +mountUpdateNotificationFixture(DesktopUpdateNotification);`, + }) + const fixture = await serve((_request, response, url) => { + if (url.pathname === '/fixture.js' || url.pathname === '/fixture.css') { + const script = url.pathname.endsWith('.js') + response.writeHead(200, { 'Content-Type': script ? 'text/javascript' : 'text/css' }) + response.end(script ? js : css) + } else if (url.pathname.startsWith('/api/')) { + response.writeHead(200, { 'Content-Type': 'application/json' }).end('{}') } else { - response.setHeader('Content-Type', 'text/html') + response.writeHead(200, { 'Content-Type': 'text/html' }) response.end( '
' ) } }) - try { - await check('load the production notification in Electron', async () => { - const config = await loadPostcssConfig({}, SIM_DIR) - const cssPath = join(SIM_DIR, 'app/_styles/globals.css') - const css = await postcss(config.plugins).process( - `${readFileSync(cssPath, 'utf8')}\n@source ${JSON.stringify(FIXTURE)};`, - { from: cssPath } - ) - const bundle = await build({ - stdin: { - contents: `import { mountUpdateNotificationFixture } from ${JSON.stringify(FIXTURE)}; -import { DesktopUpdateNotification } from '@/app/_shell/desktop-update-notification'; -mountUpdateNotificationFixture(DesktopUpdateNotification);`, - resolveDir: SIM_DIR, - loader: 'tsx', - }, - bundle: true, - write: false, - outfile: test.info().outputPath('fixture.js'), - external: ['node:async_hooks'], - banner: { js: 'var process={env:{NODE_ENV:"development"},browser:true};' }, - format: 'iife', - platform: 'browser', - tsconfig: join(SIM_DIR, 'tsconfig.json'), - define: { 'process.env.NODE_ENV': '"development"' }, - }) - javascript = bundle.outputFiles.find((file) => file.path.endsWith('.js'))?.text ?? '' - stylesheet = `${css.css}\n${bundle.outputFiles.find((file) => file.path.endsWith('.css'))?.text ?? ''}` - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - app = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { - ...process.env, - SIM_DESKTOP_ORIGIN: `http://127.0.0.1:${address.port}`, - SIM_DESKTOP_USER_DATA: userData, - }, - }) + const { app } = await desktop.launch({ + origin: fixture.origin, }) - if (!app) throw new Error('Electron did not launch') - const shell = app - const page = await shell.firstWindow() + const page = await app.firstWindow() const errors: string[] = [] page.on('pageerror', (error) => errors.push(error.message)) - await shell.evaluate(({ app, BrowserWindow }) => { + await app.evaluate(({ app, BrowserWindow }) => { const window = BrowserWindow.getAllWindows()[0] window.setContentSize(1000, 700) window.webContents.setBackgroundThrottling(false) @@ -114,87 +41,86 @@ mountUpdateNotificationFixture(DesktopUpdateNotification);`, window.focus() }) const publish = (state: DesktopUpdateState) => - shell.evaluate(({ BrowserWindow }, next) => { + app.evaluate(({ BrowserWindow }, next) => { BrowserWindow.getAllWindows()[0].webContents.send('desktop:updates:state', next) }, state) + /** How many update states the page has received since it last loaded. */ + const delivered = () => + page.evaluate(() => (globalThis as { updateStatesDelivered?: number }).updateStatesDelivered) + const countDeliveries = () => + page.evaluate(() => { + const state = globalThis as { updateStatesDelivered?: number } + state.updateStatesDelivered = 0 + ;(globalThis as DesktopBridge).simDesktop.updates.onState(() => { + state.updateStatesDelivered = (state.updateStatesDelivered ?? 0) + 1 + }) + }) + const nextFrames = () => + page.evaluate( + () => + new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())) + ) + ) const notice = page.getByRole('list', { name: 'Notifications' }) const restart = notice.getByRole('button', { name: 'Restart to update' }) const download = notice.getByRole('button', { name: 'Download update' }) - await check( - 'initial snapshot survives StrictMode and remains actionable across navigation', - async () => { - await shell.evaluate(({ ipcMain }) => { - ipcMain.removeHandler('desktop:updates:get-state') - ipcMain.handle('desktop:updates:get-state', () => ({ status: 'ready', version: '2.0.0' })) - }) - await page.reload() - await expect(restart).toHaveCount(1) - await expect(restart).toBeVisible() - await page.getByRole('button', { name: 'Switch workspace' }).click() - await expect(page.getByLabel('Current route')).toHaveText('/workspace/second') - await sleep(5_500) - await expect(restart).toBeVisible() - await page.screenshot({ - path: test.info().outputPath('update-ready-dark.png'), - animations: 'disabled', - }) - await page.evaluate(() => document.documentElement.classList.remove('dark')) - await page.screenshot({ - path: test.info().outputPath('update-ready-light.png'), - animations: 'disabled', - }) - } - ) + await test.step('initial snapshot survives StrictMode and remains actionable across navigation', async () => { + await app.evaluate(({ ipcMain }) => { + ipcMain.removeHandler('desktop:updates:get-state') + ipcMain.handle('desktop:updates:get-state', () => ({ status: 'ready', version: '2.0.0' })) + }) + await page.reload() + await expect(restart).toHaveCount(1) + await expect(restart).toBeVisible() + await page.getByRole('button', { name: 'Switch workspace' }).click() + await expect(page.getByLabel('Current route')).toHaveText('/workspace/second') + // Outlasts the 5s default toast lifetime: proving a real timer doesn't dismiss the notice needs + // its real duration, and a fake clock would also freeze the dismiss animations used below. + await page.waitForTimeout(5_500) + await expect(restart).toBeVisible() + }) - await check('dismissal survives repeated events and checking the same release', async () => { + await test.step('dismissal survives repeated events and checking the same release', async () => { await notice.getByRole('button', { name: 'Dismiss notification' }).click() await expect(restart).toHaveCount(0) + await countDeliveries() await publish({ status: 'ready', version: '2.0.0' }) await publish({ status: 'checking', version: '2.0.0' }) - await page.evaluate( - () => - new Promise((resolve) => - requestAnimationFrame(() => requestAnimationFrame(() => resolve())) - ) - ) + await nextFrames() await publish({ status: 'ready', version: '2.0.0' }) - await sleep(500) + await expect.poll(delivered).toBe(3) + await nextFrames() await expect(restart).toHaveCount(0) }) - await check( - 'a new release appears without stealing focus, and stale actions are withdrawn', - async () => { - const input = page.getByRole('textbox', { name: 'Work in progress' }) - await input.fill('Unsaved work') - await publish({ status: 'ready', version: '2.1.0' }) - await expect(restart).toBeVisible() - await expect(input).toBeFocused() - for (const status of ['checking', 'downloading', 'error', 'idle'] as const) { - await publish({ status, version: '2.1.0' }) - await expect(restart).toHaveCount(0) - await publish({ status: 'ready', version: '2.1.0' }) - await expect(restart).toHaveCount(1) - } - await expect(input).toHaveValue('Unsaved work') - } - ) - - await check( - 'a dismissed download offer can announce that the same release is ready', - async () => { - await publish({ status: 'available', version: '2.1.0' }) - await expect(download).toBeVisible() + await test.step('a new release appears without stealing focus, and stale actions are withdrawn', async () => { + const input = page.getByRole('textbox', { name: 'Work in progress' }) + await input.fill('Unsaved work') + await publish({ status: 'ready', version: '2.1.0' }) + await expect(restart).toBeVisible() + await expect(input).toBeFocused() + for (const status of ['checking', 'downloading', 'error', 'idle'] as const) { + await publish({ status, version: '2.1.0' }) await expect(restart).toHaveCount(0) - await notice.getByRole('button', { name: 'Dismiss notification' }).click() - await expect(download).toHaveCount(0) await publish({ status: 'ready', version: '2.1.0' }) - await expect(restart).toBeVisible() + await expect(restart).toHaveCount(1) } - ) + await expect(input).toHaveValue('Unsaved work') + }) - await check('stack eviction does not count as dismissing the update offer', async () => { + await test.step('a dismissed download offer can announce that the same release is ready', async () => { + await publish({ status: 'available', version: '2.1.0' }) + await expect(download).toBeVisible() + await expect(restart).toHaveCount(0) + await notice.getByRole('button', { name: 'Dismiss notification' }).click() + await expect(download).toHaveCount(0) + await publish({ status: 'ready', version: '2.1.0' }) + await expect(restart).toBeVisible() + }) + + await test.step('stack eviction does not count as dismissing the update offer', async () => { await publish({ status: 'checking', version: '2.4.0' }) await expect(restart).toHaveCount(0) await publish({ status: 'ready', version: '2.4.0' }) @@ -204,17 +130,12 @@ mountUpdateNotificationFixture(DesktopUpdateNotification);`, await page.getByRole('button', { name: 'Clear notifications' }).click() await expect(notice).toHaveCount(0) await publish({ status: 'checking', version: '2.4.0' }) - await page.evaluate( - () => - new Promise((resolve) => - requestAnimationFrame(() => requestAnimationFrame(() => resolve())) - ) - ) + await nextFrames() await publish({ status: 'ready', version: '2.4.0' }) await expect(restart).toBeVisible() }) - await check('actions reach the real preload IPC with the correct operation', async () => { + await test.step('actions reach the real preload IPC with the correct operation', async () => { for (const { state, action, channel } of [ { state: { status: 'ready', version: '2.4.0' }, @@ -234,7 +155,7 @@ mountUpdateNotificationFixture(DesktopUpdateNotification);`, ] satisfies { state: DesktopUpdateState; action: typeof restart; channel: string }[]) { await publish(state) await expect(action).toBeVisible() - const received = await shell.evaluateHandle(({ ipcMain }, name) => { + const received = await app.evaluateHandle(({ ipcMain }, name) => { const receipt: { url: string | null } = { url: null } ipcMain.once(name, (event) => { receipt.url = event.sender.getURL() @@ -249,14 +170,9 @@ mountUpdateNotificationFixture(DesktopUpdateNotification);`, await received.dispose() } } - expect(errors).toEqual([]) }) - passed = true + expect(errors).toEqual([]) } finally { - mkdirSync(dirname(reportPath), { recursive: true }) - writeFileSync(reportPath, JSON.stringify({ passed, checks }, null, 2)) - await app?.close() - await new Promise((resolve) => server.close(() => resolve())) - rmSync(userData, { recursive: true, force: true }) + await fixture.close() } }) diff --git a/apps/desktop/e2e/updater.spec.ts b/apps/desktop/e2e/updater.spec.ts index 65bdaabffcf..f5b7b57c7b7 100644 --- a/apps/desktop/e2e/updater.spec.ts +++ b/apps/desktop/e2e/updater.spec.ts @@ -1,68 +1,46 @@ import { createHash } from 'node:crypto' -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { createServer } from 'node:http' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { _electron as electron, expect, test } from '@playwright/test' -import { getErrorMessage } from '@sim/utils/errors' +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import type { ElectronApplication } from '@playwright/test' import { build } from 'esbuild' +import { DESKTOP_DIR, expect, serve, test } from './harness' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) - -test('the real MacUpdater waits for native staging, replaces old builds, retries failed staging, and restarts on one click', async () => { +test('the real MacUpdater waits for native staging, replaces old builds, retries failed staging, and restarts on one click', async ({ + desktop, +}) => { test.skip(process.platform !== 'darwin', 'Squirrel.Mac lifecycle') - const directory = mkdtempSync(join(tmpdir(), 'sim-updater-e2e-')) - const reportPath = - process.env.DESKTOP_UPDATER_REPORT_PATH ?? test.info().outputPath('updater.json') - let app: Awaited> | undefined + const directory = desktop.tempDir('sim-updater-e2e-') let offeredVersion = '2.0.0' - const requests: { path: string; status: number }[] = [] - const checks: { - name: string - status: 'passed' | 'failed' - durationMs: number - error?: string - }[] = [] - const check = async (name: string, run: () => Promise) => { - const started = Date.now() - try { - await run() - checks.push({ name, status: 'passed', durationMs: Date.now() - started }) - } catch (error) { - checks.push({ - name, - status: 'failed', - durationMs: Date.now() - started, - error: getErrorMessage(error), - }) - throw error - } - } - let snapshot: unknown - let completed = false - const server = createServer((request, response) => { - const path = new URL(request.url ?? '/', 'http://127.0.0.1').pathname - requests.push({ path, status: 200 }) - if (path === '/latest-mac.yml') { + const fixture = await serve((_request, response, url) => { + if (url.pathname === '/latest-mac.yml') { const archive = Buffer.from(offeredVersion) response.end( `version: ${offeredVersion}\nfiles:\n - url: Sim-${offeredVersion}-universal.zip\n sha512: ${createHash('sha512').update(archive).digest('base64')}\n size: ${archive.length}\n` ) } else { - response.end(/^\/Sim-(.+)-universal.zip$/.exec(path)?.[1] ?? '') + response.end(/^\/Sim-(.+)-universal.zip$/.exec(url.pathname)?.[1] ?? '') } }) - - try { - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - mkdirSync(join(directory, 'user-data')) + const writeVersion = (version: string) => writeFileSync( join(directory, 'package.json'), - JSON.stringify({ name: 'sim-updater-fixture', version: '1.0.0', main: 'main.cjs' }) + JSON.stringify({ name: 'sim-updater-fixture', version, main: 'main.cjs' }) ) + /** Launches the fixture main, which keeps its profile in `user-data` under the fixture dir. */ + const launch = () => + desktop.launch({ + origin: fixture.origin, + main: directory, + args: ['--use-mock-keychain'], + userData: join(directory, 'user-data'), + env: { SIM_UPDATER_FIXTURE_DIR: directory, SIM_UPDATER_FIXTURE_ORIGIN: fixture.origin }, + }) + const installResults = (app: ElectronApplication) => + app.evaluate(() => globalThis.desktopUpdaterFixture?.read().events) + + try { + mkdirSync(join(directory, 'user-data')) + writeVersion('1.0.0') await build({ entryPoints: [join(DESKTOP_DIR, 'e2e/fixtures/updater.ts')], outfile: join(directory, 'main.cjs'), @@ -90,193 +68,140 @@ test('the real MacUpdater waits for native staging, replaces old builds, retries }, ], }) - app = await electron.launch({ - args: [directory, '--use-mock-keychain'], - env: { - ...process.env, - SIM_UPDATER_FIXTURE_DIR: directory, - SIM_UPDATER_FIXTURE_ORIGIN: `http://127.0.0.1:${address.port}`, - }, - }) - const shell = app - const read = () => shell.evaluate(() => globalThis.desktopUpdaterFixture.read()) + const first = await launch() + const { app } = first + const read = () => app.evaluate(() => globalThis.desktopUpdaterFixture.read()) await expect - .poll(() => shell.evaluate(() => Boolean(globalThis.desktopUpdaterFixture))) + .poll(() => app.evaluate(() => Boolean(globalThis.desktopUpdaterFixture))) .toBe(true) - await check('first download waits for native staging', async () => { - await shell.evaluate(() => globalThis.desktopUpdaterFixture.check()) + await test.step('first download waits for native staging', async () => { + await app.evaluate(() => globalThis.desktopUpdaterFixture.check()) await expect.poll(async () => (await read()).nativeArchive).toBe('2.0.0') expect((await read()).state).toEqual({ status: 'downloading', version: '2.0.0', percent: 100, }) - await shell.evaluate(() => globalThis.desktopUpdaterFixture.install()) + await app.evaluate(() => globalThis.desktopUpdaterFixture.install()) expect((await read()).installed).toEqual([]) - await shell.evaluate(() => globalThis.desktopUpdaterFixture.finishStaging()) + await app.evaluate(() => globalThis.desktopUpdaterFixture.finishStaging()) expect((await read()).state).toEqual({ status: 'ready', version: '2.0.0' }) }) - await check('replacement cannot restart into stale native update', async () => { + await test.step('replacement cannot restart into stale native update', async () => { offeredVersion = '2.1.0' - await shell.evaluate(() => globalThis.desktopUpdaterFixture.check()) + await app.evaluate(() => globalThis.desktopUpdaterFixture.check()) await expect.poll(async () => (await read()).nativeArchive).toBe('2.1.0') expect((await read()).state).toEqual({ status: 'downloading', version: '2.1.0', percent: 100, }) - await shell.evaluate(() => globalThis.desktopUpdaterFixture.install()) + await app.evaluate(() => globalThis.desktopUpdaterFixture.install()) expect((await read()).installed).toEqual([]) - await shell.evaluate(() => globalThis.desktopUpdaterFixture.failStaging()) + await app.evaluate(() => globalThis.desktopUpdaterFixture.failStaging()) expect((await read()).state).toEqual({ status: 'error', version: '2.1.0' }) }) - await check('cached retry stages only the verified replacement', async () => { - await shell.evaluate(() => globalThis.desktopUpdaterFixture.check()) + await test.step('cached retry stages only the verified replacement', async () => { + await app.evaluate(() => globalThis.desktopUpdaterFixture.check()) await expect .poll(async () => (await read()).state) .toEqual({ status: 'downloading', version: '2.1.0', percent: 100 }) await expect.poll(async () => (await read()).nativeArchive).toBe('2.1.0') - await shell.evaluate(() => globalThis.desktopUpdaterFixture.finishStaging()) + await app.evaluate(() => globalThis.desktopUpdaterFixture.finishStaging()) expect((await read()).state).toEqual({ status: 'ready', version: '2.1.0' }) }) - await check( - 'restart asks only about real in-flight work, then installs on one click', - async () => { - /** Sets the work in progress, clicks Restart to update, and answers any prompt with `response`. */ - const installWith = async ( - work: { - terminalCommands?: string[] - browserToolRunning?: boolean - unloadListener: 'passive' | 'unsaved-edits' - hungWindow?: boolean + await test.step('restart asks only about real in-flight work, then installs on one click', async () => { + /** Sets the work in progress, clicks Restart to update, and answers any prompt with `response`. */ + const installWith = async ( + work: { + terminalCommands?: string[] + browserToolRunning?: boolean + unloadListener: 'passive' | 'unsaved-edits' + hungWindow?: boolean + }, + response: number + ) => { + await app.evaluate( + async ( + _electron, + [{ terminalCommands = [], browserToolRunning = false, ...rest }, answer] + ) => { + await globalThis.desktopUpdaterFixture.setWork({ + terminalCommands, + browserToolRunning, + ...rest, + }) + globalThis.updaterFixtureDialogResponse = answer + globalThis.desktopUpdaterFixture.install() }, - response: number - ) => { - await shell.evaluate( - async ( - _electron, - [{ terminalCommands = [], browserToolRunning = false, ...rest }, answer] - ) => { - await globalThis.desktopUpdaterFixture.setWork({ - terminalCommands, - browserToolRunning, - ...rest, - }) - globalThis.updaterFixtureDialogResponse = answer - globalThis.desktopUpdaterFixture.install() - }, - [work, response] as const - ) - } - const expectNotNowPrompt = async (count: number, message: string) => { - await expect.poll(async () => (await read()).dialogs.length).toBe(count) - expect((await read()).dialogs.at(-1)).toEqual({ - title: 'Restart to install Sim 2.1.0?', - message, - buttons: ['Restart and Update', 'Not Now'], - defaultId: 0, - cancelId: 1, - }) - // The decline settles asynchronously; nothing may install, and the update stays ready. - await expect - .poll(async () => (await read()).state) - .toEqual({ status: 'ready', version: '2.1.0' }) - expect((await read()).installed).toEqual([]) - } - - await installWith( - { terminalCommands: ['cd /repo && claude "fix the build"'], unloadListener: 'passive' }, - 1 + [work, response] as const ) - await expectNotNowPrompt(1, 'claude is still running in a terminal.') + } + const expectNotNowPrompt = async (count: number, message: string) => { + await expect.poll(async () => (await read()).dialogs.length).toBe(count) + expect((await read()).dialogs.at(-1)).toEqual({ + title: 'Restart to install Sim 2.1.0?', + message, + buttons: ['Restart and Update', 'Not Now'], + defaultId: 0, + cancelId: 1, + }) + // The decline settles asynchronously; nothing may install, and the update stays ready. + await expect + .poll(async () => (await read()).state) + .toEqual({ status: 'ready', version: '2.1.0' }) + expect((await read()).installed).toEqual([]) + } - await installWith({ unloadListener: 'unsaved-edits' }, 1) - await expectNotNowPrompt(2, 'A window has unsaved changes.') + await installWith( + { terminalCommands: ['cd /repo && claude "fix the build"'], unloadListener: 'passive' }, + 1 + ) + await expectNotNowPrompt(1, 'claude is still running in a terminal.') - await installWith( - { browserToolRunning: true, unloadListener: 'passive', hungWindow: true }, - 1 - ) - await expectNotNowPrompt( - 3, - "An agent is using the browser. A window isn't responding and may have unsaved changes." - ) + await installWith({ unloadListener: 'unsaved-edits' }, 1) + await expectNotNowPrompt(2, 'A window has unsaved changes.') - // Answering Not Now again would leave nothing installed if a prompt appeared. - await installWith({ unloadListener: 'passive' }, 1) - await expect.poll(async () => (await read()).installed).toEqual(['2.1.0']) - expect((await read()).dialogs).toHaveLength(3) - } - ) - snapshot = await read() - await check( - 'the next process distinguishes an incomplete update from a successful install', - async () => { - const checkpoint = readFileSync(join(directory, 'update-install.json'), 'utf8') - await app?.close() - app = await electron.launch({ - args: [directory, '--use-mock-keychain'], - env: { - ...process.env, - SIM_UPDATER_FIXTURE_DIR: directory, - SIM_UPDATER_FIXTURE_ORIGIN: `http://127.0.0.1:${address.port}`, - }, + await installWith( + { browserToolRunning: true, unloadListener: 'passive', hungWindow: true }, + 1 + ) + await expectNotNowPrompt( + 3, + "An agent is using the browser. A window isn't responding and may have unsaved changes." + ) + + // Answering Not Now again would leave nothing installed if a prompt appeared. + await installWith({ unloadListener: 'passive' }, 1) + await expect.poll(async () => (await read()).installed).toEqual(['2.1.0']) + expect((await read()).dialogs).toHaveLength(3) + }) + await test.step('the next process distinguishes an incomplete update from a successful install', async () => { + const checkpoint = readFileSync(join(directory, 'update-install.json'), 'utf8') + await desktop.close(first) + const stale = await launch() + await expect + .poll(() => installResults(stale.app)) + .toContainEqual({ + name: 'update_install_result', + data: { expected: '2.1.0', installed: '1.0.0', success: false }, }) - await expect - .poll(() => app?.evaluate(() => globalThis.desktopUpdaterFixture?.read().events)) - .toContainEqual({ - name: 'update_install_result', - data: { expected: '2.1.0', installed: '1.0.0', success: false }, - }) - await app.close() - writeFileSync(join(directory, 'update-install.json'), checkpoint) - writeFileSync( - join(directory, 'package.json'), - JSON.stringify({ name: 'sim-updater-fixture', version: '2.1.0', main: 'main.cjs' }) - ) - app = await electron.launch({ - args: [directory, '--use-mock-keychain'], - env: { - ...process.env, - SIM_UPDATER_FIXTURE_DIR: directory, - SIM_UPDATER_FIXTURE_ORIGIN: `http://127.0.0.1:${address.port}`, - }, + await desktop.close(stale) + writeFileSync(join(directory, 'update-install.json'), checkpoint) + writeVersion('2.1.0') + const updated = await launch() + await expect + .poll(() => installResults(updated.app)) + .toContainEqual({ + name: 'update_install_result', + data: { expected: '2.1.0', installed: '2.1.0', success: true }, }) - await expect - .poll(() => app?.evaluate(() => globalThis.desktopUpdaterFixture?.read().events)) - .toContainEqual({ - name: 'update_install_result', - data: { expected: '2.1.0', installed: '2.1.0', success: true }, - }) - } - ) - completed = true + }) } finally { - if (!snapshot && app) - snapshot = await app - .evaluate(() => globalThis.desktopUpdaterFixture?.read()) - .catch(() => undefined) - mkdirSync(dirname(reportPath), { recursive: true }) - writeFileSync( - reportPath, - JSON.stringify( - { - passed: completed && checks.every((check) => check.status === 'passed'), - checks, - requests, - snapshot, - }, - null, - 2 - ) - ) - await app?.close() - server.closeAllConnections() - await new Promise((resolve) => server.close(() => resolve())) - rmSync(directory, { recursive: true, force: true }) + await fixture.close() } }) diff --git a/apps/desktop/playwright.config.ts b/apps/desktop/playwright.config.ts index 00181f3924d..63372eea169 100644 --- a/apps/desktop/playwright.config.ts +++ b/apps/desktop/playwright.config.ts @@ -4,5 +4,6 @@ export default defineConfig({ testDir: './e2e', timeout: 90_000, workers: 1, + forbidOnly: Boolean(process.env.CI), reporter: process.env.CI ? [['github'], ['list']] : [['list']], }) diff --git a/apps/desktop/src/main/browser-agent/driver.test.ts b/apps/desktop/src/main/browser-agent/driver.test.ts index c729da5ebbd..97de871c4b6 100644 --- a/apps/desktop/src/main/browser-agent/driver.test.ts +++ b/apps/desktop/src/main/browser-agent/driver.test.ts @@ -1020,6 +1020,115 @@ describe('executeTool', () => { } ) + describe('a tab still loading its first page', () => { + const openLoadingTab = async () => { + await driver.executeTool('chat-test', 'browser_open_tab', {}) + const contents = session.requireTab().view.webContents + vi.mocked(contents.getURL).mockReturnValue('') + vi.mocked(contents.isLoading).mockReturnValue(true) + const listeners = (event: string) => + vi + .mocked(contents.on) + .mock.calls.filter(([name]) => String(name) === event) + .map(([, listener]) => listener as (...args: unknown[]) => void) + const registered = listeners('did-stop-loading').length + const waiting = () => + vi.waitFor(() => expect(listeners('did-stop-loading').length).toBeGreaterThan(registered)) + return { contents, listeners, registered, waiting } + } + + it('snapshots the page once it commits instead of calling the tab blank', async () => { + const { contents, listeners, registered, waiting } = await openLoadingTab() + vi.mocked(contents.executeJavaScript).mockResolvedValue({ + url: 'http://127.0.0.1/popup', + title: 'popup', + outline: '- link "Open popup" [ref=0]', + truncated: false, + refIds: [0], + refLineIndexes: { 0: 0 }, + nextElementId: 1, + }) + + const snapshot = driver.executeTool('chat-test', 'browser_snapshot', {}) + await waiting() + expect(contents.executeJavaScript).not.toHaveBeenCalled() + + vi.mocked(contents.getURL).mockReturnValue('http://127.0.0.1/popup') + vi.mocked(contents.isLoading).mockReturnValue(false) + for (const onNavigate of listeners('did-navigate')) onNavigate({}, 'http://127.0.0.1/popup') + for (const onLoaded of listeners('did-stop-loading').slice(registered)) onLoaded() + + await expect(snapshot).resolves.toMatchObject({ + ok: true, + result: { outline: expect.stringContaining('Open popup') }, + }) + }) + + it('never acts on the page when the action is cancelled during the wait', async () => { + const { contents, listeners, registered, waiting } = await openLoadingTab() + + const scroll = driver.executeTool( + 'chat-test', + 'browser_scroll', + { direction: 'down' }, + 'scroll-into-loading-popup' + ) + await waiting() + expect(driver.cancelTool('chat-test', 'scroll-into-loading-popup')).toBe(true) + await expect(scroll).resolves.toMatchObject({ + ok: false, + error: expect.stringContaining('cancelled'), + }) + + // The page commits after the cancel; a wait that ignored the cancel would act on it now. + vi.mocked(contents.getURL).mockReturnValue('http://127.0.0.1/popup') + vi.mocked(contents.isLoading).mockReturnValue(false) + for (const onLoaded of listeners('did-stop-loading').slice(registered)) onLoaded() + await driver.executeTool('chat-test', 'browser_list_tabs', {}) + expect(contents.executeJavaScript).not.toHaveBeenCalled() + expect(contents.debugger.sendCommand).not.toHaveBeenCalledWith( + 'Input.dispatchMouseEvent', + expect.anything() + ) + }) + + it('refuses a page that outlasts the bounded wait, and never acts on it once it loads', async () => { + const { contents, listeners, registered } = await openLoadingTab() + const watchdogMs = driver.browserToolWatchdogMs('browser_scroll', { direction: 'down' }) + const navigationTimeoutMs = 25_000 + const waitMs = + watchdogMs === null + ? navigationTimeoutMs + : Math.min(navigationTimeoutMs, Math.floor(watchdogMs / 2)) + vi.useFakeTimers() + try { + let outcome: unknown + void driver + .executeTool('chat-test', 'browser_scroll', { direction: 'down' }, 'scroll-slow-popup') + .then((result) => { + outcome = result + }) + await vi.advanceTimersByTimeAsync(0) + expect(listeners('did-stop-loading').length).toBeGreaterThan(registered) + + await vi.advanceTimersByTimeAsync(waitMs + 1) + expect(outcome).toEqual({ + ok: false, + error: + 'The active tab is blank. Call browser_navigate before using page inspection or interaction tools.', + }) + + vi.mocked(contents.getURL).mockReturnValue('http://127.0.0.1/popup') + vi.mocked(contents.isLoading).mockReturnValue(false) + for (const onLoaded of listeners('did-stop-loading').slice(registered)) onLoaded() + await vi.advanceTimersByTimeAsync(0) + expect(contents.executeJavaScript).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) + }) + it('leaves no watchdog timer pending once a tool finishes', async () => { vi.useFakeTimers() try { diff --git a/apps/desktop/src/main/browser-agent/driver.ts b/apps/desktop/src/main/browser-agent/driver.ts index 5a35e1d789e..e85ad6c3059 100644 --- a/apps/desktop/src/main/browser-agent/driver.ts +++ b/apps/desktop/src/main/browser-agent/driver.ts @@ -1633,11 +1633,16 @@ function unwrapPageResult(result: unknown): unknown { return result } -function waitForLoadComplete(contents: WebContents, timeoutMs: number): Promise { +function waitForLoadComplete( + contents: WebContents, + timeoutMs: number, + signal?: AbortSignal +): Promise { return new Promise((resolve, reject) => { let settled = false let sawStart = contents.isLoading() const cleanup = () => { + signal?.removeEventListener('abort', finish) contents.removeListener('did-start-loading', start) contents.removeListener('did-stop-loading', finish) contents.removeListener('did-fail-load', fail) @@ -1688,9 +1693,60 @@ function waitForLoadComplete(contents: WebContents, timeoutMs: number): Promise< contents.on('did-stop-loading', finish) contents.on('did-fail-load', fail) contents.on('destroyed', destroyed) + signal?.addEventListener('abort', finish) }) } +/** Tools that read or act in the page itself, which a tab with no page yet cannot serve. */ +const BROWSER_TOOL_USES_PAGE = { + browser_navigate: false, + browser_open_url: false, + browser_go_back: false, + browser_go_forward: false, + browser_reload: false, + browser_open_tab: false, + browser_switch_tab: false, + browser_close_tab: false, + browser_list_tabs: false, + browser_list_sessions: false, + browser_list_downloads: false, + browser_save_download: false, + browser_wait_for: true, + browser_snapshot: true, + browser_find: true, + browser_read_text: true, + browser_screenshot: true, + browser_extract: true, + browser_click: true, + browser_click_at: true, + browser_type: true, + browser_fill_form: true, + browser_batch: true, + browser_insert_text: true, + browser_press_key: true, + browser_scroll: true, + browser_select_option: true, + browser_set_checked: true, + browser_upload_file: true, + browser_hover: true, + browser_drag: true, + browser_zoom: false, + browser_request_takeover: false, +} as const satisfies Readonly> + +/** + * A tab a link or popup just opened reports no URL until its first page commits, so a page tool + * reaching it first would refuse it as blank. Returns the wait for that first load, run before the + * action records any page state, or null when the agent's tab already has a page. + */ +function firstPageLoad(signal: AbortSignal, maxWaitMs: number): Promise | null { + const contents = session.automationTab()?.view.webContents + if (!contents || contents.isDestroyed() || !contents.isLoading()) return null + const url = contents.getURL() + if (url !== '' && url !== 'about:blank') return null + return waitForLoadComplete(contents, maxWaitMs, signal) +} + async function navigationResult( contents: WebContents, completion = waitForLoadComplete(contents, NAVIGATION_TIMEOUT_MS) @@ -5454,6 +5510,22 @@ export async function executeTool( : Math.min(USER_TAKEOVER_MAX_WAIT_MS, Math.floor(watchdogMs / 2)) ) } + const firstPage = BROWSER_TOOL_USES_PAGE[tool] + ? firstPageLoad( + executionController.signal, + watchdogMs === null + ? NAVIGATION_TIMEOUT_MS + : Math.min(NAVIGATION_TIMEOUT_MS, Math.floor(watchdogMs / 2)) + ) + : null + if (firstPage) { + // Raced with the cancellation so its rejection is observed; a cancel aborts the wait + // before it rejects, which is why the abort is checked again afterwards. + await Promise.race([firstPage, cancellation]) + if (executionController.signal.aborted) { + throw new ToolError('This browser action was cancelled.') + } + } const response = dialogResponse(tool, params) state.dialogResponse = response ? { contents: session.requireAutomationTab().view.webContents, response } diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts index cd074cbe5ee..eb9e22470fb 100644 --- a/apps/desktop/src/main/index.ts +++ b/apps/desktop/src/main/index.ts @@ -118,7 +118,11 @@ import { createRunLedger } from '@/main/terminal/run-ledger' import { installTray, type TrayHandle } from '@/main/tray' import { checkForUpdatesInteractive, initUpdater, type UpdaterHandle } from '@/main/updater' import { installBrowserUserAgent } from '@/main/user-agent' -import { createMainWindow, setupPermissionHandlers } from '@/main/window' +import { + createMainWindow, + guardVisibilityListenersAfterDestroy, + setupPermissionHandlers, +} from '@/main/window' import { attachWindowOpenPolicy, isPopupContents, type WindowPolicyDeps } from '@/main/windows' const logger = createLogger('DesktopMain') @@ -318,6 +322,7 @@ function main(): void { return getWindows().at(-1) ?? null } installMainProcessFailureObservers({ events, getWindow: getMainWindow }) + app.on('browser-window-created', (_event, win) => guardVisibilityListenersAfterDestroy(win)) const windowForContents = (contents: WebContents) => { const win = BrowserWindow.fromWebContents(contents) return win && windows.has(win) && !win.isDestroyed() ? win : null diff --git a/apps/desktop/src/main/observability.test.ts b/apps/desktop/src/main/observability.test.ts index 82fbfce631b..adf6771443d 100644 --- a/apps/desktop/src/main/observability.test.ts +++ b/apps/desktop/src/main/observability.test.ts @@ -94,4 +94,70 @@ describe('installMainProcessFailureObservers', () => { await vi.waitFor(() => expect(app.relaunch).toHaveBeenCalledOnce()) expect(app.exit).toHaveBeenCalledWith(1) }) + + function emitAppEvent(event: string) { + const handler = vi.mocked(app.on).mock.calls.find(([name]) => name === event)?.[1] + if (!handler) throw new Error(`No ${event} listener`) + ;(handler as () => void)() + } + + async function settlePrompt() { + for (let turn = 0; turn < 5; turn++) await Promise.resolve() + } + + it('exits without prompting when the failure arrives once the quit is committed', () => { + const events = { filePath: '/tmp/events.log', record: vi.fn() } + const { handlers, source } = createProcessSource() + installMainProcessFailureObservers({ events, getWindow: () => null, processSource: source }) + + emitAppEvent('before-quit') + emitAppEvent('will-quit') + handlers.get('uncaughtException')?.(new Error('during shutdown') as never) + + expect(events.record).toHaveBeenCalledWith('main_uncaught_exception', { valueType: 'Error' }) + expect(dialog.showMessageBox).not.toHaveBeenCalled() + expect(app.relaunch).not.toHaveBeenCalled() + expect(app.exit).toHaveBeenCalledWith(1) + }) + + it('still offers recovery after a quit request another listener cancelled', () => { + vi.mocked(dialog.showMessageBox).mockImplementationOnce(() => new Promise(() => {})) + const events = { filePath: '/tmp/events.log', record: vi.fn() } + const { handlers, source } = createProcessSource() + installMainProcessFailureObservers({ events, getWindow: () => null, processSource: source }) + + emitAppEvent('before-quit') + handlers.get('uncaughtException')?.(new Error('after a cancelled quit') as never) + + expect(dialog.showMessageBox).toHaveBeenCalledOnce() + const [options] = vi.mocked(dialog.showMessageBox).mock.calls[0] as unknown as [ + { signal?: AbortSignal }, + ] + expect(options.signal?.aborted).toBe(false) + expect(app.exit).not.toHaveBeenCalled() + }) + + it('answers an open recovery prompt as Quit when a quit is requested', async () => { + vi.mocked(dialog.showMessageBox).mockImplementationOnce( + (options: { cancelId?: number; signal?: AbortSignal }) => + new Promise((resolve) => { + options.signal?.addEventListener('abort', () => + resolve({ response: options.cancelId ?? 0, checkboxChecked: false }) + ) + }) + ) + const events = { filePath: '/tmp/events.log', record: vi.fn() } + const { handlers, source } = createProcessSource() + installMainProcessFailureObservers({ events, getWindow: () => null, processSource: source }) + + handlers.get('uncaughtException')?.(new Error('while running') as never) + expect(dialog.showMessageBox).toHaveBeenCalledOnce() + expect(app.exit).not.toHaveBeenCalled() + + emitAppEvent('before-quit') + await settlePrompt() + + expect(app.exit).toHaveBeenCalledWith(1) + expect(app.relaunch).not.toHaveBeenCalled() + }) }) diff --git a/apps/desktop/src/main/observability.ts b/apps/desktop/src/main/observability.ts index 132eb026bdf..3a60b566f48 100644 --- a/apps/desktop/src/main/observability.ts +++ b/apps/desktop/src/main/observability.ts @@ -79,6 +79,12 @@ const FAILURE_DEDUPE_MS = 5_000 * single native recovery surface. Error text is deliberately excluded from * the structured log because rejected values can contain request payloads or * credentials; the event kind and crash dumps are enough for triage. + * + * The recovery prompt never outlives a quit: a failure once a quit is committed + * (`will-quit`) exits without asking, since a dialog opened during shutdown can + * only fall back to a blocking native alert, and any quit request while the + * prompt is open answers it as Quit. A `before-quit` that another listener + * cancels leaves later failures their prompt. */ export function installMainProcessFailureObservers({ events, @@ -86,6 +92,8 @@ export function installMainProcessFailureObservers({ processSource = process, }: MainProcessFailureObserverDeps): void { let fatalRecoveryOpen = false + let quitCommitted = false + let openPrompt: AbortController | null = null let lastChildFailure = '' let lastChildFailureAt = 0 @@ -117,6 +125,12 @@ export function installMainProcessFailureObservers({ fatalRecoveryOpen = true events.record(name, { valueType: value instanceof Error ? 'Error' : typeof value }) logger.error('Fatal main-process failure', { kind: name }) + if (quitCommitted) { + app.exit(1) + return + } + const promptAbort = new AbortController() + openPrompt = promptAbort const options = { type: 'error' as const, buttons: ['Restart Sim', 'Quit Sim'], @@ -124,6 +138,7 @@ export function installMainProcessFailureObservers({ cancelId: 1, message: 'Sim encountered a problem', detail: 'Restart Sim to recover. Diagnostic details were saved locally.', + signal: promptAbort.signal, } const win = getWindow() const prompt = @@ -145,7 +160,17 @@ export function installMainProcessFailureObservers({ reportFatal('main_uncaught_exception', error) } + const answerOpenPromptAsQuit = (): void => { + openPrompt?.abort() + } + const onWillQuit = (): void => { + quitCommitted = true + answerOpenPromptAsQuit() + } + app.on('child-process-gone', onChildProcessGone) + app.on('before-quit', answerOpenPromptAsQuit) + app.on('will-quit', onWillQuit) processSource.on('unhandledRejection', onUnhandledRejection) processSource.on('uncaughtException', onUncaughtException) } diff --git a/apps/desktop/src/main/window.test.ts b/apps/desktop/src/main/window.test.ts index f8c2ca1bd02..9472fef0ba5 100644 --- a/apps/desktop/src/main/window.test.ts +++ b/apps/desktop/src/main/window.test.ts @@ -1,3 +1,4 @@ +import { EventEmitter } from 'node:events' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createSecureWebPreferences } from '@/main/window-preferences' @@ -7,7 +8,12 @@ import { BrowserWindow, dialog, screen, systemPreferences, WebContentsView } fro import { registerAgentWebContents } from '@/main/browser-agent/registry' import type { ConfigStore } from '@/main/config' import type { EventRecorder } from '@/main/observability' -import { createMainWindow, resolvePermission, setupPermissionHandlers } from '@/main/window' +import { + createMainWindow, + guardVisibilityListenersAfterDestroy, + resolvePermission, + setupPermissionHandlers, +} from '@/main/window' const APP = 'https://sim.ai' @@ -195,3 +201,47 @@ describe('createMainWindow', () => { expect(event.preventDefault).toHaveBeenCalledOnce() }) }) + +describe('guardVisibilityListenersAfterDestroy', () => { + /** A window wired the way Electron wires every BrowserWindow: its visibility listener reads the native window. */ + function electronLikeWindow() { + let destroyed = false + const visibilityChecks = vi.fn() + const win = Object.assign(new EventEmitter(), { + isDestroyed: () => destroyed, + isVisible: () => { + if (destroyed) throw new TypeError('Object has been destroyed') + visibilityChecks() + return true + }, + destroy: () => { + destroyed = true + }, + }) + const visibilityChanged = () => win.isVisible() + for (const event of ['show', 'hide', 'minimize', 'maximize', 'restore']) { + win.on(event, visibilityChanged) + } + return { win, visibilityChecks } + } + + it('keeps tracking visibility while the window lives', () => { + const { win, visibilityChecks } = electronLikeWindow() + guardVisibilityListenersAfterDestroy(win as never) + + win.emit('show') + win.emit('minimize') + + expect(visibilityChecks).toHaveBeenCalledTimes(2) + }) + + it('a visibility event delivered after the window was destroyed no longer throws', () => { + const { win } = electronLikeWindow() + guardVisibilityListenersAfterDestroy(win as never) + + win.destroy() + + expect(() => win.emit('show')).not.toThrow() + expect(() => win.emit('hide')).not.toThrow() + }) +}) diff --git a/apps/desktop/src/main/window.ts b/apps/desktop/src/main/window.ts index 095385970f8..9e2b7ae713c 100644 --- a/apps/desktop/src/main/window.ts +++ b/apps/desktop/src/main/window.ts @@ -19,6 +19,29 @@ const MIN_HEIGHT = 600 const WINDOW_TITLE = 'Sim' const BOUNDS_SAVE_DELAY_MS = 400 const ROUTE_SAVE_DELAY_MS = 500 +/** The events Electron's own per-window `visibilityChanged` listener subscribes to. */ +const VISIBILITY_EVENTS = ['show', 'hide', 'minimize', 'maximize', 'restore'] as const + +/** + * Makes Electron's own per-window visibility listener skip a destroyed window. + * macOS can deliver a window's `show` (an occlusion change) after the window + * has been destroyed, as when the app quits just as its first window appears; + * that listener then reads `isVisible()` from the dead window and throws + * "Object has been destroyed" as an uncaught main-process exception during + * shutdown. Call it from `browser-window-created`, which Electron emits right + * after subscribing that listener, so it is the only one on these events. + */ +export function guardVisibilityListenersAfterDestroy(win: BrowserWindow): void { + const emitter: NodeJS.EventEmitter = win + for (const event of VISIBILITY_EVENTS) { + for (const listener of emitter.listeners(event) as ((...args: unknown[]) => void)[]) { + emitter.removeListener(event, listener) + emitter.on(event, (...args: unknown[]) => { + if (!win.isDestroyed()) listener.apply(win, args) + }) + } + } +} /** * The permission matrix: sanitized clipboard writes and microphone access for diff --git a/apps/docs/content/docs/cli/blocks.mdx b/apps/docs/content/docs/cli/blocks.mdx index 95b796011c2..098245dcfac 100644 --- a/apps/docs/content/docs/cli/blocks.mdx +++ b/apps/docs/content/docs/cli/blocks.mdx @@ -61,7 +61,8 @@ Reading it for `sim workflows operations apply`: inputDefinitions the block's inputs by name; one a pair of fields shares (tableId for tableSelector and manualTableId) is accepted in place of the pair outputs what it outputs on success; a failed block outputs {"error":"…"} - instead, read on its error path as + instead, read on its error path as (a Function also + outputs , the thrown message without line or code) Block settings such as retry are not fields: `sim workflows operations apply --help`. ``` diff --git a/apps/docs/content/docs/cli/index.mdx b/apps/docs/content/docs/cli/index.mdx index cccca7766cb..d44f4e9b9ee 100644 --- a/apps/docs/content/docs/cli/index.mdx +++ b/apps/docs/content/docs/cli/index.mdx @@ -7,7 +7,7 @@ Use `sim` to run workflows, query tables, move files, search knowledge bases, an ## Install -The installed CLI requires Node.js 20 or newer. Install it globally with Bun, then check the version: +The installed CLI requires Node.js 22.18 or newer on the 22 line, or 24.11 or newer. Install it globally with Bun, then check the version: ```bash bun add -g sim @@ -140,7 +140,7 @@ sim tables rows query --help | [`workflow-mcp-servers`](/cli/workflow-mcp-servers) | Expose deployed workflows as MCP tools | | [`meta`](/cli/meta) | Inspect API availability and credential status | -To edit a workflow as a TypeScript file, or a whole workspace as a directory, use `sim workflows source` and `sim workspaces source` (in preview). See [Workflows as code](/workflows/code) and [Workspace as code](/workflows/workspace-code). +To edit a workflow as a TypeScript file, or a whole workspace as a directory, use `sim workflows source` and `sim workspaces source` (in preview). See [Workflows as code](/workflows/code) and [Manage a workspace as code](/workflows/code/workspace). The [command overview](/cli/commands) lists global options and root commands. The [complete reference](/cli/reference) contains every subcommand, argument, and option on one page. Both are generated from the CLI. @@ -177,7 +177,7 @@ The repository is also a native Claude Code and Codex plugin, which exposes the The skills assume `sim` is installed and signed in, so complete [Your first command](#your-first-command) first. They never store or print API keys. These agent skills are separate from the workspace skills you manage with [`sim skills`](/cli/skills). -To have a coding agent edit workflow files directly, see [Workflows as code for coding agents](/workflows/code#for-coding-agents). +To have a coding agent edit workflow files directly, see [Use workflows as code with coding agents](/workflows/code/coding-agents). ## Related docs diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index da82b822c5d..9d740bd6ba2 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -434,7 +434,8 @@ Reading it for `sim workflows operations apply`: inputDefinitions the block's inputs by name; one a pair of fields shares (tableId for tableSelector and manualTableId) is accepted in place of the pair outputs what it outputs on success; a failed block outputs {"error":"…"} - instead, read on its error path as + instead, read on its error path as (a Function also + outputs , the thrown message without line or code) Block settings such as retry are not fields: `sim workflows operations apply --help`. ``` @@ -5890,7 +5891,7 @@ sim tables columns create [options] | Option | Required | Description | | --- | --- | --- | -| `--column ` | Yes | Column definition to add. (JSON, or @path / @- to read a file or stdin). | +| `--column ` | Yes | Column definition to add: {"name":"status","type":"string"}. Column fields: id - Optional client-provided column identifier; name (required) - Column name; type (required) - Column data type; required - Whether inserts must supply a value for this column; unique - Whether values in the column must be unique; options - Select options for select-type columns, as [{"id":"open","name":"Open"}]; multiple - Whether a select column accepts multiple values; currencyCode - ISO 4217 code for currency columns; position - Zero-based insertion position for the column. A column's type is one of string, number, currency, boolean, date, json, select; a select column also takes options. (JSON, or @path / @- to read a file or stdin). | @@ -6796,7 +6797,7 @@ sim tables create [options] | --- | --- | --- | | `--name ` | Yes | Identifier: letters, numbers, and underscores; cannot start with a number. | | `--description ` | No | Optional table description. | -| `--schema ` | Yes | Table schema: {"columns":[{"name":"email","type":"string"}]} (JSON, or @path / @- to read a file or stdin). | +| `--schema ` | Yes | Initial table column definitions: {"columns":[{"name":"email","type":"string","required":true,"unique":true}]}. Column fields: id - Optional client-provided column identifier; name (required) - Column name; type (required) - Column data type; required - Whether inserts must supply a value for this column; unique - Whether values in the column must be unique; options - Select options for select-type columns, as [{"id":"open","name":"Open"}]; multiple - Whether a select column accepts multiple values; currencyCode - ISO 4217 code for currency columns. A column's type is one of string, number, currency, boolean, date, json, select; a select column also takes options. (JSON, or @path / @- to read a file or stdin). | | `--folder ` | No | Folder path as shown in the app; the leading / is optional. | @@ -7772,7 +7773,11 @@ Edges: connections maps a source handle to its targets: {"source":""}, {"source":["",""]}, or {"source":{"block":"","handle":""}}; "success" is an alias of "source". An add's connections create the new block's edges. An edit's connections REPLACE every - outgoing edge of that block, on every handle: list again each edge to keep. + outgoing edge of that block, on every handle: list again each edge to keep; {} removes them all. + Moving a block into or out of a loop or parallel (parentId) removes each of its existing edges + that would cross the container's boundary, atomic or not, and names them in warnings. Edges the + batch itself asks for across a boundary are refused. Wire into the body from loop-start-source + and onward from loop-end-source (parallel-start-source, parallel-end-source). To remove one edge, edit its source block with {"removeEdges":[{"targetBlockId":"","sourceHandle":"source"}]} (sourceHandle defaults to "source"). @@ -7785,12 +7790,14 @@ Source handles: parallel-start-source, parallel-end-source the same for a parallel Renames: An edit's {"name":"New name"} also rewrites every reference to the block, in - other blocks' inputs and in a loop's or parallel's collection and condition. + other blocks' inputs and in a loop's or parallel's collection and condition. Edits run after the + batch's adds, so a block added in the same batch is rewritten too. Inputs: inputs takes the field ids `sim blocks get ` lists (inputSchema, operationInputSchema), or the name a pair of them shares (inputDefinitions: tableId for tableSelector and manualTableId; a string goes to the typed field). Add the type it answers with: `blocks get - table` answers table_v2, and an add of legacy table is refused. + table` answers table_v2, and an add of legacy table is refused. An edit's inputs replace each + field they name whole (a responseFormat schema too) and keep the fields they do not name. conditions (condition): [{"title":"if","value":" > 3"},{"title":"else if","value":"…"}, {"title":"else","value":""}]; the last entry is the else. Each entry's id comes from its position (-if, -else-if-0, …, -else): an id you pass is replaced. @@ -7799,12 +7806,28 @@ Inputs: Block settings, beside inputs in an add's or edit's params: "retry":{"enabled":true,"maxTries":3,"waitBetweenTriesMs":1000} retries a failed block; null clears it. An api block's retries input repeats the request after a timeout, reset, 429 or - 5xx, not when the host does not resolve or refuses the connection; "retry" covers that. + 5xx, not when the host does not resolve or refuses the connection; "retry" covers that. They + nest: every try of "retry" runs the request with its retries. Outputs: A block that fails outputs {"error":""}: connect its error handle and read - there (without one, the run fails). A Workflow block's result is the child's + there (without one, the run fails). A Function's error leads with the line and + code that threw; its is the thrown message alone, the one to reply with. + A Workflow block's result is the child's output; a child ending in a Response block gives {data, status, headers}, so read - . + . A Table block's row holds its cells under data: read a cell as + (). +References: + Inside a loop or parallel body read and , or + and ; after it, . A reference to a block + that did not run (a branch not taken) is null as a whole value, in a condition or in a + Function's code, and '' inside text. +Order: + Operations run in phases whatever their order in the batch: deletes first, then + extract_from_subflow, adds, insert_into_subflow and edits; operations of one type keep the + order given, except insert_into_subflow, which runs a parent before its children. A delete plus an add with the same name therefore replaces the block in one batch. +Run logs: + `sim logs list --workflow ` lists a workflow's runs; `sim logs get --trace + --no-include-workflow-state` shows each block's resolved inputs, outputs and errors. ``` API request and response schemas: [applyWorkflowOperations](/api-reference/workflows/applyWorkflowOperations). @@ -8495,8 +8518,8 @@ sim workflows run [options] | `--manual` | No | Run the current saved workflow state instead of the active deployment. | | `--trigger ` | No | Enter the run through this runnable trigger, by its block id; runs the current saved workflow state (implies --manual). | | `--mock-payload` | No | Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual). | -| `--from-block ` | No | Run manually from this saved workflow block: its id, display name or key. | -| `--source-run ` | No | Prior run whose persisted state supplies upstream outputs (requires --from-block). | +| `--from-block ` | No | Rerun the saved draft from this block (its id, display name or key), reusing the outputs --source-run produced before it; a failed run prints this command as next. | +| `--source-run ` | No | Earlier run of this workflow, deployed or draft, whose outputs the blocks before --from-block keep (requires --from-block). | | `--stop-after ` | No | Stop the run after this saved block (its id, display name or key), failing it if the run takes a path that skips the block; with --from-block on the same block, re-runs only that block (implies --manual). Unless --select-output names others, blockOutputs holds the output of that block under its key (or id); output stays empty. | | `--dir ` | No | This workflow's source directory: a failed run names the source file and line of the block that failed, read through its .sim/lock.json. Not with --async or --follow, and not for a run --wait-timeout leaves running. | | `--wait-timeout ` | No | Wait at most this many seconds for a synchronous run (0 waits until it settles). A run still going then continues in the background under async limits: the command prints its run record and exits 4, and `sim workflows runs wait` keeps waiting. Not with --async or --follow. | @@ -8510,6 +8533,8 @@ Without --manual (or a flag that implies it) this runs the active deployment; a The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. +A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix only that block and those after it run again. Add --stop-after <block> to stop after a block; naming the block next starts from reruns only it. + Exit codes: 0 completed or paused (--async: queued); 1 failed or cancelled (the result is printed first, then the error on stderr), or the command failed; 4 still running when --wait-timeout elapsed. API request and response schemas: [executeWorkflow](/api-reference/workflows/executeWorkflowV2). @@ -8541,12 +8566,12 @@ sim workflows export [options] | Option | Required | Description | | --- | --- | --- | | `--include-references` | No | Include non-secret resource identities for mapped import. | -| `--include-workspace-bindings` | No | Keep non-secret table, knowledge base, document, folder, channel, and other workspace bindings for a same-workspace import. Defaults to false, which clears these IDs. Registered credential fields and opaque table/tool values are cleared either way; environment references and ordinary workflow variables remain included. | +| `--include-workspace-bindings` | No | Keep table, knowledge base, document, folder, channel and other workspace bindings. On by default; --no-include-workspace-bindings clears them for a copy to share outside this workspace. Credentials are cleared either way. | | `--no-include-workspace-bindings` | No | Send --include-workspace-bindings as false. | -Workspace bindings (a table, a child workflow, a knowledge base) print as null unless --include-workspace-bindings, and credentials always do: to read what a block is set to, use `sim workflows state get`. +A table, child workflow, knowledge base or other workspace binding prints as its id; a credential always prints as null. For a copy to share outside this workspace, pass --no-include-workspace-bindings to clear the bindings too. API request and response schemas: [exportWorkflow](/api-reference/workflows/exportWorkflow). @@ -8628,7 +8653,7 @@ sim workflows source apply [workflowId] [options] | Argument | Required | Description | | --- | --- | --- | -| `workflowId` | No | Workflow whose draft the source replaces (default: the workflowId in .sim/base.json) | +| `workflowId` | No | Refuse unless .sim/base.json names this workflow (default: the workflowId there) | @@ -8639,6 +8664,7 @@ sim workflows source apply [workflowId] [options] | Option | Required | Description | | --- | --- | --- | | `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | +| `--summary-file ` | No | Also write the plan as Markdown to this file (or set SIM_SUMMARY_FILE), replacing it each run; its first line is a comment that names the directory, for a CI step that updates one pull-request comment. | | `--dir ` | No | Source directory: workflow.ts, functions/*, .sim/lock.json and .sim/base.json. Defaults to `.`. | | `--dry-run` | No | Check the source and show the outcome without saving or writing files. | | `-y, --yes` | No | Apply without asking for confirmation. | @@ -8647,7 +8673,7 @@ sim workflows source apply [workflowId] [options] -Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint) or the command failed; 5 the workflow changed since the directory was read (SOURCE_STALE, on a dry run too: get it again, reapply the edit, retry); 6 the workflow or its folder is locked (E_APPLY_LOCKED; a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was written: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it). Exit 13: not logged in, or the server refused the credential (AUTH_REQUIRED); nothing was sent. Run `sim login`, or fix or unset SIM_API_KEY when the key comes from it. Exit 130: interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflowId given is not the one .sim/base.json names (SOURCE_WORKFLOW_MISMATCH: the directory holds another workflow's source), or the command failed; 5 the workflow changed since the directory was read (SOURCE_STALE, on a dry run too: get it again, reapply the edit, retry); 6 the workflow or its folder is locked (E_APPLY_LOCKED; a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was written: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. API request and response schemas: [applyWorkflowSource](/api-reference/workflows/applyWorkflowSource), [deployWorkflow](/api-reference/workflows/deployWorkflow), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment), [getSourceResources](/api-reference/workflows/getSourceResources). @@ -8666,6 +8692,7 @@ sim workflows source create [options] | Option | Required | Description | | --- | --- | --- | | `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | +| `--summary-file ` | No | Also write the plan as Markdown to this file (or set SIM_SUMMARY_FILE), replacing it each run; its first line is a comment that names the directory, for a CI step that updates one pull-request comment. | | `--dir ` | Yes | Source directory: workflow.ts and functions/*. Without workflow.ts, writes a starter and the types instead (an error with --dry-run or --yes). | | `--dry-run` | No | Check the source and show the outcome without creating anything. | | `--name ` | No | The workflow name (default: the source's). | @@ -8675,13 +8702,13 @@ sim workflows source create [options] -Exit codes: 0 created (or a clean dry run, or a starter written); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflow name is taken (SOURCE_NAME_TAKEN: pass --name), or the command failed (a starter is created in the workspace its types were written for unless --workspace names another); 6 the folder is locked; 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was created: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was created (run the same command with --yes). Exit 13: not logged in, or the server refused the credential (AUTH_REQUIRED); nothing was sent. Run `sim login`, or fix or unset SIM_API_KEY when the key comes from it. Exit 130: interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 created (or a clean dry run, or a starter written); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflow name is taken (SOURCE_NAME_TAKEN: pass --name), or the command failed (a starter is created in the workspace its types were written for unless --workspace or SIM_WORKSPACE names another); 6 the folder is locked; 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was created: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was created (run the same command with --yes); 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. API request and response schemas: [createWorkflowFromSource](/api-reference/workflows/createWorkflowFromSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getSourceResources](/api-reference/workflows/getSourceResources), [deployWorkflow](/api-reference/workflows/deployWorkflow), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment). ### sim workflows source check -Compile a workflow source directory locally, without the server +Compile and type-check a workflow source directory locally, without the server ```bash sim workflows source check [options] @@ -8696,15 +8723,18 @@ sim workflows source check [options] | `--dir ` | No | Source directory: workflow.ts, functions/* and .sim/. Defaults to `.`. | | `--strict` | No | Fail on the warnings listed below in every block, not only new ones. | | `--no-strict` | No | Never fail on a warning an apply saves. | +| `--no-types` | No | Skip the type check (TypeScript 7.0.2 over tsconfig.json) that runs after the compile. | | `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | -Compiles workflow.ts (and the function files it names) with the compiler the server runs, against the workspace's block catalog the last get or create cached, and prints the findings as the dry run does. No request is made. It covers the source itself (syntax, builders, params, references, wiring). In a workflow folder of a workspace directory (workflows/<key>), it reads the workspace's .sim/base.json and also checks env names, resource keys and table columns against what the directory declares. The dry run still checks what only the server knows (stored values, deployment), so run it before applying. A check also adds the blocks the source now uses to the CLI's tsconfig.json, so tsc type-checks a block the edit added; in a workspace directory it also regenerates .sim/sdk/workspace.d.ts, so tsc types each workflow's inputs as its files declare them. +Compiles workflow.ts (and the function files it names) with the compiler the server runs, against the workspace's block catalog the last get or create cached, and prints the findings as the dry run does. No request is made to Sim. It covers the source itself (syntax, builders, params, references, wiring). In a workflow folder of a workspace directory (workflows/<key>), it reads the workspace's .sim/base.json and also checks env names, resource keys and table columns against what the directory declares. The dry run still checks what only the server knows (stored values, deployment), so run it before applying. A check also adds the blocks the source now uses to the CLI's tsconfig.json, so a block the edit added is typed; in a workspace directory it also regenerates .sim/sdk/workspace.d.ts from the files, so each key and workflow input they declare is. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code. One is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them). The first check installs that release with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported, as the server reports it, only on a field the edit made store the reference anew: one whose text differs from what the printed source stored, through block renames, or where the reference was typed then, as when an edit elsewhere (a Start input, a Function's code) changes its type. Without the record or that catalog, it is reported on every block the edit added or changed; with --strict, on every block. + +Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. ### sim workflows source status @@ -8720,6 +8750,7 @@ sim workflows source status [options] | Option | Required | Description | | --- | --- | --- | +| `--summary-file ` | No | Also write the plan as Markdown to this file (or set SIM_SUMMARY_FILE), replacing it each run; its first line is a comment that names the directory, for a CI step that updates one pull-request comment. | | `--dir ` | No | Source directory: workflow.ts, functions/* and .sim/. Defaults to `.`. | | `--offline` | No | Report local changes only, without asking the server. | | `--json` | No | Print the machine-readable status (same as --output json). | @@ -8728,9 +8759,9 @@ sim workflows source status [options] With --json, `plan` is what applying would do as `apply --dry-run --allow-delete` reports it (its errors and warnings counted the same, a conflict as an error), and `next` the command to run (with --allow-delete only when the plan deletes something). -Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 7 the source is too large for the server to read in one dry run; 1 the command failed; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. A server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11). +Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); a server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11); 1 the command failed; 7 the source is too large for the server to read in one dry run; 9 rate limited (HTTP 429) after the CLI's retries: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. -API request and response schemas: [planWorkflowSource](/api-reference/workflows/planWorkflowSource), [applyWorkflowSource](/api-reference/workflows/applyWorkflowSource), [getSourceResources](/api-reference/workflows/getSourceResources). +API request and response schemas: [planWorkflowSource](/api-reference/workflows/planWorkflowSource), [getSourceResources](/api-reference/workflows/getSourceResources). ### sim workflows source diff @@ -8791,10 +8822,11 @@ sim workflows source params [options] | Option | Required | Description | | --- | --- | --- | | `--dir ` | No | Source directory whose catalog to read. Defaults to `.`. | +| `--full` | No | Print every param with its type, enum, default and doc, not the brief form. | -Prints a builder's params (required first, with enums and defaults), the gate field that picks which others apply, and its outputs, from the block catalog the last get, create or check cached. No request is made. <builder> is the dotted builder path as source writes it: table.upsertRow, agent, trigger.schedule, slack.sendMessage (slack.tool.sendMessage names the same builder). A namespace (gmail, trigger.gmail) lists its builders; a block type prints the builder written for it (function is fn) or lists them (table_v2); a construct core.d.ts declares (loop, parallel, t, env) prints its declaration. Run it from a workflow or workspace source directory, or pass --dir. +Prints a builder in brief (an example call, the required params with types, the optional ones by name, the gate field that picks which others apply, and the outputs), from the block catalog the last get, create or check cached. --full prints every param with its type, enum, default and doc. A legacy builder names the one that replaces it. No request is made. <builder> is the dotted builder path as source writes it: table.upsertRow, agent, trigger.schedule, slack.sendMessage (slack.tool.sendMessage names the same builder). A namespace (gmail, trigger.gmail) lists its builders; a block type prints the builder written for it (function is fn) or lists them (table_v2); a construct core.d.ts declares (loop, parallel, t, env) prints its declaration. Run it from a workflow or workspace source directory, or pass --dir. Exit codes: 0 printed; 1 no builder or namespace of that name (the closest one is named), or no cached catalog (run a get once). @@ -10025,7 +10057,7 @@ sim workspaces source get [options] A directory that already holds a .sim/base.json is refreshed from the workspace it was read from, whatever the profile's default workspace. -Exit codes: 0 written; 1 the command failed, the directory holds edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force), --workspace names another workspace than the one the directory was read from (SOURCE_OTHER_WORKSPACE), the directory is a workflow source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or a downloaded binary file does not match its listing (SOURCE_BLOB_MISMATCH: nothing was written); 7 the workspace has more resources of a kind than one directory holds; 9 rate limited (HTTP 429) after the CLI's retries: nothing was written, the binary files already downloaded are kept in .sim/downloads, and running the get again downloads only the rest; 10 (busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was read or written, run `sim login` and the get again. +Exit codes: 0 written; 1 the command failed, the directory holds edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force), --workspace or SIM_WORKSPACE names another workspace than the one the directory was read from (SOURCE_OTHER_WORKSPACE), the directory is a workflow source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or a downloaded binary file does not match its listing (SOURCE_BLOB_MISMATCH: nothing was written); 9 rate limited (HTTP 429) after the CLI's retries: nothing was written, the binary files already downloaded are kept in .sim/downloads, and running the get again downloads only the rest; 10 (busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was read or written, run `sim login` and the get again. API request and response schemas: [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getSourceResources](/api-reference/workflows/getSourceResources), [downloadFile](/api-reference/files/downloadFile), [downloadKnowledgeDocument](/api-reference/knowledge-bases/downloadKnowledgeDocument). @@ -10044,6 +10076,7 @@ sim workspaces source apply [options] | Option | Required | Description | | --- | --- | --- | | `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | +| `--summary-file ` | No | Also write the plan as Markdown to this file (or set SIM_SUMMARY_FILE), replacing it each run; its first line is a comment that names the directory, for a CI step that updates one pull-request comment. | | `--dir ` | No | Workspace source directory written by `workspaces source get`. Defaults to `.`. | | `--dry-run` | No | Plan and check without writing anything. | | `-y, --yes` | No | Apply without asking for confirmation. | @@ -10054,13 +10087,13 @@ sim workspaces source apply [options] -Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing. Exit 13: not logged in, or the server refused the credential (AUTH_REQUIRED); nothing was sent. Run `sim login`, or fix or unset SIM_API_KEY when the key comes from it. Exit 130: interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace or SIM_WORKSPACE names (SOURCE_OTHER_WORKSPACE: drop it, or promote it with --to; without either an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing; 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. API request and response schemas: [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource), [findMissingWorkspaceSourceBlobs](/api-reference/workflows/findMissingWorkspaceSourceBlobs), [stageWorkspaceSourceBlobs](/api-reference/workflows/stageWorkspaceSourceBlobs), [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment). ### sim workspaces source check -Compile every workflow of a workspace source directory locally, without the server +Compile and type-check every workflow of a workspace source directory locally, without the server ```bash sim workspaces source check [options] @@ -10075,15 +10108,16 @@ sim workspaces source check [options] | `--dir ` | No | Workspace source directory: the kind folders and .sim/base.json. Defaults to `.`. | | `--strict` | No | Fail on the warnings listed below in every block, not only new ones. | | `--no-strict` | No | Never fail on a warning an apply saves. | +| `--no-types` | No | Skip the type check (TypeScript 7.0.2 over tsconfig.json) that runs after the compile. | | `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | -Compiles every workflows/<key>/workflow.ts (and the function files each names) with the compiler the server runs, against the workspace's block catalog the last get cached (in a fresh clone with no cache, such as CI, it downloads the catalog once with the profile's credentials). No other request is made. It checks, against what the directory declares: - env names (secrets.ts), with a did-you-mean - credential keys (credentials.ts) - the keys of tables, knowledge bases, skills, custom tools, MCP servers and workflows, with a did-you-mean, and a key holding a look-alike letter (a Cyrillic а) named by its code point - the columns and select options of a table row write - a child workflow call: an inputMapping key the child's Start trigger does not declare, and a child with no Start trigger - each tables/<key>.rows.jsonl: a malformed line, an undeclared column, a managed key two lines share, an empty required cell, a repeated unique value, a value its column's type or options cannot hold - block names whose words mix Latin with Cyrillic, Greek, Armenian or Cherokee letters The dry run still checks what only the server knows (stored values, MCP tool names, model ids, deployments, credential bindings), so run it before applying. A check also regenerates .sim/sdk/workspace.d.ts from the declarations (so tsc types a key added since the get, and each workflow's inputs) and adds the blocks the workflows now use to the CLI's tsconfig.json. +Compiles every workflows/<key>/workflow.ts (and the function files each names) with the compiler the server runs, against the workspace's block catalog the last get cached (in a fresh clone with no cache, such as CI, it downloads the catalog once with the profile's credentials). No other request is made to Sim. It checks, against what the directory declares: - env names (secrets.ts), with a did-you-mean - credential keys (credentials.ts) - the keys of tables, knowledge bases, skills, custom tools, MCP servers and workflows, with a did-you-mean, and a key holding a look-alike letter (a Cyrillic а) named by its code point - the columns and select options of a table row write - a child workflow call: an inputMapping key the child's Start trigger does not declare, and a child with no Start trigger - each tables/<key>.rows.jsonl: a malformed line, an undeclared column, a managed key two lines share, an empty required cell, a repeated unique value, a value its column's type or options cannot hold - block names whose words mix Latin with Cyrillic, Greek, Armenian or Cherokee letters The dry run still checks what only the server knows (stored values, MCP tool names, model ids, deployments, credential bindings), so run it before applying. A check also regenerates .sim/sdk/workspace.d.ts from the declarations (so a key added since the get is typed, and each workflow's inputs) and adds the blocks the workflows now use to the CLI's tsconfig.json. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code. One is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them). The first check installs that release with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. -Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. +Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog that could not be downloaded (a check downloads it once when none is cached, with the profile's credentials; 13 when there is no login to download it with). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported, as the server reports it, only on a field the edit made store the reference anew: one whose text differs from what the printed source stored, through block renames, or where the reference was typed then, as when an edit elsewhere (a Start input, a Function's code) changes its type. Without the record or that catalog, it is reported on every block the edit added or changed; with --strict, on every block. Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. @@ -10103,6 +10137,7 @@ sim workspaces source status [options] | Option | Required | Description | | --- | --- | --- | +| `--summary-file ` | No | Also write the plan as Markdown to this file (or set SIM_SUMMARY_FILE), replacing it each run; its first line is a comment that names the directory, for a CI step that updates one pull-request comment. | | `--dir ` | No | Workspace source directory written by `workspaces source get`. Defaults to `.`. | | `--only ` | No | Report only these kinds (comma-separated folders: secrets.ts, credentials.ts, tools, skills, mcp, tables, knowledge, files, workflows, deployments). | | `--offline` | No | Report local changes only, without asking the server. | @@ -10112,11 +10147,9 @@ sim workspaces source status [options] With --json, `plan` is what applying would do as `apply --dry-run --allow-delete` reports it (its errors and warnings counted the same, a conflict as an error), and `next` the command to run (with --allow-delete only when the plan deletes something). -Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 7 the source is too large for the server to read in one dry run; 1 the command failed; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. A server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11). - -Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. +Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); a server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11); 1 the command failed; 7 the source is too large for the server to read in one dry run; 9 rate limited (HTTP 429) after the CLI's retries: wait a minute and run it again; 10 (busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. -API request and response schemas: [planWorkspaceSource](/api-reference/workflows/planWorkspaceSource), [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource). +API request and response schemas: [planWorkspaceSource](/api-reference/workflows/planWorkspaceSource). ### sim workspaces source diff diff --git a/apps/docs/content/docs/cli/scripting.mdx b/apps/docs/content/docs/cli/scripting.mdx index 5391ed9864a..15c947b0f17 100644 --- a/apps/docs/content/docs/cli/scripting.mdx +++ b/apps/docs/content/docs/cli/scripting.mdx @@ -112,11 +112,11 @@ Run the next command only when the cursor is non-null. `--limit` applies to each Results go to stdout; diagnostics go to stderr. JSON/YAML modes serialize API errors as `{error:{code,message,details?}}`. Display formats use `Error:` plus any supplied code/details. Configuration and argument-parser errors, run-wait outcome messages, and unexpected stack traces can remain text. Do not assume every stderr stream is a single JSON document. -`sim workflows source check`, `sim workspaces source check` and both `source apply` commands (dry run or not) print their findings on stderr as `file:line:column` with the code frame. In JSON output (the [default](/cli/output)) or `--output yaml`, stdout is one document holding the counts and every finding as well: +`sim workflows source check`, `sim workspaces source check` and both `source apply` commands (dry run or not) print their findings on stderr as `file:line:column` with the code frame. A check's `checked` lists what ran: `compile`, and `types` unless `--no-types` or an offline first run (`W_TYPES_UNCHECKED`) skipped the type check. In JSON output (the [default](/cli/output)) or `--output yaml`, stdout is one document holding the counts and every finding as well: ```json { - "checked": "compile", + "checked": ["compile", "types"], "errors": 1, "warnings": 0, "diagnostics": [ @@ -142,7 +142,7 @@ Most successful actions exit 0; API, configuration, or argument failures exit 1. | `13` | `AUTH_REQUIRED`: the profile has no credential, its OAuth login expired and could not be refreshed, or the server answered `401` (the server's own code is kept when it sends one). Nothing was done: run `sim login` and the same command again. | | `9` | Rate limited: the API answered `429` and the CLI gave up. Nothing more was sent: wait a minute and run the command again. | -The CLI resends a request the API answers `429` only when sending it twice is safe: every `GET`, and the source writes that are all-or-nothing (`sim workflows source apply` and `create`, `sim workspaces source apply` and its file uploads, dry runs and the dry run `status` sends included). It resends up to 6 times, waiting each time for the longer of the server's `Retry-After` (honoured up to 60 seconds) and a backoff of about 1, 2, 4, 8, 16 and 30 seconds (each ±20%), so one wait is at most a minute. Any other write answered `429` exits 9 at once. Interactive secret entry cancelled with Ctrl-C exits 130. Other outcomes are command-specific: +The CLI resends a request the API answers `429` only when sending it twice is safe: every `GET`, and the source writes that are all-or-nothing (`sim workflows source apply` and `create`, `sim workspaces source apply` and its file uploads, dry runs and the dry run `status` sends included). It resends up to 6 times, waiting each time for the longer of the server's `Retry-After` (honoured up to 60 seconds) and a backoff of about 1, 2, 4, 8, 16 and 30 seconds (each ±20%, never past 30), so one wait is at most a minute. Any other write answered `429` exits 9 at once. Interactive secret entry cancelled with Ctrl-C exits 130. Other outcomes are command-specific: | Code | `sim whoami` | | --- | --- | @@ -165,61 +165,7 @@ The CLI resends a request the API answers `429` only when sending it twice is sa | `3` | Committed operation requires configuration | | `4` | Wait timed out | -| Code | `sim workflows source apply` or `create` | -| --- | --- | -| `0` | Applied or created, or a dry run with no errors | -| `1` | The source has errors (each printed as `file:line:column` with its frame and hint), `create`'s workflow name is taken (`SOURCE_NAME_TAKEN`: pass `--name`), or command/request failure | -| `5` | The workflow changed since the directory was read (`409 SOURCE_STALE`): get it again, reapply the edit, and retry | -| `6` | The workflow or its folder is locked (`423`, `E_APPLY_LOCKED`); a locked block exits `1` (`E_APPLY_LOCKED_BLOCK`) | -| `7` | The source is over the size limits (`413`) | -| `9` | Still rate limited (`429`) after the CLI's retries; nothing was written | -| `10` | Busy, retry: another `sim` command is using `--dir`, or the workspace directory it is a workflow folder of (`SOURCE_DIR_BUSY`); nothing was read or written: run it again once the other finished | -| `13` | `AUTH_REQUIRED`: not logged in, or the server refused the credential; nothing was sent | -| `14` | Run without `--yes` and with no terminal to ask: the plan was printed with no errors and nothing was written; run the same command with `--yes` | -| `130` | Interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check | - -| Code | `sim workflows source status` or `sim workspaces source status` | -| --- | --- | -| `0` | Clean: nothing to apply, and the server changed nothing since the directory was read | -| `1` | Command/request failure | -| `7` | The source is too large for the server to read in one dry run | -| `10` | `sim workspaces source status` only: another `sim workspaces source` command is using the directory (`SOURCE_DIR_BUSY`); nothing was read: run it again once the other finished | -| `11` | Local changes only: applying writes them | -| `12` | The server changed since the directory was read (drift, or a conflict with local changes) | -| `13` | `AUTH_REQUIRED`: not logged in, or the server refused the credential; the local changes are still shown | - -| Code | `sim workflows source check` or `sim workspaces source check` | -| --- | --- | -| `0` | No errors (warnings may still print) | -| `1` | The source has errors, or a warning that fails the check on a block the edit added (see `--strict`), or no block catalog is cached: run the get once | -| `10` | `sim workspaces source check` only: another `sim workspaces source` command is using the directory (`SOURCE_DIR_BUSY`); nothing was read: run it again once the other finished | - -| Code | `sim workflows source get --dir` or `sim workspaces source get` | -| --- | --- | -| `0` | Written | -| `1` | The directory holds edits no apply has saved (`SOURCE_LOCAL_EDITS`) or another workflow's source (`SOURCE_WORKFLOW_MISMATCH`): apply them, get into another directory, or pass `--force`; it is the other kind of source directory (`SOURCE_DIR_KIND_MISMATCH`, even with `--force`); for a workspace, `--workspace` names another workspace than the one the directory was read from (`SOURCE_OTHER_WORKSPACE`) or a downloaded binary file does not match its listing (`SOURCE_BLOB_MISMATCH`); or command/request failure | -| `7` | The workflow, or a kind of resource, is too large for one directory | -| `9` | Still rate limited (`429`) after the CLI's retries; nothing was written | -| `10` | Busy, retry: another `sim` command is using the directory (or, for a workflow folder, its workspace directory) (`SOURCE_DIR_BUSY`); nothing was read or written: run it again once the other finished | -| `13` | `AUTH_REQUIRED`: not logged in, the login expired, or the server refused the credential; nothing was read or written: run `sim login` and the get again | -| `130` | Interrupted (Ctrl-C): run the get again | - -| Code | `sim workspaces source apply` | -| --- | --- | -| `0` | Applied, or a dry run with no errors | -| `1` | The source has errors, every change it would write was held back for a secret or credential the workspace cannot satisfy (nothing was written; its dry run exits `1` too), or command/request failure | -| `5` | A resource changed since the directory was read (`409 SOURCE_STALE`): get it again into a fresh directory, reapply the edit, and retry | -| `6` | A resource (a workflow or its folder, a table) is locked (`423`); a locked block exits `1` (`E_APPLY_LOCKED_BLOCK`) | -| `7` | The directory is over the size limits (`413`) | -| `8` | The apply stopped part-way: what was written is saved into the directory; apply again | -| `9` | Still rate limited (`429`) after the CLI's retries; nothing was written | -| `10` | Busy, retry: another apply is writing the workspace (`409 SOURCE_BUSY`), or another `sim workspaces source` command is using the same directory (`SOURCE_DIR_BUSY`); nothing was written: run the command again once the other finished | -| `13` | `AUTH_REQUIRED`: not logged in, or the server refused the credential; nothing was sent | -| `14` | Run without `--yes` and with no terminal to ask: the plan was printed with no errors and nothing was written; run the same command with `--yes` | -| `15` | Written in part: changes that use a declared secret with no value, or a credential key nothing binds to, were held back and the rest was applied and saved; set the secret or connect the credential, then apply again (a promotion with `--to` too). A dry run that would do so exits `15` too, having written nothing | -| `130` | Interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check | - -Earlier CLI releases exited `1` when an apply held changes back, whether or not it wrote the rest, and its dry run exited `1` in either case. A script that reads `1` as "held back" should test for `15` too. +The source commands (`sim workflows source` and `sim workspaces source`) have codes of their own, among them `5` stale, `10` busy, `11` and `12` for `status`, `14` for an apply without `--yes`, and `15` for an apply that held changes back. [Exit codes](/workflows/code/exit-codes) lists each one with what to do next. Both waits default to 3600 seconds; `--wait-timeout 0` waits indefinitely. `SIM_TIMEOUT_SECONDS` independently bounds one API request. A timeout does not cancel the underlying run or operation. @@ -381,63 +327,14 @@ exit "$status" ## Workspace source in CI -Keep a [workspace source directory](/workflows/workspace-code) in a repository, `.sim/` included, and let CI plan each pull request and apply each merge. The dry run exits `1` on errors, `5` when the workspace changed since the committed base, and `15` when the apply would hold back changes that use a secret with no value or a credential nothing binds to; `check` downloads the block catalog once on a fresh runner. On GitHub Actions (`GITHUB_ACTIONS=true`), every source command also annotates each error and warning at its file and line, so they show inline on the pull request, and `apply` (a dry run too) appends its plan and errors to the job's step summary. - -```yaml title=".github/workflows/sim-workspace.yml" -on: - pull_request: - paths: ['workspace/**'] - push: - branches: [main] - paths: ['workspace/**'] - -concurrency: sim-workspace - -permissions: - contents: write - -jobs: - workspace: - runs-on: ubuntu-latest - env: - SIM_API_KEY: ${{ secrets.SIM_API_KEY }} - SIM_WORKSPACE: ${{ vars.SIM_WORKSPACE }} - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: '20' - - uses: oven-sh/setup-bun@v2 - - run: bun add -g sim - - run: sim workspaces source check --dir workspace - - run: bunx -p typescript@7.0.2 tsc -p workspace - - run: sim workspaces source apply --dir workspace --dry-run - - if: github.event_name == 'push' - run: sim workspaces source apply --dir workspace --yes - - if: ${{ !cancelled() && github.event_name == 'push' }} - run: | - git add -A workspace - if ! git diff --cached --quiet; then - git -c user.name=sim-bot -c user.email=sim-bot@users.noreply.github.com \ - commit -m "chore(workspace): files the apply rewrote [skip ci]" - git push - fi -``` - -`check` runs first because it is offline and fast, and it regenerates `.sim/sdk/workspace.d.ts`, so the `tsc` step after it types resources the pull request adds. A workspace API key can apply tables, rows, knowledge bases, files, custom tools, MCP servers and credential bindings. Workflows, skills, secrets and deployments need a member's personal API key, and deployments need an admin. Apply rewrites files under the directory (each `.sim/base.json`, ids it allocated, values the server normalized), and the next apply compares with them, so the last step commits them back to the branch; `[skip ci]` keeps that commit from running the job again. That step runs even when the apply failed (`!cancelled()`), because an apply can fail having written part of its plan: exit `15` means it held back changes that use a secret with no value or a credential nothing binds to and applied the rest, and exit `8` means it stopped part-way. Either way the directory records what was written, so committing it keeps the next run from being refused as stale (exit `5`) for resources this run wrote; the job still fails, so set the secret, connect the credential or fix the failure, and push again. Where the branch is protected, run `sim workspaces source get --dir workspace` on a new branch instead and open a pull request. After merging two branches that each applied, a dry run with no changes means the files match the workspace. Exit `5` means a resource changed since this branch's base: get the workspace into a fresh directory and carry the edit over. Exit `10` means another apply is writing the workspace (or another command is using the directory), so retry; the `concurrency` key keeps two runs of this job from overlapping. - -To promote the same directory to a second workspace, add a step with `--to` before the step that commits the files back: - -```bash -sim workspaces source apply --dir workspace --to "$PROD_WORKSPACE_ID" --yes -``` - -The promotion writes `workspace/.sim/targets/.json`, what it left in that workspace. Committing it lets the next run tell a change made in that workspace since (kept, or exit `5` when the directory changed the same resource) from one to promote. +Dry-run source on pull requests, apply on merge, comment the plan and detect drift on a schedule: see [Run in CI](/workflows/code/ci) for GitHub Actions recipes. ## Related docs - [Output formats](/cli/output) - [Workflow commands](/cli/workflows) +- [Workflows as code: run in CI](/workflows/code/ci) +- [Workflows as code: exit codes](/workflows/code/exit-codes) - [Workflow imports and workspace sync](/cli/workflow-sync) - [Organization commands](/cli/organizations) - [Troubleshooting](/cli/troubleshooting) diff --git a/apps/docs/content/docs/cli/tables.mdx b/apps/docs/content/docs/cli/tables.mdx index 589050deb8a..5a94a7998e4 100644 --- a/apps/docs/content/docs/cli/tables.mdx +++ b/apps/docs/content/docs/cli/tables.mdx @@ -68,7 +68,7 @@ sim tables create [options] | --- | --- | --- | | `--name ` | Yes | Identifier: letters, numbers, and underscores; cannot start with a number. | | `--description ` | No | Optional table description. | -| `--schema ` | Yes | Table schema: {"columns":[{"name":"email","type":"string"}]} (JSON, or @path / @- to read a file or stdin). | +| `--schema ` | Yes | Initial table column definitions: {"columns":[{"name":"email","type":"string","required":true,"unique":true}]}. Column fields: id - Optional client-provided column identifier; name (required) - Column name; type (required) - Column data type; required - Whether inserts must supply a value for this column; unique - Whether values in the column must be unique; options - Select options for select-type columns, as [{"id":"open","name":"Open"}]; multiple - Whether a select column accepts multiple values; currencyCode - ISO 4217 code for currency columns. A column's type is one of string, number, currency, boolean, date, json, select; a select column also takes options. (JSON, or @path / @- to read a file or stdin). | | `--folder ` | No | Folder path as shown in the app; the leading / is optional. | @@ -624,7 +624,7 @@ sim tables columns create [options] | Option | Required | Description | | --- | --- | --- | -| `--column ` | Yes | Column definition to add. (JSON, or @path / @- to read a file or stdin). | +| `--column ` | Yes | Column definition to add: {"name":"status","type":"string"}. Column fields: id - Optional client-provided column identifier; name (required) - Column name; type (required) - Column data type; required - Whether inserts must supply a value for this column; unique - Whether values in the column must be unique; options - Select options for select-type columns, as [{"id":"open","name":"Open"}]; multiple - Whether a select column accepts multiple values; currencyCode - ISO 4217 code for currency columns; position - Zero-based insertion position for the column. A column's type is one of string, number, currency, boolean, date, json, select; a select column also takes options. (JSON, or @path / @- to read a file or stdin). | diff --git a/apps/docs/content/docs/cli/troubleshooting.mdx b/apps/docs/content/docs/cli/troubleshooting.mdx index 1b27eed3a54..5b7fb7591c4 100644 --- a/apps/docs/content/docs/cli/troubleshooting.mdx +++ b/apps/docs/content/docs/cli/troubleshooting.mdx @@ -148,6 +148,10 @@ Retain the original request/operation IDs and exact input. An operation may have A workflow wait timeout also leaves its run active. Inspect that run ID; do not assume another execution is a retry of the same work. +## A `sim workflows source` or `sim workspaces source` command failed + +These commands exit with codes of their own, such as `5` when the workflow changed since it was read and `10` when another apply is running, and print each problem with its file, line and code. [Workflows as code troubleshooting](/workflows/code/troubleshooting) covers each exit code and the common diagnostic codes. + ## Anything else For an unexpected stack trace, [open an issue](https://github.com/simstudioai/sim/issues) with the CLI version, command, sanitized trace, and relevant resolved settings. Remove credentials, sensitive inputs, and private file contents before posting. Debug output can contain request selectors. @@ -158,3 +162,4 @@ For an unexpected stack trace, [open an issue](https://github.com/simstudioai/si - [Configuration](/cli/configuration) - [Output formats](/cli/output) - [Scripting](/cli/scripting) +- [Workflows as code troubleshooting](/workflows/code/troubleshooting) diff --git a/apps/docs/content/docs/cli/workflow-sync.mdx b/apps/docs/content/docs/cli/workflow-sync.mdx index 7431f696b9b..664e50d03e2 100644 --- a/apps/docs/content/docs/cli/workflow-sync.mdx +++ b/apps/docs/content/docs/cli/workflow-sync.mdx @@ -28,7 +28,7 @@ Forking and sync require Enterprise on billing-enabled deployments. Billing-disa ### 1. Export and inspect the workflow -`--include-references` adds a versioned manifest of resource identities and their occurrences. Default export clears registered credential fields and workspace bindings. It does not remove every ordinary variable value or literal configuration; inspect the payload before sharing it. Credentials and secret values are not transferred as destination resources. +`--include-references` adds a versioned manifest of resource identities and their occurrences. `sim workflows export` clears registered credential fields and keeps non-secret workspace bindings, such as table and knowledge base IDs; `--no-include-workspace-bindings` clears those too. It does not remove every ordinary variable value or literal configuration; inspect the payload before sharing it. Credentials and secret values are not transferred as destination resources. Pin JSON because import does not accept YAML: @@ -40,7 +40,7 @@ sim --profile destination --workspace "$DESTINATION_WORKSPACE" --output json \ workflows import-preview --workflow @workflow.json > preview.json ``` -`--include-workspace-bindings` can preserve non-secret bindings for a same-workspace round trip. Otherwise, configure required bindings reported by import. +With `--include-references`, import preview lists the bindings the destination has to map. ### 2. Map destination resources @@ -239,6 +239,7 @@ Validate provider connections in the destination environment as well as the plat - [Workspace forking](/platform/enterprise/forks) - [Workflow commands](/cli/workflows) - [Workspace commands](/cli/workspaces) +- [Promote to another workspace](/workflows/code/promote): copy a workspace directory kept in git to another workspace, without linking the two - [Selectors](/cli/selectors) - [Exit codes](/cli/scripting#exit-codes) - [Workflow-sync contributor harness](/api-reference/workflow-sync#related-docs) diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 87fc3f80201..2db4c32aecb 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -342,7 +342,11 @@ Edges: connections maps a source handle to its targets: {"source":""}, {"source":["",""]}, or {"source":{"block":"","handle":""}}; "success" is an alias of "source". An add's connections create the new block's edges. An edit's connections REPLACE every - outgoing edge of that block, on every handle: list again each edge to keep. + outgoing edge of that block, on every handle: list again each edge to keep; {} removes them all. + Moving a block into or out of a loop or parallel (parentId) removes each of its existing edges + that would cross the container's boundary, atomic or not, and names them in warnings. Edges the + batch itself asks for across a boundary are refused. Wire into the body from loop-start-source + and onward from loop-end-source (parallel-start-source, parallel-end-source). To remove one edge, edit its source block with {"removeEdges":[{"targetBlockId":"","sourceHandle":"source"}]} (sourceHandle defaults to "source"). @@ -355,12 +359,14 @@ Source handles: parallel-start-source, parallel-end-source the same for a parallel Renames: An edit's {"name":"New name"} also rewrites every reference to the block, in - other blocks' inputs and in a loop's or parallel's collection and condition. + other blocks' inputs and in a loop's or parallel's collection and condition. Edits run after the + batch's adds, so a block added in the same batch is rewritten too. Inputs: inputs takes the field ids `sim blocks get ` lists (inputSchema, operationInputSchema), or the name a pair of them shares (inputDefinitions: tableId for tableSelector and manualTableId; a string goes to the typed field). Add the type it answers with: `blocks get - table` answers table_v2, and an add of legacy table is refused. + table` answers table_v2, and an add of legacy table is refused. An edit's inputs replace each + field they name whole (a responseFormat schema too) and keep the fields they do not name. conditions (condition): [{"title":"if","value":" > 3"},{"title":"else if","value":"…"}, {"title":"else","value":""}]; the last entry is the else. Each entry's id comes from its position (-if, -else-if-0, …, -else): an id you pass is replaced. @@ -369,12 +375,28 @@ Inputs: Block settings, beside inputs in an add's or edit's params: "retry":{"enabled":true,"maxTries":3,"waitBetweenTriesMs":1000} retries a failed block; null clears it. An api block's retries input repeats the request after a timeout, reset, 429 or - 5xx, not when the host does not resolve or refuses the connection; "retry" covers that. + 5xx, not when the host does not resolve or refuses the connection; "retry" covers that. They + nest: every try of "retry" runs the request with its retries. Outputs: A block that fails outputs {"error":""}: connect its error handle and read - there (without one, the run fails). A Workflow block's result is the child's + there (without one, the run fails). A Function's error leads with the line and + code that threw; its is the thrown message alone, the one to reply with. + A Workflow block's result is the child's output; a child ending in a Response block gives {data, status, headers}, so read - . + . A Table block's row holds its cells under data: read a cell as + (). +References: + Inside a loop or parallel body read and , or + and ; after it, . A reference to a block + that did not run (a branch not taken) is null as a whole value, in a condition or in a + Function's code, and '' inside text. +Order: + Operations run in phases whatever their order in the batch: deletes first, then + extract_from_subflow, adds, insert_into_subflow and edits; operations of one type keep the + order given, except insert_into_subflow, which runs a parent before its children. A delete plus an add with the same name therefore replaces the block in one batch. +Run logs: + `sim logs list --workflow ` lists a workflow's runs; `sim logs get --trace + --no-include-workflow-state` shows each block's resolved inputs, outputs and errors. ``` API request and response schemas: [applyWorkflowOperations](/api-reference/workflows/applyWorkflowOperations). @@ -813,8 +835,8 @@ sim workflows run [options] | `--manual` | No | Run the current saved workflow state instead of the active deployment. | | `--trigger ` | No | Enter the run through this runnable trigger, by its block id; runs the current saved workflow state (implies --manual). | | `--mock-payload` | No | Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual). | -| `--from-block ` | No | Run manually from this saved workflow block: its id, display name or key. | -| `--source-run ` | No | Prior run whose persisted state supplies upstream outputs (requires --from-block). | +| `--from-block ` | No | Rerun the saved draft from this block (its id, display name or key), reusing the outputs --source-run produced before it; a failed run prints this command as next. | +| `--source-run ` | No | Earlier run of this workflow, deployed or draft, whose outputs the blocks before --from-block keep (requires --from-block). | | `--stop-after ` | No | Stop the run after this saved block (its id, display name or key), failing it if the run takes a path that skips the block; with --from-block on the same block, re-runs only that block (implies --manual). Unless --select-output names others, blockOutputs holds the output of that block under its key (or id); output stays empty. | | `--dir ` | No | This workflow's source directory: a failed run names the source file and line of the block that failed, read through its .sim/lock.json. Not with --async or --follow, and not for a run --wait-timeout leaves running. | | `--wait-timeout ` | No | Wait at most this many seconds for a synchronous run (0 waits until it settles). A run still going then continues in the background under async limits: the command prints its run record and exits 4, and `sim workflows runs wait` keeps waiting. Not with --async or --follow. | @@ -828,6 +850,8 @@ Without --manual (or a flag that implies it) this runs the active deployment; a The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. +A run that failed in a block has next: the command that reruns the saved draft from that block (or from the outermost loop or parallel holding it) with this run as --source-run, so after a fix only that block and those after it run again. Add --stop-after <block> to stop after a block; naming the block next starts from reruns only it. + Exit codes: 0 completed or paused (--async: queued); 1 failed or cancelled (the result is printed first, then the error on stderr), or the command failed; 4 still running when --wait-timeout elapsed. API request and response schemas: [executeWorkflow](/api-reference/workflows/executeWorkflowV2). @@ -1135,12 +1159,12 @@ sim workflows export [options] | Option | Required | Description | | --- | --- | --- | | `--include-references` | No | Include non-secret resource identities for mapped import. | -| `--include-workspace-bindings` | No | Keep non-secret table, knowledge base, document, folder, channel, and other workspace bindings for a same-workspace import. Defaults to false, which clears these IDs. Registered credential fields and opaque table/tool values are cleared either way; environment references and ordinary workflow variables remain included. | +| `--include-workspace-bindings` | No | Keep table, knowledge base, document, folder, channel and other workspace bindings. On by default; --no-include-workspace-bindings clears them for a copy to share outside this workspace. Credentials are cleared either way. | | `--no-include-workspace-bindings` | No | Send --include-workspace-bindings as false. | -Workspace bindings (a table, a child workflow, a knowledge base) print as null unless --include-workspace-bindings, and credentials always do: to read what a block is set to, use `sim workflows state get`. +A table, child workflow, knowledge base or other workspace binding prints as its id; a credential always prints as null. For a copy to share outside this workspace, pass --no-include-workspace-bindings to clear the bindings too. API request and response schemas: [exportWorkflow](/api-reference/workflows/exportWorkflow). @@ -1338,7 +1362,7 @@ sim workflows mkdir API request and response schemas: [createWorkflowFolder](/api-reference/workflows/createWorkflowsFolder). -## Other commands +## Workflows as code ### Show a workflow’s draft as TypeScript source with its identity lock @@ -1384,6 +1408,7 @@ sim workflows source status [options] | Option | Required | Description | | --- | --- | --- | +| `--summary-file ` | No | Also write the plan as Markdown to this file (or set SIM_SUMMARY_FILE), replacing it each run; its first line is a comment that names the directory, for a CI step that updates one pull-request comment. | | `--dir ` | No | Source directory: workflow.ts, functions/* and .sim/. Defaults to `.`. | | `--offline` | No | Report local changes only, without asking the server. | | `--json` | No | Print the machine-readable status (same as --output json). | @@ -1392,9 +1417,9 @@ sim workflows source status [options] With --json, `plan` is what applying would do as `apply --dry-run --allow-delete` reports it (its errors and warnings counted the same, a conflict as an error), and `next` the command to run (with --allow-delete only when the plan deletes something). -Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 7 the source is too large for the server to read in one dry run; 1 the command failed; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. A server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11). +Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); a server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11); 1 the command failed; 7 the source is too large for the server to read in one dry run; 9 rate limited (HTTP 429) after the CLI's retries: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. -API request and response schemas: [planWorkflowSource](/api-reference/workflows/planWorkflowSource), [applyWorkflowSource](/api-reference/workflows/applyWorkflowSource), [getSourceResources](/api-reference/workflows/getSourceResources). +API request and response schemas: [planWorkflowSource](/api-reference/workflows/planWorkflowSource), [getSourceResources](/api-reference/workflows/getSourceResources). ### Create a workflow from a workflow source directory @@ -1409,6 +1434,7 @@ sim workflows source create [options] | Option | Required | Description | | --- | --- | --- | | `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | +| `--summary-file ` | No | Also write the plan as Markdown to this file (or set SIM_SUMMARY_FILE), replacing it each run; its first line is a comment that names the directory, for a CI step that updates one pull-request comment. | | `--dir ` | Yes | Source directory: workflow.ts and functions/*. Without workflow.ts, writes a starter and the types instead (an error with --dry-run or --yes). | | `--dry-run` | No | Check the source and show the outcome without creating anything. | | `--name ` | No | The workflow name (default: the source's). | @@ -1418,7 +1444,7 @@ sim workflows source create [options] -Exit codes: 0 created (or a clean dry run, or a starter written); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflow name is taken (SOURCE_NAME_TAKEN: pass --name), or the command failed (a starter is created in the workspace its types were written for unless --workspace names another); 6 the folder is locked; 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was created: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was created (run the same command with --yes). Exit 13: not logged in, or the server refused the credential (AUTH_REQUIRED); nothing was sent. Run `sim login`, or fix or unset SIM_API_KEY when the key comes from it. Exit 130: interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 created (or a clean dry run, or a starter written); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflow name is taken (SOURCE_NAME_TAKEN: pass --name), or the command failed (a starter is created in the workspace its types were written for unless --workspace or SIM_WORKSPACE names another); 6 the folder is locked; 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was created: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was created (run the same command with --yes); 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. API request and response schemas: [createWorkflowFromSource](/api-reference/workflows/createWorkflowFromSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getSourceResources](/api-reference/workflows/getSourceResources), [deployWorkflow](/api-reference/workflows/deployWorkflow), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment). @@ -1434,7 +1460,7 @@ sim workflows source apply [workflowId] [options] | Argument | Required | Description | | --- | --- | --- | -| `workflowId` | No | Workflow whose draft the source replaces (default: the workflowId in .sim/base.json) | +| `workflowId` | No | Refuse unless .sim/base.json names this workflow (default: the workflowId there) | @@ -1445,6 +1471,7 @@ sim workflows source apply [workflowId] [options] | Option | Required | Description | | --- | --- | --- | | `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | +| `--summary-file ` | No | Also write the plan as Markdown to this file (or set SIM_SUMMARY_FILE), replacing it each run; its first line is a comment that names the directory, for a CI step that updates one pull-request comment. | | `--dir ` | No | Source directory: workflow.ts, functions/*, .sim/lock.json and .sim/base.json. Defaults to `.`. | | `--dry-run` | No | Check the source and show the outcome without saving or writing files. | | `-y, --yes` | No | Apply without asking for confirmation. | @@ -1453,7 +1480,7 @@ sim workflows source apply [workflowId] [options] -Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint) or the command failed; 5 the workflow changed since the directory was read (SOURCE_STALE, on a dry run too: get it again, reapply the edit, retry); 6 the workflow or its folder is locked (E_APPLY_LOCKED; a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was written: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it). Exit 13: not logged in, or the server refused the credential (AUTH_REQUIRED); nothing was sent. Run `sim login`, or fix or unset SIM_API_KEY when the key comes from it. Exit 130: interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflowId given is not the one .sim/base.json names (SOURCE_WORKFLOW_MISMATCH: the directory holds another workflow's source), or the command failed; 5 the workflow changed since the directory was read (SOURCE_STALE, on a dry run too: get it again, reapply the edit, retry); 6 the workflow or its folder is locked (E_APPLY_LOCKED; a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was written: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. API request and response schemas: [applyWorkflowSource](/api-reference/workflows/applyWorkflowSource), [deployWorkflow](/api-reference/workflows/deployWorkflow), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment), [getSourceResources](/api-reference/workflows/getSourceResources). @@ -1475,7 +1502,7 @@ sim workflows source catalog [options] API request and response schemas: [getSourceCatalog](/api-reference/catalog/getSourceCatalog). -### Compile a workflow source directory locally, without the server +### Compile and type-check a workflow source directory locally, without the server ```bash sim workflows source check [options] @@ -1490,15 +1517,18 @@ sim workflows source check [options] | `--dir ` | No | Source directory: workflow.ts, functions/* and .sim/. Defaults to `.`. | | `--strict` | No | Fail on the warnings listed below in every block, not only new ones. | | `--no-strict` | No | Never fail on a warning an apply saves. | +| `--no-types` | No | Skip the type check (TypeScript 7.0.2 over tsconfig.json) that runs after the compile. | | `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | -Compiles workflow.ts (and the function files it names) with the compiler the server runs, against the workspace's block catalog the last get or create cached, and prints the findings as the dry run does. No request is made. It covers the source itself (syntax, builders, params, references, wiring). In a workflow folder of a workspace directory (workflows/<key>), it reads the workspace's .sim/base.json and also checks env names, resource keys and table columns against what the directory declares. The dry run still checks what only the server knows (stored values, deployment), so run it before applying. A check also adds the blocks the source now uses to the CLI's tsconfig.json, so tsc type-checks a block the edit added; in a workspace directory it also regenerates .sim/sdk/workspace.d.ts, so tsc types each workflow's inputs as its files declare them. +Compiles workflow.ts (and the function files it names) with the compiler the server runs, against the workspace's block catalog the last get or create cached, and prints the findings as the dry run does. No request is made to Sim. It covers the source itself (syntax, builders, params, references, wiring). In a workflow folder of a workspace directory (workflows/<key>), it reads the workspace's .sim/base.json and also checks env names, resource keys and table columns against what the directory declares. The dry run still checks what only the server knows (stored values, deployment), so run it before applying. A check also adds the blocks the source now uses to the CLI's tsconfig.json, so a block the edit added is typed; in a workspace directory it also regenerates .sim/sdk/workspace.d.ts from the files, so each key and workflow input they declare is. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code. One is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them). The first check installs that release with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported, as the server reports it, only on a field the edit made store the reference anew: one whose text differs from what the printed source stored, through block renames, or where the reference was typed then, as when an edit elsewhere (a Start input, a Function's code) changes its type. Without the record or that catalog, it is reported on every block the edit added or changed; with --strict, on every block. + +Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. ### Show the content of the changes in a workflow source directory @@ -1557,10 +1587,11 @@ sim workflows source params [options] | Option | Required | Description | | --- | --- | --- | | `--dir ` | No | Source directory whose catalog to read. Defaults to `.`. | +| `--full` | No | Print every param with its type, enum, default and doc, not the brief form. | -Prints a builder's params (required first, with enums and defaults), the gate field that picks which others apply, and its outputs, from the block catalog the last get, create or check cached. No request is made. <builder> is the dotted builder path as source writes it: table.upsertRow, agent, trigger.schedule, slack.sendMessage (slack.tool.sendMessage names the same builder). A namespace (gmail, trigger.gmail) lists its builders; a block type prints the builder written for it (function is fn) or lists them (table_v2); a construct core.d.ts declares (loop, parallel, t, env) prints its declaration. Run it from a workflow or workspace source directory, or pass --dir. +Prints a builder in brief (an example call, the required params with types, the optional ones by name, the gate field that picks which others apply, and the outputs), from the block catalog the last get, create or check cached. --full prints every param with its type, enum, default and doc. A legacy builder names the one that replaces it. No request is made. <builder> is the dotted builder path as source writes it: table.upsertRow, agent, trigger.schedule, slack.sendMessage (slack.tool.sendMessage names the same builder). A namespace (gmail, trigger.gmail) lists its builders; a block type prints the builder written for it (function is fn) or lists them (table_v2); a construct core.d.ts declares (loop, parallel, t, env) prints its declaration. Run it from a workflow or workspace source directory, or pass --dir. Exit codes: 0 printed; 1 no builder or namespace of that name (the closest one is named), or no cached catalog (run a get once). diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index 3f9f86374d0..c2d428879a1 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -708,7 +708,7 @@ sim workspaces source get [options] A directory that already holds a .sim/base.json is refreshed from the workspace it was read from, whatever the profile's default workspace. -Exit codes: 0 written; 1 the command failed, the directory holds edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force), --workspace names another workspace than the one the directory was read from (SOURCE_OTHER_WORKSPACE), the directory is a workflow source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or a downloaded binary file does not match its listing (SOURCE_BLOB_MISMATCH: nothing was written); 7 the workspace has more resources of a kind than one directory holds; 9 rate limited (HTTP 429) after the CLI's retries: nothing was written, the binary files already downloaded are kept in .sim/downloads, and running the get again downloads only the rest; 10 (busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was read or written, run `sim login` and the get again. +Exit codes: 0 written; 1 the command failed, the directory holds edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force), --workspace or SIM_WORKSPACE names another workspace than the one the directory was read from (SOURCE_OTHER_WORKSPACE), the directory is a workflow source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or a downloaded binary file does not match its listing (SOURCE_BLOB_MISMATCH: nothing was written); 9 rate limited (HTTP 429) after the CLI's retries: nothing was written, the binary files already downloaded are kept in .sim/downloads, and running the get again downloads only the rest; 10 (busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was read or written, run `sim login` and the get again. API request and response schemas: [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getSourceResources](/api-reference/workflows/getSourceResources), [downloadFile](/api-reference/files/downloadFile), [downloadKnowledgeDocument](/api-reference/knowledge-bases/downloadKnowledgeDocument). @@ -724,6 +724,7 @@ sim workspaces source status [options] | Option | Required | Description | | --- | --- | --- | +| `--summary-file ` | No | Also write the plan as Markdown to this file (or set SIM_SUMMARY_FILE), replacing it each run; its first line is a comment that names the directory, for a CI step that updates one pull-request comment. | | `--dir ` | No | Workspace source directory written by `workspaces source get`. Defaults to `.`. | | `--only ` | No | Report only these kinds (comma-separated folders: secrets.ts, credentials.ts, tools, skills, mcp, tables, knowledge, files, workflows, deployments). | | `--offline` | No | Report local changes only, without asking the server. | @@ -733,11 +734,9 @@ sim workspaces source status [options] With --json, `plan` is what applying would do as `apply --dry-run --allow-delete` reports it (its errors and warnings counted the same, a conflict as an error), and `next` the command to run (with --allow-delete only when the plan deletes something). -Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 7 the source is too large for the server to read in one dry run; 1 the command failed; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. A server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11). +Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was read); a server that cannot be reached is not a failure: the status shows the local changes only and says so (exit 0 or 11); 1 the command failed; 7 the source is too large for the server to read in one dry run; 9 rate limited (HTTP 429) after the CLI's retries: wait a minute and run it again; 10 (busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 11 local changes only (applying writes them); 12 the server changed since the directory was read: drift (a resource edited, added or deleted there that the directory leaves alone) or a conflict (also changed here, so applying it is refused as stale), with or without local changes; 13 not logged in (AUTH_REQUIRED) or the credential was refused: the status shows the local changes only, then run `sim login`. -Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. - -API request and response schemas: [planWorkspaceSource](/api-reference/workflows/planWorkspaceSource), [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource). +API request and response schemas: [planWorkspaceSource](/api-reference/workflows/planWorkspaceSource). ### Apply a workspace source directory @@ -752,6 +751,7 @@ sim workspaces source apply [options] | Option | Required | Description | | --- | --- | --- | | `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | +| `--summary-file ` | No | Also write the plan as Markdown to this file (or set SIM_SUMMARY_FILE), replacing it each run; its first line is a comment that names the directory, for a CI step that updates one pull-request comment. | | `--dir ` | No | Workspace source directory written by `workspaces source get`. Defaults to `.`. | | `--dry-run` | No | Plan and check without writing anything. | | `-y, --yes` | No | Apply without asking for confirmation. | @@ -762,11 +762,11 @@ sim workspaces source apply [options] -Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing. Exit 13: not logged in, or the server refused the credential (AUTH_REQUIRED); nothing was sent. Run `sim login`, or fix or unset SIM_API_KEY when the key comes from it. Exit 130: interrupted (Ctrl-C). A write already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace or SIM_WORKSPACE names (SOURCE_OTHER_WORKSPACE: drop it, or promote it with --to; without either an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing; 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. API request and response schemas: [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource), [findMissingWorkspaceSourceBlobs](/api-reference/workflows/findMissingWorkspaceSourceBlobs), [stageWorkspaceSourceBlobs](/api-reference/workflows/stageWorkspaceSourceBlobs), [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment). -### Compile every workflow of a workspace source directory locally, without the server +### Compile and type-check every workflow of a workspace source directory locally, without the server ```bash sim workspaces source check [options] @@ -781,15 +781,16 @@ sim workspaces source check [options] | `--dir ` | No | Workspace source directory: the kind folders and .sim/base.json. Defaults to `.`. | | `--strict` | No | Fail on the warnings listed below in every block, not only new ones. | | `--no-strict` | No | Never fail on a warning an apply saves. | +| `--no-types` | No | Skip the type check (TypeScript 7.0.2 over tsconfig.json) that runs after the compile. | | `--verbose` | No | Also list the info findings hidden by default: every one with --output json, blocks placed by autolayout in the display. | -Compiles every workflows/<key>/workflow.ts (and the function files each names) with the compiler the server runs, against the workspace's block catalog the last get cached (in a fresh clone with no cache, such as CI, it downloads the catalog once with the profile's credentials). No other request is made. It checks, against what the directory declares: - env names (secrets.ts), with a did-you-mean - credential keys (credentials.ts) - the keys of tables, knowledge bases, skills, custom tools, MCP servers and workflows, with a did-you-mean, and a key holding a look-alike letter (a Cyrillic а) named by its code point - the columns and select options of a table row write - a child workflow call: an inputMapping key the child's Start trigger does not declare, and a child with no Start trigger - each tables/<key>.rows.jsonl: a malformed line, an undeclared column, a managed key two lines share, an empty required cell, a repeated unique value, a value its column's type or options cannot hold - block names whose words mix Latin with Cyrillic, Greek, Armenian or Cherokee letters The dry run still checks what only the server knows (stored values, MCP tool names, model ids, deployments, credential bindings), so run it before applying. A check also regenerates .sim/sdk/workspace.d.ts from the declarations (so tsc types a key added since the get, and each workflow's inputs) and adds the blocks the workflows now use to the CLI's tsconfig.json. +Compiles every workflows/<key>/workflow.ts (and the function files each names) with the compiler the server runs, against the workspace's block catalog the last get cached (in a fresh clone with no cache, such as CI, it downloads the catalog once with the profile's credentials). No other request is made to Sim. It checks, against what the directory declares: - env names (secrets.ts), with a did-you-mean - credential keys (credentials.ts) - the keys of tables, knowledge bases, skills, custom tools, MCP servers and workflows, with a did-you-mean, and a key holding a look-alike letter (a Cyrillic а) named by its code point - the columns and select options of a table row write - a child workflow call: an inputMapping key the child's Start trigger does not declare, and a child with no Start trigger - each tables/<key>.rows.jsonl: a malformed line, an undeclared column, a managed key two lines share, an empty required cell, a repeated unique value, a value its column's type or options cannot hold - block names whose words mix Latin with Cyrillic, Greek, Armenian or Cherokee letters The dry run still checks what only the server knows (stored values, MCP tool names, model ids, deployments, credential bindings), so run it before applying. A check also regenerates .sim/sdk/workspace.d.ts from the declarations (so a key added since the get is typed, and each workflow's inputs) and adds the blocks the workflows now use to the CLI's tsconfig.json. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code. One is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them). The first check installs that release with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. -Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. +Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog that could not be downloaded (a check downloads it once when none is cached, with the profile's credentials; 13 when there is no login to download it with). With --output json, stdout is one document that also lists every finding under diagnostics. -These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported only on blocks the lock does not bind, and with --strict on every block. +These warnings, which an apply saves as written, fail the check as errors on every block the lock does not bind (a block added since the get, or every block of a new workflow): W_REQUIRED_MISSING, W_UNKNOWN_OPTION, W_UNKNOWN_OUTPUT_PATH, W_VALUE_KIND, W_OUT_OF_RANGE, W_LITERAL_SECRET, W_TABLE_UNKNOWN_COLUMN, W_CHILD_INPUT_UNKNOWN, W_CHILD_RESULT_PATH, W_BRANCH_UNWIRED, W_UNRESOLVED_REF, W_REF_OUT_OF_SCOPE, W_LOOP_CONDITION_SYNTAX. --strict fails on them in every block, except W_BRANCH_UNWIRED on a block the lock binds (the stored workflow may hold it, and the server then stays quiet); --no-strict fails on none of them. In every mode, as the server refuses them: W_REF_OUT_OF_SCOPE is the error E_APPLY_REF_OUT_OF_SCOPE in any file of a block the edit added or changed; W_LOOP_CONDITION_SYNTAX is the error E_APPLY_LOOP_CONDITION_SYNTAX in any file of a block the edit added or changed; W_UNKNOWN_OPTION is the error E_APPLY_INVALID_SUBBLOCK_FIELD in workflow.ts on a block the edit added or changed; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in workflow.ts on a block the edit added or changed; W_UNKNOWN_BLOCK_TYPE is the error E_APPLY_INVALID_BLOCK_TYPE in workflow.ts on a block the edit added or changed; W_TYPE_NOT_ADDABLE is the error E_APPLY_TYPE_NOT_ADDABLE in workflow.ts on a block the edit added or changed; W_UNRESOLVED_REF is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_UNKNOWN_OUTPUT_PATH is the error E_APPLY_UNRESOLVED_REF in a function file changed since the get; W_CODE_FILE_REF_SYNTAX is the error E_APPLY_CODE_FILE_REF_SYNTAX in a function file changed since the get. A block counts as changed when the lock does not bind it, when the source moved it into another container, or when it compiles differently than in the source the last get or apply printed (.sim/stored-edges.json records a digest of each block). That last comparison needs the catalog the source was printed with in the cache: without it, a bound block that did not move counts as unchanged, so the server may refuse what the check passes. A $ref in a function file to a block the lock binds that the source no longer declares stays a warning, unless a warning cap left findings out: the server may infer that block was renamed and rewrite the reference, and refuses it otherwise. W_JSON_REF_UNTYPED is reported, as the server reports it, only on a field the edit made store the reference anew: one whose text differs from what the printed source stored, through block renames, or where the reference was typed then, as when an edit elsewhere (a Start input, a Function's code) changes its type. Without the record or that catalog, it is reported on every block the edit added or changed; with --strict, on every block. Exit 10 (busy, retry): another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY); nothing was read or written. Run this one again once it finished. diff --git a/apps/docs/content/docs/integrations/slack.mdx b/apps/docs/content/docs/integrations/slack.mdx index a7260e75879..d97664d897d 100644 --- a/apps/docs/content/docs/integrations/slack.mdx +++ b/apps/docs/content/docs/integrations/slack.mdx @@ -31,6 +31,9 @@ Custom-bot Slack triggers can stream workflow outputs directly back into the con - Loop and parallel invocations each create their own Slack response. - The response status label defaults to `Running` and can be customized in the trigger's advanced settings. - Optional thinking and tool-call updates appear as Slack tasks in a timeline or plan. +- **Show progress from** (`streamTimelineSources`) shows an Agent's tool steps, and its thinking when enabled, without posting its text. Use it when an Agent's output is reviewed or reformatted by a later block: the steps and the first streamed answer share one Slack reply. Agents in child workflows can be selected. A block cannot be both an output to stream and a progress source. +- **Tool step labels** (`streamToolLabels`) renames tool steps by tool name, for example `lc_cur` → `Reading AWS cost data`. Unlisted tools use a generated name. Steps never show tool arguments. +- With PII block-output redaction on, Agent output is not streamed live, so no progress steps appear; selected outputs are still sent when their block completes. - Slack Agent Sessions remain in processing state for the run, return to active when it finishes, and the native Slack stop button cancels active workflow executions. Automatic trigger responses require a custom bot created by the Slack setup wizard. They are not available with the shared Sim Slack app. Where the deployment enables shared-app triggers, the Sim app can receive its subscribed event subset without automatic streaming. @@ -75,7 +78,7 @@ Sim requests these scopes when someone connects a Slack account. For a self-host | `reactions:write` | Add emoji reactions to messages | | `reactions:read` | View emoji reactions on messages | -Requested only when `SLACK_EXTENDED_SCOPES` and `NEXT_PUBLIC_SLACK_EXTENDED_SCOPES` are enabled. Enable them only after Slack approves the app for these scopes: +Requested only when `SLACK_EXTENDED_SCOPES` is enabled. Enable them only after Slack approves the app for these scopes: | Scope | Description | | ----- | ----------- | @@ -3867,6 +3870,8 @@ Trigger from Slack events, interactions, and slash commands | `threads` | string | No | Include thread replies, exclude them \(top-level only\), or fire only on thread replies. | | `streamResponse` | boolean | No | Create a Slack agent session and stream selected workflow outputs into the conversation that started this run. Custom bots only. | | `streamOutputs` | workflow-output-selector | No | Use `<blockName>.<outputPath>` for this workflow or `<childWorkflowId>.<blockName>.<outputPath>` for a child workflow. Selecting a child workflow applies to every invocation of it. Agent outputs stream live; other outputs are sent when the block completes. | +| `streamTimelineSources` | workflow-output-selector | No | Agent blocks, including ones in child workflows, whose tool steps appear in the reply while they run. Their text is never posted. No steps appear when PII block-output redaction is on. | +| `streamToolLabels` | table | No | Optional names for tool steps, keyed by tool name \(an MCP tool by its own name, like lc_cur\). Unlisted tools use a generated name. | | `streamTaskTitle` | string | No | Optional status Slack shows while each selected response is being produced. Leave empty to use Running. | | `streamTaskDisplayMode` | string | No | Choose how Slack displays thinking and tool progress. | | `streamIncludeThinking` | boolean | No | Show agent thinking as Slack task updates while the response is generated. | diff --git a/apps/docs/content/docs/integrations/table.mdx b/apps/docs/content/docs/integrations/table.mdx index 79a60a6957c..a7290d139be 100644 --- a/apps/docs/content/docs/integrations/table.mdx +++ b/apps/docs/content/docs/integrations/table.mdx @@ -52,6 +52,7 @@ Insert a new row into a table. IMPORTANT: You must use the "data" parameter (not | Parameter | Type | Description | | --------- | ---- | ----------- | +| `ignoredColumns` | array | Keys of the written data that name no column of the table, which the write dropped. Empty when every key matched a column. | | `success` | boolean | Whether row was inserted | | `row` | json | Inserted row data | | `message` | string | Status message | @@ -75,6 +76,7 @@ Insert multiple rows into a table at once (up to 1000 rows) | Parameter | Type | Description | | --------- | ---- | ----------- | +| `ignoredColumns` | array | Keys of the written data that name no column of the table, which the write dropped. Empty when every key matched a column. | | `success` | boolean | Whether rows were inserted | | `rows` | array | Inserted rows data | | `insertedCount` | number | Number of rows inserted | @@ -94,12 +96,13 @@ Insert or update a row based on unique column constraints. If a row with matchin | --------- | ---- | -------- | ----------- | | `tableId` | string | Yes | Table ID in the execution workspace. In a workflow, the table must belong to the same workspace as the workflow. | | `data` | object | Yes | Row data to insert or update | -| `conflictTarget` | string | No | Unique column to match on. Required only when the table has more than one unique column. | +| `conflictTarget` | string | No | Unique column \(name or id\) to match on. Required only when the table has more than one unique column. | #### Output | Parameter | Type | Description | | --------- | ---- | ----------- | +| `ignoredColumns` | array | Keys of the written data that name no column of the table, which the write dropped. Empty when every key matched a column. | | `success` | boolean | Whether row was upserted | | `row` | json | Upserted row data | | `operation` | string | Operation performed: insert or update | @@ -125,6 +128,7 @@ Update an existing row in a table. Supports partial updates - only include the f | Parameter | Type | Description | | --------- | ---- | ----------- | +| `ignoredColumns` | array | Keys of the written data that name no column of the table, which the write dropped. Empty when every key matched a column. | | `success` | boolean | Whether row was updated | | `row` | json | Updated row data | | `message` | string | Status message | @@ -150,6 +154,7 @@ Update multiple rows that match filter criteria. Data is merged with existing ro | Parameter | Type | Description | | --------- | ---- | ----------- | +| `ignoredColumns` | array | Keys of the written data that name no column of the table, which the write dropped. Empty when every key matched a column. | | `success` | boolean | Whether rows were updated | | `updatedCount` | number | Number of rows updated | | `updatedRowIds` | array | IDs of updated rows | diff --git a/apps/docs/content/docs/introduction/index.mdx b/apps/docs/content/docs/introduction/index.mdx index 78c208e0151..5e56aef065d 100644 --- a/apps/docs/content/docs/introduction/index.mdx +++ b/apps/docs/content/docs/introduction/index.mdx @@ -57,7 +57,7 @@ The core source is available on [GitHub](https://github.com/simstudioai/sim) und ## Security and compliance -Sim is SOC 2 Type II compliant. Find reports and security details in the [trust center](https://trust.sim.ai/). +Sim has completed a SOC 2 Type II audit covering the Security Trust Services Criterion, and ISO 27001 certification is in progress. Find reports and security details in the [trust center](https://trust.sim.ai/). Enterprise organizations can sign in through [SSO](/platform/enterprise/sso) with SAML 2.0 or OIDC, including Microsoft Entra ID, Okta, and Google Workspace. They can also sync members from Entra ID or Okta with [SCIM](/platform/enterprise/scim), review [audit logs](/platform/enterprise/audit-logs), and restrict models, blocks, and tools with [permission groups](/platform/enterprise/access-control). diff --git a/apps/docs/content/docs/meta.json b/apps/docs/content/docs/meta.json index 4a9220fc06b..46999555c52 100644 --- a/apps/docs/content/docs/meta.json +++ b/apps/docs/content/docs/meta.json @@ -11,6 +11,7 @@ "---Build---", "chat", "workflows", + "workflows/code", "agents", "---Workspace---", "knowledgebase", diff --git a/apps/docs/content/docs/platform/costs.mdx b/apps/docs/content/docs/platform/costs.mdx index 13a483821e9..5b6141895d1 100644 --- a/apps/docs/content/docs/platform/costs.mdx +++ b/apps/docs/content/docs/platform/costs.mdx @@ -21,7 +21,7 @@ A billable workflow run can include: | Hosted tools | Operation charges when using Sim-provided provider keys | | Sandbox runtime | Applicable runtime charges, such as a Pi sandbox | -Sim-hosted models and tools are available on paid plans. On the Free plan, add your own provider keys under **Settings → BYOK**; a run that needs a Sim-hosted key fails with an upgrade message instead. +Sim-hosted models and tools, and Chat with Sim, are available on paid plans. On the Free plan, add your own provider keys under **Settings → BYOK**; a run that needs a Sim-hosted key fails with an upgrade message instead. Free credits cover run charges, code execution, knowledge base indexing, and AI-assisted editing in the workflow editor. With your own provider keys, you pay the provider directly for those calls. The workflow base charge and unrelated hosted-tool or sandbox usage still apply. Local Ollama or vLLM inference avoids an external model API charge, but still needs infrastructure and any enabled Sim run charge. @@ -181,6 +181,12 @@ Current monthly pricing and allocations are: Pro and Max are available for individuals or teams. Team subscriptions pool credits across internal seats. For example, Max for Teams with three seats has a 75,000-credit monthly allocation and a 12,000-credit weekly refresh allowance. External collaborators do not add seats, but their work in an organization-owned workspace is billed to that organization. +### Pro free trial + +A new individual Pro subscriber gets a 14-day free trial. Checkout requires a card, which is charged for Pro when the trial ends unless you cancel first under **Settings → Subscription**. During the trial you get Pro features and Sim-hosted models and tools, with a fixed allowance of 2,000 credits: there is no weekly refresh, the usage limit cannot be raised, and nothing is billed past it. When the trial converts, the full Pro allowance applies. + +Each account and each card can start one trial. A checkout whose card already started a trial is charged right away instead. Team plans and Max don't include a trial. + See [current pricing](https://www.sim.ai/pricing) and **Settings → Subscription** for the plan available to your account. Internal membership, external eligibility, and workspace migration are explained in [Roles and permissions](/platform/permissions#internal-and-external-membership). ### Weekly refresh @@ -189,7 +195,7 @@ Each seven-day window from the billing period's start excludes usage up to the w ### Annual billing -Pro and Max annual subscriptions have a 15% discount while retaining their advertised included credits. Team pricing uses the same per-seat rate. +Pro and Max annual subscriptions have a 15% discount while retaining their advertised included credits. An annual billing period is the whole year, so it includes twelve months of credits up front (72,000 per seat on Pro, 300,000 on Max), usable any time during the year. Team pricing uses the same per-seat rate. | Plan | Monthly billing | Annual equivalent per month | Annual price per seat | | --- | --- | --- | --- | diff --git a/apps/docs/content/docs/platform/enterprise/scim/index.mdx b/apps/docs/content/docs/platform/enterprise/scim/index.mdx index 0882bc06595..3aeed9e3c1e 100644 --- a/apps/docs/content/docs/platform/enterprise/scim/index.mdx +++ b/apps/docs/content/docs/platform/enterprise/scim/index.mdx @@ -170,13 +170,13 @@ Sim tracks grants made through directory mappings. Removing a member from a grou Other directory mappings and independent access can still keep the person in a workspace. Removing a permission-group membership changes their governing policy; it does not remove workspace access. Sim then uses another applicable workspace policy, the organization default, or no permission-group restrictions if neither exists. An empty mapped group applies to nobody and never turns into an all-members policy. Verify both workspace access and the fallback policy when testing a removal. -**Lock managed membership** is enabled by default on a new connection. It makes the directory authoritative for provisioned members: Sim refuses manual invitations, workspace grants, workspace role changes, and organization role changes for them. Manual access already held when a mapping begins covering it becomes directory-managed and is withdrawn with that mapping. Administrators can still remove access in an emergency. +**Lock managed membership** is enabled by default on a new connection. It makes the directory authoritative for provisioned members: Sim refuses manual organization invitations and organization role changes for them, and manual grants and role changes on any workspace one of their groups is mapped to. Other workspace access stays shareable by hand, since the directory does not manage it. To have the directory own a member's access to a workspace, map one of their groups to it. Manual access already held when a mapping begins covering it becomes directory-managed and is withdrawn with that mapping. Administrators can still remove access in an emergency. The lock does not prevent editing permission-group membership directly in Sim. A manual removal can be restored by reconciliation, and a manual addition to an overlapping policy can block a directory assignment. Manage mapped policy membership through the directory and check **Group mappings** for unassigned members after resolving conflicts. With locking off, prior manual workspace access is preserved. If a member had manual Read access and a directory mapping raises it to Admin, removing the mapping restores Read. A role manually raised above the directory's level also remains. [Older grants have a baseline limitation](#deployment-and-upgrades). -You can manually invite people the directory does not manage. For managed members with locking on, grant access through directory groups. +You can manually invite people the directory does not manage. For managed members with locking on, change access to workspaces their groups are mapped to through the directory; share other workspaces with them as usual. ## Provisioning and SSO together diff --git a/apps/docs/content/docs/platform/enterprise/scim/okta.mdx b/apps/docs/content/docs/platform/enterprise/scim/okta.mdx index 92bf74946e9..a5f16ef5a9e 100644 --- a/apps/docs/content/docs/platform/enterprise/scim/okta.mdx +++ b/apps/docs/content/docs/platform/enterprise/scim/okta.mdx @@ -118,7 +118,7 @@ For example, use `Sim users` to assign the app and `Finance` as the pushed group Header Auth Test App Group Push selecting an engineering group and Create Group for the downstream group -With **Lock managed membership** enabled, Sim blocks manual invitations and grants for provisioned members. Read [How access is withdrawn](/platform/enterprise/scim#how-access-is-withdrawn) before mapping groups that overlap existing manual access. +With **Lock managed membership** enabled, Sim blocks manual grants for provisioned members on workspaces their groups are mapped to. Read [How access is withdrawn](/platform/enterprise/scim#how-access-is-withdrawn) before mapping groups that overlap existing manual access. ## Rotate a token diff --git a/apps/docs/content/docs/platform/enterprise/self-hosted.mdx b/apps/docs/content/docs/platform/enterprise/self-hosted.mdx index 602ea92d74f..27fa5a70675 100644 --- a/apps/docs/content/docs/platform/enterprise/self-hosted.mdx +++ b/apps/docs/content/docs/platform/enterprise/self-hosted.mdx @@ -162,7 +162,7 @@ curl -X PATCH https://sim.example.com/api/v1/admin/organizations/$ORG_ID/session -When invitations are disabled with `DISABLE_INVITATIONS` and `NEXT_PUBLIC_DISABLE_INVITATIONS`, use the Admin API to manage organization membership and workspace access. Internal members join the organization. External workspace members receive access to a specific workspace without joining the organization. +When invitations are disabled with `DISABLE_INVITATIONS`, use the Admin API to manage organization membership and workspace access. Internal members join the organization. External workspace members receive access to a specific workspace without joining the organization. ### Read audit logs and permission groups diff --git a/apps/docs/content/docs/platform/self-hosting/authentication.mdx b/apps/docs/content/docs/platform/self-hosting/authentication.mdx index 9a459e00094..9cfd8b2d04a 100644 --- a/apps/docs/content/docs/platform/self-hosting/authentication.mdx +++ b/apps/docs/content/docs/platform/self-hosting/authentication.mdx @@ -189,8 +189,8 @@ Requests use a shared anonymous session. | Variable | Effect | | --- | --- | -| `DISABLE_INVITATIONS=true` / `NEXT_PUBLIC_DISABLE_INVITATIONS=true` | Disable workspace invitations globally. | -| `DISABLE_PUBLIC_API=true` / `NEXT_PUBLIC_DISABLE_PUBLIC_API=true` | Disable the public API globally. | +| `DISABLE_INVITATIONS=true` | Disable workspace invitations globally. | +| `DISABLE_PUBLIC_API=true` | Disable the public API globally. | | `ADMIN_API_KEY` | Enables Admin API GitOps operations and organization provisioning. | Set both server and `NEXT_PUBLIC_` flags where a pair is listed. The server flag enforces the restriction; its counterpart controls the UI. diff --git a/apps/docs/content/docs/platform/self-hosting/environment-variables.mdx b/apps/docs/content/docs/platform/self-hosting/environment-variables.mdx index 72e006b327b..9aba3b7f1b5 100644 --- a/apps/docs/content/docs/platform/self-hosting/environment-variables.mdx +++ b/apps/docs/content/docs/platform/self-hosting/environment-variables.mdx @@ -199,7 +199,7 @@ Plain JavaScript without imports runs in isolated-vm within Node child workers i | Variable | Description | |----------|-------------| -| `WORKFLOW_CODE` | Set to `true` to enable [workflows as code](/workflows/code) and [workspace as code](/workflows/workspace-code): the read-only **Code** tab in the workflow builder, and the source API and MCP operations that the `sim workflows source` and `sim workspaces source` CLI commands call. Off when unset; while off, those operations answer `403` | +| `WORKFLOW_CODE` | Set to `true` to enable [workflows as code](/workflows/code) and [workspace as code](/workflows/code/workspace): the read-only **Code** tab in the workflow builder, and the source API and MCP operations that the `sim workflows source` and `sim workspaces source` CLI commands call. Off when unset; while off, those operations answer `403` | ## Chat and PII [#chat--pii] @@ -268,7 +268,7 @@ Most `/api` routes also pass through Next.js Proxy, which buffers only the first ## Limits -With `BILLING_ENABLED` disabled, hosted-plan execution rates/timeouts and table/storage quotas are not enforced unless you set their free-tier variables. Independent protocol, body-size, concurrency, and security rate limits still apply. Billing-enabled deployments enforce their plan limits. Keep `BILLING_ENABLED` and `NEXT_PUBLIC_BILLING_ENABLED` consistent so enforcement and the UI agree. +With `BILLING_ENABLED` disabled, hosted-plan execution rates/timeouts and table/storage quotas are not enforced unless you set their free-tier variables. Independent protocol, body-size, concurrency, and security rate limits still apply. Billing-enabled deployments enforce their plan limits. Retention cleanup is separately opt-in through `DATA_RETENTION_ENABLED` or the enterprise suite. A configured retention policy still applies without billing; see [Data retention](/platform/enterprise/data-retention). diff --git a/apps/docs/content/docs/platform/self-hosting/integrations-oauth.mdx b/apps/docs/content/docs/platform/self-hosting/integrations-oauth.mdx index 0d125a545a7..51b0d71f48d 100644 --- a/apps/docs/content/docs/platform/self-hosting/integrations-oauth.mdx +++ b/apps/docs/content/docs/platform/self-hosting/integrations-oauth.mdx @@ -477,7 +477,7 @@ Webhook triggers receive callbacks from the provider and must be able to verify | Variable | Needed for | |---|---| | `SLACK_SIGNING_SECRET` | Verifying Slack event and slash-command signatures | -| `SLACK_EXTENDED_SCOPES` / `NEXT_PUBLIC_SLACK_EXTENDED_SCOPES` | Enabling the native Sim-app trigger and its broader Slack scope set; set both to the same value | +| `SLACK_EXTENDED_SCOPES` | Enabling the native Sim-app trigger and its broader Slack scope set | When enabling the native Sim Slack trigger, configure all three variables together. Enable the extended-scope flags only after Slack approves the app for `assistant:write`, `app_mentions:read`, and `im:history`; otherwise Slack rejects OAuth authorization. Slack OAuth actions can use `SLACK_CLIENT_ID` and `SLACK_CLIENT_SECRET` without enabling the native trigger or supplying a signing secret. diff --git a/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx b/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx index 763d5869541..2fca0deee9a 100644 --- a/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx +++ b/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx @@ -134,7 +134,7 @@ MOTHERSHIP_E2B_TEMPLATE_ID= DAYTONA_SHELL_SNAPSHOT_ID= ``` -These values do not replace `E2B_FUNCTION_TEMPLATE_ID` or `DAYTONA_FUNCTION_SNAPSHOT_ID`. Shell, Function, document, and Pi images have separate package contracts and release cadences. Pi also needs `E2B_PI_TEMPLATE_ID` or `DAYTONA_PI_SNAPSHOT_ID`; revealing a Pi mode with `NEXT_PUBLIC_E2B_ENABLED` does not supply that image. +These values do not replace `E2B_FUNCTION_TEMPLATE_ID` or `DAYTONA_FUNCTION_SNAPSHOT_ID`. Shell, Function, document, and Pi images have separate package contracts and release cadences. Pi also needs `E2B_PI_TEMPLATE_ID` or `DAYTONA_PI_SNAPSHOT_ID`; `E2B_ENABLED` reveals the Pi cloud modes but does not supply that image. ## Related docs diff --git a/apps/docs/content/docs/platform/self-hosting/security.mdx b/apps/docs/content/docs/platform/self-hosting/security.mdx index 2d1c1bad019..0babcb06fb5 100644 --- a/apps/docs/content/docs/platform/self-hosting/security.mdx +++ b/apps/docs/content/docs/platform/self-hosting/security.mdx @@ -195,13 +195,7 @@ no remote provider is configured. Without valid provider credentials and the required Function image, code that needs a remote sandbox fails with a configuration error. Verify readiness before enabling its browser controls. -The Function block's Sandbox selector, Shell, and **Settings → Sandboxes** follow the server's own readiness check; no browser variable is involved. One browser-side variable relates to sandbox readiness and is not derived automatically: - -| Variable | Effect when unset | -|---|---| -| `NEXT_PUBLIC_E2B_ENABLED` | The E2B-backed Pi block modes stay hidden; `sim-setup doctor` reports it as a mismatch against `E2B_ENABLED`. Revealing them is not enough to make them run — Pi executes on its own image, pinned with `E2B_PI_TEMPLATE_ID` or `DAYTONA_PI_SNAPSHOT_ID`, and fails closed without it | - -Set it only **after** the server-side configuration above is complete — it is an assertion about readiness, not a switch, and the server-side check has its own conditions beyond it. See [Sandboxes](/platform/self-hosting/sandboxes) for the base-image build and promotion procedure. `bunx sim-setup doctor` reports a mismatch in either direction. +The Function block's Sandbox selector, Shell, and **Settings → Sandboxes** follow the server's own readiness check; no browser variable is involved. The E2B-backed Pi block modes appear when `E2B_ENABLED` is set. Revealing them is not enough to make them run — Pi executes on its own image, pinned with `E2B_PI_TEMPLATE_ID` or `DAYTONA_PI_SNAPSHOT_ID`, and fails closed without it. See [Sandboxes](/platform/self-hosting/sandboxes) for the base-image build and promotion procedure. With the default local sandbox, treat everyone who can author a workflow as someone running code in your app container's security context. If your Sim instance is open to a wide or partly-trusted audience, use a remote sandbox provider and enable the NetworkPolicy egress restrictions. diff --git a/apps/docs/content/docs/platform/self-hosting/upgrades.mdx b/apps/docs/content/docs/platform/self-hosting/upgrades.mdx index 10c22694f2a..f4e9cecda22 100644 --- a/apps/docs/content/docs/platform/self-hosting/upgrades.mdx +++ b/apps/docs/content/docs/platform/self-hosting/upgrades.mdx @@ -75,7 +75,7 @@ Check the changes for every release between your current version and the target |---|---| | **Redis is required.** Sim refuses to start without `REDIS_URL`; there is no PostgreSQL or in-memory fallback. | Keep the bundled Redis, or point `REDIS_URL` at a managed instance before upgrading. App and realtime must reach the same Redis. See [Redis](/platform/self-hosting/redis). | | **`REGISTRATION_MODE` replaces `DISABLE_REGISTRATION`, `DISABLE_EMAIL_SIGNUP`, and `EMAIL_PASSWORD_SIGNUP_ENABLED`** (and its `NEXT_PUBLIC_` twin). The old variables are still honored as deprecated aliases, and the most restrictive setting wins. `NEXT_PUBLIC_EMAIL_PASSWORD_SIGNUP_ENABLED=false` now also disables email/password sign-in on the server. | Move to `REGISTRATION_MODE`. See [Control registration and sign-in](/platform/self-hosting/authentication#controlling-who-can-sign-up). | -| **Enterprise `NEXT_PUBLIC_*` flags and `NEXT_PUBLIC_SANDBOXES_ENABLED` are no longer read.** The browser reads the server's resolved settings. | Set the server variable for each feature. See the [feature flag reference](/platform/enterprise/self-hosted#feature-flag-reference). | +| **Enterprise `NEXT_PUBLIC_*` flags and `NEXT_PUBLIC_SANDBOXES_ENABLED` are no longer read, nor are `NEXT_PUBLIC_BILLING_ENABLED`, `NEXT_PUBLIC_E2B_ENABLED`, `NEXT_PUBLIC_SLACK_EXTENDED_SCOPES`, `NEXT_PUBLIC_DISABLE_INVITATIONS`, and `NEXT_PUBLIC_DISABLE_PUBLIC_API`.** The browser reads the server's resolved settings. | Set the server variable for each feature (`BILLING_ENABLED`, `E2B_ENABLED`, `SLACK_EXTENDED_SCOPES`, `DISABLE_INVITATIONS`, `DISABLE_PUBLIC_API`, …). See the [feature flag reference](/platform/enterprise/self-hosted#feature-flag-reference). | | **`ALLOW_PRIVATE_DATABASE_HOSTS` was removed.** The app logs an error at startup if it is still set. | Name your database, cache, and mail hosts in the egress allowlists. See [Upgrading from an earlier release](/platform/self-hosting/security#upgrading-from-an-earlier-release). | | **White-labeling was removed.** `NEXT_PUBLIC_BRAND_*`, `NEXT_PUBLIC_CUSTOM_CSS_URL`, `NEXT_PUBLIC_SUPPORT_EMAIL`, `NEXT_PUBLIC_DOCUMENTATION_URL`, `NEXT_PUBLIC_TERMS_URL`, `NEXT_PUBLIC_PRIVACY_URL`, `WHITELABELING_ENABLED`, and `NEXT_PUBLIC_WHITELABELING_ENABLED` are ignored. | Remove them at your convenience; leaving them set is harmless. | | **`docker-compose.ollama.yml` is now an overlay on `docker-compose.prod.yml`.** | A stack started from the previous standalone file needs its project name carried over, or it starts on an empty database. See [Migrating from the previous Ollama stack](/platform/self-hosting/docker#migrating-from-the-previous-ollama-stack). | diff --git a/apps/docs/content/docs/tables/using-in-workflows.mdx b/apps/docs/content/docs/tables/using-in-workflows.mdx index 71693f3e1a9..2192a27aefa 100644 --- a/apps/docs/content/docs/tables/using-in-workflows.mdx +++ b/apps/docs/content/docs/tables/using-in-workflows.mdx @@ -126,6 +126,8 @@ Use **Get Row by ID** for a point lookup and **Get Schema** for column definitio } ``` +A key that names no column is dropped, and the write still succeeds. Every insert, upsert, and update reports the dropped keys in ``, an empty list when every key matched, so a downstream condition can catch a misspelled column. Public v2 API writes reject an unknown column instead. + Upsert requires a unique column. If the table has several, select **Conflict Column** to choose the match target. Unlisted fields remain unchanged in a partial update. For different results per row, use a sequential Loop and **Update Row by ID**. A filter update applies the same values to every match; with no **Limit**, it walks all matches in batches. The 1,000 maximum applies to an explicitly supplied update limit, not the total for an unlimited filtered update. diff --git a/apps/docs/content/docs/workflows/blocks/agent.mdx b/apps/docs/content/docs/workflows/blocks/agent.mdx index 751799feead..fd5cc0c4e3b 100644 --- a/apps/docs/content/docs/workflows/blocks/agent.mdx +++ b/apps/docs/content/docs/workflows/blocks/agent.mdx @@ -32,7 +32,7 @@ Answer in two sentences, cite the doc you used, and never guess a price. ### Model -The model that runs the step. Defaults to `claude-sonnet-5-5`. Type or pick any model from OpenAI, Anthropic, Google, xAI, Groq, Cerebras, DeepSeek, Azure, AWS Bedrock, Google Vertex, or OpenRouter, or a local model through Ollama or vLLM. +The model that runs the step. Defaults to `claude-sonnet-5-5`. Type or pick any model from OpenAI, Anthropic, Google, xAI, Groq, Cerebras, DeepSeek, Azure, AWS Bedrock, Google Vertex, or OpenRouter, or a local or self-hosted model through Ollama, vLLM, or LiteLLM. For a custom cloud deployment, enter its provider prefix and model ID: `azure/my-deployment`, `azure-anthropic/my-deployment`, `bedrock/my-inference-profile`, or `vertex/my-gemini-model`. The prefix selects the provider and shows its credential fields even when the ID is absent from the catalog. Bedrock accepts full inference profile ARNs after `bedrock/`; Vertex uses the Gemini API and accepts Google model resource names. The deployment must support the selected provider's API. Custom IDs have no catalog pricing or token limits. diff --git a/apps/docs/content/docs/workflows/blocks/function.mdx b/apps/docs/content/docs/workflows/blocks/function.mdx index ef5d27b755b..17932ba1660 100644 --- a/apps/docs/content/docs/workflows/blocks/function.mdx +++ b/apps/docs/content/docs/workflows/blocks/function.mdx @@ -435,6 +435,15 @@ The lazy `sim.files` and `sim.values` helpers are available only in JavaScript f An uncaught error follows the connected error port or fails the run. Catch an error only when your code can return a meaningful recovery result. `console.log()`, `print()`, and ordinary Shell output appear in `stdout` and the run logs. +On the error path, the failed block has two outputs: + +| Output | What it is | +| --- | --- | +| `` | The message with the line and code that threw: ``Line 4: `throw new Error('invalid phone')` - invalid phone`` | +| `` | The thrown message alone: `invalid phone` | + +Use `` in a reply to a caller, such as a Response block's body, so the caller never sees your code. Use `` when you need the line to debug. A failure your code did not throw, such as a timeout, has no line, so both hold the same message. + Function uses the workflow's remaining execution time when a deadline exists. Without a workflow deadline, it still has a fallback timeout of 300,000 ms (5 minutes) by default, configurable through `EXECUTION_TIMEOUT_FREE`. An explicit internal timeout can replace that fallback or shorten the workflow budget; it cannot extend the workflow deadline. There is no separate timeout field in the current block editor. Exceeding the budget terminates execution and reports a block error. ## Related docs diff --git a/apps/docs/content/docs/workflows/blocks/human-in-the-loop.mdx b/apps/docs/content/docs/workflows/blocks/human-in-the-loop.mdx index 15eb134623c..15fb1ec23e1 100644 --- a/apps/docs/content/docs/workflows/blocks/human-in-the-loop.mdx +++ b/apps/docs/content/docs/workflows/blocks/human-in-the-loop.mdx @@ -76,7 +76,7 @@ HITL blocks are excluded from the selected-output picker because pause data is i ## Resume with the v2 API -A v2 execute call can return `data.status: "paused"`. Read `contextId` from `data.output.data._resume` and the paused run's ID from `data.runId`: +A v2 execute call can return `data.status: "paused"`. Read the run to resume from `data.paused.runId`, and the `contextId` of a waiting `human` point from `data.paused.points`: ```bash curl -X POST 'https://www.sim.ai/api/v2/workflows/WORKFLOW_ID/runs/RUN_ID/resume' \ @@ -102,12 +102,13 @@ For an originally synchronous run, the response waits for the resumed execution "error": null, "startedAt": "2026-10-13T10:00:00.000Z", "endedAt": "2026-10-13T10:00:01.234Z", - "durationMs": 1234 + "durationMs": 1234, + "paused": null } } ``` -A later Human block can pause the resumed run again, returning new pause data. The resumed attempt has its own `runId`. +A later Human block can pause the resumed run again. The response then has `status: "paused"` and new `paused.points`, and `paused.runId` names the run to resume next: the run you resumed, not the attempt's own `runId`. ### Asynchronous and originally streaming runs diff --git a/apps/docs/content/docs/workflows/blocks/pi.mdx b/apps/docs/content/docs/workflows/blocks/pi.mdx index 868d1c3b499..c7301eb3876 100644 --- a/apps/docs/content/docs/workflows/blocks/pi.mdx +++ b/apps/docs/content/docs/workflows/blocks/pi.mdx @@ -232,7 +232,7 @@ Enable the Pi sandbox as below and supply a provider BYOK key. For private repos Create PR runs in a sandbox image with the Pi CLI, Git, Node.js, and Bun baked in. Repository dependencies are not preinstalled; Pi can run `bun install` when a repository needs them. -1. **Enable sandbox execution.** On self-hosted Sim, set `E2B_ENABLED=true`, `E2B_API_KEY`, `E2B_PI_TEMPLATE_ID` (the Pi template id), and `NEXT_PUBLIC_E2B_ENABLED=true` (this reveals Plan, Create PR, Update PR, and Review Code in the UI). Build the template with `bun run apps/sim/scripts/build-pi-e2b-template.ts`. These modes stay hidden until `NEXT_PUBLIC_E2B_ENABLED` is set. +1. **Enable sandbox execution.** On self-hosted Sim, set `E2B_ENABLED=true`, `E2B_API_KEY`, and `E2B_PI_TEMPLATE_ID` (the Pi template id). Build the template with `bun run apps/sim/scripts/build-pi-e2b-template.ts`. Plan, Create PR, Update PR, and Review Code stay hidden until `E2B_ENABLED` is set. The repository template requests **4 vCPU and 8 GiB of RAM**. Confirm your account’s build and session limits against [E2B pricing](https://e2b.dev/pricing); account limits can be lower than Sim’s requested lifetime. Sizing is fixed when the template is built — E2B has no per-sandbox override — so changing it means rebuilding the template, not restarting Sim. Sandboxes are billed per second against the resources they are allocated, not the ones they use. Both numbers live in `apps/sim/scripts/pi-sandbox-packages.ts` and are shared with the Daytona snapshot so the failover image cannot drift from the primary. diff --git a/apps/docs/content/docs/workflows/blocks/router.mdx b/apps/docs/content/docs/workflows/blocks/router.mdx index f2a04ac3491..15570614a3b 100644 --- a/apps/docs/content/docs/workflows/blocks/router.mdx +++ b/apps/docs/content/docs/workflows/blocks/router.mdx @@ -22,7 +22,7 @@ Pass `` as Context, describe Sales, Support, and Billing routes, an | --- | --- | | **Context** | Text to analyze, often `` or ``. | | **Routes** | Each route has a title and a description of when to choose it. It adds a separate output port. | -| **Model** | Defaults to `claude-sonnet-5-5`. Select a supported model, including a compatible local Ollama or vLLM model. | +| **Model** | Defaults to `claude-sonnet-5-5`. Select a supported model, including a compatible local Ollama, vLLM, or LiteLLM model. | Make descriptions specific and distinguishable. For example, “Payments, invoices, and refunds” separates Billing from general product support. Test the routes on representative requests rather than assuming a larger model always routes more accurately. diff --git a/apps/docs/content/docs/workflows/code.mdx b/apps/docs/content/docs/workflows/code.mdx deleted file mode 100644 index 81d14deb04d..00000000000 --- a/apps/docs/content/docs/workflows/code.mdx +++ /dev/null @@ -1,224 +0,0 @@ ---- -title: Workflows as code -description: Read and edit a workflow as one TypeScript file, check it before saving, and review changes as diffs. ---- - -import { Callout } from '@/components/ui/callout' - -Every workflow can be read and written as a TypeScript file. The file and the workflow builder show the same workflow: edit either one and the other follows. Use it to review agent changes as a diff, keep workflows in git, or let a coding agent such as Claude Code build and change them for you. - - -Workflows as code is in preview. When it is [enabled on your Sim deployment](/platform/self-hosting/environment-variables#preview-features), the workflow builder shows a read-only **Code** tab and the [CLI](/cli) gains the `sim workflows source` commands. - - -## For coding agents [#for-coding-agents] - -Claude Code, Cursor, Codex and other coding agents work from a directory that `get` writes. `get` prints a short primer (the edit loop, how block identity, references and renames work, failures and retries, test runs, deletes, deploy, exit codes, and the params of each builder the workflow already uses; in JSON output, its `primer` field), and the same primer opens `.sim/AGENTS.md`, the full guide. The loop: - -1. `sim workflows source get --dir ` writes the workflow and the guide. -2. Edit `workflow.ts`. -3. `sim workflows source check --dir ` compiles it offline. -4. `sim workflows source status --dir ` shows what changed and what to run next. -5. `sim workflows source apply --dir --dry-run`, then `--yes`, saves the draft. - -To write a block the workflow does not use yet, `sim workflows source params ` (for example `table.upsertRow` or `trigger.schedule`) prints its params, required ones first with their options and defaults, and its outputs, from the cached block catalog without a request. A namespace such as `gmail` lists its builders. - -For a whole workspace, use `sim workspaces source` with the same steps; see [Workspace as code](/workflows/workspace-code). - -## What the file holds - -The file states what the workflow runs: its blocks, their settings, the connections between them, branches, loops, and variables. Layout and other builder-only details stay in the stored workflow, so the file stays short and a change to one setting is a one-line diff. - -Nothing in the file runs on your machine. Sim reads it statically, checks it against your workspace, and saves it as the workflow draft. Deploying stays a separate step. - -## Edit a workflow from the CLI - -1. Write the workflow into a directory: - - ```bash - sim workflows source get --dir ./support-triage - ``` - - This writes `workflow.ts`, any function code under `functions/`, and type declarations for the blocks the workflow uses and for your workspace's tables, credentials, knowledge bases, and environment variable names, with `.sim/sdk/INDEX.md` listing those blocks' builders. The declarations of every block are generated once per block catalog into the CLI's cache (`~/.sim/cache/source-catalog/`) and shared by every directory. It also writes a `tsconfig.json` that resolves them and type-checks the blocks the workflow uses, and a `tsconfig.full.json` that type-checks every block through that cache, unless the directory already has files of those names, which are left as they are. For coding agents it writes `.sim/AGENTS.md`, the primer `get` prints followed by a reference, and example workflows under `.sim/examples/` with one correct example of each common block to copy from. The examples name placeholder resources, so the tsconfig files leave them out of the type-check. - - `get` into a directory that already holds source refuses to overwrite edits you have not applied, and refuses a directory that holds a different workflow. Pass `--force` to replace them. A workspace source directory is always refused, `--force` included (and `sim workspaces source get` refuses a workflow directory the same way). - -2. Edit `workflow.ts`, then compile it on your machine with Sim's compiler, without a request: - - ```bash - sim workflows source check --dir ./support-triage - ``` - - It exits 1 on an error, and on the warnings `sim workflows source check --help` lists (a missing required field, an unknown option, an unwired condition or router branch, a literal secret and more) in a block you added since the get (`--strict` fails on these in every block, except an unwired branch on a block the get printed, which the stored workflow may hold; `--no-strict` never fails on a warning). It also adds the blocks the workflow now uses to `tsconfig.json`. Your editor type-checks the file against the generated declarations, and `bunx -p typescript@7.0.2 tsc -p ./support-triage` checks it from the command line with the TypeScript release the declarations are built for; `-p ./support-triage/tsconfig.full.json` type-checks against every block. - -3. See what changed, and whether someone changed the workflow since your `get`: - - ```bash - sim workflows source status --dir ./support-triage - sim workflows source diff --dir ./support-triage - ``` - - `status` lists the files you created, edited, or deleted, asks the server (with a dry run that saves nothing) whether the workflow changed since the `get`, and ends with the one command to run next. It exits `0` when nothing changed, `11` when only your edits are unsaved, and `12` when the workflow changed in the editor since the `get` (a conflict, if you edited it too). Without a connection it shows your edits only and says so; `--offline` skips the server. `diff` prints each edit as a unified diff, and `diff --server` compares the directory with the workflow as it is saved now. Both take `--json` (or `--output json`). - -4. Check the change without saving it: - - ```bash - sim workflows source apply --dir ./support-triage --dry-run - ``` - - `apply` reads the workflow ID from `.sim/base.json`. Pass it as `apply --dir …` to have the CLI confirm the directory holds that workflow. Every command that reads a source directory (`check`, `status`, `diff`, `params`, `apply`, and their `sim workspaces source` counterparts) defaults `--dir` to the current directory; `get` and `create`, which write one, always need `--dir`. - - Sim compiles the file and runs every check a save would run: unknown settings, missing required fields, broken references, permissions, and locked blocks. Each problem prints with its line, the code around it, and a hint: - - ``` - workflow.ts:56:7 error E_UNKNOWN_PARAM: Slack has no param chanel. - 54 | const notify = slack.sendMessage('Notify', { - 55 | credential: credential('support-slack'), - > 56 | chanel: 'C0SUPPORT', - | ^^^^^^^^^^^^^^^^^^^ - 57 | text: t`New ${classify.category} ticket: ${ticketIn.subject}`, - hint: Did you mean channel? - ``` - -5. Save the draft: - - ```bash - sim workflows source apply --dir ./support-triage --yes - ``` - - The workflow builder updates for anyone who has the workflow open. Deploy when you are ready, or add `--deploy` to deploy right after the save, which also prints the URL of each webhook the workflow now serves; without it, a deployed workflow whose draft now differs prints the `sim workflows deploy` command to run. `--yes` refuses everything a dry run would, so step 4 is optional: without `--yes`, and with no terminal to ask, `apply` prints the plan, writes nothing and exits `14`. The save rewrites `workflow.ts` in canonical form, so read it again before the next edit. - - Editing the name or description in `workflow('…')` renames or redescribes the workflow; a name another workflow in its folder already has is refused with `E_NAME_TAKEN`. Lines starting with `note:` report something the save did beyond what the file says; read them. - - A save that removes a block (its declaration is gone from `workflow.ts`) is refused with `E_APPLY_BLOCK_DELETE`, naming the blocks, and one that removes a workflow variable with `E_APPLY_VARIABLE_DELETE`. Pass `--allow-delete` when the deletion is intended. - -To create a new workflow, run `sim workflows source create --dir --workspace ` on an empty directory: without `--dry-run` or `--yes` it creates nothing and writes a starter `workflow.ts` with that workspace's type declarations, `tsconfig.json` and `.sim/AGENTS.md`, and records the workspace in `.sim/starter.json`. Edit the starter, check it, then run `sim workflows source create --dir --workspace --dry-run` and `--yes` (the starter prints both). A create goes to the starter's workspace whatever your default workspace, unless `--workspace` names another. Until the workflow is created the directory has no `.sim/base.json`, so `status`, `diff` and `apply` refuse it. The file starts with the `// @sim-sdk 1` line and default-exports one `workflow('Name', {}, () => { ... })`. The command prints the new workflow ID and writes the same type declarations, `tsconfig.json`, and `.sim/` files that `get` writes, so you can continue editing with `apply`. If another workflow already has that name, the command exits `1`; pass `--name` to choose another. - -Keep the `.sim/` folder the commands write. `.sim/lock.json` ties each block in the file to the stored block, so renaming a block keeps the same block, with its webhook URL, schedules and run history. Changing its name string keeps it through the lock; renaming the variable too keeps it when the block's type, parent and connections are unchanged, and the dry run reports that as `W_MAT_INFERRED_RENAME`. Renaming two blocks of the same type in the same place in one save is ambiguous, so do those one save at a time. `.sim/base.json` records the version you read. - -## Example: support triage - -A webhook receives a ticket, an agent classifies it, billing tickets are logged to a table, and the team hears about every ticket in Slack. This is the file `sim workflows source get` prints for it: - -```ts title="workflow.ts" -// @sim-sdk 1 -import { - agent, - condition, - credential, - env, - js, - slack, - t, - table, - trigger, - workflow, -} from '@sim/workflow-sdk' - -export default workflow( - 'Support triage', - { variables: { escalations: { type: 'number', value: 0 } } }, - () => { - const ticketIn = trigger.webhook('Ticket in', { - requireAuth: true, - token: env.TICKETS_WEBHOOK_TOKEN, - inputFormat: { subject: 'string', body: 'string', contacts: 'array' }, - responseMode: 'custom', - responseStatusCode: 202, - responseBody: { ok: true }, - }) - const classify = agent('Classify', { - messages: [ - { role: 'system', content: 'Classify support tickets.' }, - { - role: 'user', - content: t`${ticketIn.subject} - -${ticketIn.body}`, - }, - ], - model: 'claude-sonnet-5-5', - responseFormat: { - name: 'ticket', - strict: true, - schema: { - type: 'object', - additionalProperties: false, - required: ['category', 'urgent'], - properties: { - category: { type: 'string', enum: ['billing', 'bug', 'other'] }, - urgent: { type: 'boolean' }, - }, - }, - }, - }) - const byCategory = condition('By category', { - billing: js`${classify.category} === 'billing'`, - else: true, - }) - const logTicket = table.insertRow('Log ticket', { - tableId: table('tickets'), - data: { subject: ticketIn.subject, category: classify.category }, - }) - const notify = slack.sendMessage('Notify', { - credential: credential('support-slack'), - channel: 'C0SUPPORT', - text: t`New ${classify.category} ticket (urgent: ${classify.urgent}): ${ticketIn.subject}`, - }) - - ticketIn.to(classify) - classify.to(byCategory) - byCategory.billing.to(logTicket) - byCategory.else.to(notify) - logTicket.to(notify) - logTicket.onError(notify) - } -) -``` - -How to read it: - -- Each `const` is a block. `agent`, `condition`, `table.insertRow`, and `slack.sendMessage` are the blocks you know from the workflow builder, with the same settings. -- `classify.category` is a typed reference to another block's output, the same as `` in the builder. `t` writes text with references in it; `js` writes code. -- `table('tickets')` and `credential('support-slack')` name workspace resources by a stable key. Renaming the table in Sim keeps the key. -- `env.TICKETS_WEBHOOK_TOKEN` reads an environment variable. Secret values are never printed: a key pasted into a password field prints as `stored()`, which keeps the saved value. -- `.to()` connects blocks, `byCategory.billing` is one branch of the condition, and `.onError()` follows the error path. `notify` has three incoming edges and runs once, after the branch that was taken. -- A webhook answers its caller as soon as the request is accepted and runs the workflow in the background, so the caller never sees a `response` block's output. `responseMode: 'custom'` sets that fixed answer (here `202` with `{ "ok": true }`; without it, `200` with `{ "message": "Webhook processed" }`). To answer with values the run computes, start the workflow with `trigger.start` and call it through the API; a `response` block then sets what the caller receives. - -## Function code - -Code that does not fit a block goes in a Function block, kept in its own file: - -```ts -const score = fn('Score lead', { code: codeFile('./functions/score-lead.js') }) -``` - -In the file, `$ref.block.path` reads another block's output and `$env.NAME` reads an environment variable. `block` is the block's key: its name lowercased with all whitespace and every `.` removed (`$ref.triageagent.content` for "Triage Agent", `$ref.v2result.text` for "V2. Result"). Inside a loop body, `$ref.loop.currentItem` and `$ref.loop.index` read the iteration's item and position; inside a parallel body, `$ref.parallel.currentItem` and `$ref.parallel.index`. A `$ref` that names no block is refused in a file you edited, because it would not resolve when the workflow runs. Python and shell files are saved as written, so `$ref` and `$env` mean nothing there: read an output as `` (``) and an environment variable as `{{NAME}}`. - -## Use it in CI - -Run `sim workflows source apply --dir --dry-run` in CI to catch a broken workflow before it is saved. It exits `0` when the workflow is valid and `1` when it has errors, so a failing check blocks the merge. It exits `5` when the workflow was changed in the editor after you committed the directory; run `get` again and reapply your edit. - -- **Commit** `workflow.ts`, `functions/`, `.sim/lock.json`, `.sim/base.json`, `.sim/written.json`, `tsconfig.json` and `.gitattributes`. CI finds the workflow from `workflowId` in `.sim/base.json`, and `status` and `get` use `.sim/written.json` to tell your edits apart from what the CLI last wrote. -- **Optionally gitignore** `.sim/sdk/`, the generated type declarations of the blocks in use (a few dozen files); `get` and `check` write them again. Gitignore `tsconfig.full.json`, which names the CLI's cache on your machine; `check` writes it again. A single-workflow directory gets no `.gitignore`, so add the lines yourself. -- **A whole workspace** in one repository, with dry runs on pull requests, apply on merge and promotion from one workspace to another, is covered in [Git and CI](/workflows/workspace-code#git-and-ci) and [Promote to another workspace](/workflows/workspace-code#promote-to-another-workspace). -- **Git provenance:** in a git repository, `apply` and `create` send the commit checked out (`HEAD`) and the `origin` remote URL, with any credentials, query or fragment removed, as `provenance.gitSha` and `provenance.repo`, each only when `git` can read it (a repository with no `origin` sends only the commit). A saved write records what was sent in its [audit log](/platform/enterprise/audit-logs) entry (`workflow.updated` or `workflow.created`). A directory outside a repository sends neither. -- **Credentials:** use a personal API key (**Settings → Sim API keys**, passed as `SIM_API_KEY`) or an OAuth login, not a workspace API key. Saving and dry-running source act as a person, so a workspace key is refused with `403`. Set `SIM_WORKSPACE` unless you pass `--workspace`, and `SIM_ENDPOINT` if you use a self-hosted Sim. See [Authenticating CI](/cli/authentication#authenticating-ci). - -## Working with other people - -- If someone changes the workflow after you read it, the save (or `--dry-run`) is refused with exit code `5` and nothing is overwritten. Run `get` into a new directory, reapply your edit, and save. -- Locked blocks cannot be changed from the file. Unlock them in the workflow builder first. -- Removing a block that serves a live webhook, schedule, chat, or MCP tool warns you: the deployed version keeps serving it until the next deploy. - -## Limits and known gaps - -- The file holds block declarations and connections only. Helper functions, loops that create blocks, and imports are refused; use Loop, Condition, and Workflow blocks instead. -- Function code is one file per block, with no imports between files. -- A change anyone makes while you edit means reading the workflow again; there is no automatic merge. -- Workflows run in Sim, not locally. `--dry-run` checks everything a save checks, without running the workflow. -- A workflow can have up to 2,000 blocks and 2,000 variables, and its source up to 4 MB across `workflow.ts` and its function files together. A larger workflow is refused when you read or save it, and the CLI exits with code `7`. - -To keep the tables, knowledge bases, tools and skills a workflow uses in the same directory, see [Workspace as code](/workflows/workspace-code). - -See [CLI workflow commands](/cli/workflows) for every flag. diff --git a/apps/docs/content/docs/workflows/code/adopt.mdx b/apps/docs/content/docs/workflows/code/adopt.mdx new file mode 100644 index 00000000000..1ac43570882 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/adopt.mdx @@ -0,0 +1,84 @@ +--- +title: Bring existing workflows into code +description: Put workflows built in the workflow builder into git, keep editing them in the builder, and decide who owns each change. +--- + +Result: workflows you built in the workflow builder kept in a git repository, with edits from the builder and from the files brought together instead of overwritten. + +Nothing has to be converted. Every workflow already has a source form: `get` prints it, and the workflow keeps its ID, block IDs, webhook URLs, schedules and run history. + +## Choose what to put in git + +- **One workflow**: `sim workflows source get --dir ` writes one workflow directory. Use it when a few workflows change through code and the rest stay in the builder. +- **A whole workspace**: `sim workspaces source get --dir ` writes the workflows together with the tables, knowledge bases, files, custom tools, skills, MCP servers, secret names and credential keys they use. Use it when the repository should describe the workspace, so one apply can create what a workflow needs before the workflow. + +A workspace directory manages only the kinds whose folder or file it holds: to leave one kind in the builder only, read the rest with `--only`, such as `--only tables,workflows`. + +## 1. Read the workflows + +```bash +sim workspaces source get --dir ./workspace +``` + +`get` names everything it could not write, such as a resource over a [limit](/workflows/code/limits), and lists it in `.sim/skipped.json`. Each workflow lands in `workflows//workflow.ts`, keyed by its name. + +## 2. Confirm the files match Sim + +```bash +sim workspaces source check --dir ./workspace +sim workspaces source status --dir ./workspace +``` + +A fresh `get` applies back unchanged, so `check` reports no errors and `status` exits `0` until someone edits either side. A warning on a block you have not changed does not fail the check: it describes a value the workflow already stores, such as a required field left empty in the builder. Fix it in the file when you next change that block. + +## 3. Commit the directory + +Commit everything `get` wrote, `.sim/` included. The `.sim/` files are how a later apply recognizes each block and resource and knows which version you read. [Directory layout](/workflows/code/directory) lists what to commit for each kind of directory. + +## 4. Change it from the files + +Make the first change through the loop in [Edit a workflow](/workflows/code/edit) or [Manage a workspace as code](/workflows/code/workspace), then commit the files the apply rewrote. To review changes on pull requests and apply them on merge, see [Run in CI](/workflows/code/ci). + +## Keep editing in the workflow builder + +The builder stays fully editable. Its **Code** tab shows the same workflow as read-only source. The files and the builder never overwrite each other silently: + +- A builder edit since the `get` is **drift**: `status` exits `12`. When the directory holds no unapplied edits, its `Next:` line is a `get` into the same directory, which brings the files up to date. Commit them. +- When the files and the builder changed the same workflow, it is a **conflict**: an apply is refused with exit `5` and writes nothing; see [Exit 5](/workflows/code/troubleshooting#exit-5). There is no automatic merge. +- In a workspace directory, drift on a resource you did not edit is kept: the apply writes your changes and leaves the other resource as Sim holds it (`W_SERVER_CHANGED`). + +To find drift before an apply does, run `status` on a schedule; see [Detect drift on a schedule](/workflows/code/ci#detect-drift-on-a-schedule). + +## What stays in the builder + +Block positions, values in fields the current settings hide, and your comments stay in the stored workflow, and an apply keeps them; [How it works](/workflows/code/how-it-works#the-canonical-form) has the rules. An apply saves the draft only: deploy with `apply --deploy` or `sim workflows deploy`, or, in a workspace directory, with a file in `deployments/`. + +## Agree on who changes what + +Decide per workflow where its changes are made, and write it down for the team: + +- **Files first**: changes go through pull requests, and the builder is for viewing and quick fixes that someone brings back with a `get`. Run the scheduled drift check. +- **Builder first**: the repository is a record. Refresh it with a `get` on a schedule or after a change, and open a pull request with what changed. + +Locked blocks cannot be changed from the files, by anyone. Lock a block in the builder to keep it out of reach of an apply. + +## Roll back + +- **The deployed version**: `sim workflows rollback ` (workspace Admin) makes the previous deployment live again and leaves the draft and the directory as they are. +- **The draft, from a deployment**: `sim workflows revert create --yes` replaces the draft with that deployed version. The directory then has drift (`status` exits `12`); `get` brings it up to date. +- **The draft, from git**: restore the source files of an earlier commit but keep the current `.sim/`, then apply: + + ```bash + git restore --source= -- ./support-triage ':(exclude,glob)support-triage/**/.sim/**' + sim workflows source apply --dir ./support-triage --dry-run + ``` + + Applying an earlier commit as a whole, `.sim/` included, is refused as stale (exit `5`), because its `.sim/base.json` records an older version than Sim holds. A block or resource deleted since that commit comes back as a new one, without its run history, webhook URLs or schedules, and blocks added since are deletes the apply refuses without `--allow-delete`. + +## Related docs + +- [Edit a workflow](/workflows/code/edit) +- [Manage a workspace as code](/workflows/code/workspace) +- [Run in CI](/workflows/code/ci) +- [How it works](/workflows/code/how-it-works) +- [Troubleshooting](/workflows/code/troubleshooting) diff --git a/apps/docs/content/docs/workflows/code/ci.mdx b/apps/docs/content/docs/workflows/code/ci.mdx new file mode 100644 index 00000000000..121c7392e0c --- /dev/null +++ b/apps/docs/content/docs/workflows/code/ci.mdx @@ -0,0 +1,183 @@ +--- +title: Run in CI +description: Dry-run source on pull requests, apply on merge, comment the plan, detect drift on a schedule, and promote, with GitHub Actions recipes. +--- + +Result: a pull request that shows what an apply would change, an apply on merge, and a scheduled check that tells you when someone edited the workspace in Sim. + +## Credentials + +Saving and dry-running source act as a person. Use a personal API key (**Settings → Sim API keys**, passed as `SIM_API_KEY`) or an OAuth login. A workspace API key is refused with `403` for workflows, and for a workspace directory it can apply only the kinds it can write; see [Workspace API keys](/workflows/code/workspace#workspace-api-keys). Set `SIM_WORKSPACE` unless you pass `--workspace`, and `SIM_ENDPOINT` if you use a self-hosted Sim. See [Authenticating CI](/cli/authentication#authenticating-ci). + +## What to commit + +- **A workflow directory:** commit `workflow.ts`, `functions/`, `.sim/lock.json`, `.sim/base.json`, `.sim/written.json`, `.sim/stored-edges.json`, `tsconfig.json` and `.gitattributes`. CI finds the workflow from `workflowId` in `.sim/base.json`, and `status` and `get` use `.sim/written.json` to tell your edits apart from what the CLI last wrote. Gitignore `tsconfig.full.json`; `.sim/sdk/` is optional. +- **A workspace directory:** commit everything, including `.sim/`. Its generated `.gitignore` leaves out only temporary files. + +[Directory layout](/workflows/code/directory) lists every file. + +## One workflow + +Run `sim workflows source apply --dir --dry-run` on pull requests. It exits `0` when the workflow is valid, `1` when it has errors, and `5` when the workflow was changed in the workflow builder after you committed the directory, so a failing check blocks the merge. `check` is not needed: the dry run runs every check a save runs, and `check` fails on a fresh runner that has no cached block catalog. + +```yaml title=".github/workflows/sim-workflow.yml" +on: + pull_request: + paths: ['support-triage/**'] + +permissions: + contents: read + +jobs: + dry-run: + runs-on: ubuntu-latest + env: + SIM_API_KEY: ${{ secrets.SIM_API_KEY }} + SIM_WORKSPACE: ${{ vars.SIM_WORKSPACE }} + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: 24 + - uses: oven-sh/setup-bun@v2 + - run: bun add -g sim + - run: sim workflows source apply --dir support-triage --dry-run +``` + +## A workspace + +Keep a [workspace directory](/workflows/code/workspace) in a repository, `.sim/` included, and let CI plan each pull request and apply each merge. The dry run exits `1` on errors, `5` when the workspace changed since the committed base, and `15` when the apply would hold back changes that use a secret with no value or a credential nothing binds to. `check` downloads the block catalog once on a fresh runner. On GitHub Actions (`GITHUB_ACTIONS=true`), every source command also annotates each error and warning at its file and line, so they show inline on the pull request, and an `apply` (a dry run too), `create` and `status` append the plan and errors to the job's step summary. `--summary-file ` (or `SIM_SUMMARY_FILE`) also writes the same Markdown to a file on any CI, replacing it each run. + +```yaml title=".github/workflows/sim-workspace.yml" +on: + pull_request: + paths: ['workspace/**'] + push: + branches: [main] + paths: ['workspace/**'] + +concurrency: sim-workspace + +permissions: + contents: write + +jobs: + workspace: + runs-on: ubuntu-latest + env: + SIM_API_KEY: ${{ secrets.SIM_API_KEY }} + SIM_WORKSPACE: ${{ vars.SIM_WORKSPACE }} + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: 24 + - uses: oven-sh/setup-bun@v2 + - run: bun add -g sim + - run: sim workspaces source check --dir workspace + - run: sim workspaces source apply --dir workspace --dry-run + - if: github.event_name == 'push' + run: sim workspaces source apply --dir workspace --yes + - if: ${{ !cancelled() && github.event_name == 'push' }} + run: | + git add -A workspace + if ! git diff --cached --quiet; then + git -c user.name=sim-bot -c user.email=sim-bot@users.noreply.github.com \ + commit -m "chore(workspace): files the apply rewrote [skip ci]" + git push + fi +``` + +`check` runs first because it is fast and, after a one-time catalog download, needs no server: it compiles every workflow and type-checks the directory after regenerating `.sim/sdk/workspace.d.ts`, so resources the pull request adds are typed. Each finding is also a GitHub annotation at its line. Apply rewrites files under the directory (each `.sim/base.json`, ids it allocated, values the server normalized), and the next apply compares with them, so the last step commits them back to the branch; `[skip ci]` keeps that commit from running the job again. That step runs even when the apply failed (`!cancelled()`), because an apply can fail having written part of its plan: exit `15` means it held back changes that use a secret with no value or a credential nothing binds to and applied the rest, and exit `8` means it stopped part-way. Either way the directory records what was written, so committing it keeps the next run from being refused as stale (exit `5`) for resources this run wrote; the job still fails, so set the secret, connect the credential or fix the failure, and push again. Where the branch is protected, run `sim workspaces source get --dir workspace` on a new branch instead and open a pull request. + +After merging two branches that each applied, a dry run with no changes means the files match the workspace. Exit `5` means a resource changed since this branch's base: get the workspace into a fresh directory and carry the edit over. Exit `10` means another apply is writing the workspace (or another command is using the directory), so retry; the `concurrency` key keeps two runs of this job from overlapping. Pull requests from forks do not receive repository secrets, so the dry run needs a branch in the same repository. + +### Comment the plan on the pull request + +The step summary appears on the run page, not in the pull request. To post the plan as one comment that later pushes edit instead of adding another, write the plan to a file with `--summary-file` in the step that runs the dry run and post that file, with `pull-requests: write` in `permissions`: + +```yaml + - if: github.event_name == 'pull_request' + env: + GH_TOKEN: ${{ github.token }} + run: | + status=0 + sim workspaces source apply --dir workspace --dry-run --summary-file plan.md || status=$? + gh pr comment "${{ github.event.pull_request.number }}" --edit-last --create-if-none --body-file plan.md + exit "$status" +``` + +Use this step in place of the plain dry-run step for pull requests. The comment lists the first 50 changes and errors and counts the rest. `--edit-last` edits the last comment from the same account, which is the Actions bot here, so do not post other comments from this token on the pull request. + +### Detect drift on a schedule + +A change made in Sim, such as a hotfix in the workflow builder, makes the next apply exit `5`. A scheduled job finds it first: `status` exits `12` when the server changed since the directory was read, and `11` when the committed directory holds edits no apply has saved, for example after a merge whose apply failed. + +```yaml title=".github/workflows/sim-drift.yml" +on: + schedule: + - cron: '17 6 * * 1-5' + workflow_dispatch: + +permissions: + contents: read + issues: write + +jobs: + drift: + runs-on: ubuntu-latest + env: + SIM_API_KEY: ${{ secrets.SIM_API_KEY }} + SIM_WORKSPACE: ${{ vars.SIM_WORKSPACE }} + GH_TOKEN: ${{ github.token }} + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: 24 + - uses: oven-sh/setup-bun@v2 + - run: bun add -g sim + - run: | + status=0 + sim workspaces source status --dir workspace --output json > status.json || status=$? + if [ "$status" -eq 0 ] || [ "$status" -eq 11 ] || [ "$status" -eq 12 ]; then + [ "$(jq -r .server status.json)" = checked ] || { echo "Sim was not checked: $(jq -r .note status.json)"; exit 1; } + fi + case "$status" in + 0) exit 0 ;; + 11|12) ;; + *) exit "$status" ;; + esac + run_url="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" + body="sim workspaces source status exited $status ($run_url). Run it locally for the changes and the next command." + gh label create sim-drift --force + number=$(gh issue list --label sim-drift --state open --json number --jq '.[0].number // empty') + if [ -n "$number" ]; then + gh issue comment "$number" --body "$body" + else + gh issue create --label sim-drift --title "Sim workspace drift" --body "$body" + fi +``` + +`status` exits `0` or `11` without asking Sim when the server is unreachable, so the job reads the `server` field of its JSON output and fails unless it is `checked`. To bring the change into git instead, run `sim workspaces source get --dir workspace` on a new branch and open a pull request. + +### Promote in CI + +To promote the same directory to a second workspace, add a step with `--to` before the step that commits the files back: + +```bash +sim workspaces source apply --dir workspace --to "$PROD_WORKSPACE_ID" --yes +``` + +The promotion writes `workspace/.sim/targets/.json`, what it left in that workspace. Committing it lets the next run tell a change made in that workspace since (kept, or exit `5` when the directory changed the same resource) from one to promote. See [Promote to another workspace](/workflows/code/promote). + +## Git provenance + +In a git repository, `apply` and `create` send the commit checked out (`HEAD`) and the `origin` remote URL, with any credentials, query or fragment removed, as `provenance.gitSha` and `provenance.repo`, each only when `git` can read it (a repository with no `origin` sends only the commit). A saved write records what was sent in its [audit log](/platform/enterprise/audit-logs) entry (`workflow.updated` or `workflow.created` for a workflow, `workspace.updated` for a workspace apply). A directory outside a repository sends neither. + +## Related docs + +- [Exit codes](/workflows/code/exit-codes) +- [Promote to another workspace](/workflows/code/promote) +- [Scripting](/cli/scripting) +- [Authenticating CI](/cli/authentication#authenticating-ci) diff --git a/apps/docs/content/docs/workflows/code/coding-agents.mdx b/apps/docs/content/docs/workflows/code/coding-agents.mdx new file mode 100644 index 00000000000..42ec35a8469 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/coding-agents.mdx @@ -0,0 +1,49 @@ +--- +title: Use with coding agents +description: What get gives a coding agent, how it edits and saves a workflow, and the MCP and API paths for the same operations. +--- + +Claude Code, Cursor, Codex and other coding agents work from a directory that `get` writes. + +## What get gives an agent + +- A **primer**, which opens `.sim/AGENTS.md`. `get` prints a short summary instead (the files written, the guide, and the `editLoop` command to run). It covers the edit loop, how block identity, references and renames work, failures and retries, test runs, deletes, deploy, exit codes, and the params of each builder the workflow already uses. +- **`.sim/AGENTS.md`**: the primer followed by a reference, by task. A workspace directory also gets `.sim/GUIDE-advanced.md`. +- **`.sim/examples/`**: one correct example of each common block to copy from. +- **`.sim/sdk/`**: the type declarations, with `.sim/sdk/INDEX.md` listing the builders. + +Point the agent at `.sim/AGENTS.md` before it edits. + +## The loop + +1. `sim workflows source get --dir ` writes the workflow and the guide. +2. Write every file the change needs. +3. Run one chained command, then fix whatever it reports in the next step: + + ```bash + sim workflows source check --dir && sim workflows source apply --dir --yes && sim workflows run --manual --input '{...}' + ``` + + A non-zero exit code stops the chain at the first failure. `apply` compiles the source and compares it with the saved draft again, so an agent can skip `--dry-run`. `check` also type-checks the directory, so the chain needs no separate `tsc`. People and CI use `apply --dry-run` to review the plan, and `status` shows what changed and what to run next. + +For a whole workspace, use `sim workspaces source` with the same steps; see [Manage a workspace as code](/workflows/code/workspace). + +## Look things up + +- `sim workflows source params ` prints a builder in brief (an example call, the required params with types, the optional ones by name and the outputs) from the cached block catalog without a request. `--full` prints every param with its type, options, default and doc. A legacy builder names the one that replaces it, and a namespace such as `gmail` lists its builders. +- `sim workflows source resources` lists the tables, knowledge bases, credentials, workflows, skills, custom tools, MCP servers and environment variable names the file can name. +- `sim workflows source catalog` shows the block catalog the source is checked against. + +## Exit codes and retries + +An agent can branch on the exit code: `5` means the workflow changed and it must `get` into a fresh directory, `14` means it forgot `--yes`, and `9` means wait a minute. See [Exit codes](/workflows/code/exit-codes). + +## Over MCP and the API + +`getWorkflowSource` returns a workflow as TypeScript source files with its `lock` and `base`. Edit the files and send them back, with the same `lock` and `base`, through `applyWorkflowSource`, first with `query: {"dryRun": true}`. One call replaces a batch of graph operations. See [MCP tools](/mcp/tools#workflow-source) and [Build and run workflows](/api-reference/build-and-run-workflows). + +## Related docs + +- [Edit a workflow](/workflows/code/edit) +- [File syntax](/workflows/code/syntax) +- [Directory layout](/workflows/code/directory) diff --git a/apps/docs/content/docs/workflows/code/create.mdx b/apps/docs/content/docs/workflows/code/create.mdx new file mode 100644 index 00000000000..eb571abb483 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/create.mdx @@ -0,0 +1,45 @@ +--- +title: Create a workflow +description: Start a new workflow from a starter file, check it, and create it from a directory. +--- + +Result: a new workflow created from a file, in the workspace you choose. + +## Steps + +1. Write a starter into an empty directory: + + ```bash + sim workflows source create --dir ./lead-intake --workspace + ``` + + Without `--dry-run` or `--yes` this creates nothing. It writes a starter `workflow.ts` with that workspace's type declarations, `tsconfig.json` and `.sim/AGENTS.md`, and records the workspace in `.sim/starter.json`. The file starts with the `// @sim-sdk 1` line and default-exports one `workflow('Name', {}, () => { ... })`. + +2. Edit the starter and check it as in [Edit a workflow](/workflows/code/edit). + +3. Create the workflow: + + ```bash + sim workflows source create --dir ./lead-intake --workspace --dry-run + sim workflows source create --dir ./lead-intake --workspace --yes + ``` + + The starter prints both commands with its workspace filled in. The command prints the new workflow ID and writes the same type declarations, `tsconfig.json`, and `.sim/` files that `get` writes, so you can continue editing with `apply`. + +A create goes to the starter's workspace whatever your default workspace, unless `--workspace` names another. Until the workflow is created the directory has no `.sim/base.json`, so `status`, `diff` and `apply` refuse it. + +If another workflow already has that name, the command exits `1` with `SOURCE_NAME_TAKEN`; pass `--name` to choose another. Without `--yes` and with no terminal to ask, `create` prints the plan, writes nothing and exits `14`. + +## Fork a workflow + +Copy its directory, delete the copy's `.sim/`, and create it under a new name. A copy has no stored workflow to take a saved secret from, so replace each `stored()` in the file, which `get` printed for a value it does not show, with `env.NAME` or the value; otherwise the create fails with `E_STORED_VALUE_MISSING`. + +```bash +sim workflows source create --dir ./copy --workspace --name "New name" --yes +``` + +## Related docs + +- [Get started](/workflows/code/get-started) +- [Edit a workflow](/workflows/code/edit) +- [Exit codes](/workflows/code/exit-codes) diff --git a/apps/docs/content/docs/workflows/code/diagnostics.mdx b/apps/docs/content/docs/workflows/code/diagnostics.mdx new file mode 100644 index 00000000000..cbd3060b1e0 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/diagnostics.mdx @@ -0,0 +1,379 @@ +--- +title: Diagnostic codes +description: Every error, warning and info code that workflow and workspace source report, grouped by where it comes from. +--- + +Every finding that `check`, `status` and `apply` print has a code. The first letter is its severity: `E_` is an error, `W_` a warning and `I_` information. An error refuses the apply and makes `check` exit `1`. A warning is reported and the apply saves the source as written, except where a row below says the apply refuses it as the matching `E_APPLY_…` error. Information never blocks anything. + +A finding prints as `file:line:column` with the code around it and a hint; in `--output json` it is an entry of `diagnostics` (see [Scripting](/cli/scripting#exit-codes) for the shape). The codes are frozen at release, so a script can match on them. + +{/* workflow-code-docs:diagnostics:begin — generated by `bun run generate:workflow-code-docs`; do not edit between markers */} + +### Workflow source + +#### Compile and print + +Reading and writing `workflow.ts`. + +| Code | Meaning | +| --- | --- | +| `E_SYNTAX` | Babel could not parse the file. | +| `E_INVALID_CHARACTER` | A NUL or an unpaired UTF-16 surrogate, raw or escaped in a string, in the file or a code file: a workflow cannot store either. | +| `E_NUMBER_NOT_FINITE` | A number literal too large to store (`1e999` reads as `Infinity`). | +| `W_NUMBER_PRECISION` | A number literal whose digits a number cannot hold; write it as a string. | +| `E_SDK_HEADER` | Line 1 is not `// @sim-sdk N`. | +| `E_SDK_MAJOR` | The header's major is not the one the server reads. | +| `E_UNSUPPORTED_SYNTAX` | A construct outside this grammar; the hint names the supported form. | +| `E_WORKFLOW_EXPORT` | Not exactly one `export default workflow(…)`. | +| `E_LIMIT_EXCEEDED` | Over the block, edge, total-byte, depth or `codeFile()` reference cap (`SOURCE_LIMITS`). Apply answers 413. | +| `E_TOO_MANY_ERRORS` | The compile stopped after 100 errors; fix those and compile again to see the rest. | +| `I_FINDINGS_TRUNCATED` | 100 warnings, or 20 of one code, were listed and the rest omitted, so a flood of one finding never hides another. A finding repeated at the same place is listed once. Infos are capped apart (100, the rest dropped), so they never displace a warning, and errors are never displaced by either. An answer that merges findings from several stages is capped the same way as a whole; when that cuts it, it ends in one `I_FINDINGS_TRUNCATED` counting what it left out, in place of the stages' own. | +| `E_DUPLICATE_NAME` | Two blocks normalize to one key. | +| `E_RESERVED_NAME` | A block name normalizes to `loop`, `parallel` or `variable`. | +| `E_KEY_OVERRIDE` | A `meta.key` that is not a legacy key the stored workflow already has. | +| `E_EMPTY_NAME` | An empty block name. | +| `E_NAME_NOT_LITERAL` | A block or workflow name that is not a string literal. | +| `E_LOOKALIKE_NAME` | Two block names whose keys differ only by Unicode normalization (NFC vs NFD), or a block name with a word that mixes Latin letters with Cyrillic, Greek, Armenian or Cherokee ones (`Сlaude`); the message names the code point. | +| `W_LOOKALIKE_NAME` | A look-alike pair the stored workflow already holds, kept so it round-trips. | +| `W_SUSPICIOUS_CHARACTER` | A block or workflow name holds a bidi control or zero-width character. | +| `E_UNKNOWN_IDENTIFIER` | An identifier that names nothing in scope; the hint has a did-you-mean, says to write the value for a const refused for holding one, and points `process.env` at `env.NAME`. | +| `E_OUT_OF_SCOPE` | A ref or wiring into a sibling subflow's child. | +| `E_UNKNOWN_VARIABLE` | `vars.x` names no declared variable. | +| `E_DUPLICATE_VARIABLE` | Two variables with one key. | +| `E_VARIABLE_NAME_MISMATCH` | A variable's `name` does not normalize to its key. | +| `E_INVALID_ENV_NAME` | `env.X` with an invalid name. | +| `W_ENV_UNKNOWN` | `env.X`, or a code file `$env`, naming a variable the workspace does not hold (checked only when the env names are known); the hint has a did-you-mean. An offline check in a workspace directory knows only the names `secrets.ts` declares, so there the finding says `secrets.ts` does not declare it, and the hint points there. | +| `W_CHILD_INPUT_UNKNOWN` | A child workflow call's `inputMapping` sets an input the child's Start trigger does not declare (`sim workspaces source check`, with the child in the same directory); the hint names the nearest input. | +| `W_CHILD_NO_START` | A child workflow call names a workflow of the same directory that has no Start trigger (`sim workspaces source check`). | +| `W_CHILD_RESULT_PATH` | A reference to a child workflow call's `result.` whose child (in the same directory) ends at a Response block on every run, where `` is not `data`, `status` or `headers`: the child's result is its Response output, so the path reads nothing (`sim workspaces source check`); the hint names `result.data.`. The dry run reports the same reference as a `W_APPLY_LINT` warning. | +| `E_UNKNOWN_SUBFLOW_PROPERTY` | `p.` that a loop or parallel does not have. | +| `W_FORWARD_REF` | A ref to a block declared later; it resolves. | +| `W_REF_NOT_NORMALIZED` | Hand-written `` text that is not in key form. | +| `E_REF_UNREPRESENTABLE` | A reference to a block whose key holds a character a reference cannot carry (`Q&A`, `x>y`); rename the block. | +| `E_EDGE_SCOPE` | An edge across subflow scopes. | +| `E_EDGE_NOTE` | An edge to or from a note. | +| `E_TARGET_TRIGGER` | An edge into a trigger. | +| `E_NO_DEFAULT_OUTPUT` | `.to()` on a condition or router; wire a branch. | +| `E_DUPLICATE_EDGE` | The same edge twice. | +| `E_ERROR_PORT_UNSUPPORTED` | `onError` on a block with no error port. | +| `W_ERROR_PORT_STORED` | `onError` on a block with no error port (a loop or parallel) that the stored workflow already wires; kept so it round-trips. An offline check, which cannot read the stored workflow, reports it for any such edge between two blocks the lock binds: an apply keeps it only if the stored workflow holds it. | +| `E_UNKNOWN_BRANCH` | `x.key.to()` where `key` is not a branch of `x`. | +| `E_DUPLICATE_BRANCH_KEY` | Two rows with one key. | +| `E_BRANCH_KEY_COLLIDES` | A branch key equal to an output name, `to` or `onError`. | +| `E_BRANCH_ELSE_LAST` | Two or more condition rows that do not end with `else`. | +| `W_RAW_HANDLE` | `edge()` with a handle kept verbatim. | +| `W_SUBFLOW_HANDLE_SCOPE` | `edge()` from a loop or parallel's start handle to a block outside it (the executor runs it as the container's exit), or from another of its handles into its own child. The canvas never draws one; stored ones print this way so they round-trip. | +| `E_EDGE_CYCLE` | Wiring that closes a cycle among enabled blocks, a self-loop included: no block on it ever runs. Framed at the edge back to a block declared earlier, the one to remove; repeat work with `loop()`/`parallel()`. | +| `W_EDGE_CYCLE` | A cycle the stored workflow already holds, kept so it round-trips; none of it runs. An offline check reports it for a cycle among blocks the lock binds, which an apply keeps only if the stored workflow holds every edge of it. | +| `W_BRANCH_UNWIRED` | A condition or router branch no edge leaves, so a run that takes it ends there; the hint names the wiring. Not reported for a branch the stored workflow already leaves unwired. | +| `E_UNKNOWN_BUILDER` | A builder path the catalog does not have, a bare builder-shaped call (`apii('Name', …)`) nothing binds, or a namespace the SDK lacks or the file did not import; `hint` names the builder a common other name stands for (`http.request` → `api`), then prefers a synonymous verb (`postMessage` → `sendMessage`), then the closest path, then the namespace's builders. | +| `E_UNKNOWN_PARAM` | A param the block does not have; the hint has a did-you-mean, or for block meta written there (`retry`, `disabled`, `locked`, `errorPort`) the third argument that takes it. | +| `E_FIXED_PARAM` | A param the builder already pins. | +| `W_FIELD_NOT_APPLICABLE` | A param not visible under the block's values; apply keeps the stored value and the written-back source drops it. | +| `W_REQUIRED_MISSING` | A required field left empty, including `todo()`; not repeated for a field an `E_UNKNOWN_PARAM` did-you-mean names, or one written with a value that failed to compile. | +| `W_UNKNOWN_OPTION` | A dropdown value none of its options names; `hint` lists them. | +| `E_UNKNOWN_OPERATION` | An `operation` the block does not offer; `hint` lists them. A retired one the stored block holds is `W_UNKNOWN_OPTION`. | +| `W_UNKNOWN_MODEL` | A `model` the catalog does not list (kept: custom models are free text). | +| `W_LEGACY_BLOCK_TYPE` | A new block of a legacy or deprecated type; `hint` names the replacement's builders. | +| `I_SCHEDULE_UTC` | A schedule created from source with no `timezone`, which runs in UTC (the editor would have seeded the viewer's zone). | +| `E_STORED_VALUE_MISSING` | `stored()` where the stored workflow holds no value. | +| `W_VALUE_KIND` | A value whose JSON type differs from the field's. | +| `W_OUT_OF_RANGE` | A literal slider value outside the catalog `min`/`max`, off its `step`, or fractional where it takes whole numbers; kept as written, and the executor forwards it unclamped. | +| `W_TABLE_FILTER_SHAPE` | A literal table filter the runtime refuses: the legacy `$` operator grammar, or predicate and builder rows mixed. | +| `W_LITERAL_SECRET` | A password field (an API key, a token) holding literal text instead of an env reference, or any field holding a detected credential (a token format, an `Authorization` header, a credential-named property or query parameter); get prints it as `stored()`. For a literal token in a credential field, the hint says `credential('')`. | +| `W_SUBFLOW_COUNT` | A loop or parallel count, or a parallel batch size, the runtime replaces or clamps. | +| `W_UNKNOWN_OUTPUT_PATH` | A ref path the block's outputs do not have; the hint has a did-you-mean or lists the outputs. | +| `W_OUTPUT_PATH_UNDECLARED` | A path the block does not declare that the run still accepts: an undeclared `inputFormat` input, or `x.error` with no error edge. Never refused. | +| `W_JSON_REF_UNTYPED` | A bare ref in a JSON literal whose type nothing declares. | +| `W_LOOP_CONDITION_SYNTAX` | A while or do-while condition that is not a JavaScript expression once each reference stands in as a value, as the run evaluates it (`return Boolean()`): the run fails there. Refused as `E_APPLY_LOOP_CONDITION_SYNTAX` on a loop the edit added or changed. A loop reading its own `index` (or `currentItem`, `items`) by its name in its condition is `W_REF_OUT_OF_SCOPE`: the condition is evaluated outside the loop's body, so only `` reads the iteration there. | +| `W_REF_OUT_OF_SCOPE` | A loop or parallel iteration field (`index`, `currentItem`, `items`) read from a block outside that container: `lp.index` after the loop, `$ref.loop.index` or `` in a block in no loop. The run fails (or reads nothing) there. Refused as `E_APPLY_REF_OUT_OF_SCOPE` on a block the edit changed. | +| `W_UNKNOWN_BLOCK_TYPE` | A new block of a type the catalog does not hold; refused as `E_APPLY_INVALID_BLOCK_TYPE`. A block the stored workflow or the lock already holds keeps its type quietly. | +| `W_TYPE_NOT_ADDABLE` | A new block of a type the catalog keeps only for blocks already using it; refused as `E_APPLY_TYPE_NOT_ADDABLE`. | +| `E_CODE_FILE_MISSING` | `codeFile()` names a file the request did not send. | +| `E_CODE_FILE_PATH` | A code file path outside the directory, or with the wrong extension. | +| `W_CODE_FILE_INLINED` | Print: the code could not round-trip through a file and was inlined. | +| `W_CODE_FILE_REF_SYNTAX` | `$ref.key.path` or `$env.NAME` in a Python or shell code file, which runs as text; the hint names the `` or `{{NAME}}` form. Refused as `E_APPLY_CODE_FILE_REF_SYNTAX` in a file the edit changed. | +| `W_UNRESOLVED_REF` | Print: a stored `` token that resolves to nothing. Compile: a code file `$ref` chain that does. Either is kept as text. | +| `W_FORWARD_REF_LITERALIZED` | Print: a ref in a cycle printed as text. | +| `W_COMMENT_MOVED` | A comment hoisted to the nearest anchor. | +| `W_COMMENT_DROPPED` | A comment whose block no longer exists. | + +#### Lock and source meta + +Reading `.sim/lock.json`. Each finding names a JSON `path`. + +| Code | Meaning | +| --- | --- | +| `E_LOCK_JSON`, `E_SOURCE_META_JSON` | Not valid JSON. | +| `E_LOCK_VERSION`, `E_SOURCE_META_VERSION` | `version` missing or not `1`. | +| `E_LOCK_SHAPE`, `E_SOURCE_META_SHAPE` | A required field missing or of the wrong type or format. | +| `E_LOCK_UNKNOWN_FIELD`, `E_SOURCE_META_UNKNOWN_FIELD` | A field the schema does not define (`x-` keys are allowed). | +| `E_LOCK_KEY` | A block or variable key not in normalized form. | +| `E_LOCK_IDENT`, `E_SOURCE_META_IDENT` | An ident that is not a JS identifier, or is reserved. | +| `E_LOCK_DUPLICATE_IDENT`, `E_SOURCE_META_DUPLICATE_IDENT` | Two blocks with one ident. | +| `E_LOCK_DUPLICATE_ID` | One block, variable or branch id under two keys. | +| `E_LOCK_PARENT` | A parent naming no block, itself, or forming a cycle. | +| `E_LOCK_BRANCH` | A branch key that is not a JS identifier. | +| `E_LOCK_CODE_FILE_PATH` | A `codeFile` that is absolute, escapes the directory, or uses backslashes. | +| `E_SOURCE_META_ANCHOR` | A comment key that is not a valid anchor. | + +#### Canonicalize + +Reading the stored workflow in a get. + +| Code | Meaning | +| --- | --- | +| `E_CANON_LEGACY_NAME_COLLISION` | Two stored names normalize alike; the loser is keyed `key~n`. | +| `E_CANON_EDGE_SCOPE` | A stored edge crosses subflow scopes. | +| `W_CANON_RESERVED_NAME` | A stored name normalizes to a reserved key. | +| `W_CANON_DANGLING_EDGE` | A stored edge to a missing block; dropped. | +| `W_CANON_DANGLING_PARENT` | A parent that does not exist; the block is placed at the root and the raw parent kept. | +| `W_CANON_RAW_HANDLE` | An unknown edge handle, kept as a raw port. | +| `W_CANON_UNKNOWN_BLOCK_TYPE` | A type the catalog does not have; params kept. | +| `W_CANON_UNRESOLVED_ID` | A resource id with no key; kept verbatim. | +| `W_CANON_TITLE_OVERRIDE` | A branch title that differs from its positional title. | +| `W_CANON_SUBFLOW_REPAIRED` | A loop or parallel config the loader would repair. | +| `W_CANON_SUBBLOCK_TYPE_DRIFT` | A stored subBlock type differs from the catalog's. | +| `W_CANON_UNDECODABLE_JSON` | A stored JSON-text field that does not parse, kept as text; or a branch list that is not rows with distinct ids, kept verbatim. | + +#### Materialize + +Matching the compiled file to the stored blocks. + +| Code | Meaning | +| --- | --- | +| `E_MAT_DUPLICATE_LOCK_ID` | Two lock keys carry one block id. | +| `E_MAT_UNKNOWN_RESOURCE` | A resource key with no live resource in this workspace. | +| `E_MAT_UNKNOWN_VARIABLE` | A `vars.x` reference to a variable the workflow does not declare. | +| `W_MAT_DELETED_SINCE_PULL` | A lock entry whose block was deleted since the read; re-created. | +| `W_MAT_INFERRED_RENAME` | A rename inferred from type, parent and edges (the key and the ident both changed). | +| `W_MAT_RETYPE_RECREATED` | A key kept with a new type: delete plus create, so webhook URLs and schedules change. | +| `W_MAT_LOCK_ID_CLAIMED` | A lock id another workflow holds, ignored: the block binds to the stored block it matches, or gets a new id. | +| `I_MAT_NEEDS_LAYOUT` | A new block with no position, or one moved into or out of a loop or parallel; placed by autolayout. | + +#### Apply + +Saving the workflow draft. + +| Code | Meaning | +| --- | --- | +| `E_APPLY_STALE` | The workflow changed since the source was read (HTTP 409). | +| `E_APPLY_WORKFLOW_MISMATCH` | `base.workflowId` names another workflow (HTTP 400). | +| `E_APPLY_LOCKED_BLOCK` | The change touches a locked block or a child of a locked container. | +| `E_APPLY_TYPE_NOT_ADDABLE` | A new block of a type that may stay but not be added. | +| `E_APPLY_INVALID_STATE` | The resulting graph fails validation. | +| `E_APPLY_BLOCK_NOT_FOUND`, `E_APPLY_INVALID_BLOCK_TYPE` | A block or type the engine cannot place. | +| `E_APPLY_BLOCK_NOT_ALLOWED`, `E_APPLY_MODEL_NOT_ALLOWED`, `E_APPLY_TOOL_NOT_ALLOWED` | Refused by the workspace's permission group. | +| `E_APPLY_INVALID_EDGE_SOURCE`, `E_APPLY_INVALID_EDGE_SCOPE`, `E_APPLY_INVALID_SOURCE_HANDLE`, `E_APPLY_INVALID_TARGET_HANDLE` | An edge the engine refuses. | +| `E_APPLY_INVALID_SUBBLOCK_FIELD`, `E_APPLY_MISSING_REQUIRED_PARAMS` | A field the engine refuses, or required params missing. | +| `E_APPLY_RETRY_NOT_SUPPORTED` | A new or changed retry policy on a block that always runs once (triggers, human-in-the-loop, containers). | +| `E_APPLY_DUPLICATE_TRIGGER`, `E_APPLY_DUPLICATE_SINGLE_INSTANCE_BLOCK` | A second trigger or single-instance block. | +| `E_APPLY_DISABLED_ANCESTOR` | An enabled block inside a disabled container. | +| `E_APPLY_CREDENTIAL_UNREACHABLE` | A credential the acting user cannot use. | +| `W_APPLY_CREDENTIAL_KEPT` | A credential key the caller cannot resolve stands where the workflow stores a credential the caller cannot see; the stored one is kept, whatever the key. | +| `E_APPLY_SANDBOX_PLAN_REQUIRED` | The sandbox needs a plan the workspace does not have. | +| `W_APPLY_HOSTED_KEY_DROPPED` | A hosted key that does not apply was cleared. | +| `W_APPLY_VALUE_NORMALIZED` | Validation rewrote a value; the returned files show it. | +| `W_APPLY_TYPE_CHANGED` | A block's type changed; its id, webhook URL and schedules are replaced. | +| `W_APPLY_TRIGGER_REMOVED` | A deleted or retyped block still serves a live webhook, schedule, chat output or MCP tool until the next deploy. | +| `W_APPLY_CATALOG_MOVED` | Compile failed and the block catalog changed since the read: get the source again. | +| `E_APPLY_LINT`, `W_APPLY_LINT` | A workflow lint finding, mapped to a source line. | +| `E_APPLY_UNRESOLVED_REF` | A `$ref` naming no block or variable, or a path no output has, in code or a block the edit changed (`W_UNRESOLVED_REF`, `W_UNKNOWN_OUTPUT_PATH` elsewhere). | +| `E_APPLY_REF_OUT_OF_SCOPE` | A `W_REF_OUT_OF_SCOPE` iteration reference on a block the edit added, changed or moved. | +| `E_APPLY_CODE_FILE_REF_SYNTAX` | A `W_CODE_FILE_REF_SYNTAX` in a code file the edit changed. | +| `E_APPLY_LOOP_CONDITION_SYNTAX` | A `W_LOOP_CONDITION_SYNTAX` on a loop the edit added or changed. | +| `E_APPLY_BLOCK_DELETE` | The apply deletes blocks the source no longer declares; pass `--allow-delete`. When it also adds blocks of a deleted one's type, it names them as possible renames and says how to keep the ids. | +| `E_APPLY_VARIABLE_DELETE` | The apply removes workflow variables the source no longer declares; pass `--allow-delete`, as for blocks. | +| `W_APPLY_PROBABLE_RENAME` | With `--allow-delete`, a deleted block and an added one share a type and parent: a probable rename that gets a new id. | +| `E_NAME_TAKEN` | The `workflow('…')` name renames the workflow to one another workflow in its folder holds. | +| `E_WORKFLOW_META_INVALID` | The `workflow('…')` name is empty or over 255 characters, or its description is over 50,000 characters: limits the workflow API holds every workflow to. | +| `E_APPLY_INVALID_SCHEDULE` | An added or changed schedule whose cron, timezone or interval deploy would refuse. | +| `W_TABLE_UNKNOWN_COLUMN` | A table row write whose data names a key that is not a column of the table; the run drops it. The hint names the nearest column. | + +#### Type check + +`sim workflows source check` and `sim workspaces source check` type-checking the directory with TypeScript after the compile. The server never reports these. + +| Code | Meaning | +| --- | --- | +| `E_TYPE` | TypeScript (the release the declarations are built for) reported an error; the message starts with its `TS` code. A type error is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them). | +| `W_TYPES_UNCHECKED` | The type check did not run: TypeScript could not be installed (offline, or no `npm`) or did not start. The other findings stand; pass `--no-types` to skip it. | + +### Workspace source + +Workspace source reports every workflow code above for the files of `workflows//`, with that path as the file, and these codes for the rest of the directory. + +#### Declaration files and the directory layout + +| Code | Meaning | +| --- | --- | +| `E_DECL_SYNTAX` | A Babel parse error, re-coded. | +| `E_DECL_HEADER` | The first line is not `// @sim-sdk 1`. | +| `E_DECL_IMPORT` | An import from anything but `@sim/workflow-sdk/workspace`, or a non-named import. | +| `E_DECL_EXPORT` | Not exactly one `export default defineX({ … })` with the kind's `defineX`. | +| `E_DECL_UNSUPPORTED` | A construct outside the declaration grammar: JSON literals, the kind's helper calls. | +| `E_DECL_DUPLICATE_KEY` | An object key declared twice. | +| `E_DECL_SHAPE` | A required field is missing, or a field has the wrong type. | +| `E_DECL_UNKNOWN_FIELD` | A field the kind does not define. | +| `E_DECL_UNKNOWN_FILE` | A path inside a kind's folder that no resource owns. | +| `W_PATH_NOT_SENT` | A file under a kind's folder whose path no workspace holds (a hidden name such as `.env`, or a character such as `:` or `?`): the CLI does not send it, so an apply neither writes nor deletes anything for it. | +| `E_BLOB_MANIFEST` | A blob manifest entry listed twice, or at a path that holds no binary file: the apply writes nothing. | +| `E_BLOB_MISSING` | A binary file a write needs whose bytes are not staged (or were staged at another size): the apply writes nothing. Stage it, then apply again. | +| `E_KEY_INVALID` | A resource key outside `^[a-z][a-z0-9_-]{0,63}$`. | +| `W_DECL_SUSPICIOUS_CHARACTER` | A resource name, a skill name, a workspace file path or a knowledge document name holds a bidi control or zero-width character, so it reads differently from what it stores. The workflow-file counterpart is `W_SUSPICIOUS_CHARACTER`. | + +#### `.sim/base.json` + +| Code | Meaning | +| --- | --- | +| `E_BASE_JSON` | The base is not valid JSON. | +| `E_BASE_VERSION` | `version` is missing or not `1`. | +| `E_BASE_SHAPE` | A required field is missing or of the wrong type or format. | +| `E_BASE_UNKNOWN_FIELD` | A field the base does not define (`x-` keys are allowed). | + +#### Secrets (`secrets.ts`) + +| Code | Meaning | +| --- | --- | +| `E_SECRET_NAME` | A declared name outside the secret name format. | +| `E_SECRET_MISSING` | A workflow uses a declared secret the workspace holds no value for: it is held back. | +| `W_SECRET_MISSING` | A declared secret the workspace holds no value for. | + +#### Credentials (`credentials.ts`) + +| Code | Meaning | +| --- | --- | +| `E_CREDENTIAL_MISSING` | A workflow uses a declared key no credential of its provider binds to: it is held back. | +| `E_CREDENTIAL_AMBIGUOUS` | A workflow uses a declared key several credentials could bind to: it is held back. | +| `W_CREDENTIAL_MISSING` | A declared key no credential of its provider binds to. | +| `W_CREDENTIAL_AMBIGUOUS` | A declared key several credentials could bind to. | + +#### Tables + +| Code | Meaning | +| --- | --- | +| `E_TABLE_COLUMN_NAME` | A column key or name outside the table name pattern. | +| `E_TABLE_DUPLICATE_COLUMN` | Two columns resolve to one name. | +| `E_TABLE_TOO_MANY_COLUMNS` | More columns than a table may hold: a size limit, classed like `E_LIMIT_EXCEEDED`. | +| `E_TABLE_OPTIONS` | A select column without options, an option declared twice, or options on another type. | +| `E_TABLE_TYPE_CONVERSION` | A type change the stored cells cannot convert to. | +| `E_TABLE_FOLDER` | A table folder that does not exist in the workspace. | +| `E_TABLE_ROWS` | The declaration's `rows` or its `tables/.rows.jsonl`: a bad mode or key column, a line that is not a row of declared columns, a managed row without its key or repeating one. | +| `I_TABLE_SEED_SKIPPED` | Seed rows declared for a table that already holds rows: only a new or empty table is seeded. | +| `I_TABLE_ROWS_UNKEYED` | Managed rows whose key cell is empty (a row the table's "add row" made and nobody keyed): no file line can name them, so a get leaves them out and an apply keeps them as they are. | +| `W_LIKELY_RENAME` | A column dropped and one of the same type added: probably a rename, which loses the cells. | + +#### Custom tools + +| Code | Meaning | +| --- | --- | +| `E_TOOL_SCHEMA` | The schema is not a function declaration a custom tool may store. | +| `E_TOOL_CODE` | `code` is not `codeFile('./.js')`, a string or `stored()`, or its code file is missing or does not parse. | +| `E_TOOL_STORED_MISSING` | `code: stored()` for a tool the server holds no code of (none stored under the key or title). | +| `W_TOOL_LITERAL_SECRET` | The code holds what looks like a literal credential (`holdsSecret`, as for function code): a get prints it as `stored()`, and code a directory writes with one applies with this warning. | + +#### Skills + +| Code | Meaning | +| --- | --- | +| `E_SKILL_FRONTMATTER` | `skills/.md` does not open with a frontmatter block of `name` and `description`. | + +#### MCP servers + +| Code | Meaning | +| --- | --- | +| `E_MCP_LITERAL_SECRET` | A credential header (`Authorization`, `X-Api-Key`, …) holds literal text, not an env reference. | +| `E_MCP_STORED_MISSING` | `stored()` names a header the stored server holds no value for. | +| `E_MCP_TOOL_UNKNOWN` | A workflow names a tool the MCP server does not list. | +| `W_MCP_REPLACE` | A changed URL replaces the server: a new server id, the old one deleted. | +| `W_MCP_TOOLS_UNCHECKED` | The server's tools could not be listed, so the tool names workflows use are not checked. | + +#### Workspace files + +| Code | Meaning | +| --- | --- | +| `E_FILE_PATH` | A path no workspace file may have: a dot or empty segment, a reserved name or character. | +| `E_FILE_PATH_COLLISION` | Two paths that differ only in letter case, or a path that is both a file and a folder. | +| `E_FILE_NAME` | A name the server would store differently (trimmed, whitespace collapsed, NFC). | +| `E_FILE_TOO_LARGE` | A file over the per-blob cap: a get skips it and an apply never writes it. | +| `E_FILE_CONTENT` | A workspace file sent as text, or listed without a valid SHA-256 and size. | + +#### Knowledge bases + +| Code | Meaning | +| --- | --- | +| `E_KB_EMBEDDING_IMMUTABLE` | A declared embedding model that differs from the stored one: it is fixed at creation. | +| `E_KB_EMBEDDING_MODEL` | A new knowledge base declares a model this server does not create knowledge bases with. | +| `E_KB_DOC_AMBIGUOUS` | The server holds several documents under one declared file name. | +| `E_KB_DOC_NAME` | A document file name or type the knowledge base cannot hold. | +| `E_KB_DOC_EMPTY` | An empty document, which a knowledge base cannot index. | +| `E_KB_CHUNKING` | Chunking settings outside what a knowledge base accepts. | +| `E_KB_FOLDER` | A knowledge base folder that does not exist in the workspace. | +| `W_KB_DOC_UNCHECKED` | A stored document whose bytes this request had no budget left to download and compare. | +| `W_KB_DOC_FAILED` | Documents whose indexing failed: search does not find them until they are indexed again. | +| `I_KB_REEMBED` | How many documents the apply indexes (embeds) after it writes them. | +| `I_KB_CHUNKING` | Changed chunking applies to documents indexed from now on; stored ones keep their chunks. | +| `I_KB_PROCESSING` | Documents still waiting to be indexed or being indexed: search finds them once that ends. | +| `I_KB_DOCS_UNHASHED` | Documents a get lists without a hash: it had no budget left to download them. | +| `I_KB_UNMANAGED_DOCS` | Documents source leaves alone: connector-synced, too large, or not a plain file name. | +| `I_KB_REPLACE_UNFINISHED` | A replace that stopped partway left a replacement document (under its upload name): the next apply that changes the knowledge base finishes the replace, or removes the replacement. | + +#### Deployments + +| Code | Meaning | +| --- | --- | +| `E_DEPLOY_WORKFLOW` | `deployments/.ts` names no workflow this workspace holds or this directory declares. | +| `E_DEPLOY_SECRET` | A chat password written as a value instead of `env.NAME`, an unset variable, or `stored()` where no password is stored. | +| `E_DEPLOY_CHAT_OUTPUT` | A chat output names a block the workflow does not have. | +| `E_DEPLOY_CHAT_IDENTIFIER` | A chat identifier another live chat already holds. | +| `E_DEPLOY_PINNED_CHAT` | A chat change on a pinned deployment whose draft differs: deploying a chat publishes it. | +| `W_DEPLOYED_DRAFT_CHANGED` | An apply edits a deployed workflow that no `live: 'draft'` deployment republishes. | +| `W_DEPLOY_DRAFT_NOT_SOURCE` | A `live: 'draft'` deployment whose draft holds edits the directory does not declare (made in the editor, say): the apply does not publish it. | +| `E_DEPLOY_DRAFT_NOT_SOURCE_CHAT` | A chat change while the draft holds edits the directory does not: deploying a chat publishes it. | +| `I_DEPLOY_DRAFT_NOT_LIVE` | A pinned deployment's draft differs from its live version, which keeps running. | + +#### Plan and apply + +| Code | Meaning | +| --- | --- | +| `E_APPLY_NO_BASE` | The server holds the resource but the directory has no base for it: get it first. | +| `E_APPLY_FORBIDDEN` | The caller may not make this change. | +| `E_APPLY_DELETE_NOT_ALLOWED` | The change deletes a resource or data and `--allow-delete` was not given. | +| `E_APPLY_LOCKED` | The resource is locked against this change (HTTP 423). | +| `E_APPLY_REFUSED` | A change a child operation refused, with its message. | +| `E_APPLY_FAILED` | A write failed for a reason that is not the source's (logged on the server). | +| `E_PLAN_TOO_LARGE` | The apply would make more changes or touch more workflows than one request may. | +| `E_PLAN_REF_DELETED` | A declared resource references one this apply deletes. | +| `E_PLAN_REF_HELD` | A declared resource references one this apply holds back, so it is held back too. | +| `W_RESOURCE_IN_USE` | A resource this apply deletes is still used by stored workflows. | +| `W_TABLE_COLUMN_RENAMED_IN_USE` | A table column this apply renames is still written, filtered or sorted by its old name in a stored workflow's Table block, which the run then drops. | +| `E_WORKFLOW_FILES_MISSING` | A workflow folder sent without its files whose base names no workflow of this workspace. | +| `E_WORKFLOW_FOLDER_COPIED` | A workflow folder holding the base of another declared folder's workflow: a copy. | +| `W_UNDECLARED` | A resource the server holds that the directory does not declare (kept without `--allow-delete`). | +| `W_BASE_OTHER_WORKSPACE` | The directory's base was read from another workspace: every resource is created anew. | +| `W_PROMOTE_TARGET_DELETED` | A promotion (`apply --to`) keeps deleted a resource the directory declares that the target deleted since the last promotion: the target no longer holds it. | +| `W_PROMOTE_DELETES_TARGET_ONLY` | A promotion with `--allow-delete` deletes a resource only the target holds (the directory does not declare it). | +| `W_SERVER_CHANGED` | The server changed a resource the directory leaves alone; the apply keeps it. | +| `W_SERVER_DELETED` | The server deleted a resource the directory leaves as it was; it is not created again. | +| `W_SERVER_MOVED` | The server moved a resource the directory leaves as it was; it is not created again. | +| `I_KEY_REBOUND` | A key bound to a deleted resource was bound to the one this apply wrote. | +| `E_KEY_RENAMED` | A declaration under a new key for a resource the base read under another: keys never move. | + +#### Shared with workflow source + +A workspace finding with the same meaning as a workflow finding uses its code. + +| Code | Meaning | +| --- | --- | +| `E_APPLY_STALE` | The workflow changed since the source was read (HTTP 409). | +| `E_LIMIT_EXCEEDED` | Over the block, edge, total-byte, depth or `codeFile()` reference cap (`SOURCE_LIMITS`). Apply answers 413. | +| `E_NAME_TAKEN` | The `workflow('…')` name renames the workflow to one another workflow in its folder holds. | +| `I_FINDINGS_TRUNCATED` | 100 warnings, or 20 of one code, were listed and the rest omitted, so a flood of one finding never hides another. A finding repeated at the same place is listed once. Infos are capped apart (100, the rest dropped), so they never displace a warning, and errors are never displaced by either. An answer that merges findings from several stages is capped the same way as a whole; when that cuts it, it ends in one `I_FINDINGS_TRUNCATED` counting what it left out, in place of the stages' own. | + +{/* workflow-code-docs:diagnostics:end */} + +## Related docs + +- [File syntax](/workflows/code/syntax) +- [Exit codes](/workflows/code/exit-codes) +- [Limits](/workflows/code/limits) diff --git a/apps/docs/content/docs/workflows/code/directory.mdx b/apps/docs/content/docs/workflows/code/directory.mdx new file mode 100644 index 00000000000..e51c6068209 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/directory.mdx @@ -0,0 +1,89 @@ +--- +title: Directory layout +description: Every file a workflow directory and a workspace directory holds, who writes it, and what to commit. +--- + +`get` writes a directory, and every later command reads and rewrites it. Keep the `.sim/` folder: it is how Sim recognizes each block and resource again, and how an apply knows what version you read. + +## Workflow directory + +`sim workflows source get --dir ` writes: + +| Path | What it is | In git | +| --- | --- | --- | +| `workflow.ts` | The workflow, in [file syntax](/workflows/code/syntax) | Commit | +| `functions/` | One file per Function block's code | Commit | +| `.sim/lock.json` | Ties each block in the file to the stored block, so renaming a block keeps its webhook URL, schedules and run history | Commit | +| `.sim/base.json` | The workflow ID and the version you read | Commit | +| `.sim/written.json` | A digest of each file as the CLI last wrote it, so `status` and `get` tell your edits from the CLI's | Commit | +| `.sim/stored-edges.json` | The connections the stored workflow held when it was printed, so an offline `check` tells them from connections you added. The CLI's own record, never sent | Commit | +| `.sim/starter.json` | The workspace a starter was written for, before `create` | Not kept: removed once the workflow exists | +| `.sim/AGENTS.md` | The guide for coding agents: the primer, then a reference | Optional, written again by `get` | +| `.sim/examples/` | Example workflows to copy from | Optional, written again by `get` | +| `.sim/sdk/` | Type declarations for the blocks the workflow uses, and your workspace's tables, credentials, knowledge bases and environment variable names. `.sim/sdk/INDEX.md` lists the builders | Optional, written again by `get` and `check` | +| `tsconfig.json` | Resolves the declarations and type-checks the blocks the workflow uses. Left as it is if you already have one | Commit | +| `tsconfig.full.json` | Type-checks every block through the CLI's cache | Ignore: it names the cache on your machine, and `check` writes it again | +| `.gitattributes` | Keeps the source files on LF line endings | Commit | + +The declarations of every block are generated once per block catalog into the CLI's cache, `~/.sim/cache/source-catalog/`, and shared by every directory. A workflow directory gets no `.gitignore`, so add the lines for what you ignore. + +While a command runs it holds `.sim/command.lock/`, so two commands on one directory never interleave. A second one exits `10`. + +## Workspace directory + +`sim workspaces source get --dir ` writes one folder per kind of resource. A kind is managed only when its folder or file exists. + +``` +secrets.ts the env variable names workflows read (never a value) +credentials.ts the saved credentials workflows use, by provider +tables/orders.ts a table: name, description, columns +tables/plans.rows.jsonl a table's rows, one JSON object per line (only when the table opts in) +knowledge/policies/knowledge.ts a knowledge base: name, chunking +knowledge/policies/docs/*.md one file per document +files/templates/reply.md a workspace file, at its folder path +tools/lookup-order.ts a custom tool: title and schema +tools/lookup-order.js the tool's code +skills/tone.md a skill: name and description, then its content +mcp/docs.ts an MCP server: url, headers +workflows/support/workflow.ts a workflow directory +deployments/support.ts how workflows/support is deployed +``` + +A resource's key is its file or folder name, and a workflow names it by that key. Every `.ts` file starts with the line `// @sim-sdk 1`, a deployment included; the one-line forms below show only the call. What each kind's file holds: + +{/* workflow-code-docs:directory-kinds:begin — generated by `bun run generate:workflow-code-docs`; do not edit between markers */} + +- `secrets.ts`: `export default defineSecrets({ NAME: { description? } })`, the workspace secrets workflows read, by name and description only (never a value: set one with `sim secrets set NAME --scope workspace`). A workflow: `env.NAME`; one using a declared secret the workspace has no value for is held back, and the rest apply. +- `credentials.ts`: `export default defineCredentials({ : { provider, name? } })`, binding each key to this workspace's credential for that provider (never a token): the one bound already, else the only one, else the one whose display name is `name`. A workflow: `credential('')`; one using a key no credential binds to is held back, and the rest apply. +- `tools/.ts` (`defineTool({ title, schema, code: codeFile('./.js') })`) and its code in `tools/.js`, where each schema parameter is a variable. Code holding a literal credential prints as `code: stored()`, which keeps the stored code. A workflow: `customTool('')`. +- `skills/.md`: a frontmatter block of `name` and `description`, then the content. A workflow: `skills: [skill('')]` on an agent. +- `mcp/.ts`: `export default defineMcpServer({ name?, url, headers?, auth?, timeout?, retries?, enabled? })`. A credential header holds `env.NAME` or `'Bearer {{NAME}}'`, never a literal secret; `stored()` keeps the value the server holds. A new host or path in `url` replaces the server; a new query string updates it in place. A workflow: `mcp('').tool('')`. +- `tables/.ts`: `export default defineTable({ name, description?, folder?, columns: { … } })` with `column.string()`, `column.number()`, `column.select({ options: [...] })`, … from `@sim/workflow-sdk/workspace`. Rows stay out of source unless `rows` opts in: `{ mode: 'managed', key: '' }` keeps the rows equal to `tables/.rows.jsonl` (one JSON object per line, keyed by column key), `{ mode: 'seed' }` writes them once into a new table. A workflow: `table('')`. +- `knowledge//knowledge.ts` (`defineKnowledgeBase({ name, description?, folder?, chunking?, embeddingModel? })`) and `knowledge//docs/`, one file per document, flat. A workflow: `knowledgeBase('')`. Connector-synced documents are never part of source. +- `files/`: every file is one workspace file at that folder path; no declaration. +- `workflows//`: one workflow each, exactly a `sim workflows source get --dir` directory (`workflow.ts`, `functions/*`, `.sim/lock.json`, `.sim/base.json`). +- `deployments/.ts`: `defineDeployment({ live: 'draft' | 'pinned', api?: { public? }, chat? })` deploys `workflows//`, so its schedule, webhook, API and chat triggers run. `live: 'draft'` publishes the draft whenever it differs from the live version; `'pinned'` never redeploys and says when the draft differs. A chat password is `env.NAME` (or `stored()` to keep the stored one); chat outputs name a block by its name. Removing the file undeploys the workflow (needs `--allow-delete`). Deploying needs workspace admin, never a workspace API key. MCP publishing is not part of source. + +{/* workflow-code-docs:directory-kinds:end */} + +Beside the resources: + +| Path | What it is | In git | +| --- | --- | --- | +| `.sim/base.json` | The workspace the directory was read from and the version of every resource | Commit | +| `workflows//.sim/` | Each workflow's `lock.json`, `base.json` and `stored-edges.json`, as above | Commit | +| `.sim/written.json` | A digest of each file as the CLI last wrote it, so `status` and `get` tell your edits from the CLI's | Commit | +| `.sim/targets/.json` | What each [promotion](/workflows/code/promote) left in that workspace | Commit | +| `.sim/skipped.json` | Documents and files a get left out, with the reason | Optional | +| `.sim/AGENTS.md`, `.sim/GUIDE-advanced.md`, `.sim/examples/`, `.sim/sdk/` | The agent guide with deletes, Git and CI, and promotion in depth; examples of every kind; type declarations including `.sim/sdk/workspace.d.ts` | Optional, written again by `get` | +| `.sim/cache/` | This machine's file stats. It ignores itself | Not committed | +| `tsconfig.json`, `tsconfig.full.json`, `.gitattributes`, `.gitignore` | As for a workflow directory. `.gitattributes` also keeps workspace files and knowledge base documents byte for byte | Commit all but `tsconfig.full.json` | + +The generated `.gitignore` leaves out only what a command keeps while it runs (`.sim/downloads/`, `.sim/command.lock/`, `.sim-staging-*`) and `tsconfig.full.json`. Commit the rest, including `.sim/`: a fresh clone can then run `check`, `apply --dry-run` and `apply`. + +## Related docs + +- [Edit a workflow](/workflows/code/edit) +- [Manage a workspace as code](/workflows/code/workspace) +- [Run in CI](/workflows/code/ci) +- [Limits](/workflows/code/limits) diff --git a/apps/docs/content/docs/workflows/code/edit.mdx b/apps/docs/content/docs/workflows/code/edit.mdx new file mode 100644 index 00000000000..5a637b6a2c2 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/edit.mdx @@ -0,0 +1,104 @@ +--- +title: Edit a workflow +description: Read a workflow into a directory, edit it, check it, and save it, including renames, deletes and deploys. +--- + +Result: a workflow saved from a file you edited, with the problems found before the save. + +## Prerequisites + +The Sim CLI, signed in, with [workflows as code enabled](/workflows/code). Run every command on the same `--dir`; commands that read a directory (`check`, `status`, `diff`, `params`, `apply`) default it to the current directory, while `get` and `create`, which write one, always need `--dir`. + +## 1. Read the workflow + +```bash +sim workflows source get --dir ./support-triage +``` + +This writes `workflow.ts`, any function code under `functions/`, type declarations for the blocks the workflow uses and for your workspace's resources, and the `.sim/` folder. See [Directory layout](/workflows/code/directory) for each file. For coding agents it writes `.sim/AGENTS.md` and example workflows under `.sim/examples/`. + +`get` into a directory that already holds source refuses to overwrite edits you have not applied, and refuses a directory that holds a different workflow. Pass `--force` to replace them. A workspace directory is always refused, `--force` included. + +To write a block the workflow does not use yet, `sim workflows source params ` (for example `table.upsertRow` or `trigger.schedule`) prints an example call, its required params with their types, its optional params by name and its outputs, from the cached block catalog without a request (`--full` adds every param's options, default and doc). A namespace such as `gmail` lists its builders. + +## 2. Edit and check + +Edit `workflow.ts`, then compile it on your machine with Sim's compiler: + +```bash +sim workflows source check --dir ./support-triage +``` + +`check` makes no request. It needs the block catalog the last `get` cached in `~/.sim/cache/source-catalog/`; with none cached it exits `1` and tells you to run `get` once. It exits `1` on an error, and on the warnings `sim workflows source check --help` lists (a missing required field, an unknown option, an unwired condition or router branch, a literal secret and more) in a block you added since the get. `--strict` fails on these in every block, except an unwired branch on a block the get printed; `--no-strict` never fails on a warning. + +Then it adds the blocks the workflow now uses to `tsconfig.json` and type-checks the directory with it, using the TypeScript release the generated declarations are built for, as your editor does. Each type error is an `E_TYPE` error at its line, with TypeScript's own code (`TS2339: …`) at the start of the message. A type error is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them), where the dry run decides; one that another file's edit causes there is reported. The first check installs that release with `npm` into `~/.sim/cache/typescript/`, once; offline before then, `check` warns `W_TYPES_UNCHECKED` and passes or fails on the compile alone. `--no-types` skips the type check. `tsconfig.full.json` includes every block, for an editor. + +## 3. See what changed + +```bash +sim workflows source status --dir ./support-triage +sim workflows source diff --dir ./support-triage +``` + +`status` lists the files you created, edited, or deleted, asks the server (with a plan read that saves nothing) whether the workflow changed since the `get`, and ends with the one command to run next. It exits `0` when nothing changed, `11` when only your edits are unsaved, and `12` when the workflow changed in the workflow builder since the `get` (a conflict, if you edited it too). Without a connection it shows your edits only and says so; `--offline` skips the server. `diff` prints each edit as a unified diff, and `diff --server` compares the directory with the workflow as it is saved now. Both take `--json` (or `--output json`). + +## 4. Dry run + +```bash +sim workflows source apply --dir ./support-triage --dry-run +``` + +`apply` reads the workflow ID from `.sim/base.json`. Pass it as `apply --dir …` to have the CLI confirm the directory holds that workflow. + +Sim compiles the file and runs every check a save would run: unknown settings, missing required fields, broken references, permissions, and locked blocks. Each problem prints with its line, the code around it, and a hint: + +``` +workflow.ts:56:7 error E_UNKNOWN_PARAM: Slack has no param chanel. + 54 | const notify = slack.sendMessage('Notify', { + 55 | credential: credential('support-slack'), +> 56 | chanel: 'C0SUPPORT', + | ^^^^^^^^^^^^^^^^^^^ + 57 | text: t`New ${classify.category} ticket: ${ticketIn.subject}`, + hint: Did you mean channel? +``` + +Every code is in [Diagnostic codes](/workflows/code/diagnostics). + +## 5. Save the draft + +```bash +sim workflows source apply --dir ./support-triage --yes +``` + +The workflow builder updates for anyone who has the workflow open. `--yes` refuses everything a dry run would, so step 4 is optional: without `--yes`, and with no terminal to ask, `apply` prints the plan, writes nothing and exits `14`. The save rewrites `workflow.ts` in canonical form, so read it again before the next edit. + +Editing the name or description in `workflow('…')` renames or redescribes the workflow; a name another workflow in its folder already has is refused with `E_NAME_TAKEN`. Lines starting with `note:` report something the save did beyond what the file says; read them. + +### Deploy + +Saving writes the draft. Add `--deploy` to deploy right after the save, which also prints the URL of each webhook the workflow now serves. Without it, a deployed workflow whose draft now differs prints the `sim workflows deploy` command to run. + +### Deletes + +A save that removes a block (its declaration is gone from `workflow.ts`) is refused with `E_APPLY_BLOCK_DELETE`, naming the blocks, and one that removes a workflow variable with `E_APPLY_VARIABLE_DELETE`. Pass `--allow-delete` when the deletion is intended. Removing a block that serves a live webhook, schedule, chat, or MCP tool warns you: the deployed version keeps serving it until the next deploy. + +### Renames + +Keep the `.sim/` folder the commands write. `.sim/lock.json` ties each block in the file to the stored block, so renaming a block keeps the same block, with its webhook URL, schedules and run history. Changing its name string keeps it through the lock; renaming the variable too keeps it when the block's type, parent and connections are unchanged, and the dry run reports that as `W_MAT_INFERRED_RENAME`. Renaming two blocks of the same type in the same place in one save is ambiguous, so do those one save at a time. `.sim/base.json` records the version you read. + +## Working with other people + +- If someone changes the workflow after you read it, the save (or `--dry-run`) is refused with exit code `5` and nothing is overwritten. Run `get` into a new directory, reapply your edit, and save. There is no automatic merge. +- Locked blocks cannot be changed from the file. Unlock them in the workflow builder first. + +## Limits + +The file holds block declarations and connections only: helpers, loops that create blocks, and imports are refused. Function code is one file per block, with no imports between files. Workflows run in Sim, not locally, and `--dry-run` checks everything a save checks without running the workflow. Size caps are in [Limits](/workflows/code/limits). + +## Related docs + +- [File syntax](/workflows/code/syntax) +- [Create a workflow](/workflows/code/create) +- [Run in CI](/workflows/code/ci) +- [Exit codes](/workflows/code/exit-codes) +- [CLI workflow commands](/cli/workflows#workflows-as-code) diff --git a/apps/docs/content/docs/workflows/code/exit-codes.mdx b/apps/docs/content/docs/workflows/code/exit-codes.mdx new file mode 100644 index 00000000000..5b16b21f531 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/exit-codes.mdx @@ -0,0 +1,82 @@ +--- +title: Exit codes +description: What the sim workflows source and sim workspaces source commands exit with, and what to run next. +--- + +import { Tab, Tabs } from '@/components/ui/tabs' + +The `sim workflows source` and `sim workspaces source` commands exit with a code a script or CI job can branch on. Findings print on stderr, and the result of a command goes to stdout. A code of its own is set aside for each outcome a script handles differently, so test for the code you act on, not for any non-zero status. + +`status` is the command to branch on: it exits `0` when nothing differs, `11` when only your edits are unsaved, and `12` when the server changed since the directory was read. + +```bash +sim workspaces source status --dir workspace --output json > status.json +case $? in + 0) echo "in sync" ;; + 11) echo "local edits to apply" ;; + 12) echo "the workspace changed in Sim since the get" ;; + *) echo "status failed"; exit 1 ;; +esac +``` + +## Codes + +The table for the kind of directory you work in. Both are built from the table `--help`, the generated [CLI reference](/cli/workflows#workflows-as-code) and `.sim/AGENTS.md` print, so they cannot disagree with the CLI. + +{/* workflow-code-docs:exit-codes:begin — generated by `bun run generate:workflow-code-docs`; do not edit between markers */} + + + + + | Code | Meaning | What to do | + | --- | --- | --- | + | `0` | Applied or created, a dry run or check with no errors, or a clean status | Go on | + | `1` | The source has errors (each printed as `file:line:column` with a hint), a locked block (`E_APPLY_LOCKED_BLOCK`), a name another workflow holds (`SOURCE_NAME_TAKEN`), a cancelled prompt, or the command failed | Fix what it printed and run it again | + | `5` | Stale (`SOURCE_STALE`, or `E_APPLY_STALE` on a dry run): the server changed what this directory was read from, and nothing was written | `sim workflows source get --dir `, reapply your edit there, dry-run, apply | + | `6` | A workflow or its folder is locked (`E_APPLY_LOCKED`); a locked block exits 1 instead | Ask someone to unlock it in the workflow builder | + | `7` | The source is over the size limits (on a get, status or diff too) | Split function code, or remove blocks or resources | + | `8` | `sim workspaces source apply` stopped part-way: what was written is saved into the directory | Apply again until it exits 0 | + | `9` | Still rate limited (HTTP 429) after the CLI's retries (up to 6, at most a minute apart); nothing more was written | Wait a minute and run the same command again | + | `10` | Busy: another apply is writing the workspace (`SOURCE_BUSY`), or another sim command is using this directory (`SOURCE_DIR_BUSY`); nothing was written | Run it again once the other finished | + | `11` | `status`: only your edits, which applying writes | Dry-run, then apply | + | `12` | `status`: the server changed since the get (drift, or a conflict with your edits) | Follow the `Next:` line it prints | + | `13` | Not logged in, the login expired, or the server refused the credential (`AUTH_REQUIRED`); nothing was sent | `sim login`, or fix or unset `SIM_API_KEY` when the key comes from it; then the same command again | + | `14` | `apply` or `create` without `--yes` and no terminal to ask: it printed the plan, found no errors, and wrote nothing | Run the same command with `--yes` | + | `15` | `sim workspaces source apply` (or `--to`) wrote part of its plan and held the rest back: a change that uses a declared secret the workspace has no value for, or a credential key nothing binds to. Its dry run exits 15 too, so a script can tell beforehand that the apply would write only part | Set the secret (`sim secrets set`) or connect the credential, then apply again | + | `130` | Interrupted (Ctrl-C). An apply or create already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written | `sim workflows source status --dir .` | + + + + + | Code | Meaning | What to do | + | --- | --- | --- | + | `0` | Applied or created, a dry run or check with no errors, or a clean status | Go on | + | `1` | The source has errors (each printed as `file:line:column` with a hint), a locked block (`E_APPLY_LOCKED_BLOCK`), a name another resource holds (`E_NAME_TAKEN`), a cancelled prompt, or the command failed | Fix what it printed and run it again | + | `5` | Stale (`SOURCE_STALE`, or `E_APPLY_STALE` on a dry run): the server changed what this directory was read from, and nothing was written | `sim workspaces source get --dir `, reapply your edit there, dry-run, apply | + | `6` | A resource is locked (`E_APPLY_LOCKED`): a workflow or its folder, or a table; a locked block exits 1 instead | Ask someone to unlock it: a workflow in the workflow builder, a table in its settings (the finding's hint names which) | + | `7` | The source is over the size limits (on a get, status or diff too) | Split function code, or remove blocks or resources | + | `8` | `sim workspaces source apply` stopped part-way: what was written is saved into the directory | Apply again until it exits 0 | + | `9` | Still rate limited (HTTP 429) after the CLI's retries (up to 6, at most a minute apart); nothing more was written | Wait a minute and run the same command again | + | `10` | Busy: another apply is writing the workspace (`SOURCE_BUSY`), or another sim command is using this directory (`SOURCE_DIR_BUSY`); nothing was written | Run it again once the other finished | + | `11` | `status`: only your edits, which applying writes | Dry-run, then apply | + | `12` | `status`: the server changed since the get (drift, or a conflict with your edits) | Follow the `Next:` line it prints | + | `13` | Not logged in, the login expired, or the server refused the credential (`AUTH_REQUIRED`); nothing was sent | `sim login`, or fix or unset `SIM_API_KEY` when the key comes from it; then the same command again | + | `14` | `apply` or `create` without `--yes` and no terminal to ask: it printed the plan, found no errors, and wrote nothing | Run the same command with `--yes` | + | `15` | `sim workspaces source apply` (or `--to`) wrote part of its plan and held the rest back: a change that uses a declared secret the workspace has no value for, or a credential key nothing binds to. Its dry run exits 15 too, so a script can tell beforehand that the apply would write only part | Set the secret (`sim secrets set`) or connect the credential, then apply again | + | `130` | Interrupted (Ctrl-C). An apply or create already sent is finished and saved into the directory first, waiting up to 60s for its answer; a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written | `sim workspaces source status --dir .` | + + + + +{/* workflow-code-docs:exit-codes:end */} + +Exit `9` follows the CLI's retries: it resends a request the API answered `429` only when sending it twice is safe, which includes every `GET`, a source `apply` and a `create`. See [Scripting](/cli/scripting#exit-codes) for the retry schedule and the codes every command shares (`13` and `9`). + +## Related docs + +- [Troubleshooting](/workflows/code/troubleshooting): the causes behind each code +- [Run in CI](/workflows/code/ci) +- [Diagnostic codes](/workflows/code/diagnostics) +- [Limits](/workflows/code/limits) +- [Scripting: exit codes](/cli/scripting#exit-codes) +- [CLI workflow commands](/cli/workflows#workflows-as-code) and [workspace commands](/cli/workspaces#workspace-as-code) diff --git a/apps/docs/content/docs/workflows/code/get-started.mdx b/apps/docs/content/docs/workflows/code/get-started.mdx new file mode 100644 index 00000000000..d8c7ecec2e6 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/get-started.mdx @@ -0,0 +1,74 @@ +--- +title: Get started +description: Change one setting of a workflow from your terminal, save it, and see it in the workflow builder. +--- + +This walks through one change end to end: read a workflow as a file, edit it, check it, save it, and see the result in the workflow builder. + +## Before you start + +- Workflows as code is [enabled](/workflows/code) for your workspace. Where it is not, step 2 answers `403`. +- The Sim CLI is installed and you are signed in with a default workspace. See [Your first command](/cli#your-first-command). +- Optional: npm (Node.js), which the type check in step 4 uses once to install TypeScript; without it `check` reports `W_TYPES_UNCHECKED` and the compile still runs. + +## 1. Find the workflow ID + +```bash +sim workflows list --search "support" +``` + +## 2. Read it as a file + +```bash +sim workflows source get --dir ./support-triage +``` + +This writes `workflow.ts`, the type declarations, and `.sim/`, which records which block is which. See [Directory layout](/workflows/code/directory). + +## 3. Change one setting + +Open `workflow.ts` and change one value, such as an agent's `model` or a message's `text`. Each `const` is a block, and a change to one setting is a one-line diff. The forms you can write are in [File syntax](/workflows/code/syntax). + +## 4. Check it + +```bash +sim workflows source check --dir ./support-triage +``` + +`check` compiles the file on your machine and type-checks it. Each problem prints with its line, the code around it, and a hint. The first check installs the TypeScript release the declarations are built for, once. + +## 5. See what changed + +```bash +sim workflows source status --dir ./support-triage +sim workflows source diff --dir ./support-triage +``` + +`status` lists your edits, asks the server whether the workflow changed since the `get`, and ends with the one command to run next. + +## 6. Save the draft + +```bash +sim workflows source apply --dir ./support-triage --dry-run +sim workflows source apply --dir ./support-triage --yes +``` + +The dry run runs every check a save runs and writes nothing. `--yes` saves the draft and rewrites `workflow.ts` in canonical form, so read it again before the next edit. + +## 7. See it in the builder + +Open the workflow in the workflow builder. It shows your change, and updates for anyone who has the workflow open. The **Code** tab shows the same workflow as read-only source. Saving writes the draft only: deploy it when you are ready. + +## Create a new workflow + +```bash +sim workflows source create --dir ./new-workflow --workspace +``` + +See [Create a workflow](/workflows/code/create). + +## Related docs + +- [Edit a workflow](/workflows/code/edit) +- [Use with coding agents](/workflows/code/coding-agents) +- [Exit codes](/workflows/code/exit-codes) diff --git a/apps/docs/content/docs/workflows/code/how-it-works.mdx b/apps/docs/content/docs/workflows/code/how-it-works.mdx new file mode 100644 index 00000000000..8241a7bd726 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/how-it-works.mdx @@ -0,0 +1,102 @@ +--- +title: How it works +description: How Sim turns a file into a saved workflow, keeps each block's identity, and refuses an apply that would overwrite someone else's change. +--- + +A source file is a declaration, not a program. Sim reads it, compares it with the stored workflow, and saves the difference. This page explains the rules behind `get`, `check` and `apply`, so their results and refusals are predictable. + +## Nothing in the file runs + +`workflow.ts` is TypeScript so that your editor can complete and type-check it, but no command executes it. Sim parses the file and reads each `const x = builder('Name', {…})` as one block, each `.to()` as one connection, and each param as one setting. That is why the file holds declarations only: a helper function, a loop that creates blocks, or an import from anything but `@sim/workflow-sdk` has no value Sim could read without running it, so it is refused with `E_UNSUPPORTED_SYNTAX` and a hint. + +`check` runs this compiler on your machine, the same one the server runs, against the block catalog the last `get` cached, then type-checks the directory with the TypeScript release the generated declarations are built for. Function code under `functions/` is not run either: it is stored as the Function block's code and runs in Sim, like code typed into the workflow builder. + +## From a file to a saved draft + +An apply goes through three steps, and a dry run stops after the second: + +1. **Compile.** The file becomes the workflow's canonical form: its blocks keyed by name, their settings, connections, branches, loops and variables, with no IDs and no layout. +2. **Evaluate.** Sim reads the stored draft into the same form, matches each compiled block to a stored one, and checks what a save would change: unknown settings, missing required fields, references, permissions, locked blocks, deletes and the workflow's lint. Every finding maps back to a line in your files. +3. **Commit.** Sim writes the new draft in one transaction, after checking again that nobody saved the workflow meanwhile. + +Deploying is never part of an apply unless you pass `--deploy` (or, for a workspace directory, add a file under `deployments/`). + +## The canonical form + +The stored workflow and the file are two views of one canonical form, so a round trip changes nothing: + +- `get` prints the canonical form. An `apply` of an unchanged directory is a no-op, and the stored workflow stays byte for byte the same. +- A setting equal to the value a block gets when you add it in the workflow builder is left out of the file. Writing it out has the same effect as leaving it out. +- After a save, Sim prints the files again from what it stored. A value the server normalized, a resource key it allocated, or a reference it rewrote for a rename shows up in your files, so read them again before the next edit and commit what changed. + +Some state has no syntax in the file. Sim keeps it from the stored workflow on every apply: + +- **Layout.** Block positions stay in Sim. `.sim/lock.json` keeps a copy, used only to place a block the target does not hold yet (a promotion or a fresh create); a new block is placed automatically. Moving blocks never makes a directory stale. +- **Settings that do not run.** A value in a field that the block's current choices hide stays stored, so switching back in the workflow builder brings it back. +- **Comments.** Comments in `workflow.ts` are stored with the workflow, by block, so a builder edit or a rename keeps them. + +## Block identity + +Each stored block has an ID that its webhook URL, schedules and run history hang on. The file names blocks by `const` name and display name instead, so Sim needs a way to tell an edited block from a new one. + +`.sim/lock.json` records, for each block in the file, the ID of the stored block it is. An apply matches each block in the file, in this order: + +1. by its block key in the lock, the display name lowercased with whitespace and dots removed; +2. by its `const` name in the lock, so changing only the display name keeps the block; +3. by its block key in the stored workflow, when the lock does not have it; +4. by inference: when a block left and one of the same type appeared in the same place with the same connections or settings, it is a rename (`W_MAT_INFERRED_RENAME`). + +A block that matches nothing is new, and a stored block nothing matched is a delete, which an apply refuses without `--allow-delete` (`E_APPLY_BLOCK_DELETE`). Renaming two blocks of the same type in the same place in one save leaves the inference nothing to tell apart, so rename them one save at a time. + +Sim also stores each block's `const` name, its order in the file and its comments, by block ID. A `get` into a new directory, or after a builder edit, prints the same names in the same order, so a one-setting change stays a one-line diff. + +## Stale: what you read is not what Sim holds + +`.sim/base.json` records a fingerprint of the draft you read: a hash of its canonical form, its variables and its block IDs, without layout. An apply sends it, and Sim computes the fingerprint of the draft it holds now: + +- the same: the apply goes ahead; +- different: someone saved the workflow since you read it. The apply is refused as stale with exit `5`, on a dry run too, and nothing is written; [Troubleshooting](/workflows/code/troubleshooting#exit-5) has the steps. + +The check is made again inside the write's transaction, so two applies that race cannot both win. `status` asks the same question with a plan read that saves nothing and reports it as drift (exit `12`) before you apply. + +The base also records the block catalog you read against. When a compile fails and the catalog changed since, for example after a block gained a setting, the apply adds `W_APPLY_CATALOG_MOVED`: run `get` again to pick up the new types. + +## Workspaces: one rule per resource + +A workspace directory adds tables, knowledge bases, files, custom tools, skills, MCP servers, secret names, credential keys and deployments. Each resource has a key, its file or folder name, which Sim stores and never changes: a rename in Sim keeps the key, and a workflow names the resource by it, as in `table('orders')`. + +`.sim/base.json` at the root records each resource's ID and fingerprint as the last `get` or apply saw it. An apply decides each declared resource by comparing three fingerprints: your file (local), the base, and what Sim holds now (server): + +| Your file vs the base | Sim vs the base | Outcome | +| --- | --- | --- | +| Same | Any | Nothing to do. When Sim changed it, the apply keeps Sim's version (`W_SERVER_CHANGED`) | +| Changed | Same | Written | +| Changed | Changed | Nothing to do when both made the same change; otherwise stale, exit `5` | + +A resource with no base entry is created, or **adopted** when Sim already holds one under the same name. An adopt only adds to what is there, such as a column or a document; one that would change or remove anything is refused with `E_APPLY_NO_BASE`. A resource the directory stops declaring is deleted only when the base recorded it and you pass `--allow-delete`; anything else Sim holds is kept and named in a `W_UNDECLARED` warning. + +Workflows are the exception to this table. Each workflow folder is applied exactly as a single workflow, with its own `.sim/lock.json` and `.sim/base.json`: a folder you did not edit is skipped without asking whether Sim changed it, so it gets no `W_SERVER_CHANGED`, and an edited folder is refused as stale whenever Sim changed the workflow since its base, even when both made the same change. + +An apply writes resources in dependency order, so a table exists before the workflow that writes to it, and deletes run in reverse. + +### Applying a workspace + +- **Whole or nothing at planning.** Every check runs before the first write. One error refuses the whole apply. +- **One apply at a time.** An apply holds the workspace from planning to its last write. A second apply meanwhile exits `10` with nothing written. A dry run does not take part, so it never waits. +- **Writes commit one by one.** If a write fails part-way, the apply stops, saves what it wrote into the directory and exits `8`. Applying the same directory again finishes the rest. +- **Held back.** A change that uses a secret with no value in the workspace, or a credential key nothing binds to, is held back while the rest is written, and the apply exits `15`. +- **Files travel separately.** Workspace files and knowledge base documents are uploaded before the apply, and only the ones Sim does not have yet, so a retry uploads nothing again. + +## Promotion + +`apply --to ` sends a directory read from one workspace to another. Sim sees an ordinary apply against the target's own IDs: each resource binds by key, so a workflow keeps its ID and webhook URLs in the target, and secrets and credentials bind by name to the target's own. + +The directory stays bound to the workspace it was read from. The only file a promotion writes is `.sim/targets/.json`, a record of what it left in the target. The next promotion uses that record as the base for the three-way rule above, so a hotfix made in the target is kept when the directory left that resource alone, and refused as stale when the directory changed it too. See [Promote to another workspace](/workflows/code/promote). + +## Related docs + +- [Edit a workflow](/workflows/code/edit) +- [Manage a workspace as code](/workflows/code/workspace) +- [Directory layout](/workflows/code/directory) +- [Troubleshooting](/workflows/code/troubleshooting) +- [Diagnostic codes](/workflows/code/diagnostics) diff --git a/apps/docs/content/docs/workflows/code/index.mdx b/apps/docs/content/docs/workflows/code/index.mdx new file mode 100644 index 00000000000..b7891446174 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/index.mdx @@ -0,0 +1,60 @@ +--- +title: Workflows as code +description: Read and edit workflows and whole workspaces as TypeScript files, check them before saving, and review changes as diffs. +--- + +import { Callout } from '@/components/ui/callout' + +Every workflow can be read and written as one TypeScript file, and a whole workspace as a directory of files. The file and the workflow builder show the same workflow: edit either one and the other follows. Use it to review agent changes as a diff, keep workflows in git, or let a coding agent such as Claude Code build and change them for you. + + +Workflows as code is in preview. When it is enabled, the workflow builder shows a read-only **Code** tab and the [CLI](/cli) gains the `sim workflows source` and `sim workspaces source` commands. On a self-hosted deployment, set [`WORKFLOW_CODE`](/platform/self-hosting/environment-variables#preview-features). On Sim Cloud it is enabled per organization, workspace or user. Where it is off, the **Code** tab is not shown and a source command answers `403` with "Workflows as code is in preview and not enabled for this workspace". + + +## Workflow or workspace + +- **A workflow** is one `workflow.ts` plus its function code files. Use `sim workflows source`. +- **A workspace** is a directory with a folder for each kind of resource: tables, knowledge bases, files, custom tools, skills, MCP servers, secrets and credential bindings, deployments and workflows. Each workflow is written exactly as above. One apply creates the resources before the workflows that use them, so a coding agent can build a working setup from scratch. Use `sim workspaces source`. + +The file states what the workflow runs: its blocks, their settings, the connections between them, branches, loops, and variables. Layout and other builder-only details stay in the stored workflow, so the file stays short and a change to one setting is a one-line diff. Nothing in the file runs on your machine: Sim reads it statically, checks it against your workspace, and saves it as the workflow draft. Deploying stays a separate step. + +## The loop + +Both commands follow the same five steps: + +```bash +sim workflows source get --dir ./support-triage +# edit ./support-triage/workflow.ts +sim workflows source check --dir ./support-triage +sim workflows source status --dir ./support-triage +sim workflows source apply --dir ./support-triage --dry-run +sim workflows source apply --dir ./support-triage --yes +``` + +`get` writes the directory, `check` compiles it on your machine, `status` shows what changed and what to run next, a dry run checks everything a save checks, and `apply --yes` saves the draft. + +## Terms + +- **As code** names the feature; **source** names its files and commands. +- A **workflow directory** is the directory `sim workflows source get` writes; a **workspace directory** is the one `sim workspaces source get` writes. +- **Get** reads from Sim and **apply** writes to Sim. Neither is a sync: [fork, push and pull](/cli/workflow-sync) are a different feature. +- **Check** compiles offline. A **dry run** asks the server and saves nothing. The **plan** is what a dry run prints. +- **Stale** means an apply was refused because the server changed what you read (exit `5`). **Drift** means the server changed since the get (`status` exits `12`). A **conflict** is a resource changed on both sides. +- A **resource key** is the file or folder name of a table, skill or other resource. A **block key** is a block's name lowercased with whitespace and dots removed, as in `$ref.triageagent.content`. + +## For coding agents [#for-coding-agents] + +Claude Code, Cursor, Codex and other coding agents work from a directory that `get` writes. `get` prints a summary with the edit loop and writes the primer and full guide to `.sim/AGENTS.md`. See [Use with coding agents](/workflows/code/coding-agents). + +## Related docs + +- [Get started](/workflows/code/get-started): change one setting and see it in the builder +- [Edit a workflow](/workflows/code/edit) +- [Manage a workspace as code](/workflows/code/workspace) +- [Run in CI](/workflows/code/ci) +- [Bring existing workflows into code](/workflows/code/adopt) +- [Troubleshooting](/workflows/code/troubleshooting) +- [How it works](/workflows/code/how-it-works) +- [File syntax](/workflows/code/syntax) +- [Exit codes](/workflows/code/exit-codes), [diagnostic codes](/workflows/code/diagnostics) and [limits](/workflows/code/limits) +- [CLI workflow commands](/cli/workflows#workflows-as-code) and [workspace commands](/cli/workspaces#workspace-as-code) diff --git a/apps/docs/content/docs/workflows/code/limits.mdx b/apps/docs/content/docs/workflows/code/limits.mdx new file mode 100644 index 00000000000..d6461c7c863 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/limits.mdx @@ -0,0 +1,61 @@ +--- +title: Limits +description: The size limits of workflow source and workspace source, and what happens when a directory goes over one. +--- + +A get leaves out what an apply would refuse, so anything a get writes can be applied back unchanged. The numbers below are hard limits, read from the same constants the CLI and the server enforce. + +## What happens over a limit + +- **A workflow** over a limit is refused when you read or save it (`E_LIMIT_EXCEEDED`), and the CLI exits `7`. +- **An apply of a workspace directory** that would make more changes than the limit, send more edited workflows, or hold more resources of a kind is refused before anything is written, and the CLI exits `7`. +- **A get of a workspace** that holds more resources of a kind than one directory takes leaves that kind out (`E_LIMIT_EXCEEDED`, hint `--only`), writes the rest and exits `0`; the directory does not manage that kind. +- **A workspace file or knowledge base document** over its limit, or whose name a directory cannot hold, is left out of the get and listed in `.sim/skipped.json`. An apply never writes or deletes it. + +{/* workflow-code-docs:limits:begin — generated by `bun run generate:workflow-code-docs`; do not edit between markers */} + +### One workflow + +| Limit | Value | +| --- | --- | +| Blocks in one workflow | 2,000 | +| Connections (edges) in one workflow | 10,000 | +| Variables in one workflow | 2,000 | +| Files in one source: `workflow.ts` plus one function file per block | 2,001 | +| Bytes of all files together, `workflow.ts` and function files | 4,000,000 bytes | +| Nesting depth of `workflow.ts`, and of each JavaScript function file | 200 | + +### A workspace directory + +| Limit | Value | +| --- | --- | +| Resources of one kind in one directory | 500 | +| Bytes of every declaration file together, workflow files excluded | 2,000,000 bytes | +| Edited workflows one apply sends | 100 | +| Bytes of every workflow file one apply sends | 8,000,000 bytes | +| Bytes of every workflow file one get writes; a workflow past it is left out | 32,000,000 bytes | +| Changes one apply makes, no-ops excluded | 1,000 | +| Rows in one `tables/.rows.jsonl` | 10,000 | +| Bytes of every rows file together | 16,000,000 bytes | +| Columns in one table | 1,000 | +| Bytes of one workspace file or knowledge base document | 10,000,000 bytes | +| Workspace files and knowledge base documents together in one directory | 20,000 | +| Nesting depth of a declaration file | 200 | + +### Uploading and downloading files + +| Limit | Value | +| --- | --- | +| Bytes of files one upload request carries; a larger file goes in a request of its own | 8,000,000 bytes | +| Files in one upload request | 1,000 | +| Bytes of stored files one get or apply downloads to compare | 24,000,000 bytes | +| Files one caller may hold staged in one workspace at once | 20,000 | +| Bytes one caller may hold staged in one workspace at once | 4,000,000,000 bytes | + +{/* workflow-code-docs:limits:end */} + +## Related docs + +- [Exit codes](/workflows/code/exit-codes) +- [Diagnostic codes](/workflows/code/diagnostics) +- [Manage a workspace as code](/workflows/code/workspace) diff --git a/apps/docs/content/docs/workflows/code/meta.json b/apps/docs/content/docs/workflows/code/meta.json new file mode 100644 index 00000000000..42ecb64f9ae --- /dev/null +++ b/apps/docs/content/docs/workflows/code/meta.json @@ -0,0 +1,24 @@ +{ + "title": "Workflows as code", + "pages": [ + "index", + "get-started", + "---How-to guides---", + "edit", + "create", + "workspace", + "promote", + "ci", + "coding-agents", + "adopt", + "troubleshooting", + "---Reference---", + "syntax", + "directory", + "exit-codes", + "diagnostics", + "limits", + "---Explanation---", + "how-it-works" + ] +} diff --git a/apps/docs/content/docs/workflows/code/promote.mdx b/apps/docs/content/docs/workflows/code/promote.mdx new file mode 100644 index 00000000000..4dd1ba68ded --- /dev/null +++ b/apps/docs/content/docs/workflows/code/promote.mdx @@ -0,0 +1,51 @@ +--- +title: Promote to another workspace +description: Apply a workspace directory read from one workspace to another with --to, such as dev to prod, and how the target record works. +--- + +Result: the resources of a directory created or updated in a second workspace, with changes made there since the last promotion kept or refused. + +## Promote or fork? + +- Use **promote** (`--to`) when the directory, usually in git, is the source of truth and the target workspace need not be linked to the source. +- Use **fork, push and pull** when two workspaces should stay linked as parent and child and exchange reviewed changes. They need an Admin on both workspaces, and Enterprise on billing-enabled deployments. See [Workflow imports and workspace sync](/cli/workflow-sync). + +## Before the first promotion + +Set the target's secrets (`sim secrets set NAME --scope workspace -w `) and connect its credentials, or the workflows that use them are held back and the apply exits `15`. + +## Promote + +Apply a directory read from one workspace (dev) to another (prod) with `--to`: + +```bash +sim workspaces source apply --dir ./my-workspace --to "$PROD_WORKSPACE_ID" --dry-run +sim workspaces source apply --dir ./my-workspace --to "$PROD_WORKSPACE_ID" --yes +``` + +Each resource binds by key to the target's own. One the target holds under the same key is updated in place, so a workflow keeps its id and its webhook URLs. A key the target lacks is created. Secrets and credentials bind by name to the target's own, and no value is copied. The directory stays bound to the workspace it was read from. Without `--to`, `check`, `status`, `diff` and `apply` act on the workspace the directory was read from, whatever your default workspace; a `--workspace` naming another one is refused. + +## Deletes + +A resource you deleted from the directory since the last promotion is deleted in the target too, and like any delete it needs `--allow-delete`. Resources only the target holds, such as a table created in prod and the rows its runs wrote, are kept, with or without `--allow-delete`: the plan names each with a `W_UNDECLARED` warning. To delete them as well, pass `--delete-target-only` beside `--allow-delete`; the plan then names each with a `W_PROMOTE_DELETES_TARGET_ONLY` warning, so run it with `--dry-run` first. + +## The target record + +Each promotion records what it left in the target in `.sim/targets/.json`, and the next promotion compares with that record: + +- A resource changed in the target since the last promotion, such as a hotfix made in Sim, is kept when the directory left it alone. +- When the directory changed it too, the promotion is refused as stale and exits `5`. Carry the target's change into the source workspace, or undo it in the target, then promote again. +- A resource deleted in the target since the last promotion stays deleted, with a `W_PROMOTE_TARGET_DELETED` warning. Remove its entry from the record to create it again. +- The first promotion, and any resource the record does not hold (one created in the target since), updates the target to match the directory. Review the dry run first. + +Commit the record with the rest of the directory, so a promotion from CI or another clone compares with it. Don't delete it to get past a stale refusal: without it, the next promotion overwrites every change made in the target since, including rows its workflows wrote. + +## In CI + +To promote after each merge, add the step after the apply to the source workspace and before the step that commits the files back; see [Run in CI](/workflows/code/ci#promote-in-ci). + +## Related docs + +- [Manage a workspace as code](/workflows/code/workspace) +- [Run in CI](/workflows/code/ci) +- [Exit codes](/workflows/code/exit-codes) diff --git a/apps/docs/content/docs/workflows/code/syntax.mdx b/apps/docs/content/docs/workflows/code/syntax.mdx new file mode 100644 index 00000000000..2690afe854b --- /dev/null +++ b/apps/docs/content/docs/workflows/code/syntax.mdx @@ -0,0 +1,268 @@ +--- +title: File syntax +description: The TypeScript subset a workflow file accepts, from builders, values, references, wiring, branches, loops and function code. +--- + +A workflow file is a declaration of blocks and connections, not a program. Sim reads it statically and never runs it, so the file holds a fixed set of forms. This page lists them. A form outside it is refused with `E_UNSUPPORTED_SYNTAX` and a hint that names the supported form. The types for every builder are in `.sim/sdk/` after a `get`, and `sim workflows source params ` prints one builder's params. + +## An example + +A webhook receives a ticket, an agent classifies it, billing tickets are logged to a table, and the team hears about every ticket in Slack. This is the file `sim workflows source get` prints for it: + +```ts title="workflow.ts" +// @sim-sdk 1 +import { + agent, + condition, + credential, + env, + js, + slack, + t, + table, + trigger, + workflow, +} from '@sim/workflow-sdk' + +export default workflow( + 'Support triage', + { variables: { escalations: { type: 'number', value: 0 } } }, + () => { + const ticketIn = trigger.webhook('Ticket in', { + requireAuth: true, + token: env.TICKETS_WEBHOOK_TOKEN, + inputFormat: { subject: 'string', body: 'string', contacts: 'array' }, + responseMode: 'custom', + responseStatusCode: 202, + responseBody: { ok: true }, + }) + const classify = agent('Classify', { + messages: [ + { role: 'system', content: 'Classify support tickets.' }, + { + role: 'user', + content: t`${ticketIn.subject} + +${ticketIn.body}`, + }, + ], + model: 'claude-sonnet-5-5', + responseFormat: { + name: 'ticket', + strict: true, + schema: { + type: 'object', + additionalProperties: false, + required: ['category', 'urgent'], + properties: { + category: { type: 'string', enum: ['billing', 'bug', 'other'] }, + urgent: { type: 'boolean' }, + }, + }, + }, + }) + const byCategory = condition('By category', { + billing: js`${classify.category} === 'billing'`, + else: true, + }) + const logTicket = table.insertRow('Log ticket', { + tableId: table('tickets'), + data: { subject: ticketIn.subject, category: classify.category }, + }) + const notify = slack.sendMessage('Notify', { + credential: credential('support-slack'), + channel: 'C0SUPPORT', + text: t`New ${classify.category} ticket (urgent: ${classify.urgent}): ${ticketIn.subject}`, + }) + + ticketIn.to(classify) + classify.to(byCategory) + byCategory.billing.to(logTicket) + byCategory.else.to(notify) + logTicket.to(notify) + logTicket.onError(notify) + } +) +``` + +How to read it: + +- Each `const` is a block. `agent`, `condition`, `table.insertRow`, and `slack.sendMessage` are the blocks you know from the workflow builder, with the same settings. +- `classify.category` is a typed reference to another block's output, the same as `` in the builder. `t` writes text with references in it; `js` writes code. +- `table('tickets')` and `credential('support-slack')` name workspace resources by a stable key. Renaming the table in Sim keeps the key. +- `env.TICKETS_WEBHOOK_TOKEN` reads an environment variable. Secret values are never printed: a key pasted into a password field prints as `stored()`, which keeps the saved value. +- `.to()` connects blocks, `byCategory.billing` is one branch of the condition, and `.onError()` follows the error path. `notify` has three incoming edges and runs once, after the branch that was taken. +- A webhook answers its caller as soon as the request is accepted and runs the workflow in the background, so the caller never sees a `response` block's output. `responseMode: 'custom'` sets that fixed answer (here `202` with `{ "ok": true }`; without it, `200` with `{ "message": "Webhook processed" }`). To answer with values the run computes, start the workflow with `trigger.start` and call it through the API; a `response` block then sets what the caller receives. + +## The file + +```ts +// @sim-sdk 1 +import { agent, t, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('Name', { description: '…', variables: { /* … */ } }, ({ vars }) => { + const start = trigger.start('Start', { inputFormat: { question: 'string' } }) + const answer = agent('Answer', { model: 'claude-sonnet-5-5', messages: [ /* … */ ] }) + start.to(answer) +}) +``` + +- Line 1 is `// @sim-sdk N`. Without it the file is refused with `E_SDK_HEADER`; a number other than the one the server reads is `E_SDK_MAJOR`. +- Imports are named imports from `'@sim/workflow-sdk'` only. Aliases are allowed. +- The file has exactly one `export default workflow(name, options?, body)` (`E_WORKFLOW_EXPORT`). `options` is `{ description?, variables? }`. `body` is `() => { … }` or `({ vars }) => { … }`. +- Variables are `variables: { : { name?, type, value } }`. `type` is `string`, `number`, `boolean`, `object`, `array` or `plain`, and both `type` and `value` are required; `value` is plain JSON. The key is the variable's key: lowercased, with spaces and dots removed. `name` is written only when it differs, and must normalize to the key (`E_VARIABLE_NAME_MISMATCH`). Read one as `vars.`. +- The body holds block declarations and wiring statements. Helpers, loops, conditionals and imports of your own have no stored form and are refused. Use `loop`, `parallel`, `condition` and `runWorkflow` blocks instead. + +## Blocks + +- `const x = builder('Name', params?, meta?)` declares a block; a bare `builder(…)` statement does too. The builder is the block's dotted path in the catalog: `agent`, `slack.sendMessage`, `table.insertRow`, `trigger.gmail.poller`. An unknown path is `E_UNKNOWN_BUILDER`, with a did-you-mean. Builders under `legacy.` are old block versions a workflow may already hold; do not write new ones. +- `block(type, 'Name', params?, meta?)` writes any block type, including a custom or legacy one that no builder fits. Params are checked against the catalog when it knows the type, and kept as written when it does not. +- A name is a non-empty string literal (`E_NAME_NOT_LITERAL`, `E_EMPTY_NAME`), unique once normalized (`E_DUPLICATE_NAME`), and not `loop`, `parallel` or `variable` (`E_RESERVED_NAME`). A name with a look-alike character, such as a Cyrillic letter inside a Latin word, is `E_LOOKALIKE_NAME`, and one with a bidirectional control or zero-width character is `W_SUSPICIOUS_CHARACTER`. +- `response(name, { body, status?, headers? })` is the Response block. Any other key is `E_UNKNOWN_PARAM`. + +### Params + +- A param is a setting of the block, named as `sim workflows source params ` lists it. For a setting the builder shows as a basic or advanced pair, you write the shared name, not either member. Writing a member by its own name is `E_UNKNOWN_PARAM`, and the hint names the right one. +- An omitted param is the default the workflow builder fills in, so a block with no params is stored like one made in the builder. `null` for a whole param stores it as absent. +- A param the builder already fixes, such as `operation`, is `E_FIXED_PARAM`. +- A param that is not visible under the block's other settings is `W_FIELD_NOT_APPLICABLE`. It never runs, so the apply keeps the stored value and the next `get` leaves the line out. +- A required field left empty, or written as `todo()`, is `W_REQUIRED_MISSING`. A value of the wrong JSON type is `W_VALUE_KIND`; it is never converted. + +### Selecting a resource or typing an ID + +For a field that offers a selector in the builder, a resource helper (`credential('key')`, `table('key')` and the others in the next section) or a non-empty array of them selects the resource. Anything else, such as `channel: 'C0123'`, is the value typed into the field. The kind of value alone decides which one you mean. + +### `meta` + +The optional third argument holds what belongs to the block, not to its settings. + +| Key | Meaning | +| --- | --- | +| `disabled: true` | The block is disabled. | +| `locked: true` | An apply refuses any change to this block. | +| `errorPort: boolean` | Exposes the error port. A block with an `onError` edge has one without this. | +| `retry: { enabled, maxTries, waitBetweenTriesMs }` | The block's retry policy, written whole. `maxTries` is a whole number from 2 to 5 and `waitBetweenTriesMs` from 0 to 5000; anything else is `E_UNSUPPORTED_SYNTAX`. | +| `advancedMode: boolean` | The block's advanced toggle, which changes what it sends. | +| `triggerMode: boolean` | Runs the block as a trigger. Trigger builders set it. | +| `branches: { : { title? } }` | The display title of a condition or router row. | +| `key: ''` | A legacy block key the name cannot produce. A `get` writes it for a stored block that needs it; any other value is `E_KEY_OVERRIDE`. | + +## Values + +- Literals, objects, arrays and negative numbers are written as in TypeScript. A number too large to store is `E_NUMBER_NOT_FINITE`, and one whose digits a number cannot hold is `W_NUMBER_PRECISION`: write it as a string. +- A string is `'…'`, an untagged template without `${}`, or a tagged template: + + | Tag | For | + | --- | --- | + | `` t`…` `` | Text with references or `env.X` in it | + | `` js`…` `` | JavaScript: a condition expression, or function code inline | + | `` py`…` ``, `` sh`…` `` | Python and shell code | + | `` json`…` `` | JSON text kept as written | + | `` md`…` `` | Markdown, such as a note's content | + +### Resource helpers + +A key is the resource's stable key in the workspace; `.sim/sdk/workspace.d.ts` lists them. A key with no live resource is `E_MAT_UNKNOWN_RESOURCE` on apply. + +| Form | Stands for | +| --- | --- | +| `credential('key')` | A saved credential | +| `table('key')` | A workspace table | +| `knowledgeBase('key')` | A knowledge base | +| `file('path')` | A workspace file | +| `folder('key')` | A workspace folder | +| `childWorkflow('key')` | A workflow, for `runWorkflow`; `.asTool()` in a `tools` list | +| `customTool('key')` | A custom tool, in a `tools` list | +| `mcp('key')` | An MCP server; `.tool(name)` in a `tools` list | +| `skill('key')` | A workspace skill | +| `codeFile('./functions/x.js')` | Function code kept in its own file | +| `stored()` | The value already stored for this param, which is not printed | +| `todo()` | No value yet | +| `env.X` | The environment variable `X`, which a block reads as `{{X}}`. The name must match `[A-Za-z_][A-Za-z0-9_]*` (`E_INVALID_ENV_NAME`) | + +In a workspace directory, `sim workspaces source check` reports a key the directory does not declare; see [Manage a workspace as code](/workflows/code/workspace). + +### Secrets and `stored()` + +A secret is never printed. A literal value in a password field prints as `stored()`, which compiles to the value the stored workflow already holds for the same block and param. A new block, another block type or an empty field has nothing stored: `stored()` there is `E_STORED_VALUE_MISSING`. To set a secret, write `env.NAME` and keep the value in the workspace's environment variables. A literal key in the file is `W_LITERAL_SECRET`. + +### References + +- `block.output`, `block['x-y']` and `block.items[0]` read another block's output; they are stored as ``, `` and ``. The path is typed from the block's outputs. A path no output has is `W_UNKNOWN_OUTPUT_PATH`, which the apply refuses as an error on a block the edit changed. +- An agent's declared `responseFormat` fields and a Start, API or Input trigger's declared `inputFormat` fields count as outputs. An input the trigger does not declare, and `x.error` on a block with no error edge, are `W_OUTPUT_PATH_UNDECLARED`: a warning the apply never refuses, because a caller may still pass the input. +- A reference to a block declared later is `W_FORWARD_REF` and still resolves. A reference into a sibling loop or parallel's child is `E_OUT_OF_SCOPE`. An identifier that names nothing is `E_UNKNOWN_IDENTIFIER`, with a did-you-mean. +- `vars.x` reads a workflow variable; an undeclared one is `E_UNKNOWN_VARIABLE`. +- `ref('Raw.path')` writes the reference text `` as you gave it. Hand-written `` text whose head is not a block key is `W_REF_NOT_NORMALIZED`. + +### JSON fields + +A field that holds JSON text, such as `responseFormat`, a table row's `data` or a response body, takes an object or array literal and stores it as formatted JSON. Each bare reference inside is quoted when the output is a string and left bare otherwise, because the run splices a bare string as JSON when it reads as JSON (`12345` would become a number) and quoted text always as text. A Function's `result`, or a field of it, has the type its JavaScript certainly returns there (a string literal, `String(…)`, `.toISOString().slice(…)` and the like are text; arithmetic, comparisons and literals are not); a Function `result` or an API `data` whose code or response may be text is untyped unless the code says. A reference no output type is known for is stored bare with `W_JSON_REF_UNTYPED`. A template is a JSON string, which is how a value becomes text on purpose. `source get` prints a stored quoted reference as the bare reference only when a declaration (the catalog, a variable's type, an input or response format) types it a string; one typed only by what a Function's code or a child workflow returns prints as ``t`${ref}` ``, so editing that code never changes how a field that reads it is stored. A resource helper inside the literal is `E_UNSUPPORTED_SYNTAX`. + +### Input formats and tools + +- `inputFormat` is a record: `name: 'string'` declares a string input, and `name: { type, … }` declares one with options. An entry with no type, such as `count: 5`, is refused. +- An agent's `tools` is an array of: + - `slack.tool.sendMessage(params)`: an integration operation, written as the block's namespace, `tool`, and the operation; + - `customTool('key')`: a workspace custom tool; + - `mcp('key').tool('name', { args? })`: one tool of an MCP server, with the arguments the workflow fixes; + - `childWorkflow('key').asTool()`: a child workflow; + - `raw(tool)`: any other stored tool, which a `get` writes when a tool does not fit the forms above. +- A tool's secret prints as `params: { key: stored() }`, resolved like a block's `stored()`. A tool that no rule matches to a stored one is `E_STORED_VALUE_MISSING`, so a deleted or reordered tool never takes another tool's secret. + +## Function code + +Code that does not fit a block goes in a Function block, kept in its own file: + +```ts +const score = fn('Score lead', { code: codeFile('./functions/score-lead.js') }) +``` + +The path is `./functions/.`, relative to `workflow.ts`, and the extension matches the block's `language`: `js` for JavaScript (the default), `py` for Python, `sh` for shell. Any other path is `E_CODE_FILE_PATH`, and a file that was not sent is `E_CODE_FILE_MISSING`. When code cannot be kept in a file, a `get` writes it inline as `` js`…` `` and reports `W_CODE_FILE_INLINED`. + +In a JavaScript file, `$ref.block.path` reads another block's output and `$env.NAME` reads an environment variable. `block` is the block's key: its name lowercased with all whitespace and every `.` removed (`$ref.triageagent.content` for "Triage Agent", `$ref.v2result.text` for "V2. Result"). Inside a loop body, `$ref.loop.currentItem` and `$ref.loop.index` read the iteration's item and position; inside a parallel body, `$ref.parallel.currentItem` and `$ref.parallel.index`. A `$ref` that names no block is refused in a file you edited, because it would not resolve when the workflow runs. Python and shell files are saved as written, so `$ref` and `$env` mean nothing there: read an output as `` (``) and an environment variable as `{{NAME}}`; a `$ref` in one is `W_CODE_FILE_REF_SYNTAX`. + +## Branches + +- A condition's params object lists its rows in order, each a string or template. Write `else: true` last for the empty else. Two or more rows must end with `else` (`E_BRANCH_ELSE_LAST`). +- A router's rows are `routes: { key: text }`. +- A branch key is unique (`E_DUPLICATE_BRANCH_KEY`) and may not be an output name, `to` or `onError` (`E_BRANCH_KEY_COLLIDES`). +- A branch that no edge leaves ends the run on that path; `check` reports it as `W_BRANCH_UNWIRED`. + +## Loops and parallel blocks + +| Form | Runs | +| --- | --- | +| `loop.for('Name', { count }, body)` | `count` times; a loop with no `count` runs 5 | +| `loop.forEach('Name', { collection }, body)` | once per item | +| `loop.while('Name', { condition }, body)` | while the condition holds | +| `loop.doWhile('Name', { condition, count }, body)` | until the condition stops it; with no condition, `count` times | +| `parallel.count('Name', { count, batchSize }, body)` | `count` branches | +| `parallel.collection('Name', { collection, batchSize }, body)` | one branch per item | + +- `body` is `(p) => { … }`, where `p.to(x)` connects the container's start to a block inside it, or `(p) => block(…)`, which does the same for one block. +- `p.index`, `p.currentItem` and `p.items` read the iteration; any other property is `E_UNKNOWN_SUBFLOW_PROPERTY`. They are stored as `` or ``. +- A `count` that is not a whole number of at least 1, or a `batchSize` outside 1 to 20, is `W_SUBFLOW_COUNT`: the run replaces or clamps it. + +## Wiring + +| Form | Connects | +| --- | --- | +| `a.to(b, c)` | `a` to `b` and `a` to `c` | +| `a.to(b).to(c)` | a chain | +| `a.to(b, c).to(d)` | `b` to `d` and `c` to `d` | +| `a.onError(b)` | the error path of `a` | +| `cond.key.to(x)` | one branch of a condition or router | +| `container.to(x)` | what runs after the loop or parallel finishes | + +Refused: `.to()` on a condition or router itself (`E_NO_DEFAULT_OUTPUT`; wire a branch), a branch that does not exist (`E_UNKNOWN_BRANCH`), an edge into a trigger (`E_TARGET_TRIGGER`), `onError` on a block with no error port (`E_ERROR_PORT_UNSUPPORTED`), an edge to or from a note (`E_EDGE_NOTE`), an edge across loop or parallel scopes (`E_EDGE_SCOPE`), a repeated edge (`E_DUPLICATE_EDGE`) and a cycle (`E_EDGE_CYCLE`). Repeat work with a `loop` instead. + +## Comments + +Comments you write are kept and written back where they were. One inside an expression moves to the statement it belongs to (`W_COMMENT_MOVED`). One whose block no longer exists is dropped (`W_COMMENT_DROPPED`). + +## Related docs + +- [Diagnostic codes](/workflows/code/diagnostics) +- [Edit a workflow](/workflows/code/edit) +- [Directory layout](/workflows/code/directory) +- [Limits](/workflows/code/limits) diff --git a/apps/docs/content/docs/workflows/code/troubleshooting.mdx b/apps/docs/content/docs/workflows/code/troubleshooting.mdx new file mode 100644 index 00000000000..5fd2eacde6c --- /dev/null +++ b/apps/docs/content/docs/workflows/code/troubleshooting.mdx @@ -0,0 +1,164 @@ +--- +title: Troubleshooting +description: Fix a failed sim workflows source or sim workspaces source command, by exit code and by diagnostic code. +--- + +Every `sim workflows source` and `sim workspaces source` command reports a failure in two ways: an exit code for the kind of failure, and findings that each name a code, a file, a line and a hint. Find the exit code below first, then the code of the first error it printed. + +Each finding prints as `file:line:column`, with the code around it and a hint. `--output json` puts the same findings in a `diagnostics` array, and a refused write prints an `{error:…}` document on stderr whose `details.code` names the refusal, such as `SOURCE_STALE`. Fix the first error first: later ones often follow from it. + +## By exit code + +[Exit codes](/workflows/code/exit-codes) has the full table. These are the causes behind each code and how to get past them. + +### Exit `1`: errors, or the command failed [#exit-1] + +- **The source has errors.** Fix each one at the line it names. The [diagnostic codes](#by-diagnostic-code) below cover the common ones, and [Diagnostic codes](/workflows/code/diagnostics) lists every code. +- **`check` failed on a warning.** An apply saves some warnings as written, such as a required field left empty, so `check` fails on them in a block you added since the `get`. `sim workflows source check --help` lists them. +- **"No block catalog is cached".** `sim workflows source check` and `params` work from the catalog the last `get` or `create` cached on this machine. Run `get` once, for example on a fresh CI runner. `sim workspaces source check` downloads the catalog itself. +- **A name is taken.** `SOURCE_NAME_TAKEN` on `create`: pass `--name`. `E_NAME_TAKEN` on an apply: another resource of the same kind already has that name, such as another workflow in the folder for the name `workflow('…')` gives, or another skill or custom tool in a workspace directory. +- **`get` refused the directory.** `SOURCE_LOCAL_EDITS` means the directory holds edits no apply has saved: apply them, get into another directory, or pass `--force` to discard them. `SOURCE_WORKFLOW_MISMATCH` means it holds another workflow, and `SOURCE_DIR_KIND_MISMATCH` that it is the other kind of directory, which `--force` never overrides. +- **The directory belongs to another workspace.** `SOURCE_OTHER_WORKSPACE`: a directory acts on the workspace it was read from. Drop `--workspace`, or promote it with `--to`. +- **Binary files were never downloaded.** `SOURCE_BLOBS_NOT_FETCHED`: run `get` again before applying. + +### Exit `5`: stale [#exit-5] + +Someone saved what this directory was read from after you read it, in the workflow builder, through the API, or with another apply. A workflow apply, and a workspace apply refused while planning, writes nothing; a dry run exits `5` the same way. A workspace apply that found a resource changed part-way through its writes has saved the changes before it into the directory, so carry over only the rest. + +1. See what changed in Sim: `sim workflows source diff --dir --server`. +2. Get the current version into a fresh directory: `sim workflows source get --dir `. +3. Carry your edit over, then dry-run and apply from the fresh directory. + +In CI, this happens when an apply rewrote files that were not committed back, or when two branches each applied: commit the files an apply rewrites, as [Run in CI](/workflows/code/ci) does. In a promotion, it means the target changed a resource the directory changed too; carry the target's change into the source workspace, or undo it in the target. + +### Exit `6`: locked [#exit-6] + +The workflow, its folder or a table is locked against changes (`E_APPLY_LOCKED`). Ask someone who can to unlock it in Sim. A locked block inside an unlocked workflow exits `1` instead, with `E_APPLY_LOCKED_BLOCK`. + +### Exit `7`: over a limit [#exit-7] + +The workflow or directory is larger than one get or apply may handle, and the finding names each measured size. Split a large workflow into a parent and a child workflow, or apply a workspace in parts with `--only`. The numbers are in [Limits](/workflows/code/limits). + +### Exit `8`: a workspace apply stopped part-way [#exit-8] + +A write failed on the server after earlier writes were saved. The CLI saved what was written into the directory and printed the plan with each change marked written or not written. Run the same apply again until it exits `0`; it continues where it stopped. + +### Exit `9`: rate limited [#exit-9] + +The API still answered `429` after the CLI's retries, and nothing more was written. Wait a minute and run the same command again. In CI, avoid several jobs applying at once with a `concurrency` key. + +### Exit `10`: busy [#exit-10] + +- `SOURCE_BUSY`: another apply is writing the same workspace. Run yours again once it finished. +- `SOURCE_DIR_BUSY`: another `sim` command is using this directory, or the workspace directory it is a folder of. The CLI holds `.sim/command.lock/` while a command runs, and takes it over once the process holding it has gone, so run the command again. + +Nothing was read or written either way. + +### Exit `11`: your edits are not applied [#exit-11] + +Only `status` exits `11`, and it is not a failure: the directory holds edits that applying would write. Dry-run, then apply. In a scheduled CI check, `11` usually means a merge whose apply failed. + +### Exit `12`: Sim changed since the get [#exit-12] + +Only `status` exits `12`. Follow its `Next:` line: + +- **Drift**, Sim changed and the directory did not: `get` into the same directory brings it up to date. Commit the result. +- **A conflict**, both changed the same workflow or resource: an apply would be refused as stale. Get into a fresh directory and carry your edit over, as for [exit `5`](#exit-5). + +### Exit `13`: not signed in [#exit-13] + +No login, an expired login, or a credential the server refused (`AUTH_REQUIRED`). Run `sim login`, or fix or unset `SIM_API_KEY` when the key comes from it, then run the same command again. See [Authentication](/cli/authentication). + +### Exit `14`: apply without `--yes` [#exit-14] + +`apply` or `create` found no errors, printed the plan, and wrote nothing, because there was no terminal to confirm in. Run the same command with `--yes`. + +### Exit `15`: changes held back [#exit-15] + +A workspace apply wrote what it could and held back each change that uses a secret the workspace has no value for (`E_SECRET_MISSING`) or a credential key no credential binds to (`E_CREDENTIAL_MISSING`, `E_CREDENTIAL_AMBIGUOUS`). Set the secret with `sim secrets set NAME --scope workspace`, or connect the credential, then apply again. A dry run exits `15` too, so a script can find out first. + +### Exit `130`: interrupted [#exit-130] + +Ctrl-C. If the CLI says a write may have happened, `status` shows whether it did. + +## A command answers `403` [#forbidden] + +- **"Workflows as code is in preview and not enabled for this workspace".** The feature is off for this workspace; see [Workflows as code](/workflows/code) for how it is enabled. +- **A workspace API key.** Saving a workflow acts as a person, so it needs a personal API key or an OAuth login. In a workspace directory, a workspace key can apply only some kinds and the rest are refused with `E_APPLY_FORBIDDEN`; see [Workspace API keys](/workflows/code/workspace#workspace-api-keys). + +## By diagnostic code + +### `E_UNSUPPORTED_SYNTAX` [#e-unsupported-syntax] + +The file holds a form Sim cannot read without running it, such as a helper function, an `if`, a loop that creates blocks, or an import from anything but `@sim/workflow-sdk`. Write each block as its own `const`, use `loop()`, `parallel()`, `condition` or `router` blocks for control flow, and put logic inside function code. The hint names the supported form; [File syntax](/workflows/code/syntax) lists them all. + +### `E_UNKNOWN_BUILDER` and `E_UNKNOWN_PARAM` [#e-unknown-param] + +A builder or param name the block catalog does not have. The hint suggests the closest name. `sim workflows source params ` prints a builder's params and outputs, and a namespace such as `gmail` lists its builders. + +### `E_TYPE` and `W_TYPES_UNCHECKED` [#e-type] + +`E_TYPE` is a type error `check` found after the compile; its message starts with TypeScript's own code, such as `TS2339: Property 'emial' does not exist`. Fix it at the line it names: it usually reads an output or input the block does not declare, or passes a value of the wrong type. `W_TYPES_UNCHECKED` means the type check did not run, most often because the first `check` on this machine could not install TypeScript offline. The compile's findings still stand; run `check` once with network access, or pass `--no-types`. + +### `W_REQUIRED_MISSING` [#w-required-missing] + +A required field is empty, or holds `todo()`. Fill it in, or use `env.NAME` for a value you keep in an environment variable. + +### `E_APPLY_UNRESOLVED_REF` [#e-apply-unresolved-ref] + +A reference names a block that does not exist, or an output path the block does not have. In `workflow.ts`, read an output through the block's `const`, as in `triage.content`. In function code, `$ref.` uses the block key: the display name lowercased with whitespace and dots removed. The hint lists the outputs the block has. + +### `E_MAT_UNKNOWN_RESOURCE` [#e-mat-unknown-resource] + +A resource helper, such as `table('orders')` or `credential('support-slack')`, names a key no live resource has. Keys are exact. `sim workflows source resources` lists the keys of your workspace; in a workspace directory, a key is the resource's file or folder name, and `check` lists the declared ones. + +### `E_APPLY_BLOCK_DELETE` and `W_MAT_INFERRED_RENAME` [#e-apply-block-delete] + +The save would delete blocks: a stored block no longer matches any block in the file. If you meant to delete them, apply again with `--allow-delete`; a deleted block's webhook URL, schedules and run history go with it. + +If you meant a rename, keep the `.sim/` folder, change the display name and keep the `const` name, or the other way round, and apply that before the next rename. When the file adds a block of the deleted one's type, the finding names it as a possible rename and says how to keep the ID. A rename Sim inferred from type, position and connections is reported as `W_MAT_INFERRED_RENAME`: check the plan names the block you meant. `E_APPLY_VARIABLE_DELETE` is the same for workflow variables. + +### `E_APPLY_LOCKED_BLOCK` [#e-apply-locked-block] + +The change touches a locked block, or a block inside a locked loop or parallel. Nobody can change it from the file. Unlock it in the workflow builder, or leave it as it is. + +### `E_APPLY_NO_BASE` [#e-apply-no-base] + +A declaration in a workspace directory matches a resource Sim holds that the directory never read, such as a table someone made in Sim under the same name. The apply may only add to such a resource. Run `get` into a new directory to read it, then make your edit there, or give the declaration another name. + +### `E_KEY_RENAMED` [#e-key-renamed] + +A resource file or folder in a workspace directory was renamed. Keys never change: move it back to its key, and change the resource's `name` inside the file instead. + +### `E_APPLY_FORBIDDEN` [#e-apply-forbidden] + +Your role in the workspace, or a workspace API key, does not allow the change. The finding names each resource. Use a personal API key or an OAuth login with the role the change needs, or narrow the apply with `--only`. + +### `E_EDGE_CYCLE` [#e-edge-cycle] + +The wiring closes a cycle, so no block on it would ever run. Remove the edge the finding points at, and repeat work with `loop()` instead. + +### `E_STORED_VALUE_MISSING` [#e-stored-value-missing] + +`stored()` stands for a saved value, such as a secret, that `get` does not print. A workflow created from a copy has no saved value to keep. Replace `stored()` with `env.NAME` or the value. + +### `W_APPLY_CATALOG_MOVED` [#w-apply-catalog-moved] + +The compile failed, and the block catalog changed since you read the workflow, for example because a block gained a setting. Run `get` again to update the types, then reapply your edit. + +### `W_APPLY_TRIGGER_REMOVED` [#w-apply-trigger-removed] + +You deleted or retyped a block that serves a live webhook, schedule, chat or MCP tool. The deployed version keeps serving it until the next deploy. Deploy when the change should take effect, and update whatever called the old webhook URL. + +## Other problems + +- **The builder does not show a change.** An apply saves the draft. The builder shows it at once, but runs of the deployed version do not change until you deploy. +- **The Code tab is missing.** Workflows as code is not enabled for the workspace; see [Workflows as code](/workflows/code). + +## Related docs + +- [Exit codes](/workflows/code/exit-codes) +- [Diagnostic codes](/workflows/code/diagnostics) +- [Limits](/workflows/code/limits) +- [How it works](/workflows/code/how-it-works) +- [CLI troubleshooting](/cli/troubleshooting) diff --git a/apps/docs/content/docs/workflows/code/workspace.mdx b/apps/docs/content/docs/workflows/code/workspace.mdx new file mode 100644 index 00000000000..3a525475ee7 --- /dev/null +++ b/apps/docs/content/docs/workflows/code/workspace.mdx @@ -0,0 +1,88 @@ +--- +title: Manage a workspace as code +description: Keep a workspace's tables, knowledge bases, files, custom tools, skills and workflows in one directory, and apply it in one step. +--- + +import { Callout } from '@/components/ui/callout' + +A whole workspace can be read and written as a directory: one folder per kind of resource, with each workflow written exactly as [workflows as code](/workflows/code) writes it. One apply creates the resources before the workflows that use them, so a coding agent can build a working setup from scratch. + + +Workspace as code is in preview, behind the [same setting](/workflows/code) as workflows as code. It adds the `sim workspaces source` commands to the [CLI](/cli/workspaces#workspace-as-code). + + +## The directory + +The layout of every kind and each file's role is in [Directory layout](/workflows/code/directory). A resource's key is its file or folder name, and a workflow names it by that key: + +```ts title="workflows/support/workflow.ts" +const policy = knowledge.search('Policy Search', { + knowledgeBaseId: knowledgeBase('policies'), + query: start.question, +}) +const answer = agent('Answer', { + model: 'claude-sonnet-4-6', + messages: [{ role: 'user', content: t`${policy.results}\n\n${start.question}` }], + tools: [customTool('lookup-order')], + skills: [skill('tone')], +}) +const log = table.insertRow('Log Question', { + tableId: table('orders'), + data: { orderId: start.orderId, status: 'answered' }, +}) +``` + +`get` writes a short primer for coding agents atop `.sim/AGENTS.md`, the guide, with deletes in depth, Git and CI, and promoting to another workspace in `.sim/GUIDE-advanced.md`. It also writes `.sim/examples/workspace/`, a complete example of every kind and the workflow that uses them. + +## Edit a workspace + +```bash +sim workspaces source get --dir ./my-workspace +sim workspaces source check --dir ./my-workspace +sim workspaces source status --dir ./my-workspace +sim workspaces source apply --dir ./my-workspace --dry-run +sim workspaces source apply --dir ./my-workspace --yes +``` + +`check` compiles every workflow on your machine against what the directory declares: an unknown table, credential, knowledge base, skill, custom tool, MCP server or workflow key, a table row write naming a column the table does not declare, and a child workflow call whose `inputMapping` names an input the child's Start trigger does not declare, are reported, and an env name `secrets.ts` lacks is a warning. It checks each `tables/.rows.jsonl` line against its table the way an apply writes it (a required cell, a unique value, a column's type and select options), so the dry run's `E_TABLE_ROWS` shows up offline at its line. It exits 1 on errors and, as `sim workflows source check` does, on a broken block you added. + +Unlike a workflow directory's `check`, it needs the block catalog but fetches it for you: on a fresh clone with none cached it downloads the catalog once with the profile's credentials, and without credentials it exits `1` and tells you to run `get`. It also regenerates `.sim/sdk/workspace.d.ts` from the declarations and then type-checks every file, so a table, workflow or other key the directory declares since the get is typed in the same check. Run in a `workflows/` folder, `sim workflows source check --dir .` checks that one workflow the same way. + +The dry run prints the plan (`+` create, `~` update, `=` adopt an existing resource with the same name, `-` delete) and every error with its file and line. `--only tables,workflows` limits a get or an apply to some kinds. + +An apply adopts a resource it never read (one made in Sim under the name a new declaration gives) only when the declaration matches it, or only adds to it: a column, rows into an empty table, a document. An adopt that would change or remove anything the resource holds is refused with `E_APPLY_NO_BASE`, even with `--allow-delete`. Run `get` into a new directory to read the resource, then make your edit there, or give the declaration another name. + +`status` shows what would happen if you applied, without writing anything: the files you created, edited, or deleted, grouped by resource; what changed in Sim since the `get` (a resource edited, added, or deleted there, a workflow edited in the workflow builder included); the conflicts, where a resource changed on both sides; and the one command to run next. It exits `0` when nothing changed, `11` when only your edits are unapplied, and `12` when something changed in Sim since the `get`, so a script or an agent can branch on it. Its JSON `plan` counts errors and warnings as the dry run of the apply it names next would, a conflict as an error. Without a connection it shows your edits only and says so; `--offline` skips the server. `diff [paths or kind:key…]` prints the edits as unified diffs (a binary file by its sizes), and `diff --server` compares the directory with what Sim holds now. Both take `--json` (or `--output json`). + +## Workspace API keys [#workspace-api-keys] + +A personal API key or an OAuth login can apply every kind its workspace role allows. A workspace API key cannot create or change workflows, skills, secrets or deployments. An apply with one that would is refused with `E_APPLY_FORBIDDEN`, naming each resource, before anything is written. A `get` with a workspace key leaves out the kinds it cannot read, such as `secrets.ts`, and names them with the same code. + +To apply the rest with a workspace key, such as in CI, narrow the apply to the kinds it can write: `sim workspaces source apply --dir ./my-workspace --only tables,knowledge,files,tools,mcp,credentials.ts --yes`. Deployments need an admin's personal key. + +## Deletes + +- A kind is managed only when its folder exists. A directory without `skills/` never touches a skill. +- Removing the file of a resource the directory manages deletes it only with `--allow-delete`; without the flag the apply is refused. The flag also covers a removed table column, managed table row, knowledge base document, workspace file, workflow block or workflow variable. +- A resource the directory never managed is kept, and the apply names it in a warning. +- Something deleted in Sim is not re-created by an unchanged directory, and an edit to it is refused as stale. +- Table rows are part of the directory only when the table's `rows` opts in (`tables/.rows.jsonl`). Connector-synced documents and run history never are. +- Seed rows (`rows: { mode: 'seed' }`) belong to the directory: `get` keeps the declaration and the rows file beside it, but Sim does not store them, so a get into a new directory has the declaration without the file. +- A delete cannot be undone by applying an older copy of the directory, such as a reverted commit. The resource stays deleted, and its rows, documents, run history, webhook URLs and schedules are gone. The dry run marks each change that deletes data and counts them as `destructive`, a workflow update that removes blocks or variables included. + +## Good to know + +- Secret values never appear. Workflows read environment variables as `env.NAME`, tool code as `$env.NAME`, and credentials by key. +- Renaming a skill does not rewrite the workflows that use it: each agent keeps the name it stored until its skills list is next edited. +- Hidden files (a name starting with a dot, such as `files/.env`) and names with a character no workspace path holds (such as `:` or `?`) are never sent. An apply names each one in a `W_PATH_NOT_SENT` warning. +- A knowledge base's `embeddingModel` is fixed when it is created. An apply that changes it is refused. +- An apply that stops part-way exits `8`, prints the plan again with each change marked written or not written (`notWritten` in JSON), and saves what it wrote into the directory. Run the same apply again until it exits `0`. The dry run checks an MCP server's URL as the write does, so an unresolvable host is refused before anything is written. +- An apply exits `5` when a resource changed in Sim after you read it. Run `get` into a new directory and reapply your edit. +- Size caps, and what is left out of a get, are in [Limits](/workflows/code/limits). + +## Related docs + +- [Promote to another workspace](/workflows/code/promote) +- [Run in CI](/workflows/code/ci) +- [Directory layout](/workflows/code/directory) +- [CLI workspace commands](/cli/workspaces#workspace-as-code) diff --git a/apps/docs/content/docs/workflows/meta.json b/apps/docs/content/docs/workflows/meta.json index 8762490d5cb..bfbd3c07fdc 100644 --- a/apps/docs/content/docs/workflows/meta.json +++ b/apps/docs/content/docs/workflows/meta.json @@ -6,8 +6,6 @@ "connections", "variables", "large-data", - "code", - "workspace-code", "deployment", "triggers", "blocks" diff --git a/apps/docs/content/docs/workflows/workspace-code.mdx b/apps/docs/content/docs/workflows/workspace-code.mdx deleted file mode 100644 index e75a9f22189..00000000000 --- a/apps/docs/content/docs/workflows/workspace-code.mdx +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: Workspace as code -description: Keep a workspace's tables, knowledge bases, files, custom tools, skills and workflows in one directory, and apply it in one step. ---- - -import { Callout } from '@/components/ui/callout' - -A whole workspace can be read and written as a directory: one folder per kind of resource, with each workflow written exactly as [workflows as code](/workflows/code) writes it. One apply creates the resources before the workflows that use them, so a coding agent can build a working setup from scratch. - - -Workspace as code is in preview, behind the [same setting](/platform/self-hosting/environment-variables#preview-features) as workflows as code. It adds the `sim workspaces source` commands to the [CLI](/cli/workspaces). - - -## The directory - -``` -secrets.ts the env variable names workflows read (never a value) -credentials.ts the saved credentials workflows use, by provider -tables/orders.ts a table: name, description, columns -tables/plans.rows.jsonl a table's rows, one JSON object per line (only when the table opts in) -knowledge/policies/knowledge.ts a knowledge base: name, chunking -knowledge/policies/docs/*.md one file per document -files/templates/reply.md a workspace file, at its folder path -tools/lookup-order.ts a custom tool: title and schema -tools/lookup-order.js the tool's code -skills/tone.md a skill: name and description, then its content -mcp/docs.ts an MCP server: url, headers -workflows/support/workflow.ts a workflow source directory -deployments/support.ts how workflows/support is deployed -``` - -A resource's key is its file or folder name, and a workflow names it by that key: - -```ts title="workflows/support/workflow.ts" -const policy = knowledge.search('Policy Search', { - knowledgeBaseId: knowledgeBase('policies'), - query: start.question, -}) -const answer = agent('Answer', { - model: 'claude-sonnet-4-6', - messages: [{ role: 'user', content: t`${policy.results}\n\n${start.question}` }], - tools: [customTool('lookup-order')], - skills: [skill('tone')], -}) -const log = table.insertRow('Log Question', { - tableId: table('orders'), - data: { orderId: start.orderId, status: 'answered' }, -}) -``` - -`get` prints a short primer for coding agents (in JSON output, its `primer` field) and writes it atop `.sim/AGENTS.md`, the guide, with deletes in depth, Git and CI, and promoting to another workspace in `.sim/GUIDE-advanced.md`. It also writes `.sim/examples/workspace/`, a complete example of every kind and the workflow that uses them. - -## Edit a workspace from the CLI - -```bash -sim workspaces source get --dir ./my-workspace -sim workspaces source check --dir ./my-workspace -sim workspaces source status --dir ./my-workspace -sim workspaces source apply --dir ./my-workspace --dry-run -sim workspaces source apply --dir ./my-workspace --yes -``` - -`check` compiles every workflow on your machine, without a request, against what the directory declares: an unknown table, credential, knowledge base, skill, custom tool, MCP server or workflow key, a table row write naming a column the table does not declare, and a child workflow call whose `inputMapping` names an input the child's Start trigger does not declare, are reported, and an env name `secrets.ts` lacks is a warning. It checks each `tables/.rows.jsonl` line against its table the way an apply writes it (a required cell, a unique value, a column's type and select options), so the dry run's `E_TABLE_ROWS` shows up offline at its line. It exits 1 on errors and, as `sim workflows source check` does, on a broken block you added. It also regenerates `.sim/sdk/workspace.d.ts` from the declarations, so run `bunx -p typescript@7.0.2 tsc -p ./my-workspace` after it to type-check every file, keys added since the get included. Run in a `workflows/` folder, `sim workflows source check --dir .` checks that one workflow the same way. - -The dry run prints the plan (`+` create, `~` update, `=` adopt an existing resource with the same name, `-` delete) and every error with its file and line. `--only tables,workflows` limits a get or an apply to some kinds. - -An apply adopts a resource it never read (one made in Sim under the name a new declaration gives) only when the declaration matches it, or only adds to it: a column, rows into an empty table, a document. An adopt that would change or remove anything the resource holds is refused with `E_APPLY_NO_BASE`, even with `--allow-delete`. Run `get` into a new directory to read the resource, then make your edit there, or give the declaration another name. - -`status` shows what would happen if you applied, without writing anything: the files you created, edited, or deleted, grouped by resource; what changed in Sim since the `get` (a resource edited, added, or deleted there, a workflow edited in the editor included); the conflicts, where a resource changed on both sides; and the one command to run next. It exits `0` when nothing changed, `11` when only your edits are unapplied, and `12` when something changed in Sim since the `get`, so a script or an agent can branch on it. Its JSON `plan` counts errors and warnings as the dry run of the apply it names next would, a conflict as an error. Without a connection it shows your edits only and says so; `--offline` skips the server. `diff [paths or kind:key…]` prints the edits as unified diffs (a binary file by its sizes), and `diff --server` compares the directory with what Sim holds now. Both take `--json` (or `--output json`). - -## Workspace API keys [#workspace-api-keys] - -A personal API key or an OAuth login can apply every kind its workspace role allows. A workspace API key cannot create or change workflows, skills, secrets or deployments. An apply with one that would is refused with `E_APPLY_FORBIDDEN`, naming each resource, before anything is written. A `get` with a workspace key leaves out the kinds it cannot read, such as `secrets.ts`, and names them with the same code. - -To apply the rest with a workspace key, such as in CI, narrow the apply to the kinds it can write: `sim workspaces source apply --dir ./my-workspace --only tables,knowledge,files,tools,mcp --yes`. - -## Deletes - -- A kind is managed only when its folder exists. A directory without `skills/` never touches a skill. -- Removing the file of a resource the directory manages deletes it only with `--allow-delete`; without the flag the apply is refused. The flag also covers a removed table column, managed table row, knowledge base document, workspace file, workflow block or workflow variable. -- A resource the directory never managed is kept, and the apply names it in a warning. -- Something deleted in Sim is not re-created by an unchanged directory, and an edit to it is refused as stale. -- Table rows are part of the directory only when the table's `rows` opts in (`tables/.rows.jsonl`). Connector-synced documents and run history never are. -- Seed rows (`rows: { mode: 'seed' }`) belong to the directory: `get` keeps the declaration and the rows file beside it, but Sim does not store them, so a get into a new directory has the declaration without the file. -- A delete cannot be undone by applying an older copy of the directory, such as a reverted commit. The resource stays deleted, and its rows, documents, run history, webhook URLs and schedules are gone. The dry run marks each change that deletes data and counts them as `destructive`, a workflow update that removes blocks or variables included. - -## Promote to another workspace - -Apply a directory read from one workspace (dev) to another (prod) with `--to`: - -```bash -sim workspaces source apply --dir ./my-workspace --to "$PROD_WORKSPACE_ID" --dry-run -sim workspaces source apply --dir ./my-workspace --to "$PROD_WORKSPACE_ID" --yes -``` - -Each resource binds by key to the target's own. One the target holds under the same key is updated in place, so a workflow keeps its id and its webhook URLs. A key the target lacks is created. Secrets and credentials bind by name to the target's own, and no value is copied. A resource you deleted from the directory since the last promotion is deleted in the target too, and like any delete it needs `--allow-delete`. Resources only the target holds, such as a table created in prod and the rows its runs wrote, are kept, with or without `--allow-delete`: the plan names each with a `W_UNDECLARED` warning. To delete them as well, pass `--delete-target-only` beside `--allow-delete`; the plan then names each with a `W_PROMOTE_DELETES_TARGET_ONLY` warning, so run it with `--dry-run` first. The directory stays bound to the workspace it was read from. Without `--to`, `check`, `status`, `diff` and `apply` act on the workspace the directory was read from, whatever your default workspace; a `--workspace` naming another one is refused. - -Each promotion records what it left in the target in `.sim/targets/.json`, and the next promotion compares with that record: - -- A resource changed in the target since the last promotion, such as a hotfix made in Sim, is kept when the directory left it alone. -- When the directory changed it too, the promotion is refused as stale and exits `5`. Carry the target's change into the source workspace, or undo it in the target, then promote again. -- A resource deleted in the target since the last promotion stays deleted, with a `W_PROMOTE_TARGET_DELETED` warning. Remove its entry from the record to create it again. -- The first promotion, and any resource the record does not hold (one created in the target since), updates the target to match the directory. Review the dry run first. - -Commit the record with the rest of the directory, so a promotion from CI or another clone compares with it. Don't delete it to get past a stale refusal: without it, the next promotion overwrites every change made in the target since, including rows its workflows wrote. - -## Git and CI - -Commit the whole directory, including `.sim/`: its base files are what an apply compares with, from any clone. The generated `.gitignore` leaves out only temporary files. A fresh clone can run `check`, `apply --dry-run` and `apply` with nothing else. See [Workspace source in CI](/cli/scripting#workspace-source-in-ci) for a GitHub Actions setup. - -In a git repository, `apply` sends the commit checked out (`HEAD`) and the `origin` remote URL, with any credentials, query or fragment removed, as `provenance.gitSha` and `provenance.repo`, each only when `git` can read it (a repository with no `origin` sends only the commit). An apply that writes records what was sent in its `workspace.updated` [audit log](/platform/enterprise/audit-logs) entry. A directory outside a repository sends neither. - -## Good to know - -- Secret values never appear. Workflows read environment variables as `env.NAME`, tool code as `$env.NAME`, and credentials by key. -- Renaming a skill does not rewrite the workflows that use it: each agent keeps the name it stored until its skills list is next edited. -- One apply sends at most 100 edited workflows and makes at most 1,000 changes; a directory holds at most 500 resources of a kind, and a `tables/.rows.jsonl` at most 10,000 rows. An apply over a limit is refused before anything is written. -- A document or file over 10 MB, or whose name a directory cannot hold, is left out of `get` and listed in `.sim/skipped.json`. An apply never writes or deletes it. -- Hidden files (a name starting with a dot, such as `files/.env`) and names with a character no workspace path holds (such as `:` or `?`) are never sent. An apply names each one in a `W_PATH_NOT_SENT` warning. -- A knowledge base's `embeddingModel` is fixed when it is created. An apply that changes it is refused. -- An apply that stops part-way exits `8`, prints the plan again with each change marked written or not written (`notWritten` in JSON), and saves what it wrote into the directory. Run the same apply again until it exits `0`. The dry run checks an MCP server's URL as the write does, so an unresolvable host is refused before anything is written. -- An apply exits `5` when a resource changed in Sim after you read it. Run `get` into a new directory and reapply your edit. - -See [CLI workspace commands](/cli/workspaces) for every flag. diff --git a/apps/docs/lib/redirects.ts b/apps/docs/lib/redirects.ts index be04cce4921..cbc6cc8008f 100644 --- a/apps/docs/lib/redirects.ts +++ b/apps/docs/lib/redirects.ts @@ -110,6 +110,12 @@ const PATH_REDIRECTS: DocsRedirect[] = [ { source: '/building-agents/agents', destination: '/agents', permanent: true }, // form deployment removed { source: '/deployment/form', destination: '/workflows/deployment', permanent: true }, + // workspace as code moved into the workflows-as-code section + { + source: '/workflows/workspace-code', + destination: '/workflows/code/workspace', + permanent: true, + }, // copilot deprecated and removed { source: '/copilot', destination: '/chat', permanent: true }, { source: '/copilot/:path*', destination: '/chat', permanent: true }, diff --git a/apps/docs/openapi-v2-logs.json b/apps/docs/openapi-v2-logs.json index 69ab7abd928..9544e65e629 100644 --- a/apps/docs/openapi-v2-logs.json +++ b/apps/docs/openapi-v2-logs.json @@ -479,6 +479,7 @@ "startedAt": "2026-01-15T10:30:00.000Z", "endedAt": "2026-01-15T10:30:01.250Z", "totalDurationMs": 1250, + "failure": null, "files": [ { "id": "f1c3a7d0-4b52-4a8e-9f61-2d7c8b3e5a04", @@ -1394,6 +1395,10 @@ "type": "string", "description": "Workflow block associated with the span." }, + "childDeploymentVersionId": { + "type": "string", + "description": "Deployment version of the child workflow this call ran, on a workflow block span or a workflow Agent tool span. Match it to the child workflow's versions list. Absent for draft children, custom blocks, failed Agent tool calls, and runs recorded before this field existed." + }, "input": { "description": "Input captured for the traced operation." }, @@ -1653,6 +1658,55 @@ ], "description": "Total execution duration in milliseconds, or null while unavailable." }, + "failure": { + "anyOf": [ + { + "type": "object", + "properties": { + "blockId": { + "type": "string", + "description": "Identifier of the block the run failed in." + }, + "blockName": { + "type": "string", + "description": "Name of the block the run failed in." + }, + "blockType": { + "type": "string", + "description": "Type of the block the run failed in." + }, + "error": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The error the block recorded, or null when its span carries none (a withheld or compacted trace). A Function block's error leads with the line and code that threw." + }, + "errorMessage": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "The failed block's declared `errorMessage` output (Function blocks today): the thrown message alone, which is the text to reply with. Null for any other block." + } + }, + "required": ["blockId", "blockName", "blockType", "error", "errorMessage"], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "Where the run failed, read from the trace: the innermost block whose error nothing handled. Null when the run did not fail, or the trace does not name one (not recorded, compacted, or withheld by a permission group)." + }, "files": { "anyOf": [ { @@ -1913,6 +1967,7 @@ "startedAt", "endedAt", "totalDurationMs", + "failure", "files", "executedByEmail", "workflow", @@ -1951,6 +2006,7 @@ "startedAt": "2026-01-15T10:30:00.000Z", "endedAt": "2026-01-15T10:30:01.250Z", "totalDurationMs": 1250, + "failure": null, "files": [ { "id": "f1c3a7d0-4b52-4a8e-9f61-2d7c8b3e5a04", diff --git a/apps/docs/openapi-v2-resources.json b/apps/docs/openapi-v2-resources.json index 09319939460..6c474f3c6d2 100644 --- a/apps/docs/openapi-v2-resources.json +++ b/apps/docs/openapi-v2-resources.json @@ -6458,6 +6458,7 @@ "send": { "toolId": "slack_message", "toolName": "Slack Send Message", + "effect": "write", "description": "Send a message to a Slack channel.", "inputs": { "text": { @@ -6488,6 +6489,7 @@ "name": "Slack Send Message", "description": "Send a message to a Slack channel.", "version": "1.0.0", + "effect": "write", "hostedApiKey": "none", "oauth": { "required": true, @@ -6706,6 +6708,7 @@ "name": "Slack Send Message", "description": "Send a message to a Slack channel.", "version": "1.0.0", + "effect": "write", "hostedApiKey": "none", "oauth": { "required": true, @@ -6815,6 +6818,7 @@ "name": "Slack Send Message", "description": "Send a message to a Slack channel.", "version": "1.0.0", + "effect": "write", "hostedApiKey": "none", "oauth": { "required": true, @@ -21943,6 +21947,11 @@ "description": "Tool version.", "type": "string" }, + "effect": { + "type": "string", + "enum": ["read", "write"], + "description": "What running the tool does outside Sim. `read` changes nothing there: no create, update, delete, send, post, trigger, enqueue, consume, or mark-read; no asynchronous provider job or query execution started (one with its own id that can keep running, even briefly; a synchronous read-only query is fine); no run, conversation, history item, or other resource left in an account; no contact data revealed for credits; no external delivery. Usage billing for the call itself does not count. `write` is anything else, including an effect that depends on the input. Revealing a person's contact data (email, phone) for credits is `write`; company/firmographic lookups and verifications that only spend lookup credits are `read`." + }, "hostedApiKey": { "type": "string", "enum": ["always", "conditional", "none"], @@ -21992,7 +22001,7 @@ "description": "Fields the tool produces." } }, - "required": ["id", "name", "description", "hostedApiKey", "params", "outputs"], + "required": ["id", "name", "description", "effect", "hostedApiKey", "params", "outputs"], "additionalProperties": false, "title": "Tool", "description": "A built-in tool with its declared parameters and outputs." @@ -22190,6 +22199,11 @@ "description": "Display name of that tool.", "type": "string" }, + "effect": { + "description": "That tool's effect.", + "type": "string", + "enum": ["read", "write"] + }, "description": { "description": "What the operation does.", "type": "string" @@ -22253,11 +22267,47 @@ "properties": { "type": { "type": "string", - "description": "Value type of the output." + "description": "Value type of the output field." }, "description": { - "description": "What the output holds.", + "description": "What the field holds.", "type": "string" + }, + "properties": { + "description": "Members of an object-typed output, keyed by field name.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "description": "Nested output field, in this same shape." + } + }, + "items": { + "description": "Element shape of an array-typed output.", + "type": "object", + "properties": { + "type": { + "type": "string", + "description": "Element value type." + }, + "description": { + "description": "What an element holds.", + "type": "string" + }, + "properties": { + "description": "Members of an object-typed element, keyed by field name.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "description": "Nested output field, in this same shape." + } + } + }, + "required": ["type"], + "additionalProperties": false } }, "required": ["type"], @@ -22381,11 +22431,47 @@ "properties": { "type": { "type": "string", - "description": "Value type of the output." + "description": "Value type of the output field." }, "description": { - "description": "What the output holds.", + "description": "What the field holds.", "type": "string" + }, + "properties": { + "description": "Members of an object-typed output, keyed by field name.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "description": "Nested output field, in this same shape." + } + }, + "items": { + "description": "Element shape of an array-typed output.", + "type": "object", + "properties": { + "type": { + "type": "string", + "description": "Element value type." + }, + "description": { + "description": "What an element holds.", + "type": "string" + }, + "properties": { + "description": "Members of an object-typed element, keyed by field name.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "description": "Nested output field, in this same shape." + } + } + }, + "required": ["type"], + "additionalProperties": false } }, "required": ["type"], @@ -22487,6 +22573,7 @@ "send": { "toolId": "slack_message", "toolName": "Slack Send Message", + "effect": "write", "description": "Send a message to a Slack channel.", "inputs": { "text": { @@ -22517,6 +22604,7 @@ "name": "Slack Send Message", "description": "Send a message to a Slack channel.", "version": "1.0.0", + "effect": "write", "hostedApiKey": "none", "oauth": { "required": true, @@ -22585,6 +22673,11 @@ "description": "Tool version.", "type": "string" }, + "effect": { + "type": "string", + "enum": ["read", "write"], + "description": "What running the tool does outside Sim. `read` changes nothing there: no create, update, delete, send, post, trigger, enqueue, consume, or mark-read; no asynchronous provider job or query execution started (one with its own id that can keep running, even briefly; a synchronous read-only query is fine); no run, conversation, history item, or other resource left in an account; no contact data revealed for credits; no external delivery. Usage billing for the call itself does not count. `write` is anything else, including an effect that depends on the input. Revealing a person's contact data (email, phone) for credits is `write`; company/firmographic lookups and verifications that only spend lookup credits are `read`." + }, "hostedApiKey": { "type": "string", "enum": ["always", "conditional", "none"], @@ -22614,7 +22707,7 @@ "additionalProperties": false } }, - "required": ["id", "name", "description", "hostedApiKey"], + "required": ["id", "name", "description", "effect", "hostedApiKey"], "additionalProperties": false, "title": "Tool summary", "description": "List view of a built-in tool: identity, auth, and key hosting." @@ -22653,6 +22746,7 @@ "name": "Slack Send Message", "description": "Send a message to a Slack channel.", "version": "1.0.0", + "effect": "write", "hostedApiKey": "none", "oauth": { "required": true, @@ -22684,6 +22778,7 @@ "name": "Slack Send Message", "description": "Send a message to a Slack channel.", "version": "1.0.0", + "effect": "write", "hostedApiKey": "none", "oauth": { "required": true, @@ -32795,6 +32890,11 @@ "description": "Hidden from the output picker.", "type": "boolean" }, + "mayBeText": { + "description": "A `json` or `any` output whose value can still be text at run time.", + "type": "boolean", + "const": true + }, "properties": { "description": "Nested outputs by name, each of this same shape.", "type": "object", @@ -32855,6 +32955,23 @@ "additionalProperties": false } }, + "effect": { + "description": "`read` when every tool the block can run changes nothing outside Sim, else `write`. Absent for a block with no `tools.access`.", + "type": "string", + "enum": ["read", "write"] + }, + "operationEffects": { + "description": "Per operation id: its tool's effect, where it differs from `effect`.", + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "type": "string", + "enum": ["read", "write"], + "description": "What running the tool does outside Sim. `read` changes nothing there: no create, update, delete, send, post, trigger, enqueue, consume, or mark-read; no asynchronous provider job or query execution started (one with its own id that can keep running, even briefly; a synchronous read-only query is fine); no run, conversation, history item, or other resource left in an account; no contact data revealed for credits; no external delivery. Usage billing for the call itself does not count. `write` is anything else, including an effect that depends on the input. Revealing a person's contact data (email, phone) for credits is `write`; company/firmographic lookups and verifications that only spend lookup credits are `read`." + } + }, "dynamicOutputs": { "description": "Present when outputs derive from a param at run time.", "type": "object", @@ -32872,6 +32989,13 @@ "required": ["source", "param"], "additionalProperties": false }, + "errorOutputs": { + "description": "Text outputs the block writes only when it fails into an error edge, beside `error`.", + "type": "array", + "items": { + "type": "string" + } + }, "graph": { "type": "object", "properties": { @@ -32921,65 +33045,6 @@ "additionalProperties": false, "description": "Edge rules for the block." }, - "legacyIds": { - "description": "Field id renames applied on load.", - "type": "array", - "items": { - "type": "object", - "properties": { - "from": { - "type": "string", - "description": "Legacy field id." - }, - "to": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Current field id, or null when removed." - }, - "whenOperation": { - "description": "Operations the rename applies to.", - "type": "array", - "items": { - "type": "string" - } - }, - "conditional": { - "description": "Applies only to some values.", - "type": "boolean", - "const": true - } - }, - "required": ["from", "to"], - "additionalProperties": false, - "description": "One field id rename." - } - }, - "legacyCanonicalIds": { - "description": "Basic/advanced pair id renames applied on load.", - "type": "array", - "items": { - "type": "object", - "properties": { - "from": { - "type": "string", - "description": "Legacy pair id." - }, - "to": { - "type": "string", - "description": "Current pair id." - } - }, - "required": ["from", "to"], - "additionalProperties": false, - "description": "One pair id rename." - } - }, "paramAliases": { "description": "The name source writes for a param, by param name: oauthCredential → credential.", "type": "object", @@ -33831,6 +33896,11 @@ "description": "Hidden from the output picker.", "type": "boolean" }, + "mayBeText": { + "description": "A `json` or `any` output whose value can still be text at run time.", + "type": "boolean", + "const": true + }, "properties": { "description": "Nested outputs by name, each of this same shape.", "type": "object", @@ -34690,6 +34760,11 @@ "description": "Hidden from the output picker.", "type": "boolean" }, + "mayBeText": { + "description": "A `json` or `any` output whose value can still be text at run time.", + "type": "boolean", + "const": true + }, "properties": { "description": "Nested outputs by name, each of this same shape.", "type": "object", diff --git a/apps/docs/openapi-v2-tables.json b/apps/docs/openapi-v2-tables.json index e07534290df..d12176c8953 100644 --- a/apps/docs/openapi-v2-tables.json +++ b/apps/docs/openapi-v2-tables.json @@ -6383,7 +6383,7 @@ "type": "boolean" }, "options": { - "description": "Select options for select-type columns.", + "description": "Select options for select-type columns, as [{\"id\":\"open\",\"name\":\"Open\"}].", "maxItems": 100, "type": "array", "items": { @@ -6422,7 +6422,7 @@ }, "required": ["columns"], "additionalProperties": false, - "description": "Initial table column definitions." + "description": "Initial table column definitions: {\"columns\":[{\"name\":\"email\",\"type\":\"string\",\"required\":true,\"unique\":true}]}. Column fields: id - Optional client-provided column identifier; name (required) - Column name; type (required) - Column data type; required - Whether inserts must supply a value for this column; unique - Whether values in the column must be unique; options - Select options for select-type columns, as [{\"id\":\"open\",\"name\":\"Open\"}]; multiple - Whether a select column accepts multiple values; currencyCode - ISO 4217 code for currency columns. A column's type is one of string, number, currency, boolean, date, json, select; a select column also takes options." }, "folderPath": { "description": "Folder in which to create the table.", @@ -6662,7 +6662,7 @@ "type": "boolean" }, "options": { - "description": "Select options for select-type columns.", + "description": "Select options for select-type columns, as [{\"id\":\"open\",\"name\":\"Open\"}].", "maxItems": 100, "type": "array", "items": { @@ -6701,7 +6701,7 @@ }, "required": ["name", "type"], "additionalProperties": false, - "description": "Column definition to add." + "description": "Column definition to add: {\"name\":\"status\",\"type\":\"string\"}. Column fields: id - Optional client-provided column identifier; name (required) - Column name; type (required) - Column data type; required - Whether inserts must supply a value for this column; unique - Whether values in the column must be unique; options - Select options for select-type columns, as [{\"id\":\"open\",\"name\":\"Open\"}]; multiple - Whether a select column accepts multiple values; currencyCode - ISO 4217 code for currency columns; position - Zero-based insertion position for the column. A column's type is one of string, number, currency, boolean, date, json, select; a select column also takes options." } }, "required": ["workspaceId", "column"], diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 51d4c8b04ff..e1f7b4cc243 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -4394,6 +4394,7 @@ "startedAt": "2026-08-09T18:04:10.000Z", "endedAt": "2026-08-09T18:04:11.000Z", "durationMs": 1000, + "paused": null, "executionTimeoutSeconds": 3000 } } @@ -5131,7 +5132,7 @@ "post": { "operationId": "resumeWorkflowRunV2", "summary": "Resume workflow run", - "description": "Resume one human-in-the-loop pause with workspace write access, naming a `contextId` from the run's `paused.points`. The resumed attempt receives a new run ID and returns a synchronous result or queue receipt. A run that originally streamed resumes asynchronously through v2; this endpoint returns no SSE stream.\n\nOAuth scope: `api:write`.", + "description": "Resume one human-in-the-loop pause with workspace write access, naming a `contextId` from the run's `paused.points`. The resumed attempt receives a new run ID and returns a synchronous result or queue receipt; when it pauses again, `paused.runId` names the run to resume next. A run that originally streamed resumes asynchronously through v2; this endpoint returns no SSE stream.\n\nOAuth scope: `api:write`.", "x-sim-operation": "workflows.runs.resume", "x-oauth-scope": "api:write", "tags": ["Workflow Runs"], @@ -5229,7 +5230,8 @@ "error": null, "startedAt": "2026-08-09T18:04:10.000Z", "endedAt": "2026-08-09T18:04:11.000Z", - "durationMs": 1000 + "durationMs": 1000, + "paused": null } } } @@ -6736,7 +6738,7 @@ { "key": "lookup-order", "id": "ctl_2b8d6f03", - "name": "lookup_order" + "name": "Lookup order" } ], "mcpServers": [ @@ -17191,6 +17193,10 @@ "blockType": { "description": "Integration or block type that failed, when attributable. Present whenever `blockId` is.", "type": "string" + }, + "rerunFromBlockId": { + "description": "Block a rerun of this failure starts from (`run.entry` of type `block` naming it, with this run as `sourceRunId`): the failing block, or the outermost loop or parallel holding it, since a run cannot start inside one. Set by Execute workflow from the graph the run executed and by Get workflow run from the saved draft, whenever `blockId` is and that graph still has the block.", + "type": "string" } }, "required": ["message", "code"], @@ -17275,6 +17281,50 @@ } ], "description": "Execution timeout applied to this run, in seconds: the plan's timeout, lowered by `executionTimeoutSeconds` when one was requested. Null when the run has no execution timeout." + }, + "paused": { + "anyOf": [ + { + "type": "object", + "properties": { + "runId": { + "type": "string", + "description": "Run to name in Resume workflow run: the run this pause is recorded under, which for a resumed run that paused again is the run it resumed." + }, + "points": { + "type": "array", + "items": { + "type": "object", + "properties": { + "contextId": { + "type": "string", + "description": "Pause context to name in `contextId` when resuming this point." + }, + "kind": { + "type": "string", + "enum": ["human", "time"], + "description": "`human` waits for a resume request; `time` resumes automatically at `resumeAt`." + }, + "status": { + "type": "string", + "enum": ["paused", "queued", "resuming", "resumed", "failed"], + "description": "Resume state of this point: waiting, queued behind another resume, resuming, resumed, or a failed resume attempt." + } + }, + "required": ["contextId", "kind", "status"], + "additionalProperties": false + }, + "description": "Every point the run is paused at. Resume one with Resume workflow run, naming `runId` and its `contextId`." + } + }, + "required": ["runId", "points"], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "Where the run waits when `status` is `paused`; null otherwise." } }, "required": [ @@ -17284,7 +17334,8 @@ "output", "blockOutputs", "error", - "executionTimeoutSeconds" + "executionTimeoutSeconds", + "paused" ], "additionalProperties": false, "title": "Workflow run result", @@ -17316,6 +17367,7 @@ "startedAt": "2026-08-09T18:04:10.000Z", "endedAt": "2026-08-09T18:04:11.000Z", "durationMs": 1000, + "paused": null, "executionTimeoutSeconds": 3000 } } @@ -18248,6 +18300,10 @@ "type": "number", "description": "Number of pause points that have resumed." }, + "runId": { + "type": "string", + "description": "Run to name in Resume workflow run: the run this pause is recorded under, which for a resumed run that paused again is the run it resumed." + }, "points": { "type": "array", "items": { @@ -18265,6 +18321,7 @@ "automaticResumeWaitingReason", "pausePointCount", "resumedCount", + "runId", "points" ], "additionalProperties": false @@ -18457,7 +18514,40 @@ "error": { "anyOf": [ { - "$ref": "#/components/schemas/ExecutionError" + "type": "object", + "properties": { + "message": { + "type": "string", + "description": "Human-readable workflow execution failure message." + }, + "code": { + "type": "string", + "enum": [ + "TIMEOUT", + "CANCELLED", + "USAGE_LIMIT_EXCEEDED", + "INVALID_INPUT", + "BLOCK_EXECUTION_FAILED", + "CHILD_WORKFLOW_FAILED", + "EXECUTION_FAILED" + ], + "description": "Stable machine-readable execution failure code. `BLOCK_EXECUTION_FAILED` and `CHILD_WORKFLOW_FAILED` are reported only where block attribution is available; elsewhere a block-level failure is reported as `EXECUTION_FAILED`." + }, + "blockId": { + "description": "Identifier of the failing block, when attributable. Get workflow run reads it from the run trace, so it is absent there when the trace is unavailable or hidden by organization permission groups, when no failed block in the trace recorded the run error, and for a timeout, cancellation, usage-limit, or invalid-input failure.", + "type": "string" + }, + "blockName": { + "description": "Display name of the failing block, when attributable. Present whenever `blockId` is.", + "type": "string" + }, + "blockType": { + "description": "Integration or block type that failed, when attributable. Present whenever `blockId` is.", + "type": "string" + } + }, + "required": ["message", "code"], + "additionalProperties": false }, { "type": "null" @@ -18479,9 +18569,53 @@ "description": "Execution duration in milliseconds.", "type": "number", "minimum": 0 + }, + "paused": { + "anyOf": [ + { + "type": "object", + "properties": { + "runId": { + "type": "string", + "description": "Run to name in Resume workflow run: the run this pause is recorded under, which for a resumed run that paused again is the run it resumed." + }, + "points": { + "type": "array", + "items": { + "type": "object", + "properties": { + "contextId": { + "type": "string", + "description": "Pause context to name in `contextId` when resuming this point." + }, + "kind": { + "type": "string", + "enum": ["human", "time"], + "description": "`human` waits for a resume request; `time` resumes automatically at `resumeAt`." + }, + "status": { + "type": "string", + "enum": ["paused", "queued", "resuming", "resumed", "failed"], + "description": "Resume state of this point: waiting, queued behind another resume, resuming, resumed, or a failed resume attempt." + } + }, + "required": ["contextId", "kind", "status"], + "additionalProperties": false + }, + "description": "Every point the run is paused at. Resume one with Resume workflow run, naming `runId` and its `contextId`." + } + }, + "required": ["runId", "points"], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "Where the run waits when `status` is `paused`; null otherwise." } }, - "required": ["runId", "workflowId", "status", "output", "blockOutputs", "error"], + "required": ["runId", "workflowId", "status", "output", "blockOutputs", "error", "paused"], "additionalProperties": false, "title": "Workflow resume result", "description": "Synchronous resumed run output and in-band execution status. Run failures are reported in band, not as HTTP errors, so branch on `status`." @@ -18511,7 +18645,8 @@ "error": null, "startedAt": "2026-08-09T18:04:10.000Z", "endedAt": "2026-08-09T18:04:11.000Z", - "durationMs": 1000 + "durationMs": 1000, + "paused": null } } ] @@ -19090,10 +19225,9 @@ "type": "object", "properties": { "version": { - "default": 1, - "description": "Base format version; a base written before it existed reads as 1.", "type": "number", - "const": 1 + "const": 1, + "description": "Base format version." }, "workflowId": { "type": "string", @@ -19149,7 +19283,6 @@ "E_SYNTAX", "E_SDK_HEADER", "E_SDK_MAJOR", - "E_SDK_MAJOR_OLD", "E_UNSUPPORTED_SYNTAX", "E_WORKFLOW_EXPORT", "E_LIMIT_EXCEEDED", @@ -19305,7 +19438,9 @@ "E_APPLY_BLOCK_DELETE", "E_APPLY_VARIABLE_DELETE", "E_NAME_TAKEN", - "E_WORKFLOW_META_INVALID" + "E_WORKFLOW_META_INVALID", + "E_TYPE", + "W_TYPES_UNCHECKED" ], "description": "Diagnostic code, e.g. `W_CANON_UNRESOLVED_ID`." }, @@ -19625,7 +19760,6 @@ "E_SYNTAX", "E_SDK_HEADER", "E_SDK_MAJOR", - "E_SDK_MAJOR_OLD", "E_UNSUPPORTED_SYNTAX", "E_WORKFLOW_EXPORT", "E_LIMIT_EXCEEDED", @@ -19781,7 +19915,9 @@ "E_APPLY_BLOCK_DELETE", "E_APPLY_VARIABLE_DELETE", "E_NAME_TAKEN", - "E_WORKFLOW_META_INVALID" + "E_WORKFLOW_META_INVALID", + "E_TYPE", + "W_TYPES_UNCHECKED" ], "description": "Diagnostic code, e.g. `E_UNKNOWN_PARAM` or `E_APPLY_LOCKED_BLOCK`." }, @@ -20008,10 +20144,9 @@ "type": "object", "properties": { "version": { - "default": 1, - "description": "Base format version; a base written before it existed reads as 1.", "type": "number", - "const": 1 + "const": 1, + "description": "Base format version." }, "workflowId": { "type": "string", @@ -20299,10 +20434,9 @@ "type": "object", "properties": { "version": { - "default": 1, - "description": "Base format version; a base written before it existed reads as 1.", "type": "number", - "const": 1 + "const": 1, + "description": "Base format version." }, "workflowId": { "type": "string", @@ -20324,7 +20458,7 @@ "description": "Hash of the block catalog the source was printed against." } }, - "required": ["workflowId", "workspaceId", "fingerprint", "catalogHash"], + "required": ["version", "workflowId", "workspaceId", "fingerprint", "catalogHash"], "additionalProperties": { "description": "An `x-` extension field, kept verbatim." }, @@ -20593,7 +20727,6 @@ "E_SYNTAX", "E_SDK_HEADER", "E_SDK_MAJOR", - "E_SDK_MAJOR_OLD", "E_UNSUPPORTED_SYNTAX", "E_WORKFLOW_EXPORT", "E_LIMIT_EXCEEDED", @@ -20749,7 +20882,9 @@ "E_APPLY_BLOCK_DELETE", "E_APPLY_VARIABLE_DELETE", "E_NAME_TAKEN", - "E_WORKFLOW_META_INVALID" + "E_WORKFLOW_META_INVALID", + "E_TYPE", + "W_TYPES_UNCHECKED" ], "description": "Diagnostic code, e.g. `E_UNKNOWN_PARAM` or `E_APPLY_LOCKED_BLOCK`." }, @@ -20976,10 +21111,9 @@ "type": "object", "properties": { "version": { - "default": 1, - "description": "Base format version; a base written before it existed reads as 1.", "type": "number", - "const": 1 + "const": 1, + "description": "Base format version." }, "workflowId": { "type": "string", @@ -21267,10 +21401,9 @@ "type": "object", "properties": { "version": { - "default": 1, - "description": "Base format version; a base written before it existed reads as 1.", "type": "number", - "const": 1 + "const": 1, + "description": "Base format version." }, "workflowId": { "type": "string", @@ -21292,7 +21425,7 @@ "description": "Hash of the block catalog the source was printed against." } }, - "required": ["workflowId", "workspaceId", "fingerprint", "catalogHash"], + "required": ["version", "workflowId", "workspaceId", "fingerprint", "catalogHash"], "additionalProperties": { "description": "An `x-` extension field, kept verbatim." }, @@ -21537,7 +21670,6 @@ "E_SYNTAX", "E_SDK_HEADER", "E_SDK_MAJOR", - "E_SDK_MAJOR_OLD", "E_UNSUPPORTED_SYNTAX", "E_WORKFLOW_EXPORT", "E_LIMIT_EXCEEDED", @@ -21693,7 +21825,9 @@ "E_APPLY_BLOCK_DELETE", "E_APPLY_VARIABLE_DELETE", "E_NAME_TAKEN", - "E_WORKFLOW_META_INVALID" + "E_WORKFLOW_META_INVALID", + "E_TYPE", + "W_TYPES_UNCHECKED" ], "description": "Diagnostic code, e.g. `E_UNKNOWN_PARAM` or `E_APPLY_LOCKED_BLOCK`." }, @@ -21920,10 +22054,9 @@ "type": "object", "properties": { "version": { - "default": 1, - "description": "Base format version; a base written before it existed reads as 1.", "type": "number", - "const": 1 + "const": 1, + "description": "Base format version." }, "workflowId": { "type": "string", @@ -22469,7 +22602,7 @@ { "key": "lookup-order", "id": "ctl_2b8d6f03", - "name": "lookup_order" + "name": "Lookup order" } ], "mcpServers": [ @@ -26394,16 +26527,7 @@ "description": "Stored id of the binary file." }, "rev": { - "anyOf": [ - { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - { - "type": "string" - } - ], + "type": "string", "description": "Content revision as last read." }, "sha256": { @@ -26598,7 +26722,6 @@ "E_SYNTAX", "E_SDK_HEADER", "E_SDK_MAJOR", - "E_SDK_MAJOR_OLD", "E_UNSUPPORTED_SYNTAX", "E_WORKFLOW_EXPORT", "E_INVALID_CHARACTER", @@ -26750,7 +26873,9 @@ "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", "E_APPLY_VARIABLE_DELETE", - "E_WORKFLOW_META_INVALID" + "E_WORKFLOW_META_INVALID", + "E_TYPE", + "W_TYPES_UNCHECKED" ], "description": "Diagnostic code, e.g. `E_APPLY_STALE` or `E_UNKNOWN_PARAM`." }, @@ -27183,7 +27308,6 @@ "E_SYNTAX", "E_SDK_HEADER", "E_SDK_MAJOR", - "E_SDK_MAJOR_OLD", "E_UNSUPPORTED_SYNTAX", "E_WORKFLOW_EXPORT", "E_INVALID_CHARACTER", @@ -27335,7 +27459,9 @@ "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", "E_APPLY_VARIABLE_DELETE", - "E_WORKFLOW_META_INVALID" + "E_WORKFLOW_META_INVALID", + "E_TYPE", + "W_TYPES_UNCHECKED" ], "description": "Diagnostic code." }, @@ -27438,16 +27564,7 @@ "description": "Stored id of the binary file." }, "rev": { - "anyOf": [ - { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - { - "type": "string" - } - ], + "type": "string", "description": "Content revision as last read." }, "sha256": { @@ -27607,7 +27724,6 @@ "E_SYNTAX", "E_SDK_HEADER", "E_SDK_MAJOR", - "E_SDK_MAJOR_OLD", "E_UNSUPPORTED_SYNTAX", "E_WORKFLOW_EXPORT", "E_INVALID_CHARACTER", @@ -27759,7 +27875,9 @@ "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", "E_APPLY_VARIABLE_DELETE", - "E_WORKFLOW_META_INVALID" + "E_WORKFLOW_META_INVALID", + "E_TYPE", + "W_TYPES_UNCHECKED" ], "description": "Diagnostic code, e.g. `E_APPLY_STALE` or `E_UNKNOWN_PARAM`." }, @@ -28010,16 +28128,7 @@ "description": "Stored id of the binary file." }, "rev": { - "anyOf": [ - { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - { - "type": "string" - } - ], + "type": "string", "description": "Content revision as last read." }, "sha256": { @@ -28481,7 +28590,6 @@ "E_SYNTAX", "E_SDK_HEADER", "E_SDK_MAJOR", - "E_SDK_MAJOR_OLD", "E_UNSUPPORTED_SYNTAX", "E_WORKFLOW_EXPORT", "E_INVALID_CHARACTER", @@ -28633,7 +28741,9 @@ "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", "E_APPLY_VARIABLE_DELETE", - "E_WORKFLOW_META_INVALID" + "E_WORKFLOW_META_INVALID", + "E_TYPE", + "W_TYPES_UNCHECKED" ], "description": "Diagnostic code." }, @@ -28736,16 +28846,7 @@ "description": "Stored id of the binary file." }, "rev": { - "anyOf": [ - { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - { - "type": "string" - } - ], + "type": "string", "description": "Content revision as last read." }, "sha256": { @@ -28905,7 +29006,6 @@ "E_SYNTAX", "E_SDK_HEADER", "E_SDK_MAJOR", - "E_SDK_MAJOR_OLD", "E_UNSUPPORTED_SYNTAX", "E_WORKFLOW_EXPORT", "E_INVALID_CHARACTER", @@ -29057,7 +29157,9 @@ "E_APPLY_INVALID_SCHEDULE", "E_APPLY_BLOCK_DELETE", "E_APPLY_VARIABLE_DELETE", - "E_WORKFLOW_META_INVALID" + "E_WORKFLOW_META_INVALID", + "E_TYPE", + "W_TYPES_UNCHECKED" ], "description": "Diagnostic code, e.g. `E_APPLY_STALE` or `E_UNKNOWN_PARAM`." }, @@ -29308,16 +29410,7 @@ "description": "Stored id of the binary file." }, "rev": { - "anyOf": [ - { - "type": "integer", - "minimum": -9007199254740991, - "maximum": 9007199254740991 - }, - { - "type": "string" - } - ], + "type": "string", "description": "Content revision as last read." }, "sha256": { diff --git a/apps/docs/scripts/fixtures/content-baseline.json b/apps/docs/scripts/fixtures/content-baseline.json index 4d1d6e601fe..4674f4d4d8c 100644 --- a/apps/docs/scripts/fixtures/content-baseline.json +++ b/apps/docs/scripts/fixtures/content-baseline.json @@ -2281,8 +2281,8 @@ { "lang": "text", "meta": null, - "sha256": "0a752f93f36e9515fd11690153150721f3286a0736d3da79f911bdaf2a3effcb", - "bytes": 710, + "sha256": "83c910b94eeb65b4b76fd1d9852fc5709862a2786abbcb6a6569b444bd176c6f", + "bytes": 821, "line": 52 } ], @@ -11059,2548 +11059,2548 @@ "meta": null, "sha256": "e89f5163bfcc02bcec8be44abb82d7807ccaeecc397ea8b3d8575e189f05a46a", "bytes": 19, - "line": 41 + "line": 45 }, { "lang": "bash", "meta": null, "sha256": "3ce59639490b19f90613bf0b002f0d5f747ae6bf89110a31aaad132f4a5d56df", "bytes": 20, - "line": 64 + "line": 68 }, { "lang": "bash", "meta": null, "sha256": "7be8dbf1bad323118735b5a0b4cdf49c653cc20508516225fe058776f0421e2e", "bytes": 20, - "line": 82 + "line": 86 }, { "lang": "bash", "meta": null, "sha256": "5b13d0a219062e58827d50697e4cec707e48ebef466a5058abb6e524376cc18e", "bytes": 23, - "line": 102 + "line": 106 }, { "lang": "bash", "meta": null, "sha256": "fac9741c4ccc5f0596cba54e6e2ecc4997e489032315eb4c80dd872c941dd0ae", "bytes": 20, - "line": 123 + "line": 127 }, { "lang": "bash", "meta": null, "sha256": "cc2a546bb69dcb90170c414517e67c86b5a20c7918c28999cb06d15f19ad4774", "bytes": 28, - "line": 141 + "line": 145 }, { "lang": "bash", "meta": null, "sha256": "f22525d91b0a915d24281bdac40a70c066449d9310582f844446e4fb2d9b347f", "bytes": 181, - "line": 169 + "line": 173 }, { "lang": "bash", "meta": null, "sha256": "21d922f40e072101cbcfdfcd4ee3c6e9ca22fc35bc4828a37f79f57dafec8d02", "bytes": 17, - "line": 187 + "line": 191 }, { "lang": "bash", "meta": null, "sha256": "56b302d091c4b589dde86d24739634d8f7d560873ca281d9962939aa6ff46ac1", "bytes": 33, - "line": 195 + "line": 199 }, { "lang": "bash", "meta": null, "sha256": "ce318a355b5dabeedbde09c7ddeb4f9132a4a57501b15fd3c2d23b3b8c75fd7f", "bytes": 20, - "line": 229 + "line": 233 }, { "lang": "bash", "meta": null, "sha256": "c74ad02c1945ec9c5cb8316f5ffeb64cc0b9dde01530570343e2dd2ee5c2ec23", "bytes": 20, - "line": 239 + "line": 243 }, { "lang": "bash", "meta": null, "sha256": "abe19c862f574d48aa91f6a506496b6f6c414d03fab399a6c86e1c12b2f8302a", "bytes": 21, - "line": 247 + "line": 251 }, { "lang": "bash", "meta": null, "sha256": "5c4299cf8aa6117a3a1a3c728d72c2a86f9627a5766d47be8ae1f03088642346", "bytes": 25, - "line": 259 + "line": 263 }, { "lang": "bash", "meta": null, "sha256": "cf03b326f03d9bcb4260e2be1ca5bcb89551a8f7f2bb1ba85744f50a9a84b434", "bytes": 73, - "line": 277 + "line": 281 }, { "lang": "bash", "meta": null, "sha256": "1350c2e26838e2b4a68726a51de8a06e2a5d32cc9714e0171c0dafd867db1d90", "bytes": 41, - "line": 294 + "line": 298 }, { "lang": "bash", "meta": null, "sha256": "8b747ef16c178bb05ca7171ec48e801f20a250e774a44d2d3b9753bd69aa3ec2", "bytes": 29, - "line": 324 + "line": 328 }, { "lang": "bash", "meta": null, "sha256": "88526e37fa1577427e6126306dc69d3afa94894d3dd313ae31286bff5eadafa4", "bytes": 28, - "line": 359 + "line": 363 }, { "lang": "bash", "meta": null, "sha256": "437c1deab5031ec9ce664b5429f7b62c062fd592469411b7f61cc16a9e21aa15", "bytes": 26, - "line": 379 + "line": 383 }, { "lang": "bash", "meta": null, "sha256": "575f3eca46c258a161e39e0bb8154f4e8ea02ed85bc48ba09e313bad08b2bdd7", "bytes": 24, - "line": 411 + "line": 415 }, { "lang": "text", "meta": null, - "sha256": "0a752f93f36e9515fd11690153150721f3286a0736d3da79f911bdaf2a3effcb", - "bytes": 710, - "line": 425 + "sha256": "83c910b94eeb65b4b76fd1d9852fc5709862a2786abbcb6a6569b444bd176c6f", + "bytes": 821, + "line": 429 }, { "lang": "bash", "meta": null, "sha256": "ecc11df2b60a4b0dc7d6b4e95f6fbee1f43554a8e32ee7232d50543a94e22273", "bytes": 25, - "line": 443 + "line": 448 }, { "lang": "bash", "meta": null, "sha256": "451b8c0648b69af0d37673c7b6c4bd98eb8ce4baca0c902038fc1460938adf88", "bytes": 35, - "line": 475 + "line": 480 }, { "lang": "bash", "meta": null, "sha256": "5037ed0778643f28636735f01bb24cd5f938bdc923f02abfacf6e37840a822f7", "bytes": 34, - "line": 506 + "line": 511 }, { "lang": "bash", "meta": null, "sha256": "ef5100ffa39072ae2ba9bb021d546036b95ded8da431fad855f809550c8913fb", "bytes": 47, - "line": 539 + "line": 544 }, { "lang": "bash", "meta": null, "sha256": "4051f5bb25072a25196ba8e847ab22b9d42aeb0cbb36186b5e7cc051d77c00e0", "bytes": 53, - "line": 569 + "line": 574 }, { "lang": "bash", "meta": null, "sha256": "2b6d0db0f06b8f51733c7da29a0c183aab73a6da83b787db76e7c3064fc9c78c", "bytes": 64, - "line": 603 + "line": 608 }, { "lang": "bash", "meta": null, "sha256": "a74b652635bc27ca58af7b080b78d983469558a2668f0b3f033a1b5b2f4cef10", "bytes": 55, - "line": 634 + "line": 639 }, { "lang": "bash", "meta": null, "sha256": "e407b3388ac13c30e985d64e41a9fb8f68c52e6e7a020bc3db79ce9473944724", "bytes": 40, - "line": 665 + "line": 670 }, { "lang": "bash", "meta": null, "sha256": "cb3d67be4a05a8cc95870cadb5ac682c16e80889db6606e388dd48651bfc4af4", "bytes": 30, - "line": 685 + "line": 690 }, { "lang": "bash", "meta": null, "sha256": "f7e2cb3ed34992b91cdcbd2fa65eadb48134c31e0d295519421644ad0668f20e", "bytes": 47, - "line": 710 + "line": 715 }, { "lang": "bash", "meta": null, "sha256": "3ce249d6b52442bdf5df53436bae6b9718064994b4b26ecf25372ce53606db08", "bytes": 45, - "line": 763 + "line": 768 }, { "lang": "bash", "meta": null, "sha256": "48d4019bc1905094aec776873af1d5a4e94ec2f52d043c51bbbb559b6a876944", "bytes": 276, - "line": 806 + "line": 811 }, { "lang": "bash", "meta": null, "sha256": "866eaf5e25ac2d6471b52118f082a507d5300b7c80cd82ecbe3cfbce598c5f6a", "bytes": 54, - "line": 818 + "line": 823 }, { "lang": "bash", "meta": null, "sha256": "48d4019bc1905094aec776873af1d5a4e94ec2f52d043c51bbbb559b6a876944", "bytes": 276, - "line": 856 + "line": 861 }, { "lang": "bash", "meta": null, "sha256": "e0ac83da55217195ac0ca3bd1a41314be433d0a62428f36eb9666df607e8322c", "bytes": 46, - "line": 868 + "line": 873 }, { "lang": "bash", "meta": null, "sha256": "664dfa9d010be73d8c8d4c1b079e946a646cc4677891d5fd34df9e5817cabfed", "bytes": 40, - "line": 898 + "line": 903 }, { "lang": "bash", "meta": null, "sha256": "55d8bb7d28001fafb0a76ccaf87863cb67f0150ffef73889e5c363ce3775131b", "bytes": 33, - "line": 924 + "line": 929 }, { "lang": "bash", "meta": null, "sha256": "02ff8ad73ece2f21edb90fc1a69904f322032da6d90a23d28d2d490beb55ab53", "bytes": 48, - "line": 948 + "line": 953 }, { "lang": "bash", "meta": null, "sha256": "06a7f6e71ab68db991126dcf2d660866aec7b89d27f751d082d2f90030a19b00", "bytes": 35, - "line": 978 + "line": 983 }, { "lang": "bash", "meta": null, "sha256": "3c9e74b86271246976e186b32c311a50f367fcd701f0506a56c8c8150c01b400", "bytes": 31, - "line": 998 + "line": 1003 }, { "lang": "bash", "meta": null, "sha256": "c0bbfff139a69379e188cfe4bbd3393285fce565dd83f7098eb2d387356da9c4", "bytes": 48, - "line": 1021 + "line": 1026 }, { "lang": "bash", "meta": null, "sha256": "c569c5e38502a1c1e8f6078954bc90b559dd80adb577bb4cf7b63ec7bbdb3aa7", "bytes": 46, - "line": 1061 + "line": 1066 }, { "lang": "bash", "meta": null, "sha256": "939a624f32ea05ac4cddd6037a27cdc7829018f0ac8096e4afd85aa9fab93ea2", "bytes": 24, - "line": 1092 + "line": 1097 }, { "lang": "bash", "meta": null, "sha256": "428eca668e88f6323ab89a2e488c5fd403b8b04064b26b55a3b8ca7ddb966be5", "bytes": 26, - "line": 1111 + "line": 1116 }, { "lang": "bash", "meta": null, "sha256": "66b86826e7fbeb5cc1b35c54dcbf9727264c2b6d50528e8c21accaff3a708806", "bytes": 31, - "line": 1135 + "line": 1140 }, { "lang": "bash", "meta": null, "sha256": "a461b9c9fef3090d3367148a2a183410e81624e42e340c21a4138c30c6b4409c", "bytes": 41, - "line": 1157 + "line": 1162 }, { "lang": "bash", "meta": null, "sha256": "8c86de167a3b73c5430d2b15f558b7c0b2a82cd347b4e85907862196cf8e16bc", "bytes": 32, - "line": 1188 + "line": 1193 }, { "lang": "bash", "meta": null, "sha256": "8a9eb6688329292f21fecba059890d65dab0a136e86f26d38987c27d68013ad8", "bytes": 43, - "line": 1216 + "line": 1221 }, { "lang": "bash", "meta": null, "sha256": "be3c635d1b158a14e8e00c6e88d84e4126e29d89f0464ebf0b296f19b2bdf59b", "bytes": 32, - "line": 1239 + "line": 1244 }, { "lang": "bash", "meta": null, "sha256": "993262e619d4470867077b7a4e0c528f715be468511bf9e072e8a9429ef250a1", "bytes": 35, - "line": 1261 + "line": 1266 }, { "lang": "bash", "meta": null, "sha256": "adc4973b83b313bcaf5f9058297e030a9c272cb1b5612fe8465b02edf2ad1b73", "bytes": 54, - "line": 1293 + "line": 1298 }, { "lang": "bash", "meta": null, "sha256": "48fbd97b704f5e02a593cbf0020bc3c6600ff1b4d349ae80b3cba39225a4b9fc", "bytes": 46, - "line": 1324 + "line": 1329 }, { "lang": "bash", "meta": null, "sha256": "49e712965d1a8af321563bc382bb448e0b68067c3c68861f84896b5f97e70314", "bytes": 42, - "line": 1345 + "line": 1350 }, { "lang": "bash", "meta": null, "sha256": "e463cbe0c80554eaa7fe151c51523307240c2226a54924a3d984cdc0a84f529b", "bytes": 52, - "line": 1378 + "line": 1383 }, { "lang": "bash", "meta": null, "sha256": "23bede1f0d68221f4da857a62e0594d031e40e5a794bd96c79eba2de2924072a", "bytes": 54, - "line": 1411 + "line": 1416 }, { "lang": "bash", "meta": null, "sha256": "ad1df0d9a424569351d851507b674bb104654e1251d7bee11ebc6955e0f2be6c", "bytes": 56, - "line": 1443 + "line": 1448 }, { "lang": "bash", "meta": null, "sha256": "37cdd4ceab29424161734300286176b9971cd7d6c134022308d5b21e4fa9e714", "bytes": 33, - "line": 1475 + "line": 1480 }, { "lang": "bash", "meta": null, "sha256": "0bc8335422d07dfbc74c55102518d6d2965a5aa27be6994b8b4317478e13ef3d", "bytes": 37, - "line": 1506 + "line": 1511 }, { "lang": "bash", "meta": null, "sha256": "863b992687ec7121ef44d5680b290502052bfe51e7e43aa24376ddba51fc3841", "bytes": 28, - "line": 1536 + "line": 1541 }, { "lang": "bash", "meta": null, "sha256": "9d7e15ac24392a0771cf7857c3f110be1ede32e18427995923edc5978fdcaa31", "bytes": 38, - "line": 1556 + "line": 1561 }, { "lang": "bash", "meta": null, "sha256": "15849bbb5c9f4f1c0754c0c99d3048b910f6fdcbb02ab84a4e34d7ed1930cd15", "bytes": 24, - "line": 1589 + "line": 1594 }, { "lang": "bash", "meta": null, "sha256": "31cbe1979c2c645d78646d966ac83fd45e6b556d56ab0d8fc47a7abd281e524d", "bytes": 24, - "line": 1616 + "line": 1621 }, { "lang": "bash", "meta": null, "sha256": "1a728e81af7425e00df25a70a5819d272cbddcab487426cebc94de7834509999", "bytes": 33, - "line": 1639 + "line": 1644 }, { "lang": "bash", "meta": null, "sha256": "f7a8e9f75a2ea3d88d6d12b097f20a94e2b915741cc10f805b070c6ad4261a7e", "bytes": 35, - "line": 1671 + "line": 1676 }, { "lang": "bash", "meta": null, "sha256": "94537050876dfc16340c4db7965fcc2a098f09fcb9911d5e154c11721d212e6a", "bytes": 26, - "line": 1701 + "line": 1706 }, { "lang": "bash", "meta": null, "sha256": "cdee40f5dc3195f9db4462ddd0e5b7bc03b44f600a82f357d6b651ecee770840", "bytes": 26, - "line": 1721 + "line": 1726 }, { "lang": "bash", "meta": null, "sha256": "bda181f24ee73df10ced9c179ddb81b115d62b4da46eb64b63dd23e7f4c51a96", "bytes": 34, - "line": 1748 + "line": 1753 }, { "lang": "bash", "meta": null, "sha256": "14e217553dedf133ef014fd989058ee281844a55293e05a9dddf044947c058fe", "bytes": 40, - "line": 1778 + "line": 1783 }, { "lang": "bash", "meta": null, "sha256": "30f91370cbb0ddf76900ab363e83bb26c0a95cb81518de875885f66d4c9df4a3", "bytes": 33, - "line": 1810 + "line": 1815 }, { "lang": "bash", "meta": null, "sha256": "1c143b6c0cd2e76ce8c74504ecb5ee2560b147eb299d8f0d3d956854b706958c", "bytes": 32, - "line": 1841 + "line": 1846 }, { "lang": "bash", "meta": null, "sha256": "b36a5102aee98e664a1ca4cc19d91310af00b2a4afbb04c78589bb4c3a2936a9", "bytes": 29, - "line": 1872 + "line": 1877 }, { "lang": "bash", "meta": null, "sha256": "62a17f5231fba3f732cba025c16c8b6706411b9267e6abd58e4e51aff8777043", "bytes": 22, - "line": 1903 + "line": 1908 }, { "lang": "bash", "meta": null, "sha256": "760a88e6d91ed147f40d39808ae39d178b6c38b61a5c69dd37755079cff376c2", "bytes": 69, - "line": 1929 + "line": 1934 }, { "lang": "bash", "meta": null, "sha256": "e0173107cc10779c1b96d55c66a3bd628e9bc21b39234101e2f9d7519087780e", "bytes": 51, - "line": 1959 + "line": 1964 }, { "lang": "bash", "meta": null, "sha256": "71bb24f623f1958775fe0f9df499ad3f8241c3132ea8f8a40d5f26bd2041b65e", "bytes": 53, - "line": 1989 + "line": 1994 }, { "lang": "bash", "meta": null, "sha256": "51d1aa93ed9262fa8f275fbd24e805ad9a3a075ed2f5c3888d57ecf909426c3e", "bytes": 61, - "line": 2023 + "line": 2028 }, { "lang": "bash", "meta": null, "sha256": "4782c15ea248b0cb3a7cffa4242b54f9bea866ecf26f63ada4ed921455699cb3", "bytes": 54, - "line": 2056 + "line": 2061 }, { "lang": "bash", "meta": null, "sha256": "c8f14f40bbc787d13778c342211d73c9f0b118a8d37d3c82a87c72b42b9d5d93", "bytes": 56, - "line": 2088 + "line": 2093 }, { "lang": "bash", "meta": null, "sha256": "913db46a26314244a1e4c903adb6772a8e405da8cba64f7218ff3683d7daa72a", "bytes": 41, - "line": 2118 + "line": 2123 }, { "lang": "bash", "meta": null, "sha256": "7cda9f00d098a51943b10891142d7e6a8d4cb46d752e1cdae5825ab6c56b8aa9", "bytes": 42, - "line": 2138 + "line": 2143 }, { "lang": "bash", "meta": null, "sha256": "e09f666b66b4d7acdcd6aa26831c7f258ff49baa0fd762ea920b90fd39846582", "bytes": 61, - "line": 2158 + "line": 2163 }, { "lang": "bash", "meta": null, "sha256": "8b204243cf243c64557adb522d2bfd72be53400afab3c03f4c314117ed37655d", "bytes": 74, - "line": 2192 + "line": 2197 }, { "lang": "bash", "meta": null, "sha256": "cf87bc61bba385818ebc622f9b9f481213e1d86f65df7ab1a193749ab929a651", "bytes": 68, - "line": 2225 + "line": 2230 }, { "lang": "bash", "meta": null, "sha256": "2d57fee1358f9ce5a3f166aed1400940cbe737b04d8f487a16eb35bc3bb5a6d4", "bytes": 78, - "line": 2260 + "line": 2265 }, { "lang": "bash", "meta": null, "sha256": "7f02636a02ece5cd252aad171e251b18e1c29207d62dfcc962485052b799fdc4", "bytes": 65, - "line": 2292 + "line": 2297 }, { "lang": "bash", "meta": null, "sha256": "e6a2660057e8859cebd226a4420672f12beed4e274bdc57a4b70c96a0142b1b6", "bytes": 66, - "line": 2314 + "line": 2319 }, { "lang": "bash", "meta": null, "sha256": "54b00a2d3830092a8fe552bba29419710da6647ac3cc96d6a0a9ffbef596c440", "bytes": 78, - "line": 2350 + "line": 2355 }, { "lang": "bash", "meta": null, "sha256": "a0a28be794c70e6366719b49f3ad627faa087181960d287d6a17bc44d7a8bd9d", "bytes": 64, - "line": 2384 + "line": 2389 }, { "lang": "bash", "meta": null, "sha256": "2a48509e548ba0f0d2bb97bfc37ac1807f3b34cc5c44cbd1c5ca57735614fc24", "bytes": 71, - "line": 2419 + "line": 2424 }, { "lang": "bash", "meta": null, "sha256": "ea154f4a00845d5c60d54aff14d7173c8de383ec43e13454a8c326459ed7695f", "bytes": 58, - "line": 2450 + "line": 2455 }, { "lang": "bash", "meta": null, "sha256": "f14623530e7aeb20de131c59208269f9703e85ab6a89cd4368fb3c2ff7c36863", "bytes": 56, - "line": 2471 + "line": 2476 }, { "lang": "bash", "meta": null, "sha256": "cdf3ade3d9fa9f1f3a191265a2b0de8092eaaa49bd961d94eccb09355dfddb26", "bytes": 71, - "line": 2507 + "line": 2512 }, { "lang": "bash", "meta": null, "sha256": "2f509b586cc62ff6bb0b5c1ee7e5062689b1cfd987acc2c18dee6b10bc3a194f", "bytes": 65, - "line": 2561 + "line": 2566 }, { "lang": "bash", "meta": null, "sha256": "6546c4a95a217203c622f0e62f945cbe2863d42d02a5229621f43f12b68bc063", "bytes": 39, - "line": 2595 + "line": 2600 }, { "lang": "bash", "meta": null, "sha256": "e9f1685d2a50e4bd554c7daf19621a7704aa5b1aea3540af28884066ae413c69", "bytes": 36, - "line": 2615 + "line": 2620 }, { "lang": "bash", "meta": null, "sha256": "ad0c1107caee2427422e0a52a6da2df0a037010f93467fd957fb0136f938d675", "bytes": 30, - "line": 2635 + "line": 2640 }, { "lang": "bash", "meta": null, "sha256": "fae160a2cd7e296a9f9b00fa789ba95a2f1e507713a469902de21ed945d9eb25", "bytes": 59, - "line": 2658 + "line": 2663 }, { "lang": "bash", "meta": null, "sha256": "abdae7f49c77877550cfc2d7195132c12fb0117a0471faf1c525d44ad2de1321", "bytes": 73, - "line": 2694 + "line": 2699 }, { "lang": "bash", "meta": null, "sha256": "d11c4c59feac4345ba7dfb02edc2780adae89cf702e570f32e1ccc8555bdb169", "bytes": 60, - "line": 2727 + "line": 2732 }, { "lang": "bash", "meta": null, "sha256": "af533689c0b530ff902ae36c2cac7198f43ff6968d168a94da153d81fe8020fd", "bytes": 81, - "line": 2748 + "line": 2753 }, { "lang": "bash", "meta": null, "sha256": "f907eb4bee803d3f45d4abc9baae106aaec0249143dfd9cf56aa17285776a430", "bytes": 83, - "line": 2782 + "line": 2787 }, { "lang": "bash", "meta": null, "sha256": "28c4e709c778f27d924fbe49edb4bf198b7c73e9b65619e6fad43d1fb9e2cfb7", "bytes": 57, - "line": 2814 + "line": 2819 }, { "lang": "bash", "meta": null, "sha256": "0a7262cac83ce7c16b17a1364a123764e5fa8b645dd60fd5b394b3f74dd0e1fa", "bytes": 71, - "line": 2846 + "line": 2851 }, { "lang": "bash", "meta": null, "sha256": "a25c869b7add79bfe6f194ec72190bb6b4957bb303fe6b4c31c9455f4a2e11a9", "bytes": 73, - "line": 2878 + "line": 2883 }, { "lang": "bash", "meta": null, "sha256": "b3f9e190362420216749c9924e83a35c5a5c2414ab03ff89601a6b9501494bf9", "bytes": 35, - "line": 2911 + "line": 2916 }, { "lang": "bash", "meta": null, "sha256": "ae5dcbc80aeb125607ebd763669a1f335d6ddf087a6baf1853453867675ce865", "bytes": 45, - "line": 2933 + "line": 2938 }, { "lang": "bash", "meta": null, "sha256": "c91b2cb83c28571b965071d6643d955366931a6ca3dd340e54d8536ea90cefde", "bytes": 36, - "line": 2964 + "line": 2969 }, { "lang": "bash", "meta": null, "sha256": "de622393fa33cc9b0002c7d670d9f45c2bcd9fbfe3f0c99be71ae96969a005dd", "bytes": 47, - "line": 2989 + "line": 2994 }, { "lang": "bash", "meta": null, "sha256": "356cb12341ce90e24b765d02a997421c0469a3b26509c90e42a17af4dd3f9e95", "bytes": 48, - "line": 3014 + "line": 3019 }, { "lang": "bash", "meta": null, "sha256": "a611d4f425ac65781756225557a7e8f8559faccaa4c6466ef23fa78cd2a2226c", "bytes": 35, - "line": 3044 + "line": 3049 }, { "lang": "bash", "meta": null, "sha256": "8c7bab52ede04cca1dd71b466bd76c7f5b67c6b7f0fed08e14ee7656d6b2b160", "bytes": 28, - "line": 3064 + "line": 3069 }, { "lang": "bash", "meta": null, "sha256": "063e71c7485fe7d3657e692841a2f0629e6a31b48e8501282b0456202eefaa5d", "bytes": 39, - "line": 3089 + "line": 3094 }, { "lang": "bash", "meta": null, "sha256": "4f9e7b46b98628ddded377f3a73cb2e9b4751023b7b1fc90c1cefc90555c80c4", "bytes": 30, - "line": 3109 + "line": 3114 }, { "lang": "bash", "meta": null, "sha256": "efaaf65fd8057cd592d386d0e0c800eef4e71d649a1f011fd2f20495d8d942ab", "bytes": 48, - "line": 3137 + "line": 3142 }, { "lang": "bash", "meta": null, "sha256": "5303a1a6194097b3acc7546ccafb0faced44b084951b7e14ff1029cf0fdff957", "bytes": 43, - "line": 3170 + "line": 3175 }, { "lang": "bash", "meta": null, "sha256": "a9ba0ea93105e0f224ed0c3e661adf5fe706a875fb9741348134814d65c6d882", "bytes": 48, - "line": 3191 + "line": 3196 }, { "lang": "bash", "meta": null, "sha256": "a721f46390cb321c013b700b13f46f2e9833616be44a3ee8e0971c3e5c0f945b", "bytes": 37, - "line": 3223 + "line": 3228 }, { "lang": "bash", "meta": null, "sha256": "9f9b6ea8992e8fcd2bdb540857d42288ba0ecedb959ff5c1c56de708e65db79e", "bytes": 33, - "line": 3254 + "line": 3259 }, { "lang": "bash", "meta": null, "sha256": "1478c9884eb8c9bc2dd64170d3fb101030957399aab5da911d5f77d46b662c73", "bytes": 26, - "line": 3285 + "line": 3290 }, { "lang": "bash", "meta": null, "sha256": "51b81826c6f4b7933c1c802c82baca186c67efe8e59e69a6a7754360fe8675da", "bytes": 30, - "line": 3311 + "line": 3316 }, { "lang": "bash", "meta": null, "sha256": "8aeb5fc735c8037c480f3c8220149fb6f811de62c946584523d50d1cd1811a53", "bytes": 24, - "line": 3343 + "line": 3348 }, { "lang": "bash", "meta": null, "sha256": "a1bf4221604cc962c677313543850fe6cd140476ef52de3a9e29b305865ae8f0", "bytes": 23, - "line": 3372 + "line": 3377 }, { "lang": "bash", "meta": null, "sha256": "5215bc6f0c098350b8067dd283226f3444cf73599ab1989c5dfae5c563069a04", "bytes": 25, - "line": 3416 + "line": 3421 }, { "lang": "bash", "meta": null, "sha256": "98f84efeb01c77bc8c1aadb62fbd989c5ae41de97d07fd9b59e8b2b53cafe06f", "bytes": 145, - "line": 3440 + "line": 3445 }, { "lang": "bash", "meta": null, "sha256": "baad97733d922f4ef4c068577ef9f0f855c44f3b54e9b80a61733a4fecfd350d", "bytes": 32, - "line": 3460 + "line": 3465 }, { "lang": "bash", "meta": null, "sha256": "fdb563355cb89d0b6f534e825e70973c85326879a7d4f0adaee447ed78db5260", "bytes": 46, - "line": 3493 + "line": 3498 }, { "lang": "bash", "meta": null, "sha256": "8409df5d28808a04cbea45c4f0162a7a283a0d4eee0fc3391d82a8663121a495", "bytes": 33, - "line": 3523 + "line": 3528 }, { "lang": "bash", "meta": null, "sha256": "c3189f21b856e8c158f2a39d3260d7c0ac93ba2c0c73494c7e1374d45a51346f", "bytes": 30, - "line": 3543 + "line": 3548 }, { "lang": "bash", "meta": null, "sha256": "066839a4599d90ccd88f845122e61c608a8ea120e9f1476857f0a2eb8c723de7", "bytes": 50, - "line": 3566 + "line": 3571 }, { "lang": "bash", "meta": null, "sha256": "209da9ab7f502fbcaec3297113212d496eca57b124e273dc8080efa6c4e0de71", "bytes": 46, - "line": 3597 + "line": 3602 }, { "lang": "bash", "meta": null, "sha256": "c01ee6bd733ccd61abdb244baa88a17758166a1eacaa4456d3a8bbe56e6ff00f", "bytes": 15, - "line": 3642 + "line": 3647 }, { "lang": "bash", "meta": null, "sha256": "e2c2a5ffcc518a49f6cc038c691b068769101b4bf94905eb0a472299ab563620", "bytes": 39, - "line": 3656 + "line": 3661 }, { "lang": "bash", "meta": null, "sha256": "ccaaa978abfa31e70784eda567c50bec64a5cf485a205fa545e71f46c1821f3a", "bytes": 40, - "line": 3677 + "line": 3682 }, { "lang": "bash", "meta": null, "sha256": "7e6eac72f3011e3714d4eeb9914601dbe344ff899504c1324ff55c2b6eed60d5", "bytes": 53, - "line": 3702 + "line": 3707 }, { "lang": "bash", "meta": null, "sha256": "d557d9bb45aa7b4ee10d2d502d92710aafe9fcbc7b12d0a219c3eff49863e1f7", "bytes": 53, - "line": 3733 + "line": 3738 }, { "lang": "bash", "meta": null, "sha256": "6f4dc8213285da7c740b7f183f519a14d88e853125347cf4b3585c153f3d6c95", "bytes": 62, - "line": 3763 + "line": 3768 }, { "lang": "bash", "meta": null, "sha256": "c7934b9e19cf7a0ff636ecdb465b1a6727ad23d36b695eb0b08783efa08698d3", "bytes": 50, - "line": 3793 + "line": 3798 }, { "lang": "bash", "meta": null, "sha256": "c6c30823efb18475aef576f5eac37ab1a319e1de7b2462fccb62b249396e3d9f", "bytes": 52, - "line": 3815 + "line": 3820 }, { "lang": "bash", "meta": null, "sha256": "8567533e04160a832142ff673958ff2456ea163f86df91685ba5da691604a882", "bytes": 56, - "line": 3842 + "line": 3847 }, { "lang": "bash", "meta": null, "sha256": "f8809dfed9678563c959c376cf67dcc022eeee8e5e4384e8aa46ff6470838960", "bytes": 59, - "line": 3862 + "line": 3867 }, { "lang": "bash", "meta": null, "sha256": "c4202b9b75440588bb6562fce248037a4425448373f72f9ee3ad9ade135fab34", "bytes": 48, - "line": 3883 + "line": 3888 }, { "lang": "bash", "meta": null, "sha256": "711c4598e2329b7c5079f9cc2569196c4af7ebfa267e38ab904ff60e579e5169", "bytes": 48, - "line": 3908 + "line": 3913 }, { "lang": "bash", "meta": null, "sha256": "ef9a879b046809272052e1804f9ebe98b60cd0cdf476251b599ca44bb3ae1b11", "bytes": 63, - "line": 3934 + "line": 3939 }, { "lang": "bash", "meta": null, "sha256": "b07d1aa721f8a38cfc8e79bc68497e76240430fcc1fec0818294974f67755a1d", "bytes": 63, - "line": 3964 + "line": 3969 }, { "lang": "bash", "meta": null, "sha256": "48441bc81c5893bfd1567acf2a401eb191e4b7bef2862b8c29aa158a517adb82", "bytes": 93, - "line": 4000 + "line": 4005 }, { "lang": "bash", "meta": null, "sha256": "74d9b766eac6b565c6287e10884f95c2f74ecd8dd4947b488cda0ff1c1f16597", "bytes": 80, - "line": 4032 + "line": 4037 }, { "lang": "bash", "meta": null, "sha256": "4b74edf3d708c0fafd7bb8ba6a827644f65d6cd755a4cf1822b5308a45eb76c3", "bytes": 106, - "line": 4066 + "line": 4071 }, { "lang": "bash", "meta": null, "sha256": "229448ff3c47ffdfdd720fb88b38edcf58f51d063f7b7836d4f4fdc478f99b5c", "bytes": 69, - "line": 4100 + "line": 4105 }, { "lang": "bash", "meta": null, "sha256": "7863a0cbd4e2cb3715358cca55047765a210f9a42a3dd171e42f574185fe0ab9", "bytes": 73, - "line": 4132 + "line": 4137 }, { "lang": "bash", "meta": null, "sha256": "412f8bcf9151f7075294ba9e7cfcbb86581e91dbd1b217775e9fb6958df71a2e", "bytes": 72, - "line": 4165 + "line": 4170 }, { "lang": "bash", "meta": null, "sha256": "483447579062e117424ae72463645f166fea91b8a87fe6efcf48a24a3a8145f8", "bytes": 49, - "line": 4200 + "line": 4205 }, { "lang": "bash", "meta": null, "sha256": "e57bccfdde20412a95b0aeb601448b791eb566d28af3b17bbc16d1e62bbcfb4c", "bytes": 60, - "line": 4228 + "line": 4233 }, { "lang": "bash", "meta": null, "sha256": "34378bac1290005ec4e6a46fc968c097307dc2dd27dffd2ed275b885dcc8502b", "bytes": 57, - "line": 4259 + "line": 4264 }, { "lang": "bash", "meta": null, "sha256": "91c6910aa33b8d3c65dccd59a480a9d986eadf89d8d4974ade0c8cb47c7ac821", "bytes": 47, - "line": 4289 + "line": 4294 }, { "lang": "bash", "meta": null, "sha256": "303d009467865566416478bccdf9e95291862e222144f55ca61bae5d446fa9d5", "bytes": 50, - "line": 4313 + "line": 4318 }, { "lang": "bash", "meta": null, "sha256": "7deac995bc8ac114dae3500bb4792b73fdb39f5b666f4a2886428320e1ffbd00", "bytes": 60, - "line": 4337 + "line": 4342 }, { "lang": "bash", "meta": null, "sha256": "6231d67b8fca5d05ef85468209b86d04c0c016014f46f2f444da5321bd655941", "bytes": 46, - "line": 4372 + "line": 4377 }, { "lang": "bash", "meta": null, "sha256": "30a1944929f1b7cdc8d8866735022851ef133f4160fc018f736201f1531e7907", "bytes": 58, - "line": 4394 + "line": 4399 }, { "lang": "bash", "meta": null, "sha256": "6ce2fc39c89d2789f343b2590c28ff069d4bcf685241cdfd645d579b886625a5", "bytes": 44, - "line": 4424 + "line": 4429 }, { "lang": "bash", "meta": null, "sha256": "edbc6c008ae5039761ca84f5af6c63c15aab125fe0bc7b890362159598318cf6", "bytes": 65, - "line": 4450 + "line": 4455 }, { "lang": "bash", "meta": null, "sha256": "cdeb9be48212517be6994c625844b9761842bd3822c74e7d86970a022811a07d", "bytes": 61, - "line": 4485 + "line": 4490 }, { "lang": "bash", "meta": null, "sha256": "7f3233f2465f84ad271fbe67411e1651f83d9dd39e15128c477276a103443baa", "bytes": 61, - "line": 4517 + "line": 4522 }, { "lang": "bash", "meta": null, "sha256": "af80c56179adf35f94c4c1c3eb3676cf2ca68b61af3c1b43a9ac020c4205f4a2", "bytes": 61, - "line": 4550 + "line": 4555 }, { "lang": "bash", "meta": null, "sha256": "48fced6ea852f10aa3620044ca010c0bf50acfb3b743012f836a98be0d7cdf08", "bytes": 58, - "line": 4581 + "line": 4586 }, { "lang": "bash", "meta": null, "sha256": "6d9a078ab511579f7f7234fa28d72ae92f7df84c9f9957aff14951a2fe1b08f3", "bytes": 46, - "line": 4611 + "line": 4616 }, { "lang": "bash", "meta": null, "sha256": "88b2622d7dc41ea41543f26e4dd1b513c271cb0e0452b937033088f7ae80484f", "bytes": 46, - "line": 4636 + "line": 4641 }, { "lang": "bash", "meta": null, "sha256": "757036af4cd38ae573a0589ddcd08b179542a30bfa802f88ff3debb198baae47", "bytes": 62, - "line": 4684 + "line": 4689 }, { "lang": "bash", "meta": null, "sha256": "7311b5a978eda8140f8e314d709e565a535c76064199595eb139c015f16312d5", "bytes": 42, - "line": 4714 + "line": 4719 }, { "lang": "bash", "meta": null, "sha256": "c3410310e5eccb2e0a7440b8d3cbfc2508270890a08ec5a85c5b8cc5c5a3b8b8", "bytes": 45, - "line": 4734 + "line": 4739 }, { "lang": "bash", "meta": null, "sha256": "08f1a585205b784ac0527c4ffb9aae95a4d8bd1702abddb87d1aa25415de45d2", "bytes": 38, - "line": 4755 + "line": 4760 }, { "lang": "bash", "meta": null, "sha256": "e4502c5ec3c9643358cf434f3271f7f39ee39f899661c58e7af68b98f42cbcb1", "bytes": 60, - "line": 4775 + "line": 4780 }, { "lang": "bash", "meta": null, "sha256": "59e8699f41a3f06be75f1eb4addb041b762d100d6e15f61788e729a8a277f55f", "bytes": 63, - "line": 4805 + "line": 4810 }, { "lang": "bash", "meta": null, "sha256": "9a525f2d35624ea70a558a4081c20c98418fb371cce3ac2d70cb01462271f1c6", "bytes": 40, - "line": 4836 + "line": 4841 }, { "lang": "bash", "meta": null, "sha256": "5db8d4c149bb0b8378ac584947f1a8d037aa2375312e098338ee1566030988e4", "bytes": 51, - "line": 4862 + "line": 4867 }, { "lang": "bash", "meta": null, "sha256": "cba02b44f48f44f069fb55f48ec4e680a49b71ab99d8e7013ff4113236cd6e19", "bytes": 51, - "line": 4893 + "line": 4898 }, { "lang": "bash", "meta": null, "sha256": "1825feb4954c2f39280e98a8ab8f8784e097c9823d04cbccf616c28f24eeee4b", "bytes": 43, - "line": 4924 + "line": 4929 }, { "lang": "bash", "meta": null, "sha256": "0bd4be17187ea4870dfddcf74c03492e4ff3e4eb734d8e38fc710a0afd70e771", "bytes": 41, - "line": 4950 + "line": 4955 }, { "lang": "bash", "meta": null, "sha256": "e26b81a721ffd90b20b61be8168187fc20333274f6c3e537eb6cc44f87397f8b", "bytes": 40, - "line": 4974 + "line": 4979 }, { "lang": "bash", "meta": null, "sha256": "a85bb64841a5626286099eb6175af5f8d0b0c8f19d71275c41ba144d5ce6d75b", "bytes": 32, - "line": 5003 + "line": 5008 }, { "lang": "bash", "meta": null, "sha256": "c8500badf466ac4cddb64017931e69aedba037eb5c44d0be411f3e2368254f87", "bytes": 38, - "line": 5026 + "line": 5031 }, { "lang": "bash", "meta": null, "sha256": "c5da7d1cca60bf076fb11e3a830b1c639ae02b8b2413e4956b12b54d4af7869d", "bytes": 43, - "line": 5058 + "line": 5063 }, { "lang": "bash", "meta": null, "sha256": "ee42a8df21f3cb29767908892e907b58edc31fccac8414e646690b238373feac", "bytes": 49, - "line": 5080 + "line": 5085 }, { "lang": "bash", "meta": null, "sha256": "3aa75d103d8d87811ca0f13f238ef5bfc84debf02826b8883eb0a09b372b7230", "bytes": 44, - "line": 5103 + "line": 5108 }, { "lang": "bash", "meta": null, "sha256": "c97bf15cbec26edcc86e8e3a908361b4c12a7d4b5578d5ea685d4fc68993c3f9", "bytes": 55, - "line": 5129 + "line": 5134 }, { "lang": "bash", "meta": null, "sha256": "971979fe121168021fc32881c5e8807f271cbaee608d70cf22b709662e0aae21", "bytes": 38, - "line": 5161 + "line": 5166 }, { "lang": "bash", "meta": null, "sha256": "76f320882518b53d2a6055f48c06b0deba00efa8baa1c1932ec6f1c598868a82", "bytes": 48, - "line": 5189 + "line": 5194 }, { "lang": "bash", "meta": null, "sha256": "1c902a61277e58e20d330fd4f7510a922639122f3e26126aeff5a404579d210d", "bytes": 45, - "line": 5220 + "line": 5225 }, { "lang": "bash", "meta": null, "sha256": "3e09d80993bd2231d73817167d0a3e7d022d9bb5fadbf1563a854531a3c22ced", "bytes": 36, - "line": 5250 + "line": 5255 }, { "lang": "bash", "meta": null, "sha256": "39050b42d7a1e9da84fac3fa817aa0635c47c28f32bceabcaf8811283ad7d7ce", "bytes": 48, - "line": 5274 + "line": 5279 }, { "lang": "bash", "meta": null, "sha256": "a4d3e32ee5d44b474b2fe040b4be5d32c0ad725d1b3c3e4342dc2ca08fa0a157", "bytes": 30, - "line": 5316 + "line": 5321 }, { "lang": "bash", "meta": null, "sha256": "37f58f218a36b8141bd5c32fb2774d731631774d332ce2fe9f7a3af158f122c1", "bytes": 42, - "line": 5342 + "line": 5347 }, { "lang": "bash", "meta": null, "sha256": "992f83d520658780ee956610f7965ecaad8d3c782b452d78d619edccd3afa26f", "bytes": 29, - "line": 5372 + "line": 5377 }, { "lang": "bash", "meta": null, "sha256": "594f0358c607649151209b234a12f44d7a125fa9150668fbf46ad475c36e52c9", "bytes": 28, - "line": 5392 + "line": 5397 }, { "lang": "bash", "meta": null, "sha256": "1f2babf217eecbcd3edee20e939434b8b177c454ae3edad1ed0a79b24bf0929f", "bytes": 42, - "line": 5415 + "line": 5420 }, { "lang": "bash", "meta": null, "sha256": "d0f3737b421a98903f809a0b9e6dea5cd3bd96377b7dcc30fc5239e3aecf311d", "bytes": 28, - "line": 5457 + "line": 5462 }, { "lang": "bash", "meta": null, "sha256": "aa98bb7f2995f97bb02887ae3591ff0609686e634f9ad60068fbe12f38a4a026", "bytes": 35, - "line": 5490 + "line": 5495 }, { "lang": "bash", "meta": null, "sha256": "e421d326ab72354b8ec1d5711570d31868223c50da978b51961f9896acae5f35", "bytes": 26, - "line": 5521 + "line": 5526 }, { "lang": "bash", "meta": null, "sha256": "65c4b3a60ee39d43b253afd6818ed08dd93a5297f82b4648e4a3d5b0002731e4", "bytes": 32, - "line": 5545 + "line": 5550 }, { "lang": "bash", "meta": null, "sha256": "e2f60ffbb1bae7635a1e9ba79c228b19464a582144e1be50bfaba8d2c2db30c8", "bytes": 27, - "line": 5587 + "line": 5592 }, { "lang": "bash", "meta": null, "sha256": "afa0b971e60daad0dddc74b93f44fac1f51be91d47626ed4942b465fc6eba770", "bytes": 28, - "line": 5609 + "line": 5614 }, { "lang": "bash", "meta": null, "sha256": "4a0236d60519b55978f69d4eaa3ac6b8de2b354a7e63a14255abb64862d0456e", "bytes": 27, - "line": 5639 + "line": 5644 }, { "lang": "bash", "meta": null, "sha256": "ebd45772f099ce26c6315895068a1703d8e757f43daf35f6d3618c408319b37b", "bytes": 37, - "line": 5663 + "line": 5668 }, { "lang": "bash", "meta": null, "sha256": "e6e8ba88a5ede0c440346b124c101ccd53241c492f6dc28c3453fd23b8917cb3", "bytes": 24, - "line": 5693 + "line": 5698 }, { "lang": "bash", "meta": null, "sha256": "c19501e59583b680d6ce36b1133f3850ef1c96d05e7e5985b6cb8b1c5e19ff46", "bytes": 45, - "line": 5713 + "line": 5718 }, { "lang": "bash", "meta": null, "sha256": "4b84b742cd46fa81f9dc42d64c66c4b801b9fc6c381c1fda6690647d082639e3", "bytes": 43, - "line": 5743 + "line": 5748 }, { "lang": "bash", "meta": null, "sha256": "b9eefbf636684f9388fb43e708ad6dd2326b629f85a95e039f69e13651993c41", "bytes": 45, - "line": 5777 + "line": 5782 }, { "lang": "bash", "meta": null, "sha256": "bf2cc4f904e1d46c6ad5fb9c85a1a77b75062b61997add02c5c8d5b4cdcda262", "bytes": 25, - "line": 5808 + "line": 5813 }, { "lang": "bash", "meta": null, "sha256": "eef07048b814eb3b00f997c8b0907d1e21817abad072f7e8502087fdbe9a0188", "bytes": 37, - "line": 5831 + "line": 5836 }, { "lang": "bash", "meta": null, "sha256": "f35ce94c4d5abe5378ba2b6095a786d9989540caefe3b2248b43ec375b69d212", "bytes": 45, - "line": 5869 + "line": 5874 }, { "lang": "bash", "meta": null, "sha256": "f8a9f16a31241f7bed8f14a44cbc6ba4c13707b0bbc71f95abaded420f98cae8", "bytes": 45, - "line": 5901 + "line": 5906 }, { "lang": "bash", "meta": null, "sha256": "6eee9d069d9053a29e2bd61c5a85821fead20cc3af306f55e3597f9931588d32", "bytes": 45, - "line": 5932 + "line": 5937 }, { "lang": "bash", "meta": null, "sha256": "b0485a54f218265aaf8ef27b26af37e80603744b4cd13af804b9460ded6c769c", "bytes": 44, - "line": 5963 + "line": 5968 }, { "lang": "bash", "meta": null, "sha256": "eff43eafc0b5c9829de1e71e899e82b6db9bf5a3ba4da138fe2608ecf2ad96ea", "bytes": 44, - "line": 5998 + "line": 6003 }, { "lang": "bash", "meta": null, "sha256": "598ec0411dcfb12246c2ad819aeb9083cfd0dcf6a894aec2a0e908d82226e85f", "bytes": 32, - "line": 6029 + "line": 6034 }, { "lang": "bash", "meta": null, "sha256": "2869d4bb0b7552d346eca2e8bfe110dccdb3a13073c0e5a531ed34e8d111459f", "bytes": 44, - "line": 6049 + "line": 6054 }, { "lang": "bash", "meta": null, "sha256": "faa95847578604b50b3c020d50d94589351f7b1ec36e28cac7fe2140de6c4549", "bytes": 33, - "line": 6092 + "line": 6097 }, { "lang": "bash", "meta": null, "sha256": "25e24485a99181672176131b6ac2152347841a1a567430fbb98a553a929770f3", "bytes": 47, - "line": 6114 + "line": 6119 }, { "lang": "bash", "meta": null, "sha256": "9720d5ef881383f1c6da7a8a3a008f3afd615af99678d1bb81118511ff84dfcc", "bytes": 42, - "line": 6144 + "line": 6149 }, { "lang": "bash", "meta": null, "sha256": "3b9ac116c754c7e2bcf7f077f6061399dbfff4238408c4ef0d048fb442c3baf8", "bytes": 50, - "line": 6177 + "line": 6182 }, { "lang": "bash", "meta": null, "sha256": "3487041dfbdb03a03ebed0e308da4117442785d83c8158248fbad5df46f35fb2", "bytes": 48, - "line": 6210 + "line": 6215 }, { "lang": "bash", "meta": null, "sha256": "25f7e3715a24bd9657f90a5d9bc466cfe7b121a2660596c62c08a6ae0c4834f2", "bytes": 47, - "line": 6243 + "line": 6248 }, { "lang": "bash", "meta": null, "sha256": "8a310ebdd720a3d0e2fffb7db415873a53befe47ea4d638fca4ecd59ac27595e", "bytes": 40, - "line": 6275 + "line": 6280 }, { "lang": "bash", "meta": null, "sha256": "d3dba384fd5ce87e831b8454186e60d5e1cd6ae404b6324009adf4a961d85cfe", "bytes": 41, - "line": 6308 + "line": 6313 }, { "lang": "bash", "meta": null, "sha256": "4bec76dae83cf450410fd42df2a56ef2b20e69143f9631539a58f363631cb986", "bytes": 41, - "line": 6343 + "line": 6348 }, { "lang": "bash", "meta": null, "sha256": "ad373ebb46a54ef7fead24880468d70c4a415003db879817f5d78e717994573c", "bytes": 50, - "line": 6373 + "line": 6378 }, { "lang": "bash", "meta": null, "sha256": "9f85f14e7c0f00e23c82b9a097ab414df558c764e4171f8bdd6771386b02677c", "bytes": 42, - "line": 6395 + "line": 6400 }, { "lang": "bash", "meta": null, "sha256": "856a70bda3a296ed9e7d3de557191906106fd51da9fab3d2372bd4a3d0115ae1", "bytes": 48, - "line": 6429 + "line": 6434 }, { "lang": "bash", "meta": null, "sha256": "12b44782510d874df9900581914d66e8e8a0708ea6e1f8cab799c1187d4778f2", "bytes": 50, - "line": 6462 + "line": 6467 }, { "lang": "bash", "meta": null, "sha256": "908dcdcee6aa38f9ed48e63e5a70bba22dc7aaa603dfb8c62f0999259a1b9eb1", "bytes": 61, - "line": 6495 + "line": 6500 }, { "lang": "bash", "meta": null, "sha256": "55ea841db41ce49eb504636a54c29187e16b403b686059375abfa8aa51d01f7d", "bytes": 48, - "line": 6526 + "line": 6531 }, { "lang": "bash", "meta": null, "sha256": "c414854798bccb75c4b223fbed069ed445872158dbfb2b23093e140827d1e838", "bytes": 48, - "line": 6561 + "line": 6566 }, { "lang": "bash", "meta": null, "sha256": "9f45f6e6567f09f49ec40484721420a71a15d42f7ab92d3a3cfa1124ab8419fd", "bytes": 36, - "line": 6582 + "line": 6587 }, { "lang": "bash", "meta": null, "sha256": "862b4e873ebd70c303716275ebf30b3822c9c9e7f261a78e27b18f9585d798b0", "bytes": 46, - "line": 6602 + "line": 6607 }, { "lang": "bash", "meta": null, "sha256": "bb65d63f55930b4ea7b86e0475159b98a53e0525015508285c90425f28d53a55", "bytes": 45, - "line": 6623 + "line": 6628 }, { "lang": "bash", "meta": null, "sha256": "18d5a60f518896e595f00666ed45fdd624c789287809e18798e0d9f5610d48c8", "bytes": 43, - "line": 6653 + "line": 6658 }, { "lang": "bash", "meta": null, "sha256": "e44d003a6ba11690de0cc469320be892fae3b09033939a46724fccfb0aac4ab0", "bytes": 48, - "line": 6674 + "line": 6679 }, { "lang": "bash", "meta": null, "sha256": "bee16895751b8f386d2188e18ae402e521187d2bb7da9af709c2432ba9634209", "bytes": 46, - "line": 6697 + "line": 6702 }, { "lang": "bash", "meta": null, "sha256": "d3dede19db079b39e165a036fac3dd3376044ada7849f3ec70220ae188ac28e5", "bytes": 33, - "line": 6727 + "line": 6732 }, { "lang": "bash", "meta": null, "sha256": "0ac8381a83158432224d7b6bead7492d25f36e68eadc15c18e9bf84eddef77d0", "bytes": 42, - "line": 6749 + "line": 6754 }, { "lang": "bash", "meta": null, "sha256": "57308ec7b05d6b120ff6841edb51d8159d84444d6eaf36b3bccb9d1b2bb385e6", "bytes": 27, - "line": 6783 + "line": 6788 }, { "lang": "bash", "meta": null, "sha256": "90b5b274482044f6d036867177353233bf58d00f5dd345f76c0866a23be10343", "bytes": 32, - "line": 6806 + "line": 6811 }, { "lang": "bash", "meta": null, "sha256": "0636f27b84a87525a97146f65475905163efcae563920102110bdaef39d0cbe2", "bytes": 42, - "line": 6828 + "line": 6833 }, { "lang": "bash", "meta": null, "sha256": "36c08c95e7a531c73736416e90aea14eb199ad1746f90a4ecc78db9c037fd03e", "bytes": 33, - "line": 6859 + "line": 6864 }, { "lang": "bash", "meta": null, "sha256": "ab978cbdc23f7d851799251cfe01863187b2cd628b05c3c750ad1db2d26fb5fc", "bytes": 44, - "line": 6884 + "line": 6889 }, { "lang": "bash", "meta": null, "sha256": "2333fb674a47979dc56cf4e10c852516a7d179ddc234cc184130c6e82ae5811b", "bytes": 33, - "line": 6907 + "line": 6912 }, { "lang": "bash", "meta": null, "sha256": "d301cb24422359056dad68402e9f54a8ed15e21c0f183fb4c8eb937738f155dc", "bytes": 43, - "line": 6927 + "line": 6932 }, { "lang": "bash", "meta": null, "sha256": "bd3c423a63ecf70ee28e0c4aa2fe7b9e6078179ec2577ba80004cdfaf527843a", "bytes": 52, - "line": 6960 + "line": 6965 }, { "lang": "bash", "meta": null, "sha256": "a064ea603a971a2a3582988297d7293e6e0c6cabedfad714f2af97c0ff1884e7", "bytes": 39, - "line": 6991 + "line": 6996 }, { "lang": "bash", "meta": null, "sha256": "20d848044f1a1ac09fe6621d3e3f7fe7e2a6271c08e23f5eaea2c4c4b3f21c9d", "bytes": 31, - "line": 7012 + "line": 7017 }, { "lang": "bash", "meta": null, "sha256": "b19fe44255306f492be72ced4183894fe6ab47c5e87ab02cf909c5a6e89ab964", "bytes": 52, - "line": 7032 + "line": 7037 }, { "lang": "bash", "meta": null, "sha256": "0a8251333833585605881b98f9d121fa0e5669e58ba11cb583f69a333cea2ad6", "bytes": 37, - "line": 7069 + "line": 7074 }, { "lang": "bash", "meta": null, "sha256": "3f1de42768c4151cd364eb2534408179e93ca92dda918a493c9d05d4c8f03209", "bytes": 53, - "line": 7099 + "line": 7104 }, { "lang": "bash", "meta": null, "sha256": "60b57e472e506c0d6430f325c0e05c6cdfe9a62b4051a9f371929799ec7cfdef", "bytes": 24, - "line": 7121 + "line": 7126 }, { "lang": "bash", "meta": null, "sha256": "aeea8ffe933fcbb749950596d5c83192d1c42e2dac8f9532625c97afd7fe18a2", "bytes": 25, - "line": 7141 + "line": 7146 }, { "lang": "bash", "meta": null, "sha256": "3010a87af250eea55a7de4dcdda1fdcef515e73b7d2f5977d955f9d66ca4e130", "bytes": 25, - "line": 7166 + "line": 7171 }, { "lang": "bash", "meta": null, "sha256": "4cff190ec4b1d449d089493b45b00f986e3d17e563bca1816769ee3a1cfea2f2", "bytes": 28, - "line": 7188 + "line": 7193 }, { "lang": "bash", "meta": null, "sha256": "b7a3a8b8a114216dbdb506005496e5510feb227b0b6e39ba2b5145743e852577", "bytes": 37, - "line": 7208 + "line": 7213 }, { "lang": "bash", "meta": null, "sha256": "36e0677e842c003940707713b5334c6f2cabdfe6548790bc0c1b8546b0f820b6", "bytes": 32, - "line": 7240 + "line": 7245 }, { "lang": "bash", "meta": null, "sha256": "a9a07815e06f5bab4b2d1fc80a606227a8a617c105c56680c4bef68a520970c1", "bytes": 37, - "line": 7261 + "line": 7266 }, { "lang": "bash", "meta": null, "sha256": "79420742f040a499740d4b465a8e8fdbc628c275fbd2880182637c5917b67b9e", "bytes": 34, - "line": 7298 + "line": 7303 }, { "lang": "bash", "meta": null, "sha256": "a6b4fb5e2728894616f9d11df544879c4786b80458d5905a67ffc2224022ec1e", "bytes": 30, - "line": 7337 + "line": 7342 }, { "lang": "bash", "meta": null, "sha256": "1aa431dc5b8d1fdc3d54a77c56f15a1b9ac5896e343818d3d0ad2edbabc541db", "bytes": 23, - "line": 7368 + "line": 7373 }, { "lang": "bash", "meta": null, "sha256": "262692daffbb55d5cbbf1717fb2c8ff08bc009514bae8ff83ee756d4caba08d1", "bytes": 36, - "line": 7394 + "line": 7399 }, { "lang": "bash", "meta": null, "sha256": "1e9b19a7ea2fdbf0902ed74b48cecc710d7fa2272d4dbed9172af1ae0258310d", "bytes": 22, - "line": 7426 + "line": 7431 }, { "lang": "bash", "meta": null, "sha256": "734b96827127375d652bc125b1c9a243946cf5f8c251b43a7097656fcc2ce544", "bytes": 24, - "line": 7446 + "line": 7451 }, { "lang": "bash", "meta": null, "sha256": "c6544463a5be88fa1bb81e80633a6e4bf70e99d424d408c75930046e74c1dc5f", "bytes": 41, - "line": 7477 + "line": 7482 }, { "lang": "bash", "meta": null, "sha256": "2ba0e68b06d7be939be3058e281cd495a16a41611ae4dadb91c97dea4b95fe29", "bytes": 52, - "line": 7503 + "line": 7508 }, { "lang": "bash", "meta": null, "sha256": "f0f241b97b09236a5fcdc9527cff2f76cf382270caf4315aa8ae11f8ca919932", "bytes": 58, - "line": 7533 + "line": 7538 }, { "lang": "bash", "meta": null, "sha256": "fde5893586a0c2c7cbd2ab3976d7d9ef35e861b56eab07191919891e09528bd4", "bytes": 46, - "line": 7566 + "line": 7571 }, { "lang": "bash", "meta": null, "sha256": "3d28258fd09b2c94b7cb24cb37035ce71d3777b58b2270998781761f8957081e", "bytes": 71, - "line": 7588 + "line": 7593 }, { "lang": "bash", "meta": null, "sha256": "45cdb94cf834d1950ab049a6a65c398b4917312897fdcaa3f25fa0081e707912", "bytes": 39, - "line": 7619 + "line": 7624 }, { "lang": "bash", "meta": null, "sha256": "ac7f120b7e8c39cb3de7b0936dfd2f6d8f38ece480b0523518883cef7b5b643c", "bytes": 39, - "line": 7639 + "line": 7644 }, { "lang": "bash", "meta": null, "sha256": "7994ad60b43332fb5bc583bf1ea5599fa2f659cd8ad811105837cf9e87fa28ed", "bytes": 52, - "line": 7661 + "line": 7666 }, { "lang": "bash", "meta": null, "sha256": "5ed096b4dcf0efad18c54d322d528b7bb0e80336d061ee7eaa5d39d3bd505a4d", "bytes": 62, - "line": 7702 + "line": 7707 }, { "lang": "bash", "meta": null, "sha256": "daf3ccbc5a308bc4c62d1a761e01fac3d40ff67cc256c4c9624d0cd00a0072c4", "bytes": 53, - "line": 7735 + "line": 7740 }, { "lang": "text", "meta": null, - "sha256": "97cc531dfb1566ea12bc24f48050c2c311d6a45510ff45c5708b6f5c216e5e63", - "bytes": 2535, - "line": 7766 + "sha256": "aa4647efb6d9824f38c588df82cff0ce7cf0cea06c21fab0d73552cbb14556cf", + "bytes": 4323, + "line": 7771 }, { "lang": "bash", "meta": null, "sha256": "48ecf1013a285c0de3e23936d53a850d85af0564a7e089de2eba1ac7f8881a44", "bytes": 53, - "line": 7814 + "line": 7833 }, { "lang": "bash", "meta": null, "sha256": "653a412a8eeaffac8afbbbb2533375f02df67fe7ef882ca53fc7ca2755d0bcec", "bytes": 43, - "line": 7847 + "line": 7866 }, { "lang": "bash", "meta": null, "sha256": "bfb90a10455a59ef26068d176221816b9c374c4001d386ffdbb0140c4cfe40ca", "bytes": 40, - "line": 7877 + "line": 7896 }, { "lang": "bash", "meta": null, "sha256": "11658c406271a4f22a346aab51f697bc949342fbaaaabb2a786de824561bc4c3", "bytes": 35, - "line": 7912 + "line": 7931 }, { "lang": "bash", "meta": null, "sha256": "d683e8c6e5a1d063ea9f6c74fd9020d48aede0d5af7031f6f48bd5a173ad2d3d", "bytes": 33, - "line": 7937 + "line": 7956 }, { "lang": "bash", "meta": null, "sha256": "96abc89ee23cb4a7e2fc3caca2afbd2dd57d2734ca9e73816c412a71c5c5eb9d", "bytes": 43, - "line": 7964 + "line": 7983 }, { "lang": "bash", "meta": null, "sha256": "d63bf37625acc32ec1ee6e59a56f57469b9cb4dab03e23067a54d2f7d8abd3a3", "bytes": 41, - "line": 7996 + "line": 8015 }, { "lang": "bash", "meta": null, "sha256": "eb79c561c688b305a39f834bb39d74f65095db957e337d8e6081bbc00545bb08", "bytes": 53, - "line": 8029 + "line": 8048 }, { "lang": "bash", "meta": null, "sha256": "f30977b7b952e6a369b72b828256fac3f9ede78ce6e7c45560a8d09989bd4db5", "bytes": 49, - "line": 8060 + "line": 8079 }, { "lang": "bash", "meta": null, "sha256": "7d00d2a238c8794c5479e28ef14e6e104bcaff1aaaef70a094a2a51c55b6420c", "bytes": 50, - "line": 8081 + "line": 8100 }, { "lang": "bash", "meta": null, "sha256": "f34921d79bc4b608cb3e3c3f882729808afe1d8cf95ca45c63cbdf00ab494a3e", "bytes": 62, - "line": 8112 + "line": 8131 }, { "lang": "bash", "meta": null, "sha256": "ebfb60766394d803a01326b040ac37c5f122134555f1b968aeb6a79b10d74fc7", "bytes": 30, - "line": 8144 + "line": 8163 }, { "lang": "bash", "meta": null, "sha256": "432348582be57741628ca2b6a762c385ed57bbbfd4e4794b914409b7a89db582", "bytes": 35, - "line": 8168 + "line": 8187 }, { "lang": "bash", "meta": null, "sha256": "25d75743717b8e1c96f6b78e334e3e3cbc6dac5e395068308a4e358e06a0bac6", "bytes": 45, - "line": 8190 + "line": 8209 }, { "lang": "bash", "meta": null, "sha256": "2fc4fd97c2a62f635b42d646e481b18b0402ec0d051e7532988c026d838f0534", "bytes": 36, - "line": 8221 + "line": 8240 }, { "lang": "bash", "meta": null, "sha256": "3da31453cf86b97920f8d013f00122dee830af847c064e30ed3e158bd8f642cb", "bytes": 47, - "line": 8246 + "line": 8265 }, { "lang": "bash", "meta": null, "sha256": "d4de05e9142f532574133568e3fe2965c7fd82338e5b54ba0d8ae5713639eaca", "bytes": 43, - "line": 8271 + "line": 8290 }, { "lang": "bash", "meta": null, "sha256": "e63db5a4bab57e3229127bb086d0c5429dfe20de83eaf5097e8943f90520b9b3", "bytes": 51, - "line": 8303 + "line": 8322 }, { "lang": "bash", "meta": null, "sha256": "b130d4ed01c735074275b1505e7959e6dd3ae89c6b7ac159d17ccd495bec8f38", "bytes": 38, - "line": 8333 + "line": 8352 }, { "lang": "bash", "meta": null, "sha256": "32709306f0caabb4378fce9efba6b9c60a3985bb3500402d9a7f9e89fe35e00e", "bytes": 49, - "line": 8357 + "line": 8376 }, { "lang": "bash", "meta": null, "sha256": "a09f283134986b066a49a41c5ef250ff1502ae2adbc3316baacf92712112cc2d", "bytes": 43, - "line": 8399 + "line": 8418 }, { "lang": "bash", "meta": null, "sha256": "d941e4f91a379820ba5d640e7ceffd42c6fdd70b5b19da9c508c259b40ce14f7", "bytes": 53, - "line": 8432 + "line": 8451 }, { "lang": "bash", "meta": null, "sha256": "fb10d8958f9f1b03ab76713459abf552755dae3334103a451c387c9d1c7b3605", "bytes": 40, - "line": 8463 + "line": 8482 }, { "lang": "bash", "meta": null, "sha256": "b5dc1e771889fb1bf5f4d81d340cfd35d3a2263c87a725341d1d5c70405eb78d", "bytes": 43, - "line": 8519 + "line": 8538 }, { "lang": "bash", "meta": null, "sha256": "9065c4d4de3606f4362700b64aa3f856aa75214bebafe9334d48b9ff8466a80c", "bytes": 38, - "line": 8553 + "line": 8572 }, { "lang": "bash", "meta": null, "sha256": "face4eea006073000b49334d0a2bea7f15f9df86cb1f606ac8fe39004c754027", "bytes": 30, - "line": 8573 + "line": 8592 }, { "lang": "bash", "meta": null, "sha256": "29cc30facfddd548aa5873383ac3d90a6b392cf120894fd73a735f266196540d", "bytes": 47, - "line": 8583 + "line": 8602 }, { "lang": "bash", "meta": null, "sha256": "d58dd2280200d928a15de43483c5c709be8aedc38087ba95cbbe2a31a39466fa", "bytes": 49, - "line": 8617 + "line": 8636 }, { "lang": "bash", "meta": null, "sha256": "f43f6a034552660fdb745c0ac0cfe17c1af0c7a2995fd76ab45f79ebfd116bfb", "bytes": 37, - "line": 8654 + "line": 8674 }, { "lang": "bash", "meta": null, "sha256": "529d96c3ff160cf6393f3f7a1f69014d8f2f9f3f3ce5733fc11c58133accb7d7", "bytes": 36, - "line": 8682 + "line": 8703 }, { "lang": "bash", "meta": null, "sha256": "427c626ebed3055c690ff0dbbb3a20550a2daae5ae40f5f9e005f1eb47dd733a", "bytes": 37, - "line": 8709 + "line": 8730 }, { "lang": "bash", "meta": null, "sha256": "e61ba28ca4eef131ee1291f39b5cb583b2a1dd4436bde33a061ce27ac8af05af", "bytes": 46, - "line": 8735 + "line": 8757 }, { "lang": "bash", "meta": null, "sha256": "2b6c40dcef94f6188188d6369383e982f5a6dc88654b8ab76664c189f9af8ab0", "bytes": 47, - "line": 8769 + "line": 8791 }, { "lang": "bash", "meta": null, "sha256": "736889b5b5a59bc4fe7965922999b5cbec295acad8313c1e486d5668c7da961e", "bytes": 30, - "line": 8801 + "line": 8823 }, { "lang": "bash", "meta": null, "sha256": "4d6c0bc0130fd4a83c7b2fcac6f5b4b7bc2f275c05fa6101551ac61ce1405aca", "bytes": 44, - "line": 8821 + "line": 8843 }, { "lang": "bash", "meta": null, "sha256": "62d28b9be74c32c4ba00fefe878c492a6a5c671cc4a500373d7f2bdba9f7ef79", "bytes": 54, - "line": 8841 + "line": 8863 }, { "lang": "bash", "meta": null, "sha256": "185227ff19342ab461c3e652c4158d8ece85c079b2542b9243b7c7cf0b2dac2c", "bytes": 34, - "line": 8871 + "line": 8893 }, { "lang": "bash", "meta": null, "sha256": "7115696baaba8ca1ecd8f7cb22f215b7a53bf13d5757bd6932267644a0377807", "bytes": 36, - "line": 8891 + "line": 8913 }, { "lang": "bash", "meta": null, "sha256": "10330e610f59c2fb169fcff11cb8147563efbcc109f875222ecbfaaa48c05f31", "bytes": 50, - "line": 8913 + "line": 8935 }, { "lang": "bash", "meta": null, "sha256": "e88ab81833a4d529271c80e2cdf0e7ff5037a60066a918a9702a28ceca73a846", "bytes": 30, - "line": 8950 + "line": 8972 }, { "lang": "bash", "meta": null, "sha256": "f094df6732656b52792e5e766a69079c3e8bd929326bda7284e0bcb760bedd79", "bytes": 28, - "line": 8980 + "line": 9002 }, { "lang": "bash", "meta": null, "sha256": "7579bd6ac197afa0afa5f62d9b412a7e265725bd507c1c63b438a60fd72ce1d0", "bytes": 40, - "line": 9007 + "line": 9029 }, { "lang": "bash", "meta": null, "sha256": "63aac11606dc0eeb6cc452c20c405806840960425372cf2cf7c8b4b90a7de878", "bytes": 62, - "line": 9027 + "line": 9049 }, { "lang": "bash", "meta": null, "sha256": "52be4758f4289e9f75875d8401cf57fda54283b2df00e413921d07303e728638", "bytes": 28, - "line": 9058 + "line": 9080 }, { "lang": "bash", "meta": null, "sha256": "4c51312bac2ca9ea2dba0e7cf27f06d5e99502bab35ab569064057a85514cc38", "bytes": 38, - "line": 9079 + "line": 9101 }, { "lang": "bash", "meta": null, "sha256": "2b26aa6f404ab19bda2d846871eb04b732f6397d1899fc28d89a29706fc0a670", "bytes": 34, - "line": 9105 + "line": 9127 }, { "lang": "bash", "meta": null, "sha256": "47af2a240e0fa4bca92d786d1fea2d4b6cd7ee8810c4540b619271457739f829", "bytes": 60, - "line": 9127 + "line": 9149 }, { "lang": "bash", "meta": null, "sha256": "f4a5d9b54707e03cc845a3ffc99493f9990d7c0a0aa96a48a492b303ef1959b4", "bytes": 45, - "line": 9160 + "line": 9182 }, { "lang": "bash", "meta": null, "sha256": "4a4ff033e75c32373422638e4f8079487d9cc37fa2b250cc2907584e690e2699", "bytes": 45, - "line": 9193 + "line": 9215 }, { "lang": "bash", "meta": null, "sha256": "66d1f7b4fc772fcb1ac84bcba2c1aa0e1a26105dda64b564c40dec35fc5fdaf2", "bytes": 43, - "line": 9223 + "line": 9245 }, { "lang": "bash", "meta": null, "sha256": "5fc8d60c19e8e3fc1c640ea87e091d0b95642a210a7e1a7d9d19e527b6f11207", "bytes": 38, - "line": 9255 + "line": 9277 }, { "lang": "bash", "meta": null, "sha256": "a7acb92552eae9b29dd7b973751bb7f3c2f7eb1dc00f36e84c594cb88dd9fc1c", "bytes": 33, - "line": 9276 + "line": 9298 }, { "lang": "bash", "meta": null, "sha256": "bb84857c237d2bfae0c6f63653597fe55263147428a5e8d36ceacfcda6bd6246", "bytes": 26, - "line": 9307 + "line": 9329 }, { "lang": "bash", "meta": null, "sha256": "3e634421662d08fe73882dd6a0d428545c33597790333f83b4c5086c8d494a1e", "bytes": 49, - "line": 9333 + "line": 9355 }, { "lang": "bash", "meta": null, "sha256": "c48dfec9df0cebb16aa976f859770a8b5beb67e2cf01dc5472dd8b3727ea164d", "bytes": 47, - "line": 9353 + "line": 9375 }, { "lang": "bash", "meta": null, "sha256": "8fd3a890425cf05e630bcd969b2aff57b3993d6632d905cab5b23cfce60e425c", "bytes": 49, - "line": 9374 + "line": 9396 }, { "lang": "bash", "meta": null, "sha256": "bd32d826b077176044eabbf175d64a747ba1a826bb36c95efb46925525f75ba9", "bytes": 45, - "line": 9400 + "line": 9422 }, { "lang": "bash", "meta": null, "sha256": "ee94be8e7fcb3c1bdb0abd6991992563371ba113b80b433cce0c71ac499f1d48", "bytes": 43, - "line": 9424 + "line": 9446 }, { "lang": "bash", "meta": null, "sha256": "bbaecaea783d60d4e8cbaad1c6951d2aa5fde5772f050166a24415162d9de3bc", "bytes": 29, - "line": 9446 + "line": 9468 }, { "lang": "bash", "meta": null, "sha256": "627ab83bbee7d7a608e8771c98556a00cb9df200a40fe9b68d79f93c322de59d", "bytes": 18, - "line": 9471 + "line": 9493 }, { "lang": "bash", "meta": null, "sha256": "9396c5d2aba2c0ff0d484a0a778dc38368154eb19edca9372cf576f8abedac90", "bytes": 32, - "line": 9481 + "line": 9503 }, { "lang": "bash", "meta": null, "sha256": "456a3638df3f1208cc5620fe2f7744e60215930e90cdada8c6d3f3041844b81c", "bytes": 22, - "line": 9491 + "line": 9513 }, { "lang": "bash", "meta": null, "sha256": "80c6f38f04b6c653c8de67e79ba7b6ca1a5ec208e8765a036048fd0adc4b4522", "bytes": 37, - "line": 9501 + "line": 9523 }, { "lang": "bash", "meta": null, "sha256": "3be0a5bf2f996779b39f57c35c08a046709ad91ffbb1ecd700c2d0f8a1c9b554", "bytes": 40, - "line": 9526 + "line": 9548 }, { "lang": "bash", "meta": null, "sha256": "94cdaecf523029bf20f25cf278f76142041e4ad9ce6980a0de225f6dd0b93a8f", "bytes": 43, - "line": 9548 + "line": 9570 }, { "lang": "bash", "meta": null, "sha256": "1731734821194e9c9ab5d0e866031dff102eab3c67b81c83780dce706461c802", "bytes": 40, - "line": 9568 + "line": 9590 }, { "lang": "bash", "meta": null, "sha256": "466187fc1a5788ab09d7700cf7cd19c9c541a571d0bc86d70fe52a1eb831b851", "bytes": 54, - "line": 9590 + "line": 9612 }, { "lang": "bash", "meta": null, "sha256": "e10bc7e084ad3b9231262208e0ac216aee47dc0ec7b1507214690ea9c098d5c9", "bytes": 32, - "line": 9622 + "line": 9644 }, { "lang": "bash", "meta": null, "sha256": "6bb0cf09f6bd8ba02e1f24a5eed89b35c0226ec7eefce07502015a455520fd0f", "bytes": 33, - "line": 9632 + "line": 9654 }, { "lang": "bash", "meta": null, "sha256": "23acce8016e243ab651bcc860cd8f1b1d236e6a5b7951abc76282cd674b2a25e", "bytes": 39, - "line": 9655 + "line": 9677 }, { "lang": "bash", "meta": null, "sha256": "210e8ab3d8af173ce648501ca50c828325ac1f4452006ad4485cb7a24d760ae4", "bytes": 37, - "line": 9679 + "line": 9701 }, { "lang": "bash", "meta": null, "sha256": "cdff2d4272d5bc3a18729e63e5ece9053d33ac0f8faf35cfaa3a289baa2dccc1", "bytes": 48, - "line": 9701 + "line": 9723 }, { "lang": "bash", "meta": null, "sha256": "c307203dd609208b90cbc0372e3401a75e943421bdf77e4e10779ed2c89ca4ff", "bytes": 48, - "line": 9731 + "line": 9753 }, { "lang": "bash", "meta": null, "sha256": "f6340c3d5dc4eedb98435df593ff277d0e44fbcb4c61e71a05123267b5352e78", "bytes": 29, - "line": 9761 + "line": 9783 }, { "lang": "bash", "meta": null, "sha256": "ca6e405dc70365db67ec66e6c2499fedf89ae3d7a90f4b5d044a2aab13bb8f37", "bytes": 37, - "line": 9783 + "line": 9805 }, { "lang": "bash", "meta": null, "sha256": "52918df5b4d4003d22322d5785d8a0202a2b66d39a3c71171f92a65545e28788", "bytes": 37, - "line": 9804 + "line": 9826 }, { "lang": "bash", "meta": null, "sha256": "28e77f2a35930390cc7de2fc5abdce7809311c33b10eb749941d5c44b9de0cfa", "bytes": 37, - "line": 9829 + "line": 9851 }, { "lang": "bash", "meta": null, "sha256": "088f9018d5639eac73c710bf1ef4fd134b0cd4c290587a161af1322b415a013f", "bytes": 29, - "line": 9856 + "line": 9878 }, { "lang": "bash", "meta": null, "sha256": "67384a12d7642ea8a82e807a58e42f921ea37cb496e2315ac87368ae0e297e4d", "bytes": 29, - "line": 9888 + "line": 9910 }, { "lang": "bash", "meta": null, "sha256": "4c9e46c0b1c48cb348bfb37e4c705e4dfe1cd5f221d667ebd02dd7325fce7e29", "bytes": 38, - "line": 9920 + "line": 9942 }, { "lang": "bash", "meta": null, "sha256": "20fbb381c0b4ef786f755f485789ecb9e76538ec6394956bb6153ee4a79547ca", "bytes": 31, - "line": 9943 + "line": 9965 }, { "lang": "bash", "meta": null, "sha256": "ec9baafc46bf3e7425a387e9d92083a610028b2f7bf477ccc203fee669796cf1", "bytes": 31, - "line": 9964 + "line": 9986 }, { "lang": "bash", "meta": null, "sha256": "54ffdfd98a1fc3aad38e602c1d02336a81fe97d48e6732402a7980d0f55cb20d", "bytes": 40, - "line": 9985 + "line": 10007 }, { "lang": "bash", "meta": null, "sha256": "1dbcb58a66005a55dccd94c633f3be04c7b462980746ce0bdfc7275bf728f009", "bytes": 35, - "line": 10006 + "line": 10028 }, { "lang": "bash", "meta": null, "sha256": "384da7ccbd87c00eba8c8301b7904ac71161b4faa0f51c208e833ddb1eba9a3c", "bytes": 37, - "line": 10032 + "line": 10054 }, { "lang": "bash", "meta": null, "sha256": "8fae3ef13c962a97565001ae3caa4625cb9df99e17686cf13c6142b0c324a5a6", "bytes": 37, - "line": 10061 + "line": 10084 }, { "lang": "bash", "meta": null, "sha256": "7dc2bd34c299748344eadb6569a96731086b27cc503f1bff70f63a05d41782fb", "bytes": 38, - "line": 10092 + "line": 10115 }, { "lang": "bash", "meta": null, "sha256": "625019ad388b3c98472aa65b7a683a970d0d0060496e89c547c3bbef85afc867", "bytes": 47, - "line": 10121 + "line": 10145 } ], "links": [ @@ -14188,175 +14188,161 @@ "meta": null, "sha256": "b9179e0bca4639a77dbc99a0802c9c18305b65cce5c37ce114b8e215f26070a0", "bytes": 134, - "line": 6 + "line": 10 }, { "lang": "bash", "meta": null, "sha256": "6367a903928d88d568ec633957ade0b5f874989ac59a1cf31c58287830c6c777", "bytes": 170, - "line": 19 + "line": 23 }, { "lang": "bash", "meta": null, "sha256": "61a29fb19683034ec35a9a6cb6caa3a94bbb9b4fd1e8c545fbbd933478ad0844", "bytes": 241, - "line": 33 + "line": 37 }, { "lang": "bash", "meta": null, "sha256": "bc4f2b365fb6d27a0afb6b8ebcdd56e94301c40741300e10ba249e11708274fd", "bytes": 172, - "line": 45 + "line": 49 }, { "lang": "bash", "meta": null, "sha256": "dc652d6ae196b4ad1d37da8dcdee9ae36e1798498e10f94882a117410d43e45f", "bytes": 202, - "line": 56 + "line": 60 }, { "lang": "bash", "meta": null, "sha256": "5e0490835e43a237fec4df37f9bab2c053f332d26b38ae42ea710c1958d66fba", "bytes": 110, - "line": 67 + "line": 71 }, { "lang": "bash", "meta": null, "sha256": "2017d76c972d478c166fc271da149acdf01f3c5906a6b068e07d91b684fc2e24", "bytes": 65, - "line": 75 + "line": 79 }, { "lang": "bash", "meta": null, "sha256": "8237f3c905a4fed316c3cabae5b8cddd72c57d8e3e3abe712ebce4116246f82a", "bytes": 53, - "line": 84 + "line": 88 }, { "lang": "bash", "meta": null, "sha256": "abad6fbd8c82c1eb28d7a7f4b49f8cce9754472b20ffb2613a6a69ae8c2823b4", "bytes": 51, - "line": 92 + "line": 96 }, { "lang": "bash", "meta": null, "sha256": "7f0dad13a24bafce09cf14f505da3d6d956a0431e24845a80cd01b1a775e8374", "bytes": 263, - "line": 98 + "line": 102 }, { "lang": "json", "meta": null, - "sha256": "a19ec054796bc74549f7dbe83949c9eb6c5ae1f54cda5b5c9f8a7e1db5f99d80", - "bytes": 349, - "line": 113 + "sha256": "bf4d32315fcc01d909ecff9703177bc1b53ca17a1c30c875a4824d68e2899fae", + "bytes": 360, + "line": 117 }, { "lang": "bash", "meta": null, "sha256": "068b9eadd1fcffae232855024fdb4ff017b0f010ced2273c53f3b3fd2e898de2", "bytes": 236, - "line": 226 + "line": 176 }, { "lang": "bash", "meta": null, "sha256": "21d6503ee5e2f4362d6d086a74d41704bded199dd6f1a7a2f5760d4c06a78dab", "bytes": 260, - "line": 238 + "line": 188 }, { "lang": "bash", "meta": null, "sha256": "774f1a6b1c5e4ad85fa5551fba8a5faed7d82b3bb25e7d46336fb0b65e1e9522", "bytes": 220, - "line": 257 + "line": 207 }, { "lang": "bash", "meta": null, "sha256": "736d071516b05af975232c48c7e23065fc0334fc07c541ada21a806ea43f84e7", "bytes": 109, - "line": 270 + "line": 220 }, { "lang": "bash", "meta": null, "sha256": "019796d6002868ad852ec9b9bba75bff42f7f8f6eb2073dfb897aa359065721a", "bytes": 159, - "line": 276 + "line": 226 }, { "lang": "bash", "meta": null, "sha256": "3a91f6de422f9407871de6fa5bac996f2337001079def7f966bd0068086d7c63", "bytes": 199, - "line": 285 + "line": 235 }, { "lang": "bash", "meta": null, "sha256": "cdbd2c99596ad694d9ebd9eca43740e8c7371fabba9eca7cc580c16ae96bc800", "bytes": 166, - "line": 302 + "line": 252 }, { "lang": "bash", "meta": null, "sha256": "3edb250258fdf417424a8f185dd601a1a6374ce8b93dd553276cfef39875f959", "bytes": 323, - "line": 317 + "line": 267 }, { "lang": "bash", "meta": null, "sha256": "1d949072a36a628c98e3d17961acc9c59f07edcc89f63413f212adc3baec879e", "bytes": 290, - "line": 326 + "line": 276 }, { "lang": "bash", "meta": null, "sha256": "4cc080decc18686ffbbfe9c5c51c621d23d2b8de9f189ed8145973189681900b", "bytes": 219, - "line": 336 + "line": 286 }, { "lang": "bash", "meta": null, "sha256": "ab8b2eb4638d04f81b66e3eba3d9acfe49e6ae2531094ed48d0d3468537c188b", "bytes": 160, - "line": 343 + "line": 293 }, { "lang": "bash", "meta": "title=\"nightly-digest.sh\"", "sha256": "25d588b87d9f49723f0b1e41edadedfb33ec1eb28460b9b8574d2dfef87a7870", "bytes": 747, - "line": 352 - }, - { - "lang": "yaml", - "meta": "title=\".github/workflows/sim-workspace.yml\"", - "sha256": "9e7ef199fcc3626b482f4377b15d500c8cf417675cdf19fbdcf9188cce424963", - "bytes": 1136, - "line": 382 - }, - { - "lang": "bash", - "meta": null, - "sha256": "3b675df64318861fe48f8c955db2eaee667edaafd4389e2f4bb220fcf5445fee", - "bytes": 75, - "line": 427 + "line": 302 } ], "links": [ @@ -17430,392 +17416,392 @@ "meta": null, "sha256": "f094df6732656b52792e5e766a69079c3e8bd929326bda7284e0bcb760bedd79", "bytes": 28, - "line": 14 + "line": 18 }, { "lang": "bash", "meta": null, "sha256": "736889b5b5a59bc4fe7965922999b5cbec295acad8313c1e486d5668c7da961e", "bytes": 30, - "line": 39 + "line": 43 }, { "lang": "bash", "meta": null, "sha256": "ebfb60766394d803a01326b040ac37c5f122134555f1b968aeb6a79b10d74fc7", "bytes": 30, - "line": 57 + "line": 61 }, { "lang": "bash", "meta": null, "sha256": "66d1f7b4fc772fcb1ac84bcba2c1aa0e1a26105dda64b564c40dec35fc5fdaf2", "bytes": 43, - "line": 79 + "line": 83 }, { "lang": "bash", "meta": null, "sha256": "d941e4f91a379820ba5d640e7ceffd42c6fdd70b5b19da9c508c259b40ce14f7", "bytes": 53, - "line": 109 + "line": 113 }, { "lang": "bash", "meta": null, "sha256": "52be4758f4289e9f75875d8401cf57fda54283b2df00e413921d07303e728638", "bytes": 28, - "line": 138 + "line": 142 }, { "lang": "bash", "meta": null, "sha256": "5fc8d60c19e8e3fc1c640ea87e091d0b95642a210a7e1a7d9d19e527b6f11207", "bytes": 38, - "line": 157 + "line": 161 }, { "lang": "bash", "meta": null, "sha256": "d4de05e9142f532574133568e3fe2965c7fd82338e5b54ba0d8ae5713639eaca", "bytes": 43, - "line": 178 + "line": 182 }, { "lang": "bash", "meta": null, "sha256": "2b26aa6f404ab19bda2d846871eb04b732f6397d1899fc28d89a29706fc0a670", "bytes": 34, - "line": 206 + "line": 210 }, { "lang": "bash", "meta": null, "sha256": "7115696baaba8ca1ecd8f7cb22f215b7a53bf13d5757bd6932267644a0377807", "bytes": 36, - "line": 226 + "line": 230 }, { "lang": "bash", "meta": null, "sha256": "10330e610f59c2fb169fcff11cb8147563efbcc109f875222ecbfaaa48c05f31", "bytes": 50, - "line": 248 + "line": 252 }, { "lang": "bash", "meta": null, "sha256": "185227ff19342ab461c3e652c4158d8ece85c079b2542b9243b7c7cf0b2dac2c", "bytes": 34, - "line": 283 + "line": 287 }, { "lang": "bash", "meta": null, "sha256": "daf3ccbc5a308bc4c62d1a761e01fac3d40ff67cc256c4c9624d0cd00a0072c4", "bytes": 53, - "line": 305 + "line": 309 }, { "lang": "text", "meta": null, - "sha256": "97cc531dfb1566ea12bc24f48050c2c311d6a45510ff45c5708b6f5c216e5e63", - "bytes": 2535, - "line": 336 + "sha256": "aa4647efb6d9824f38c588df82cff0ce7cf0cea06c21fab0d73552cbb14556cf", + "bytes": 4323, + "line": 340 }, { "lang": "bash", "meta": null, "sha256": "48ecf1013a285c0de3e23936d53a850d85af0564a7e089de2eba1ac7f8881a44", "bytes": 53, - "line": 382 + "line": 400 }, { "lang": "bash", "meta": null, "sha256": "a09f283134986b066a49a41c5ef250ff1502ae2adbc3316baacf92712112cc2d", "bytes": 43, - "line": 415 + "line": 433 }, { "lang": "bash", "meta": null, "sha256": "4d6c0bc0130fd4a83c7b2fcac6f5b4b7bc2f275c05fa6101551ac61ce1405aca", "bytes": 44, - "line": 446 + "line": 464 }, { "lang": "bash", "meta": null, "sha256": "62d28b9be74c32c4ba00fefe878c492a6a5c671cc4a500373d7f2bdba9f7ef79", "bytes": 54, - "line": 466 + "line": 484 }, { "lang": "bash", "meta": null, "sha256": "7579bd6ac197afa0afa5f62d9b412a7e265725bd507c1c63b438a60fd72ce1d0", "bytes": 40, - "line": 494 + "line": 512 }, { "lang": "bash", "meta": null, "sha256": "63aac11606dc0eeb6cc452c20c405806840960425372cf2cf7c8b4b90a7de878", "bytes": 62, - "line": 512 + "line": 530 }, { "lang": "bash", "meta": null, "sha256": "7d00d2a238c8794c5479e28ef14e6e104bcaff1aaaef70a094a2a51c55b6420c", "bytes": 50, - "line": 541 + "line": 559 }, { "lang": "bash", "meta": null, "sha256": "f30977b7b952e6a369b72b828256fac3f9ede78ce6e7c45560a8d09989bd4db5", "bytes": 49, - "line": 570 + "line": 588 }, { "lang": "bash", "meta": null, "sha256": "f34921d79bc4b608cb3e3c3f882729808afe1d8cf95ca45c63cbdf00ab494a3e", "bytes": 62, - "line": 589 + "line": 607 }, { "lang": "bash", "meta": null, "sha256": "eb79c561c688b305a39f834bb39d74f65095db957e337d8e6081bbc00545bb08", "bytes": 53, - "line": 619 + "line": 637 }, { "lang": "bash", "meta": null, "sha256": "5ed096b4dcf0efad18c54d322d528b7bb0e80336d061ee7eaa5d39d3bd505a4d", "bytes": 62, - "line": 652 + "line": 670 }, { "lang": "bash", "meta": null, "sha256": "47af2a240e0fa4bca92d786d1fea2d4b6cd7ee8810c4540b619271457739f829", "bytes": 60, - "line": 685 + "line": 703 }, { "lang": "bash", "meta": null, "sha256": "f4a5d9b54707e03cc845a3ffc99493f9990d7c0a0aa96a48a492b303ef1959b4", "bytes": 45, - "line": 718 + "line": 736 }, { "lang": "bash", "meta": null, "sha256": "4a4ff033e75c32373422638e4f8079487d9cc37fa2b250cc2907584e690e2699", "bytes": 45, - "line": 751 + "line": 769 }, { "lang": "bash", "meta": null, "sha256": "fb10d8958f9f1b03ab76713459abf552755dae3334103a451c387c9d1c7b3605", "bytes": 40, - "line": 781 + "line": 799 }, { "lang": "bash", "meta": null, "sha256": "d683e8c6e5a1d063ea9f6c74fd9020d48aede0d5af7031f6f48bd5a173ad2d3d", "bytes": 33, - "line": 833 + "line": 851 }, { "lang": "bash", "meta": null, "sha256": "11658c406271a4f22a346aab51f697bc949342fbaaaabb2a786de824561bc4c3", "bytes": 35, - "line": 858 + "line": 876 }, { "lang": "bash", "meta": null, "sha256": "bfb90a10455a59ef26068d176221816b9c374c4001d386ffdbb0140c4cfe40ca", "bytes": 40, - "line": 883 + "line": 901 }, { "lang": "bash", "meta": null, "sha256": "d63bf37625acc32ec1ee6e59a56f57469b9cb4dab03e23067a54d2f7d8abd3a3", "bytes": 41, - "line": 916 + "line": 934 }, { "lang": "bash", "meta": null, "sha256": "96abc89ee23cb4a7e2fc3caca2afbd2dd57d2734ca9e73816c412a71c5c5eb9d", "bytes": 43, - "line": 949 + "line": 967 }, { "lang": "bash", "meta": null, "sha256": "653a412a8eeaffac8afbbbb2533375f02df67fe7ef882ca53fc7ca2755d0bcec", "bytes": 43, - "line": 981 + "line": 999 }, { "lang": "bash", "meta": null, "sha256": "b130d4ed01c735074275b1505e7959e6dd3ae89c6b7ac159d17ccd495bec8f38", "bytes": 38, - "line": 1013 + "line": 1031 }, { "lang": "bash", "meta": null, "sha256": "32709306f0caabb4378fce9efba6b9c60a3985bb3500402d9a7f9e89fe35e00e", "bytes": 49, - "line": 1037 + "line": 1055 }, { "lang": "bash", "meta": null, "sha256": "e63db5a4bab57e3229127bb086d0c5429dfe20de83eaf5097e8943f90520b9b3", "bytes": 51, - "line": 1081 + "line": 1099 }, { "lang": "bash", "meta": null, "sha256": "b5dc1e771889fb1bf5f4d81d340cfd35d3a2263c87a725341d1d5c70405eb78d", "bytes": 43, - "line": 1113 + "line": 1131 }, { "lang": "bash", "meta": null, "sha256": "4c51312bac2ca9ea2dba0e7cf27f06d5e99502bab35ab569064057a85514cc38", "bytes": 38, - "line": 1145 + "line": 1163 }, { "lang": "bash", "meta": null, "sha256": "e88ab81833a4d529271c80e2cdf0e7ff5037a60066a918a9702a28ceca73a846", "bytes": 30, - "line": 1169 + "line": 1187 }, { "lang": "bash", "meta": null, "sha256": "a7acb92552eae9b29dd7b973751bb7f3c2f7eb1dc00f36e84c594cb88dd9fc1c", "bytes": 33, - "line": 1199 + "line": 1217 }, { "lang": "bash", "meta": null, "sha256": "2fc4fd97c2a62f635b42d646e481b18b0402ec0d051e7532988c026d838f0534", "bytes": 36, - "line": 1228 + "line": 1246 }, { "lang": "bash", "meta": null, "sha256": "432348582be57741628ca2b6a762c385ed57bbbfd4e4794b914409b7a89db582", "bytes": 35, - "line": 1251 + "line": 1269 }, { "lang": "bash", "meta": null, "sha256": "25d75743717b8e1c96f6b78e334e3e3cbc6dac5e395068308a4e358e06a0bac6", "bytes": 45, - "line": 1271 + "line": 1289 }, { "lang": "bash", "meta": null, "sha256": "3da31453cf86b97920f8d013f00122dee830af847c064e30ed3e158bd8f642cb", "bytes": 47, - "line": 1300 + "line": 1318 }, { "lang": "bash", "meta": null, "sha256": "bb84857c237d2bfae0c6f63653597fe55263147428a5e8d36ceacfcda6bd6246", "bytes": 26, - "line": 1321 + "line": 1339 }, { "lang": "bash", "meta": null, "sha256": "29cc30facfddd548aa5873383ac3d90a6b392cf120894fd73a735f266196540d", "bytes": 47, - "line": 1341 + "line": 1359 }, { "lang": "bash", "meta": null, "sha256": "427c626ebed3055c690ff0dbbb3a20550a2daae5ae40f5f9e005f1eb47dd733a", "bytes": 37, - "line": 1373 + "line": 1391 }, { "lang": "bash", "meta": null, "sha256": "f43f6a034552660fdb745c0ac0cfe17c1af0c7a2995fd76ab45f79ebfd116bfb", "bytes": 37, - "line": 1397 + "line": 1416 }, { "lang": "bash", "meta": null, "sha256": "d58dd2280200d928a15de43483c5c709be8aedc38087ba95cbbe2a31a39466fa", "bytes": 49, - "line": 1423 + "line": 1443 }, { "lang": "bash", "meta": null, "sha256": "9065c4d4de3606f4362700b64aa3f856aa75214bebafe9334d48b9ff8466a80c", "bytes": 38, - "line": 1458 + "line": 1479 }, { "lang": "bash", "meta": null, "sha256": "529d96c3ff160cf6393f3f7a1f69014d8f2f9f3f3ce5733fc11c58133accb7d7", "bytes": 36, - "line": 1476 + "line": 1497 }, { "lang": "bash", "meta": null, "sha256": "e61ba28ca4eef131ee1291f39b5cb583b2a1dd4436bde33a061ce27ac8af05af", "bytes": 46, - "line": 1501 + "line": 1522 }, { "lang": "bash", "meta": null, "sha256": "2b6c40dcef94f6188188d6369383e982f5a6dc88654b8ab76664c189f9af8ab0", "bytes": 47, - "line": 1535 + "line": 1556 }, { "lang": "bash", "meta": null, "sha256": "face4eea006073000b49334d0a2bea7f15f9df86cb1f606ac8fe39004c754027", "bytes": 30, - "line": 1565 + "line": 1586 } ], "links": [ @@ -180376,8 +180362,8 @@ { "lang": "json", "meta": null, - "sha256": "a58b8caec4a62b60998e6e861527913aa75c729a95b8772f0bea51b5947f98c3", - "bytes": 302, + "sha256": "2a7fc012d9a65e44b43b9d3a71fc338005cb118dccc142cb009006420d9d329d", + "bytes": 322, "line": 90 }, { @@ -180385,7 +180371,7 @@ "meta": null, "sha256": "202789edbaae3ec51e3c5209888b456b40142eb9151fa7b2a56387b92205b373", "bytes": 135, - "line": 112 + "line": 113 } ], "links": [ diff --git a/apps/sim/app/(auth)/components/social-login-buttons.tsx b/apps/sim/app/(auth)/components/social-login-buttons.tsx index fa7cffde1bf..ea138482548 100644 --- a/apps/sim/app/(auth)/components/social-login-buttons.tsx +++ b/apps/sim/app/(auth)/components/social-login-buttons.tsx @@ -23,7 +23,7 @@ interface SocialLoginButtonsProps { microsoftAvailable: boolean view: 'login' | 'signup' callbackURL?: string - ssoEnabled?: boolean + ssoEnabled: boolean disabled?: boolean } diff --git a/apps/sim/app/(auth)/components/sso-login-button.tsx b/apps/sim/app/(auth)/components/sso-login-button.tsx index bf0e710ef0a..4e993d8980e 100644 --- a/apps/sim/app/(auth)/components/sso-login-button.tsx +++ b/apps/sim/app/(auth)/components/sso-login-button.tsx @@ -1,7 +1,6 @@ 'use client' import { AuthIcon, AuthButton as Chip } from '@sim/auth-ui' import { useRouter } from 'next/navigation' -import { isSsoEnabled } from '@/lib/core/config/env-flags' interface SSOLoginButtonProps { disabled?: boolean @@ -18,10 +17,6 @@ export function SSOLoginButton({ }: SSOLoginButtonProps) { const router = useRouter() - if (!isSsoEnabled) { - return null - } - const handleSSOClick = () => { const ssoUrl = `/sso${callbackURL ? `?callbackUrl=${encodeURIComponent(callbackURL)}` : ''}` router.push(ssoUrl) diff --git a/apps/sim/app/(auth)/login/login-form.tsx b/apps/sim/app/(auth)/login/login-form.tsx index 046e2830c73..5ac641a1ca1 100644 --- a/apps/sim/app/(auth)/login/login-form.tsx +++ b/apps/sim/app/(auth)/login/login-form.tsx @@ -9,7 +9,6 @@ import { useRouter, useSearchParams } from 'next/navigation' import { requestJson } from '@/lib/api/client/request' import { forgetPasswordContract } from '@/lib/api/contracts' import { client } from '@/lib/auth/client' -import { isSsoEnabled } from '@/lib/core/config/env-flags' import { validateCallbackUrl } from '@/lib/core/security/input-validation' import { getBaseUrl } from '@/lib/core/utils/urls' import { quickValidateEmail } from '@/lib/messaging/email/validation' @@ -79,12 +78,15 @@ export default function LoginPage({ googleAvailable, microsoftAvailable, emailPasswordEnabled, + ssoEnabled, }: { githubAvailable: boolean googleAvailable: boolean microsoftAvailable: boolean /** Whether `REGISTRATION_MODE` leaves email/password and email OTP sign-in on. */ emailPasswordEnabled: boolean + /** Whether SAML/OIDC single sign-on is enabled for this deployment. */ + ssoEnabled: boolean }) { const router = useRouter() const searchParams = useSearchParams() @@ -347,7 +349,6 @@ export default function LoginPage({ } } - const ssoEnabled = isSsoEnabled const hasSocial = githubAvailable || googleAvailable || microsoftAvailable const hasOnlySSO = ssoEnabled && !emailPasswordEnabled && !hasSocial const showTopSSO = hasOnlySSO diff --git a/apps/sim/app/(auth)/login/page.tsx b/apps/sim/app/(auth)/login/page.tsx index e5687891917..a53e1fb96b8 100644 --- a/apps/sim/app/(auth)/login/page.tsx +++ b/apps/sim/app/(auth)/login/page.tsx @@ -1,6 +1,6 @@ import { Suspense } from 'react' import type { Metadata } from 'next' -import { isEmailPasswordAuthEnabled } from '@/lib/core/config/env-flags' +import { isEmailPasswordAuthEnabled, isSsoEnabled } from '@/lib/core/config/env-flags' import { getOAuthProviderStatus } from '@/app/(auth)/components/oauth-provider-checker' import LoginLoading from '@/app/(auth)/login/loading' import LoginForm from '@/app/(auth)/login/login-form' @@ -21,6 +21,7 @@ export default async function LoginPage() { googleAvailable={googleAvailable} microsoftAvailable={microsoftAvailable} emailPasswordEnabled={isEmailPasswordAuthEnabled} + ssoEnabled={isSsoEnabled} /> ) diff --git a/apps/sim/app/(auth)/signup/page.tsx b/apps/sim/app/(auth)/signup/page.tsx index aed7c5093b1..2770c8fde10 100644 --- a/apps/sim/app/(auth)/signup/page.tsx +++ b/apps/sim/app/(auth)/signup/page.tsx @@ -1,6 +1,10 @@ import type { Metadata } from 'next' import type { SearchParams } from 'nuqs/server' -import { isEmailSignupAllowed, isSelfServeRegistrationClosed } from '@/lib/core/config/env-flags' +import { + isEmailSignupAllowed, + isSelfServeRegistrationClosed, + isSsoEnabled, +} from '@/lib/core/config/env-flags' import { validateCallbackUrl } from '@/lib/core/security/input-validation' import { isEmailVerificationEffectivelyEnabled } from '@/lib/messaging/email/verification' import { resolveAuthRedirect } from '@/app/(auth)/auth-redirect' @@ -45,6 +49,7 @@ export default async function SignupPage({ microsoftAvailable={microsoftAvailable} emailSignupEnabled={isEmailSignupAllowed} emailVerificationEnabled={isEmailVerificationEffectivelyEnabled()} + ssoEnabled={isSsoEnabled} /> ) } diff --git a/apps/sim/app/(auth)/signup/signup-form.tsx b/apps/sim/app/(auth)/signup/signup-form.tsx index 25cd401aa83..d9c91d4b207 100644 --- a/apps/sim/app/(auth)/signup/signup-form.tsx +++ b/apps/sim/app/(auth)/signup/signup-form.tsx @@ -10,7 +10,6 @@ import { client, useSession } from '@/lib/auth/client' import { DISPOSABLE_EMAIL_ERROR_CODE, DISPOSABLE_EMAIL_MESSAGE } from '@/lib/auth/constants' import { useTrackingConsent } from '@/lib/consent/tracking-consent' import { getEnv } from '@/lib/core/config/env' -import { isSsoEnabled } from '@/lib/core/config/env-flags' import { validateCallbackUrl } from '@/lib/core/security/input-validation' import { quickValidateEmail } from '@/lib/messaging/email/validation' import { captureEvent } from '@/lib/posthog/client' @@ -99,6 +98,8 @@ interface SignupFormProps { emailSignupEnabled: boolean /** Server-derived: verification is enabled AND a mail provider is configured. */ emailVerificationEnabled: boolean + /** Whether SAML/OIDC single sign-on is enabled for this deployment. */ + ssoEnabled: boolean } function SignupFormContent({ @@ -107,6 +108,7 @@ function SignupFormContent({ microsoftAvailable, emailSignupEnabled, emailVerificationEnabled, + ssoEnabled, }: SignupFormProps) { const router = useRouter() const searchParams = useSearchParams() @@ -387,7 +389,6 @@ function SignupFormContent({ } } - const ssoEnabled = isSsoEnabled const hasSocial = githubAvailable || googleAvailable || microsoftAvailable const hasOnlySSO = ssoEnabled && !emailSignupEnabled && !hasSocial const showBottomSection = hasSocial || (ssoEnabled && !hasOnlySSO) @@ -516,6 +517,7 @@ export default function SignupPage({ microsoftAvailable, emailSignupEnabled, emailVerificationEnabled, + ssoEnabled, }: SignupFormProps) { return ( }> @@ -525,6 +527,7 @@ export default function SignupPage({ microsoftAvailable={microsoftAvailable} emailSignupEnabled={emailSignupEnabled} emailVerificationEnabled={emailVerificationEnabled} + ssoEnabled={ssoEnabled} /> ) diff --git a/apps/sim/app/(landing)/components/footer/footer.tsx b/apps/sim/app/(landing)/components/footer/footer.tsx index 84ef7e7aa82..27c8f18d713 100644 --- a/apps/sim/app/(landing)/components/footer/footer.tsx +++ b/apps/sim/app/(landing)/components/footer/footer.tsx @@ -133,6 +133,7 @@ const SOCIAL_LINKS: FooterItem[] = [ href: 'https://github.com/simstudioai/sim', external: true, }, + { label: 'YouTube', href: 'https://www.youtube.com/@simdotai', external: true }, ] const LEGAL_LINKS: FooterItem[] = [ diff --git a/apps/sim/app/(landing)/components/home-faq/faqs.ts b/apps/sim/app/(landing)/components/home-faq/faqs.ts new file mode 100644 index 00000000000..79378841b0b --- /dev/null +++ b/apps/sim/app/(landing)/components/home-faq/faqs.ts @@ -0,0 +1,36 @@ +import { INTEGRATION_COUNT_LABEL } from '@sim/deployment-config/integration-claims' + +/** + * Category questions answer engines ask before they name a product: what Sim is, who can + * build with it, how it is hosted, deployed, and governed. Every answer restates a claim the + * homepage already makes (`HOME_FEATURES`, the security certifications) and names the plan or + * license a claim depends on. The FAQPage JSON-LD reads this same array, so the structured + * answers always equal the visible ones. + * Pricing questions live on `/pricing`; do not repeat them here. + */ +export const HOME_FAQS = [ + { + question: 'Is Sim an AI agent builder?', + answer: `Yes. Sim is the open-source AI workspace where teams build, deploy, and manage AI agents. Build an agent visually in the workflow builder, describe it in Chat and let Sim build it, or write it with code through the API and CLI, using ${INTEGRATION_COUNT_LABEL} integrations and every major LLM.`, + }, + { + question: 'Can non-technical teams build AI agents in Sim?', + answer: + 'Yes. In Chat, anyone can describe the agent they need in plain language and Sim builds it. The visual workflow builder shows every step, so teams can review and adjust an agent without writing code, and engineers can extend it with custom functions, the API, or the CLI.', + }, + { + question: 'Is Sim open source, and can I self-host it?', + answer: + "Yes. Sim's core is open source under the Apache 2.0 license and runs in your own cloud with Docker or Kubernetes, or you can use the hosted workspace at sim.ai. Enterprise features such as SSO and access control need a separate license.", + }, + { + question: 'How do teams deploy agents built in Sim?', + answer: + 'Deploy an agent as a chat, an API endpoint, or an MCP server, the standard way other AI tools call an agent. A chat can be public or limited to SSO, specific emails, or a password. Agents can also run on a schedule or start from event triggers in connected apps.', + }, + { + question: 'How does Sim govern AI agents across a company?', + answer: + "Sim's Enterprise plan gives administrators permission groups that control which models, integrations, and tools each team can use, organization and per-member spend limits, audit records, single sign-on with domain verification, and configurable data retention. Every plan traces each run in Logs, and Sim is SOC 2 Type II compliant.", + }, +] as const diff --git a/apps/sim/app/(landing)/components/home-faq/home-faq.tsx b/apps/sim/app/(landing)/components/home-faq/home-faq.tsx new file mode 100644 index 00000000000..f2d02026949 --- /dev/null +++ b/apps/sim/app/(landing)/components/home-faq/home-faq.tsx @@ -0,0 +1,68 @@ +import { ChevronDown, cn } from '@sim/emcn' +import { SITE_URL } from '@/lib/core/utils/urls' +import { HOME_FAQS } from '@/app/(landing)/components/home-faq/faqs' +import { JsonLd } from '@/app/(landing)/components/json-ld' +import { + HOME_INSET, + HOME_TYPE, + LANDING_CONTENT_WIDTH, + LANDING_GUTTER, +} from '@/app/(landing)/components/landing-layout' + +const HOME_FAQ_JSON_LD = { + '@context': 'https://schema.org', + '@type': 'FAQPage', + '@id': `${SITE_URL}#faq`, + mainEntity: HOME_FAQS.map(({ question, answer }) => ({ + '@type': 'Question', + name: question, + acceptedAnswer: { '@type': 'Answer', text: answer }, + })), +} + +/** + * Homepage FAQ with matching `FAQPage` JSON-LD. Native `
` rows keep it a server + * component: the homepage loads its animated islands with `next/dynamic`, and the animated + * `LandingFAQ` would put framer-motion in the initial bundle. Closed answers stay in the HTML. + */ +export function HomeFAQ() { + return ( +
+ +
+

+ Questions teams ask about Sim +

+
+ {HOME_FAQS.map(({ question, answer }, index) => ( +
+ +

{question}

+
+

{answer}

+
+ ))} +
+
+
+ ) +} diff --git a/apps/sim/app/(landing)/components/home-faq/index.ts b/apps/sim/app/(landing)/components/home-faq/index.ts new file mode 100644 index 00000000000..75cdfdc3b0a --- /dev/null +++ b/apps/sim/app/(landing)/components/home-faq/index.ts @@ -0,0 +1,2 @@ +export { HOME_FAQS } from './faqs' +export { HomeFAQ } from './home-faq' diff --git a/apps/sim/app/(landing)/components/index.ts b/apps/sim/app/(landing)/components/index.ts index a34d53b72ed..61e03318d61 100644 --- a/apps/sim/app/(landing)/components/index.ts +++ b/apps/sim/app/(landing)/components/index.ts @@ -11,6 +11,7 @@ export { FeaturedCustomer } from './featured-customer' export { Features } from './features' export { Footer } from './footer' export { Hero } from './hero' +export { HomeFAQ } from './home-faq' export { HomeStructuredData } from './home-structured-data' export type { JsonLdData } from './json-ld' export { JsonLd } from './json-ld' diff --git a/apps/sim/app/(landing)/components/security/components/cert-blocs/cert-blocs.tsx b/apps/sim/app/(landing)/components/security/components/cert-blocs/cert-blocs.tsx index 75b48705b90..5bcbb4727d1 100644 --- a/apps/sim/app/(landing)/components/security/components/cert-blocs/cert-blocs.tsx +++ b/apps/sim/app/(landing)/components/security/components/cert-blocs/cert-blocs.tsx @@ -15,11 +15,17 @@ const SCROLL_PORT_SELECTOR = '.overflow-y-auto' const MARK_STROKES = '[pathLength]' const CERT_MUTED = 'text-[var(--text-muted)]' -const CERTIFICATIONS = [ +interface Certification { + title: string + status?: string + Mark: typeof Soc2TypeIiMark +} + +const CERTIFICATIONS: readonly Certification[] = [ { title: 'SOC 2 Type II', Mark: Soc2TypeIiMark }, - { title: 'ISO 27001', Mark: Iso27001Mark }, + { title: 'ISO 27001', status: 'Certification in progress', Mark: Iso27001Mark }, { title: 'GDPR', Mark: GdprMark }, -] as const +] interface CertBlocsProps { href: string @@ -110,7 +116,7 @@ export function CertBlocs({ href }: CertBlocsProps) { drawn && styles.drawn )} > - {CERTIFICATIONS.map(({ title, Mark }) => ( + {CERTIFICATIONS.map(({ title, status, Mark }) => (
  • {title} + {status && ( + {status} + )} ` is a `flex flex-col` whose `gap` is the single source of truth for * major-section rhythm. Customer proof, platform media, and product controls @@ -67,6 +69,7 @@ export default function Landing() { + ) } diff --git a/apps/sim/app/(landing)/pricing/components/pricing-faq/pricing-faq.tsx b/apps/sim/app/(landing)/pricing/components/pricing-faq/pricing-faq.tsx index 7cbc3413457..79826d5337a 100644 --- a/apps/sim/app/(landing)/pricing/components/pricing-faq/pricing-faq.tsx +++ b/apps/sim/app/(landing)/pricing/components/pricing-faq/pricing-faq.tsx @@ -5,6 +5,8 @@ import { DEFAULT_FREE_CREDITS, MAX_CREDIT_TIER, PRO_CREDIT_TIER, + PRO_TRIAL_DAYS, + PRO_TRIAL_USAGE_LIMIT_DOLLARS, } from '@/lib/billing/constants' import { SITE_URL } from '@/lib/core/utils/urls' import { JsonLd } from '@/app/(landing)/components/json-ld' @@ -20,11 +22,15 @@ const formatCredits = (credits: number) => credits.toLocaleString('en-US') const PRICING_FAQS = [ { question: 'Is Sim free?', - answer: `Yes. The Free plan costs $0 and includes ${formatCredits(DEFAULT_FREE_CREDITS * CREDITS_PER_DOLLAR)} one-time credits, one workspace, and all ${INTEGRATION_COUNT_LABEL} integrations, with no credit card required. On Free, models and tools run on your own provider keys; Sim-hosted keys come with paid plans. Sim is also open source, so you can self-host it for free.`, + answer: `Yes. The Free plan costs $0 and includes ${formatCredits(DEFAULT_FREE_CREDITS * CREDITS_PER_DOLLAR)} one-time credits, one workspace, and all ${INTEGRATION_COUNT_LABEL} integrations, with no credit card required. On Free, models and tools run on your own provider keys, and the credits cover runs, code execution, knowledge base indexing, and AI-assisted editing. Sim-hosted models and tools, and Chat with Sim, come with paid plans. Sim is also open source, so you can self-host it for free.`, + }, + { + question: 'Does Sim have a free trial?', + answer: `Yes. New Pro subscribers get a ${PRO_TRIAL_DAYS}-day free trial with ${formatCredits(PRO_TRIAL_USAGE_LIMIT_DOLLARS * CREDITS_PER_DOLLAR)} credits, including Sim-hosted models and tools. A card is required at checkout and is charged for Pro when the trial ends unless you cancel first. Each account and card can start one trial.`, }, { question: 'How much does Sim cost?', - answer: `Pro is $${PRO_CREDIT_TIER.dollars} per user per month with ${formatCredits(PRO_CREDIT_TIER.credits)} credits a month and a weekly refresh of ${formatCredits(PRO_CREDIT_TIER.weeklyRefreshCredits)} more. Max is $${MAX_CREDIT_TIER.dollars} per user per month with ${formatCredits(MAX_CREDIT_TIER.credits)} credits a month and a weekly refresh of ${formatCredits(MAX_CREDIT_TIER.weeklyRefreshCredits)}. Annual billing costs ${ANNUAL_DISCOUNT_RATE * 100}% less for the same credits. Enterprise pricing is custom.`, + answer: `Pro is $${PRO_CREDIT_TIER.dollars} per user per month with ${formatCredits(PRO_CREDIT_TIER.credits)} credits a month and a weekly refresh of ${formatCredits(PRO_CREDIT_TIER.weeklyRefreshCredits)} more. Max is $${MAX_CREDIT_TIER.dollars} per user per month with ${formatCredits(MAX_CREDIT_TIER.credits)} credits a month and a weekly refresh of ${formatCredits(MAX_CREDIT_TIER.weeklyRefreshCredits)}. Annual billing costs ${ANNUAL_DISCOUNT_RATE * 100}% less for the same credits, and includes all twelve months of credits up front to use any time during the year. Enterprise pricing is custom.`, }, { question: 'What is a credit, and what does an agent run cost?', diff --git a/apps/sim/app/(landing)/pricing/components/pricing-plans/pricing-plans.tsx b/apps/sim/app/(landing)/pricing/components/pricing-plans/pricing-plans.tsx index 5fc794978ef..3079952a0ad 100644 --- a/apps/sim/app/(landing)/pricing/components/pricing-plans/pricing-plans.tsx +++ b/apps/sim/app/(landing)/pricing/components/pricing-plans/pricing-plans.tsx @@ -4,6 +4,7 @@ import type { ReactNode } from 'react' import { useQueryStates } from 'nuqs' import { getUpgradeCardCta, type PlanTier, type UpgradeCardId } from '@/lib/billing/client' import { ANNUAL_DISCOUNT_RATE, CREDIT_TIERS } from '@/lib/billing/constants' +import { formatMonthlyPlanPrice } from '@/lib/billing/plan-helpers' import { DEMO_HREF, SIGNUP_HREF } from '@/app/(landing)/constants' import { PricingCard, @@ -54,11 +55,6 @@ function sectionsForColumn(col: number): PricingCardSection[] { /** The four card columns (Free, Pro, Max, Enterprise) transposed once at module load - the source data is static, so this never needs to be redone per render. */ const SECTIONS_BY_COLUMN = [0, 1, 2, 3].map(sectionsForColumn) -/** Round a dollar amount down to the annual-billing discounted price. */ -function annualPrice(dollars: number): number { - return Math.round(dollars * (1 - ANNUAL_DISCOUNT_RATE)) -} - /** * Resolve a card's canonical label and variant from the free-tier matrix. A * `sales` intent ("Talk to sales") routes to the demo-request form, matching @@ -99,8 +95,8 @@ export function PricingPlans({ heading }: PricingPlansProps) { const setIsAnnual = (next: boolean) => setParams({ billing: next ? 'annual' : 'monthly' }) const discountPct = Math.round(ANNUAL_DISCOUNT_RATE * 100) - const proPrice = isAnnual ? annualPrice(CREDIT_TIERS[0].dollars) : CREDIT_TIERS[0].dollars - const maxPrice = isAnnual ? annualPrice(CREDIT_TIERS[1].dollars) : CREDIT_TIERS[1].dollars + const proPrice = formatMonthlyPlanPrice(CREDIT_TIERS[0].dollars, isAnnual) + const maxPrice = formatMonthlyPlanPrice(CREDIT_TIERS[1].dollars, isAnnual) const priceSubtext = isAnnual ? 'per user/month, billed annually' : 'per user/month, billed monthly' @@ -127,7 +123,7 @@ export function PricingPlans({ heading }: PricingPlansProps) { /> ({}), + useCase: endProTrial, + present: (data) => data, +}) diff --git a/apps/sim/app/api/billing/route.test.ts b/apps/sim/app/api/billing/route.test.ts index e6d0f5901e0..f047b050a47 100644 --- a/apps/sim/app/api/billing/route.test.ts +++ b/apps/sim/app/api/billing/route.test.ts @@ -4,16 +4,16 @@ import { billingOrganizationMock, billingOrganizationMockFns, } from '@sim/testing/mocks/billing-organization.mock' -import { - billingSubscriptionMock, - billingSubscriptionMockFns, -} from '@sim/testing/mocks/billing-subscription.mock' +import { billingSubscriptionMock } from '@sim/testing/mocks/billing-subscription.mock' import { beforeEach, describe, expect, it, vi } from 'vitest' -const { mockGetCreditBalanceForEntity } = vi.hoisted(() => ({ +const { mockGetCreditBalanceForEntity, mockIsProTrialEligible } = vi.hoisted(() => ({ mockGetCreditBalanceForEntity: vi.fn(), + mockIsProTrialEligible: vi.fn(), })) +vi.mock('@/lib/billing/trial', () => ({ isProTrialEligible: mockIsProTrialEligible })) + vi.mock('@/lib/billing/core/billing', () => billingCoreMock) vi.mock('@/lib/billing/core/organization', () => billingOrganizationMock) @@ -30,7 +30,6 @@ const mockGetSession = authMockFns.mockGetSession const mockGetOrganizationBillingData = billingOrganizationMockFns.mockGetOrganizationBillingData const mockGetOrganizationSubscription = billingCoreMockFns.mockGetOrganizationSubscription const mockGetPersonalBillingSummary = billingCoreMockFns.mockGetPersonalBillingSummary -const mockResolveBillingInterval = billingSubscriptionMockFns.mockResolveBillingInterval const PERSONAL_SUMMARY = { type: 'individual', @@ -146,10 +145,7 @@ describe('GET /api/billing', () => { mockGetOrganizationBillingData.mockResolvedValue(ACTIVE_ORG_BILLING) mockGetOrganizationSubscription.mockResolvedValue(ACTIVE_ORG_SUBSCRIPTION) mockGetCreditBalanceForEntity.mockResolvedValue(17) - mockResolveBillingInterval.mockImplementation( - (subscription: { billingInterval?: string | null } | null) => - subscription?.billingInterval === 'year' ? 'year' : 'month' - ) + mockIsProTrialEligible.mockResolvedValue(false) }) it('keeps account billing personal even when an organization ID is supplied', async () => { diff --git a/apps/sim/app/api/billing/route.ts b/apps/sim/app/api/billing/route.ts index 765240241a7..fb946745efa 100644 --- a/apps/sim/app/api/billing/route.ts +++ b/apps/sim/app/api/billing/route.ts @@ -18,9 +18,10 @@ import { getOrganizationBillingBlockState, getUpgradeWorkspaceId, } from '@/lib/billing/core/payer-context' -import { resolveBillingInterval } from '@/lib/billing/core/subscription' import { getCreditBalanceForEntity } from '@/lib/billing/credits/balance' import { isPaid } from '@/lib/billing/plan-helpers' +import { resolveBillingInterval } from '@/lib/billing/subscriptions/utils' +import { isProTrialEligible } from '@/lib/billing/trial' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' const logger = createLogger('UnifiedBillingAPI') @@ -59,9 +60,10 @@ export const GET = withRouteHandler(async (request: NextRequest) => { } if (context === 'user') { - const [personalBilling, upgradeWorkspaceId] = await Promise.all([ + const [personalBilling, upgradeWorkspaceId, proTrialEligible] = await Promise.all([ getPersonalBillingSummary(session.user.id, dbReplica), getUpgradeWorkspaceId({ type: 'user', id: session.user.id }), + isProTrialEligible(session.user.id, dbReplica), ]) let organizationMembership: { id: string; role: 'owner' | 'admin' | 'member' } | undefined @@ -89,6 +91,7 @@ export const GET = withRouteHandler(async (request: NextRequest) => { data: { ...personalBilling, upgradeWorkspaceId, + proTrialEligible, ...(organizationMembership ? { organization: organizationMembership } : {}), }, }) diff --git a/apps/sim/app/api/billing/switch-plan/route.ts b/apps/sim/app/api/billing/switch-plan/route.ts index da8465d10b0..6edfb2efa7e 100644 --- a/apps/sim/app/api/billing/switch-plan/route.ts +++ b/apps/sim/app/api/billing/switch-plan/route.ts @@ -1,22 +1,19 @@ import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit' -import { db } from '@sim/db' -import { subscription as subscriptionTable } from '@sim/db/schema' import { createLogger } from '@sim/logger' import { getErrorMessage, toError } from '@sim/utils/errors' -import { eq } from 'drizzle-orm' import { type NextRequest, NextResponse } from 'next/server' import { billingSwitchPlanContract } from '@/lib/api/contracts/subscription' import { parseRequest } from '@/lib/api/server' import { getSession } from '@/lib/auth' import { getEffectiveBillingStatus } from '@/lib/billing/core/access' -import { getOrganizationSubscription } from '@/lib/billing/core/billing' +import { getOrganizationSubscription, isSubscriptionOrgScoped } from '@/lib/billing/core/billing' import { isOrganizationOwnerOrAdmin } from '@/lib/billing/core/organization' import { getHighestPriorityPersonalSubscription, getHighestPrioritySubscription, } from '@/lib/billing/core/plan' -import { writeBillingInterval } from '@/lib/billing/core/subscription' -import { getPlanType, isEnterprise } from '@/lib/billing/plan-helpers' +import { recordPlanSwitch } from '@/lib/billing/core/plan-switch' +import { getPlanTierCredits, getPlanType, isEnterprise } from '@/lib/billing/plan-helpers' import { getPlanByName } from '@/lib/billing/plans' import { requireStripeClient } from '@/lib/billing/stripe-client' import { @@ -80,11 +77,19 @@ export const POST = withRouteHandler(async (request: NextRequest) => { return NextResponse.json({ error: 'No active subscription found' }, { status: 404 }) } - const billingBlocked = hostContext - ? hostContext.ownerBilling.billingBlocked - : (await getEffectiveBillingStatus(userId)).billingBlocked + const { billingBlocked, billingBlockedReason } = hostContext + ? hostContext.ownerBilling + : await getEffectiveBillingStatus(userId) if (!hasUsableSubscriptionAccess(sub.status, billingBlocked)) { - return NextResponse.json({ error: 'An active subscription is required' }, { status: 400 }) + return NextResponse.json( + { + error: + billingBlockedReason === 'dispute' + ? 'Plan changes are paused while a payment dispute is open. Contact support to resolve it.' + : 'Your last payment failed. Update your payment method under Settings > Billing, then change your plan.', + }, + { status: 400 } + ) } if (isEnterprise(sub.plan) || isEnterprise(targetPlanName)) { @@ -130,6 +135,21 @@ export const POST = withRouteHandler(async (request: NextRequest) => { const currentInterval = subscriptionItem.price?.recurring?.interval const targetInterval = interval ?? currentInterval ?? 'month' + // An annual term's usage was covered by its tier's allowance; a lower tier mid-term would + // re-price that usage as overage, so the downgrade waits for renewal. + if ( + currentInterval === 'year' && + getPlanTierCredits(targetPlanName) < getPlanTierCredits(sub.plan) + ) { + return NextResponse.json( + { + error: + 'A lower tier is not available partway through an annual term. You can switch when your plan renews.', + }, + { status: 400 } + ) + } + const targetPriceId = targetInterval === 'year' ? targetPlan.annualDiscountPriceId : targetPlan.priceId @@ -173,14 +193,12 @@ export const POST = withRouteHandler(async (request: NextRequest) => { }) } - if (!alreadyInDb) { - await db - .update(subscriptionTable) - .set({ plan: targetPlanName }) - .where(eq(subscriptionTable.id, sub.id)) - } - - await writeBillingInterval(sub.id, targetInterval as 'month' | 'year') + await recordPlanSwitch({ + subscription: sub, + targetPlanName, + targetInterval: targetInterval as 'month' | 'year', + orgScoped: await isSubscriptionOrgScoped(sub), + }) logger.info('Subscription switched successfully', { userId, diff --git a/apps/sim/app/api/billing/update-cost/route.ts b/apps/sim/app/api/billing/update-cost/route.ts index 08c7f941e1c..27f1f545485 100644 --- a/apps/sim/app/api/billing/update-cost/route.ts +++ b/apps/sim/app/api/billing/update-cost/route.ts @@ -23,7 +23,7 @@ import { toBillingContext, } from '@/lib/billing/core/attribution' import { - isFreeRunPayer, + isCappedRunPayer, type MidRunUsageVerdict, readMidRunAccountUsageVerdict, readMidRunUsageVerdict, @@ -88,7 +88,7 @@ function invalidBillingProtocolResponse(requestId: string, span: Span): NextResp * A duplicate callback answers too: it is often a retry whose first answer was lost. The charge * is already recorded when this runs. * - * A free payer's spend past its limit is never billed, so its standing is read from the ledger + * A capped payer's spend past its limit is never billed, so its standing is read from the ledger * on every callback, and a standing that cannot be read (a gate that cannot answer, or a read * that outlasts {@link USAGE_STANDING_TIMEOUT_MS}) pauses the run. A paid payer's admission is * cached per payer and actor (briefly once near the limit) and a refusal is always re-read, so @@ -101,7 +101,7 @@ async function readUsageStanding( billingAttribution: BillingAttributionSnapshot | undefined, accountDecision: AccountBillingDecision | undefined ): Promise { - const readOptions = { uncachedForFreePayer: true } + const readOptions = { uncachedForCappedPayer: true } const payer = billingAttribution ?? accountDecision const readVerdict = billingAttribution ? () => readMidRunUsageVerdict(billingAttribution, 0, readOptions) @@ -109,12 +109,12 @@ async function readUsageStanding( ? () => readMidRunAccountUsageVerdict(accountDecision, readOptions) : null if (!isHosted || !payer || !readVerdict) return { usageExceeded: false } - const freePayer = isFreeRunPayer(payer) + const cappedPayer = isCappedRunPayer(payer) let verdict: MidRunUsageVerdict try { verdict = await withinDeadline(readVerdict, Date.now() + USAGE_STANDING_TIMEOUT_MS) } catch { - logger.warn('Usage standing read outlasted the callback budget', { freePayer }) + logger.warn('Usage standing read outlasted the callback budget', { cappedPayer }) verdict = { status: 'unknown' } } if (verdict.status === 'exceeded') { @@ -129,7 +129,7 @@ async function readUsageStanding( } // A blocked account is refused at the run's next continuation or re-check, with // blocked-account copy rather than the upgrade card. - if (verdict.status !== 'unknown' || !freePayer) return { usageExceeded: false } + if (verdict.status !== 'unknown' || !cappedPayer) return { usageExceeded: false } return { usageExceeded: true, usageUpgrade: await resolveUsageUpgradePayload(userId, { diff --git a/apps/sim/app/api/copilot/api-keys/validate/route.test.ts b/apps/sim/app/api/copilot/api-keys/validate/route.test.ts index 160e3c756fd..48393fb1648 100644 --- a/apps/sim/app/api/copilot/api-keys/validate/route.test.ts +++ b/apps/sim/app/api/copilot/api-keys/validate/route.test.ts @@ -71,7 +71,7 @@ const ATTRIBUTION = { payerSubscription: null, } -const ACCOUNT_SUBSCRIPTION = { id: 'account-subscription' } +const ACCOUNT_SUBSCRIPTION = { id: 'account-subscription', plan: 'pro_6000', status: 'active' } const ACCOUNT_BILLING_DECISION = { userId: 'user-1', billingEntity: { type: 'organization' as const, id: 'account-org' }, @@ -463,7 +463,11 @@ describe('POST /api/copilot/api-keys/validate billing protocols', () => { expect(mockGetWorkspaceBillingSettings).not.toHaveBeenCalled() expect( JSON.parse(decodeURIComponent(res.headers.get('x-sim-billing-account-decision') ?? '')) - ).toEqual({ ...ACCOUNT_BILLING_DECISION, payerSubscriptionId: ACCOUNT_SUBSCRIPTION.id }) + ).toEqual({ + ...ACCOUNT_BILLING_DECISION, + payerSubscriptionId: ACCOUNT_SUBSCRIPTION.id, + payerBillsOverage: true, + }) }) it('fails direct-v1 admission closed when its payer cannot be resolved', async () => { diff --git a/apps/sim/app/api/copilot/api-keys/validate/route.ts b/apps/sim/app/api/copilot/api-keys/validate/route.ts index 242cd8ea90f..5d4e4c9a513 100644 --- a/apps/sim/app/api/copilot/api-keys/validate/route.ts +++ b/apps/sim/app/api/copilot/api-keys/validate/route.ts @@ -28,13 +28,14 @@ import { } from '@/lib/billing/core/attribution' import { payerHasChatAccess } from '@/lib/billing/core/chat-access' import { - isFreeRunPayer, + isCappedRunPayer, readMidRunAccountUsageVerdict, readMidRunUsageVerdict, } from '@/lib/billing/core/mid-run-usage' import { getHighestPrioritySubscription } from '@/lib/billing/core/plan' import { isEnterprisePlan } from '@/lib/billing/core/subscription' import { deriveBillingContext } from '@/lib/billing/core/usage-log' +import { billsOverage } from '@/lib/billing/subscriptions/utils' import { resolveUsageUpgradePayload, type UsageUpgradePayer } from '@/lib/billing/usage-upgrade' import { isBillingEnabled, isHosted } from '@/lib/core/config/env-flags' import { asOrchestrationError } from '@/lib/core/orchestration/types' @@ -292,6 +293,7 @@ async function checkAdmissionUsage(admission: AdmissionBillingDecision): Promise : {}), }, ...(subscription ? { payerSubscriptionId: subscription.id } : {}), + payerBillsOverage: billsOverage(subscription), }, } } @@ -431,7 +433,7 @@ export const POST = withRouteHandler((req: NextRequest) => }) // A continuation, and a worker's periodic re-check of a long run, also reads the // original payer's spend through the cached execution usage gate. A read that fails - // refuses a free payer, whose spend past the limit is never billed, and admits a paid + // refuses a capped payer, whose spend past the limit is never billed, and admits a paid // one: the run is already under way, and the next re-check reads again. const verdict = !blocked?.blocked && purpose === COPILOT_VALIDATION_PURPOSE.continuation && billing @@ -458,14 +460,14 @@ export const POST = withRouteHandler((req: NextRequest) => { status: 402 } ) } - const unreadFreePayer = + const unreadCappedPayer = verdict?.status === 'unknown' && billing !== null && - isFreeRunPayer(billing.kind === 'attributed' ? billing.attribution : billing.decision) - if (verdict?.status === 'exceeded' || unreadFreePayer) { + isCappedRunPayer(billing.kind === 'attributed' ? billing.attribution : billing.decision) + if (verdict?.status === 'exceeded' || unreadCappedPayer) { logger.info('[API VALIDATION] Continuation usage exceeded', { userId, - unread: unreadFreePayer, + unread: unreadCappedPayer, }) span.setAttribute( TraceAttr.CopilotValidateOutcome, diff --git a/apps/sim/app/api/cron/reconcile-billing-seats/route.ts b/apps/sim/app/api/cron/reconcile-billing-seats/route.ts index bba71634175..b6a8caf7a2a 100644 --- a/apps/sim/app/api/cron/reconcile-billing-seats/route.ts +++ b/apps/sim/app/api/cron/reconcile-billing-seats/route.ts @@ -4,6 +4,8 @@ import { toError } from '@sim/utils/errors' import { toRecord } from '@sim/utils/object' import { type NextRequest, NextResponse } from 'next/server' import { verifyCronAuth } from '@/lib/auth/internal' +import { runEnterpriseSeatTrueUps } from '@/lib/billing/enterprise-seat-true-up' +import { syncAnnualPlanUsageLimits } from '@/lib/billing/organization' import { reconcileTeamSeatDrift } from '@/lib/billing/organizations/seat-drift' import { OUTBOX_EVENT_TYPES } from '@/lib/billing/webhooks/outbox-events' import { findDeadLetteredEvents } from '@/lib/core/outbox/service' @@ -37,7 +39,9 @@ function describeDeadLetter(event: Awaited { try { const drift = await reconcileTeamSeatDrift() + // A failed true-up must not hide the drift and dead-letter reports below; it retries next hour. + const seatTrueUp = await runEnterpriseSeatTrueUps().catch((error: unknown) => { + logger.error('Enterprise seat true-up failed', { requestId, error: toError(error).message }) + return null + }) + const annualLimitsSynced = await syncAnnualPlanUsageLimits().catch((error: unknown) => { + logger.error('Annual plan usage-limit sync failed', { + requestId, + error: toError(error).message, + }) + return null + }) const deadLettered = await findDeadLetteredEvents(BILLING_SYNC_EVENT_TYPES) const newSince = Date.now() - NEW_DEAD_LETTER_WINDOW_MS @@ -85,6 +101,8 @@ export const GET = withRouteHandler(async (request: NextRequest) => { logger.info('Billing seat reconciliation completed', { requestId, ...drift, + seatTrueUp, + annualLimitsSynced, deadLetteredBillingSyncs: deadLettered.length, }) @@ -92,6 +110,8 @@ export const GET = withRouteHandler(async (request: NextRequest) => { success: true, requestId, drift, + seatTrueUp, + annualLimitsSynced, deadLetteredBillingSyncs: deadLettered.length, }) } catch (error) { diff --git a/apps/sim/app/api/organizations/[id]/payment-method/route.ts b/apps/sim/app/api/organizations/[id]/payment-method/route.ts new file mode 100644 index 00000000000..96e2f35aea7 --- /dev/null +++ b/apps/sim/app/api/organizations/[id]/payment-method/route.ts @@ -0,0 +1,40 @@ +import { + getOrganizationPaymentMethodContract, + startOrganizationAutoPayContract, +} from '@/lib/api/contracts/organization' +import { + defineInternalJsonRoute, + internalOrchestrationErrorPolicy, + internalRateLimits, + internalSessionAuth, +} from '@/lib/api/server/routes' +import { internalBillingReadErrorPolicy } from '@/lib/api/server/routes/billing-read' +import { + getEnterprisePaymentMethod, + startEnterpriseAutoPaySetup, +} from '@/lib/billing/application/organization-billing/enterprise-payment-method' +import { organizationBillingOperations } from '@/lib/billing/application/organization-billing/operations' + +export const dynamic = 'force-dynamic' + +export const GET = defineInternalJsonRoute({ + contract: getOrganizationPaymentMethodContract, + auth: internalSessionAuth, + operation: organizationBillingOperations.read, + rateLimit: internalRateLimits.user({ bucketName: 'organization-payment-method' }), + errorPolicy: internalBillingReadErrorPolicy, + mapInput: ({ params }) => ({ organizationId: params.id }), + useCase: getEnterprisePaymentMethod, + present: (data) => ({ success: true, data }), +}) + +export const POST = defineInternalJsonRoute({ + contract: startOrganizationAutoPayContract, + auth: internalSessionAuth, + operation: organizationBillingOperations.managePaymentMethod, + rateLimit: internalRateLimits.user({ bucketName: 'organization-payment-method' }), + errorPolicy: internalOrchestrationErrorPolicy, + mapInput: ({ params, body }) => ({ organizationId: params.id, returnUrl: body.returnUrl }), + useCase: startEnterpriseAutoPaySetup, + present: (data) => data, +}) diff --git a/apps/sim/app/api/providers/ollama/models/route.test.ts b/apps/sim/app/api/providers/ollama/models/route.test.ts index c815c43c360..0ff9e7c3d6d 100644 --- a/apps/sim/app/api/providers/ollama/models/route.test.ts +++ b/apps/sim/app/api/providers/ollama/models/route.test.ts @@ -1,6 +1,6 @@ import { createMockRequest, resetEnvFlagsMock, setEnvFlags } from '@sim/testing' +import { setEnv } from '@sim/testing/mocks/env.mock' import { providersUtilsMock, providersUtilsMockFns } from '@sim/testing/mocks/providers-utils.mock' -import { urlsMockFns } from '@sim/testing/mocks/urls.mock' import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest' const mockFetch = vi.hoisted(() => vi.fn()) @@ -10,13 +10,12 @@ vi.mock('@/providers/utils', () => providersUtilsMock) import { GET } from '@/app/api/providers/ollama/models/route' const { mockFilterBlacklistedModels, mockIsProviderBlacklisted } = providersUtilsMockFns -const mockIsOllamaUrlConfigured = urlsMockFns.mockIsOllamaUrlConfigured const request = () => createMockRequest('GET') describe('ollama models route', () => { beforeEach(() => { - mockIsOllamaUrlConfigured.mockReturnValue(false) + setEnv({ OLLAMA_URL: undefined }) mockIsProviderBlacklisted.mockReturnValue(false) mockFilterBlacklistedModels.mockImplementation((models: string[]) => models) vi.stubGlobal('fetch', mockFetch) @@ -36,7 +35,7 @@ describe('ollama models route', () => { it('still honours an explicit OLLAMA_URL on the hosted platform', async () => { setEnvFlags({ isHosted: true }) - mockIsOllamaUrlConfigured.mockReturnValue(true) + setEnv({ OLLAMA_URL: 'http://ollama.internal:11434' }) mockFetch.mockResolvedValue({ ok: true, json: async () => ({ models: [{ name: 'llama3' }] }) }) const response = await GET(request()) diff --git a/apps/sim/app/api/providers/ollama/models/route.ts b/apps/sim/app/api/providers/ollama/models/route.ts index 13274f69d6e..f32075c02d9 100644 --- a/apps/sim/app/api/providers/ollama/models/route.ts +++ b/apps/sim/app/api/providers/ollama/models/route.ts @@ -5,10 +5,9 @@ import { ollamaUpstreamResponseSchema, providerModelsResponseSchema, } from '@/lib/api/contracts/providers' -import { isHosted } from '@/lib/core/config/env-flags' -import { getOllamaUrl, isOllamaUrlConfigured } from '@/lib/core/utils/urls' +import { getOllamaUrl, isOllamaAvailable } from '@/lib/core/utils/urls' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' -import { filterBlacklistedModels, isProviderBlacklisted } from '@/providers/utils' +import { filterBlacklistedModels } from '@/providers/utils' const logger = createLogger('OllamaModelsAPI') const OLLAMA_HOST = getOllamaUrl() @@ -17,23 +16,16 @@ const OLLAMA_HOST = getOllamaUrl() * Get available Ollama models */ export const GET = withRouteHandler(async (_request: NextRequest) => { - if (isProviderBlacklisted('ollama')) { - logger.info('Ollama provider is blacklisted, returning empty models') - return NextResponse.json({ models: [] }) - } - /** - * Ollama runs alongside the app it serves, so the hosted platform never has one - * and `OLLAMA_URL`'s loopback default cannot answer there. Skip the probe rather - * than dial an address known to refuse on every poll. - * - * Only the unconfigured default is skipped: an explicit `OLLAMA_URL` states an - * intent to reach a real server and is still honoured. Self-hosted deployments - * are untouched either way, including the localhost default that needs no - * configuration to work. + * Ollama runs alongside the app it serves, so the hosted platform never has one and + * `OLLAMA_URL`'s loopback default cannot answer there: skip the probe rather than dial an + * address known to refuse on every poll. An explicit `OLLAMA_URL` is still honoured, and + * self-hosted deployments probe the localhost default that needs no configuration. */ - if (isHosted && !isOllamaUrlConfigured()) { - logger.info('Ollama is not available on the hosted platform, returning empty models') + if (!isOllamaAvailable()) { + logger.info( + 'Ollama is blacklisted or not configured on this deployment, returning empty models' + ) return NextResponse.json({ models: [] }) } diff --git a/apps/sim/app/api/resume/[workflowId]/[executionId]/[contextId]/route.test.ts b/apps/sim/app/api/resume/[workflowId]/[executionId]/[contextId]/route.test.ts index 54f3a68e6e1..8d06460b71e 100644 --- a/apps/sim/app/api/resume/[workflowId]/[executionId]/[contextId]/route.test.ts +++ b/apps/sim/app/api/resume/[workflowId]/[executionId]/[contextId]/route.test.ts @@ -480,6 +480,7 @@ describe('POST /api/resume/[workflowId]/[executionId]/[contextId]', () => { success: false, status: 'failed', output: { partial: true }, + paused: null, error: 'Route: Condition evaluation failed', structuredError: { message: 'Condition evaluation failed', diff --git a/apps/sim/app/api/schedules/execute/route.ts b/apps/sim/app/api/schedules/execute/route.ts index bff1dbad8ec..b8ae3455f4c 100644 --- a/apps/sim/app/api/schedules/execute/route.ts +++ b/apps/sim/app/api/schedules/execute/route.ts @@ -1,11 +1,4 @@ -import { - asyncJobs, - db, - workflow, - workflowDeploymentVersion, - workflowExecutionLogs, - workflowSchedule, -} from '@sim/db' +import { asyncJobs, db, workflowExecutionLogs, workflowSchedule } from '@sim/db' import { createLogger } from '@sim/logger' import { sha256Hex } from '@sim/security/hash' import { toError } from '@sim/utils/errors' @@ -14,7 +7,7 @@ import { generateId } from '@sim/utils/id' import { isRecordLike } from '@sim/utils/object' import { randomInt } from '@sim/utils/random' import { Cron } from 'croner' -import { and, asc, eq, gt, inArray, isNull, lt, lte, or, sql } from 'drizzle-orm' +import { and, asc, eq, gt, inArray, isNull, lte, or, sql } from 'drizzle-orm' import { type NextRequest, NextResponse } from 'next/server' import type { ExecuteSchedulesResponse } from '@/lib/api/contracts/schedules' import { verifyCronAuth } from '@/lib/auth/internal' @@ -55,6 +48,10 @@ import { buildCarrierReconciledMetadata, carrierNotReconciledSql, } from '@/lib/workflows/schedules/carrier-metadata' +import { + type ClaimedWorkflowSchedule, + claimDueWorkflowSchedules, +} from '@/lib/workflows/schedules/claim' import { notifyScheduleAutoDisabled } from '@/lib/workflows/schedules/disable-notifications' import { SCHEDULE_EXECUTION_CONCURRENCY_LIMIT, @@ -85,34 +82,13 @@ const WORKFLOW_CHUNK_SIZE = 100 */ const STALE_SCHEDULE_RECOVERY_NOTIFY_LIMIT = 25 const MAX_TICK_DURATION_MS = 3 * 60 * 1000 -const STALE_SCHEDULE_CLAIM_MS = getExecutionReservationTtlMs() +/** Lease for a schedule carrier that records neither its max duration nor its execution timeout. */ +const FALLBACK_SCHEDULE_EXECUTION_LEASE_MS = getExecutionReservationTtlMs() const STALE_SCHEDULE_RECOVERY_BATCH_SIZE = 100 const DATABASE_SCHEDULE_START_TURN_WAIT_MS = 1_000 type DatabaseScheduleStartResult = 'started' | 'capacity_full' | 'not_pending' let databaseScheduleStartTurn: Promise | null = null -const dueFilter = (queuedAt: Date) => - and( - isNull(workflowSchedule.archivedAt), - lte(workflowSchedule.nextRunAt, queuedAt), - sql`${workflowSchedule.status} NOT IN ('disabled', 'completed')`, - or( - isNull(workflowSchedule.lastQueuedAt), - lt(workflowSchedule.lastQueuedAt, workflowSchedule.nextRunAt), - lt(workflowSchedule.lastQueuedAt, new Date(queuedAt.getTime() - STALE_SCHEDULE_CLAIM_MS)) - ) - ) - -const activeWorkflowDeploymentFilter = () => - sql`${workflowSchedule.deploymentVersionId} = (select ${workflowDeploymentVersion.id} from ${workflowDeploymentVersion} where ${workflowDeploymentVersion.workflowId} = ${workflowSchedule.workflowId} and ${workflowDeploymentVersion.isActive} = true)` - -const workflowScheduleFilter = (queuedAt: Date) => - and( - dueFilter(queuedAt), - sql`(${workflowSchedule.sourceType} = 'workflow' OR ${workflowSchedule.sourceType} IS NULL)`, - activeWorkflowDeploymentFilter() - ) - async function runWithDatabaseScheduleStartTurn( operation: () => Promise ): Promise { @@ -160,63 +136,9 @@ function getNextRunFromCronExpression( return cron.nextRun() } -async function claimWorkflowSchedules(queuedAt: Date, limit: number) { - if (limit <= 0) return [] - - return db.transaction(async (tx) => { - const rows = await tx - .select({ - id: workflowSchedule.id, - workspaceId: workflow.workspaceId, - }) - .from(workflowSchedule) - .innerJoin(workflow, eq(workflowSchedule.workflowId, workflow.id)) - .where(workflowScheduleFilter(queuedAt)) - .for('update', { skipLocked: true }) - .limit(limit) - - if (rows.length === 0) return [] - const workspaceIdsByScheduleId = new Map(rows.map((row) => [row.id, row.workspaceId])) - - const claimedRows = await tx - .update(workflowSchedule) - .set({ lastQueuedAt: queuedAt, updatedAt: queuedAt }) - .where( - and( - workflowScheduleFilter(queuedAt), - inArray( - workflowSchedule.id, - rows.map((row) => row.id) - ) - ) - ) - .returning({ - id: workflowSchedule.id, - workflowId: workflowSchedule.workflowId, - blockId: workflowSchedule.blockId, - cronExpression: workflowSchedule.cronExpression, - lastRanAt: workflowSchedule.lastRanAt, - failedCount: workflowSchedule.failedCount, - infraRetryCount: workflowSchedule.infraRetryCount, - nextRunAt: workflowSchedule.nextRunAt, - lastQueuedAt: workflowSchedule.lastQueuedAt, - timezone: workflowSchedule.timezone, - deploymentVersionId: workflowSchedule.deploymentVersionId, - deploymentOperationId: workflowSchedule.deploymentOperationId, - sourceType: workflowSchedule.sourceType, - }) - - return claimedRows.map((row) => ({ - ...row, - workspaceId: workspaceIdsByScheduleId.get(row.id) ?? null, - })) - }) -} - -type ClaimedSchedule = Awaited>[number] type JobQueue = Awaited> type DatabaseScheduleExecutionTarget = Pick< - ClaimedSchedule, + ClaimedWorkflowSchedule, 'id' | 'workflowId' | 'cronExpression' | 'timezone' > type ScheduleRecoveryMetadata = Pick< @@ -402,7 +324,7 @@ function getScheduleExecutionLeaseMs( return payload.executionTimeoutMs + RESERVATION_TTL_BUFFER_MS } - return STALE_SCHEDULE_CLAIM_MS + return FALLBACK_SCHEDULE_EXECUTION_LEASE_MS } function isStaleScheduleClaim( @@ -456,7 +378,7 @@ function unreconciledTerminalScheduleExecutionJobsFilter() { } function staleScheduleExecutionJobsFilter(now: Date) { - const legacyMaxDurationSeconds = STALE_SCHEDULE_CLAIM_MS / 1000 + const legacyMaxDurationSeconds = FALLBACK_SCHEDULE_EXECUTION_LEASE_MS / 1000 const cleanupGraceSeconds = RESERVATION_TTL_BUFFER_MS / 1000 return and( activeScheduleExecutionJobsFilter(), @@ -801,7 +723,7 @@ async function reconcileExistingScheduleJob(params: { } async function deferClaimedScheduleAfterQueueFailure( - schedule: ClaimedSchedule, + schedule: ClaimedWorkflowSchedule, requestId: string, expectedLastQueuedAt: Date, error: unknown, @@ -853,7 +775,7 @@ async function deferClaimedScheduleAfterQueueFailure( } async function handleClaimedScheduleSetupFailure( - schedule: ClaimedSchedule, + schedule: ClaimedWorkflowSchedule, requestId: string, expectedLastQueuedAt: Date, error: unknown, @@ -1350,7 +1272,7 @@ async function resumePendingDatabaseScheduleJobs( } async function processScheduleItem( - schedule: ClaimedSchedule, + schedule: ClaimedWorkflowSchedule, queuedAt: Date, requestId: string, jobQueue: JobQueue, @@ -1608,8 +1530,8 @@ async function processScheduleItem( /** * The queue may have accepted the job before the response was lost, and * the job id is deterministic, so retrying could double-dispatch the - * occurrence. Leave the claim in place and let the next tick reconcile - * against whatever carrier actually exists. + * occurrence. Keep the claim: once it outlasts the claim recheck window, a + * tick re-claims the schedule and reconciles against whatever carrier exists. */ if (acceptance !== 'rejected') return await handleClaimedScheduleSetupFailure( @@ -1784,7 +1706,7 @@ export async function runScheduleTick(requestId: string): Promise(async (request, context) => { + const parsed = await parseRequest(adminDashboardRevertToInvoicingContract, request, context, { + validationErrorResponse: adminValidationErrorResponse, + invalidJsonResponse: adminInvalidJsonResponse, + }) + if (!parsed.success) return parsed.response + try { + await revertDashboardEnterpriseToInvoicing( + parsed.data.params.id, + await getAdminAuditActor(request) + ) + return singleResponse({ success: true as const }) + } catch (error) { + return adminBadRequestResponse(getErrorMessage(error, 'Failed to return to invoice payment')) + } + }) +) diff --git a/apps/sim/app/api/v1/admin/dashboard/organizations/[id]/self-serve/route.ts b/apps/sim/app/api/v1/admin/dashboard/organizations/[id]/self-serve/route.ts new file mode 100644 index 00000000000..2d5d3988008 --- /dev/null +++ b/apps/sim/app/api/v1/admin/dashboard/organizations/[id]/self-serve/route.ts @@ -0,0 +1,33 @@ +import { getErrorMessage } from '@sim/utils/errors' +import { updateDashboardEnterpriseSelfServe } from '@/lib/admin/dashboard' +import { adminDashboardUpdateSelfServeContract } from '@/lib/api/contracts/v1/admin/dashboard' +import { parseRequest } from '@/lib/api/server' +import { withRouteHandler } from '@/lib/core/utils/with-route-handler' +import { getAdminAuditActor } from '@/app/api/v1/admin/dashboard/actor' +import { withAdminAuthParams } from '@/app/api/v1/admin/middleware' +import { + adminBadRequestResponse, + adminInvalidJsonResponse, + adminValidationErrorResponse, + singleResponse, +} from '@/app/api/v1/admin/responses' + +export const PATCH = withRouteHandler( + withAdminAuthParams<{ id: string }>(async (request, context) => { + const parsed = await parseRequest(adminDashboardUpdateSelfServeContract, request, context, { + validationErrorResponse: adminValidationErrorResponse, + invalidJsonResponse: adminInvalidJsonResponse, + }) + if (!parsed.success) return parsed.response + try { + await updateDashboardEnterpriseSelfServe( + parsed.data.params.id, + parsed.data.body, + await getAdminAuditActor(request) + ) + return singleResponse({ success: true as const }) + } catch (error) { + return adminBadRequestResponse(getErrorMessage(error, 'Failed to update self-serve billing')) + } + }) +) diff --git a/apps/sim/app/api/v2/logs/[runId]/route.test.ts b/apps/sim/app/api/v2/logs/[runId]/route.test.ts index e2a5123e3b8..4833b786ca6 100644 --- a/apps/sim/app/api/v2/logs/[runId]/route.test.ts +++ b/apps/sim/app/api/v2/logs/[runId]/route.test.ts @@ -105,6 +105,253 @@ describe('GET /api/v2/logs/[runId]', () => { }) }) + /** + * A reader scanning a long record for why a run failed used to find it only past + * the workflow state, inside the spans. The failed block leads the record instead. + */ + it('leads with the block the run failed in and the error it recorded', async () => { + mocks.execute.mockResolvedValue({ + log: { ...log, status: 'failed', level: 'error' }, + workflowFolderPath: '/agents', + executionData: { + traceSpans: [ + { + id: 'workflow-execution', + name: 'Workflow Execution', + type: 'workflow', + duration: 120, + status: 'error', + startTime: '2026-08-06T00:00:00.000Z', + endTime: '2026-08-06T00:00:00.120Z', + children: [ + { + id: 'span-fn', + blockId: 'block-fn', + name: 'Score', + type: 'function', + duration: 10, + status: 'error', + startTime: '2026-08-06T00:00:00.010Z', + endTime: '2026-08-06T00:00:00.020Z', + output: { + error: 'Line 3: boom\nthrow new Error("boom")', + errorMessage: 'boom', + }, + }, + ], + }, + ], + finalOutput: null, + }, + }) + + const response = await GET(new NextRequest('http://localhost:3000/api/v2/logs/run-1'), { + params: Promise.resolve({ runId: 'run-1' }), + }) + const { data } = await response.json() + + expect(data.failure).toEqual({ + blockId: 'block-fn', + blockName: 'Score', + blockType: 'function', + error: 'Line 3: boom\nthrow new Error("boom")', + errorMessage: 'boom', + }) + const keys = Object.keys(data) + expect(keys.indexOf('failure')).toBeLessThan(keys.indexOf('workflowState')) + expect(keys.indexOf('failure')).toBeLessThan(keys.indexOf('traceSpans')) + }) + + /** + * Two parallel blocks failing in the same instant leave the trace unable to say which + * one ended the run; the run's own error names it. + */ + it('uses the run error to pick between blocks that failed together', async () => { + const failedBlock = (blockId: string, name: string) => ({ + id: `span-${blockId}`, + blockId, + name, + type: 'agent', + duration: 10, + status: 'error', + startTime: '2026-08-06T00:00:00.000Z', + endTime: '2026-08-06T00:00:01.000Z', + output: { error: `${name} failed` }, + }) + mocks.execute.mockResolvedValue({ + log: { ...log, status: 'failed', level: 'error' }, + workflowFolderPath: '/agents', + executionData: { + traceSpans: [ + { + id: 'workflow-execution', + name: 'Workflow Execution', + type: 'workflow', + duration: 1000, + status: 'error', + startTime: '2026-08-06T00:00:00.000Z', + endTime: '2026-08-06T00:00:01.000Z', + children: [failedBlock('a', 'Agent A'), failedBlock('b', 'Agent B')], + }, + ], + finalizationPath: 'force_failed', + completionFailure: 'Agent B: timeout', + finalOutput: { error: 'Agent B: timeout' }, + }, + }) + + const response = await GET(new NextRequest('http://localhost:3000/api/v2/logs/run-1'), { + params: Promise.resolve({ runId: 'run-1' }), + }) + + expect((await response.json()).data.failure).toMatchObject({ blockId: 'b' }) + }) + + it('reads a run error recorded as an object with a message', async () => { + const failedBlock = (blockId: string, name: string) => ({ + id: `span-${blockId}`, + blockId, + name, + type: 'agent', + duration: 10, + status: 'error', + startTime: '2026-08-06T00:00:00.000Z', + endTime: '2026-08-06T00:00:01.000Z', + output: { error: `${name} failed` }, + }) + mocks.execute.mockResolvedValue({ + log: { ...log, status: 'failed', level: 'error' }, + workflowFolderPath: '/agents', + executionData: { + traceSpans: [ + { + id: 'workflow-execution', + name: 'Workflow Execution', + type: 'workflow', + duration: 1000, + status: 'error', + startTime: '2026-08-06T00:00:00.000Z', + endTime: '2026-08-06T00:00:01.000Z', + children: [failedBlock('a', 'Agent A'), failedBlock('b', 'Agent B')], + }, + ], + error: { message: 'Agent B: timeout' }, + }, + }) + + const response = await GET(new NextRequest('http://localhost:3000/api/v2/logs/run-1'), { + params: Promise.resolve({ runId: 'run-1' }), + }) + + expect((await response.json()).data.failure).toMatchObject({ blockId: 'b' }) + }) + + it('reports no failure for a cancelled run that kept error spans', async () => { + mocks.execute.mockResolvedValue({ + log: { ...log, status: 'cancelled', level: 'error' }, + workflowFolderPath: '/agents', + executionData: { + traceSpans: [ + { + id: 'span-fn', + blockId: 'block-fn', + name: 'Score', + type: 'function', + duration: 10, + status: 'error', + startTime: '2026-08-06T00:00:00.010Z', + endTime: '2026-08-06T00:00:00.020Z', + output: { error: 'aborted' }, + }, + ], + finalOutput: null, + }, + }) + + const response = await GET(new NextRequest('http://localhost:3000/api/v2/logs/run-1'), { + params: Promise.resolve({ runId: 'run-1' }), + }) + + expect((await response.json()).data.failure).toBeNull() + }) + + it('names no block when the run error matches none of the failed ones', async () => { + mocks.execute.mockResolvedValue({ + log: { ...log, status: 'failed', level: 'error' }, + workflowFolderPath: '/agents', + executionData: { + traceSpans: [ + { + id: 'span-fn', + blockId: 'block-fn', + name: 'Score', + type: 'function', + duration: 10, + status: 'error', + startTime: '2026-08-06T00:00:00.010Z', + endTime: '2026-08-06T00:00:00.020Z', + output: { error: 'Score failed' }, + }, + ], + finalizationPath: 'force_failed', + completionFailure: 'upstream returned 500', + finalOutput: { error: 'upstream returned 500' }, + }, + }) + + const response = await GET(new NextRequest('http://localhost:3000/api/v2/logs/run-1'), { + params: Promise.resolve({ runId: 'run-1' }), + }) + + expect((await response.json()).data.failure).toBeNull() + }) + + /** + * A run whose status comes from a block's error keeps the workflow's own `finalOutput`, which + * can hold an `error` field of its own: that is the workflow's data, not the run's error. + */ + it('names the failed block of a run whose workflow output holds an error field of its own', async () => { + mocks.execute.mockResolvedValue({ + log: { ...log, status: 'failed', level: 'error' }, + workflowFolderPath: '/agents', + executionData: { + traceSpans: [ + { + id: 'span-fn', + blockId: 'block-fn', + name: 'Score', + type: 'function', + duration: 10, + status: 'error', + startTime: '2026-08-06T00:00:00.010Z', + endTime: '2026-08-06T00:00:00.020Z', + output: { error: 'Line 1 - boom' }, + }, + ], + finalizationPath: 'completed', + finalOutput: { error: 'no matching customer' }, + }, + }) + + const response = await GET(new NextRequest('http://localhost:3000/api/v2/logs/run-1'), { + params: Promise.resolve({ runId: 'run-1' }), + }) + + expect((await response.json()).data.failure).toMatchObject({ + blockId: 'block-fn', + blockName: 'Score', + error: 'Line 1 - boom', + }) + }) + + it('reports no failure for a run whose trace has none', async () => { + const response = await GET(new NextRequest('http://localhost:3000/api/v2/logs/run-1'), { + params: Promise.resolve({ runId: 'run-1' }), + }) + + expect((await response.json()).data.failure).toBeNull() + }) + /** * Stored spans carry only `duration`; the contract publishes `durationMs` * beside it, and readers that trusted the documented name found it empty on diff --git a/apps/sim/app/api/v2/logs/[runId]/route.ts b/apps/sim/app/api/v2/logs/[runId]/route.ts index 8b9847a31e3..780972b2af6 100644 --- a/apps/sim/app/api/v2/logs/[runId]/route.ts +++ b/apps/sim/app/api/v2/logs/[runId]/route.ts @@ -4,8 +4,9 @@ import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/ import { v2LogErrorPolicies } from '@/lib/logs/api/route-policies' import { getPublicLog } from '@/lib/logs/application/get-public-log' import { logOperations } from '@/lib/logs/application/operations' -import { withSpanDurationMs } from '@/lib/logs/execution/trace-spans/trace-spans' +import { findTraceFailure, withSpanDurationMs } from '@/lib/logs/execution/trace-spans/trace-spans' import { projectLogFiles } from '@/lib/logs/files' +import { runFailureMessage } from '@/lib/workflows/executor/failure-message' export const revalidate = 0 @@ -26,6 +27,16 @@ function buildCostProjection( return null } +/** + * Where a failed run failed. The run's own error names the block when several failed in the same + * instant; one that names none of them yields no failure rather than an unrelated block, as the + * status read does. A run that did not fail (a cancelled one keeps its abort spans) has none. + */ +function failureOf(status: string, executionData: Record): V2LogDetail['failure'] { + if (status !== 'failed') return null + return findTraceFailure(executionData.traceSpans, runFailureMessage(executionData)) +} + /** * Returns the diagnostic representation of a run. The run ID is the sole * public identity; canonical workflow and workspace scope come from the run. @@ -52,6 +63,7 @@ export const GET = defineV2JsonRoute({ startedAt: log.startedAt.toISOString(), endedAt: log.endedAt ? log.endedAt.toISOString() : null, totalDurationMs: log.totalDurationMs, + failure: failureOf(log.status, executionData), files: projectLogFiles(log), executedByEmail: log.executedByEmail, workflow: { diff --git a/apps/sim/app/api/v2/tools/route.test.ts b/apps/sim/app/api/v2/tools/route.test.ts index c9e867dc61f..b80be6b76fa 100644 --- a/apps/sim/app/api/v2/tools/route.test.ts +++ b/apps/sim/app/api/v2/tools/route.test.ts @@ -40,6 +40,7 @@ const summary = { name: 'Slack Send Message', description: 'Send a message.', version: '1.0.0', + effect: 'write', hostedApiKey: 'none' as const, } diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.test.ts b/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.test.ts index 0f8ecd035de..b6e70d1d042 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.test.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.test.ts @@ -333,6 +333,32 @@ describe('POST /api/v2/workflows/[workflowId]/execute', () => { }) }) + it('names where a paused run waits: the run to resume and each pause point', async () => { + mockExecuteWorkflowCore.mockResolvedValueOnce({ + success: true, + status: 'paused', + output: {}, + pausePoints: [ + { contextId: 'ctx-1', pauseKind: 'human', resumeStatus: 'paused' }, + { contextId: 'ctx-2', pauseKind: 'time', resumeStatus: 'paused' }, + ], + metadata: { duration: 5 }, + }) + + const body = await (await callExecute({ input: {} })).json() + + expect(body.data).toMatchObject({ + status: 'paused', + paused: { + runId: 'execution-123', + points: [ + { contextId: 'ctx-1', kind: 'human', status: 'paused' }, + { contextId: 'ctx-2', kind: 'time', status: 'paused' }, + ], + }, + }) + }) + it('streams an immediate heartbeat and the same sync result when NDJSON is accepted', async () => { vi.useFakeTimers() try { @@ -382,6 +408,7 @@ describe('POST /api/v2/workflows/[workflowId]/execute', () => { status: 'completed', output: { result: 'done' }, blockOutputs: null, + paused: null, error: null, startedAt: '2026-07-31T00:00:00.000Z', endedAt: '2026-07-31T00:00:01.000Z', diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts b/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts index ab53f25617b..2d54ea85391 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts @@ -36,7 +36,7 @@ import { SIM_VIA_HEADER, validateCallChain, } from '@/lib/execution/call-chain' -import { v2WorkflowErrorPolicies } from '@/lib/workflows/api' +import { presentV2RunError, presentV2RunPause, v2WorkflowErrorPolicies } from '@/lib/workflows/api' import { executeManualWorkflowFromBlockOperation, executeManualWorkflowOperation, @@ -133,13 +133,14 @@ function presentRun(result: ExecuteWorkflowServiceRun) { runId: result.executionId, workflowId: result.workflowId, status: result.status, - error: result.error, + error: presentV2RunError(result.error, result.rerunFromBlockId), startedAt: result.startedAt, endedAt: result.endedAt, durationMs: result.durationMs, executionTimeoutSeconds: executionTimeoutSeconds(result.executionTimeoutMs), output: result.output ?? null, blockOutputs: result.blockOutputs ?? null, + paused: presentV2RunPause(result.paused), } } diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.test.ts b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.test.ts index 9e8e18d0c12..53322ddd5c5 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.test.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.test.ts @@ -137,6 +137,35 @@ describe('POST /api/v2/workflows/[workflowId]/runs/[runId]/resume', () => { expect(v2ResumeWorkflowContract.response.schema.parse(body)).toEqual(body) }) + it("presents the pause the resume reports, not the resume attempt's own run id", async () => { + mocks.resume.mockResolvedValueOnce({ + kind: 'sync', + success: true, + status: 'paused', + executionId: 'resume-execution-4', + output: {}, + error: undefined, + structuredError: null, + paused: { + runId: 'run-1', + points: [{ contextId: 'context-4', pauseKind: 'human', resumeStatus: 'paused' }], + }, + }) + const { request, context } = makeRequest(JSON.stringify({ contextId: 'context-3' })) + + const body = await (await POST(request, context)).json() + + expect(body.data).toMatchObject({ + runId: 'resume-execution-4', + status: 'paused', + paused: { + runId: 'run-1', + points: [{ contextId: 'context-4', kind: 'human', status: 'paused' }], + }, + }) + expect(v2ResumeWorkflowContract.response.schema.parse(body)).toEqual(body) + }) + it('wraps synchronous resume results in the canonical v2 run shape', async () => { mocks.resume.mockResolvedValueOnce({ kind: 'sync', @@ -165,6 +194,7 @@ describe('POST /api/v2/workflows/[workflowId]/runs/[runId]/resume', () => { status: 'completed', output: { approved: true }, blockOutputs: null, + paused: null, error: null, startedAt: '2026-08-05T00:00:00.000Z', endedAt: '2026-08-05T00:00:01.000Z', @@ -208,6 +238,7 @@ describe('POST /api/v2/workflows/[workflowId]/runs/[runId]/resume', () => { status: 'failed', output: { partial: true }, blockOutputs: null, + paused: null, error: { message: 'Condition evaluation failed', code: 'BLOCK_EXECUTION_FAILED', diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.ts b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.ts index e34f27d2bcb..5608c1364ee 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route.ts @@ -18,7 +18,7 @@ import { } from '@/lib/api/server/routes' import { getBaseUrl } from '@/lib/core/utils/urls' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' -import { v2WorkflowErrorPolicies } from '@/lib/workflows/api' +import { presentV2RunPause, v2WorkflowErrorPolicies } from '@/lib/workflows/api' import { workflowOperations } from '@/lib/workflows/application/operations' import { resumeWorkflowRun } from '@/lib/workflows/application/resume-run' import { ResumeWorkflowExecutionError } from '@/lib/workflows/executor/resume-execution' @@ -118,6 +118,7 @@ export const POST = withRouteHandler( output: result.output ?? null, // Resume has no request body to name selectors in, so selection never applies here. blockOutputs: null, + paused: presentV2RunPause(result.paused), }, { headers } ) diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.test.ts b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.test.ts index 54c0fc63784..7e2e5b9aa16 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.test.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.test.ts @@ -131,6 +131,19 @@ describe('v2 run detail and cancel adapters', () => { expect(mocks.readRun).not.toHaveBeenCalled() }) + it('names on the failure the block a rerun starts from, apart from the block that failed', async () => { + mocks.readRun.mockResolvedValueOnce({ + ...baseStatus, + failedBlock: { blockId: 'send', blockName: 'Send Email', blockType: 'gmail' }, + rerunFromBlockId: 'loop', + }) + + expect((await (await callStatus()).json()).data.error).toMatchObject({ + blockId: 'send', + rerunFromBlockId: 'loop', + }) + }) + it('returns the public pause context without its internal paused-execution ID', async () => { mocks.readRun.mockResolvedValueOnce({ ...baseStatus, @@ -150,11 +163,13 @@ describe('v2 run detail and cancel adapters', () => { pausePointCount: 1, resumedCount: 0, }, + pausedRunId: 'run-parent', }) const body = await (await callStatus()).json() expect(body.data.paused.contextId).toBe('context-1') + expect(body.data.paused.runId).toBe('run-parent') expect(body.data.paused).not.toHaveProperty('pausedExecutionId') }) diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.ts b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.ts index dffdb4e639a..fcaf4a3e6cd 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/runs/[runId]/route.ts @@ -3,7 +3,7 @@ import { v2WorkflowRunStatusSchema, } from '@/lib/api/contracts/v2/workflows' import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/routes' -import { v2WorkflowErrorPolicies } from '@/lib/workflows/api' +import { presentV2RunError, v2WorkflowErrorPolicies } from '@/lib/workflows/api' import { workflowOperations } from '@/lib/workflows/application/operations' import { readWorkflowRun } from '@/lib/workflows/application/read-workflow-run' import { classifyRecordedExecutionError } from '@/executor/utils/errors' @@ -49,11 +49,15 @@ export const GET = defineV2JsonRoute({ paused: status.paused ? v2WorkflowRunStatusSchema.shape.paused.parse({ ...status.paused, + runId: status.pausedRunId, points: status.pausePoints ?? [], }) : null, cost: status.cost, - error: status.error ? classifyRecordedExecutionError(status.error, status.failedBlock) : null, + error: presentV2RunError( + status.error ? classifyRecordedExecutionError(status.error, status.failedBlock) : null, + status.rerunFromBlockId + ), output: status.finalOutput, blockOutputs: status.blockOutputs, files: status.files, diff --git a/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/resources/route.test.ts b/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/resources/route.test.ts index dcb32f2e1be..b9ed2d1ee11 100644 --- a/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/resources/route.test.ts +++ b/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/resources/route.test.ts @@ -60,7 +60,7 @@ const manifest = { }, ], skills: [{ key: 'triage', id: 'skl_1', name: 'Triage' }], - customTools: [{ key: 'lookup-order', id: 'ctl_1', name: 'lookup_order' }], + customTools: [{ key: 'lookup-order', id: 'ctl_1', name: 'Lookup order' }], mcpServers: [{ key: 'github', id: 'mcp-1', name: 'GitHub', tools: ['create_issue'] }], env: ['CRM_KEY'], truncated: false, diff --git a/apps/sim/app/api/workspaces/[id]/permissions/route.test.ts b/apps/sim/app/api/workspaces/[id]/permissions/route.test.ts index c0a70b47a38..6899a3d53ea 100644 --- a/apps/sim/app/api/workspaces/[id]/permissions/route.test.ts +++ b/apps/sim/app/api/workspaces/[id]/permissions/route.test.ts @@ -24,12 +24,12 @@ import { } from '@sim/testing/mocks/workspace-context.mock' import { beforeEach, describe, expect, it, vi } from 'vitest' -const { mockAssertMembershipNotScimManaged } = vi.hoisted(() => ({ - mockAssertMembershipNotScimManaged: vi.fn(), +const { mockAssertWorkspaceAccessNotScimManaged } = vi.hoisted(() => ({ + mockAssertWorkspaceAccessNotScimManaged: vi.fn(), })) vi.mock('@/ee/scim/lib/managed-membership', () => ({ - assertMembershipNotScimManaged: mockAssertMembershipNotScimManaged, + assertWorkspaceAccessNotScimManaged: mockAssertWorkspaceAccessNotScimManaged, })) vi.mock('@sim/audit', () => auditMock) @@ -441,7 +441,7 @@ describe('workspace permissions route', () => { it('refuses a role change for a member the directory manages', async () => { queueOrgWorkspace([], [permissionRow(MEMBER_ID, 'read')]) - mockAssertMembershipNotScimManaged.mockRejectedValueOnce( + mockAssertWorkspaceAccessNotScimManaged.mockRejectedValueOnce( new ForbiddenOperationError('SCIM_MANAGED_MEMBERSHIP', 'Managed by the directory') ) @@ -452,8 +452,12 @@ describe('workspace permissions route', () => { expect(response.status).toBe(403) await expect(response.json()).resolves.toMatchObject({ error: 'Managed by the directory' }) - expect(mockAssertMembershipNotScimManaged).toHaveBeenCalledWith( - expect.objectContaining({ organizationId: ORG_ID, userId: MEMBER_ID }) + expect(mockAssertWorkspaceAccessNotScimManaged).toHaveBeenCalledWith( + expect.objectContaining({ + organizationId: ORG_ID, + userId: MEMBER_ID, + workspaceIds: [WORKSPACE_ID], + }) ) expect(dbChainMockFns.update).not.toHaveBeenCalled() }) diff --git a/apps/sim/app/index.md/route.ts b/apps/sim/app/index.md/route.ts index 51749fc2be6..90a8791450a 100644 --- a/apps/sim/app/index.md/route.ts +++ b/apps/sim/app/index.md/route.ts @@ -1,5 +1,6 @@ import { SITE_URL } from '@/lib/core/utils/urls' import { DOCS_URL } from '@/lib/help-links' +import { HOME_FAQS } from '@/app/(landing)/components/home-faq' import { HOME_FEATURES, HOME_HERO_HEADING, @@ -53,6 +54,11 @@ export async function GET() { 'What teams do in Sim', HOME_FEATURES.map((feature) => `- ${feature}`) ), + section( + 'Questions teams ask about Sim', + HOME_FAQS.map(({ question, answer }) => `### ${question}\n\n${answer}`), + '\n\n' + ), section('Platform', navMenuLines(PLATFORM_MENU)), section('Solutions', SOLUTION_LINES), section('More', [ diff --git a/apps/sim/app/llms.txt/llms.ts b/apps/sim/app/llms.txt/llms.ts index 09292468663..38360344f8b 100644 --- a/apps/sim/app/llms.txt/llms.ts +++ b/apps/sim/app/llms.txt/llms.ts @@ -59,7 +59,7 @@ export const SECURITY_LINES = [ linkLine( 'Trust Center', 'https://trust.sim.ai/', - 'SOC 2 Type II, ISO 27001, and GDPR: reports, policies, and subprocessors' + 'SOC 2 Type II (Security criterion), GDPR, and ISO 27001 certification in progress: reports, policies, and subprocessors' ), linkLine( 'Single sign-on', diff --git a/apps/sim/app/manifest.ts b/apps/sim/app/manifest.ts index 1a0b3f0e160..9cada5117d0 100644 --- a/apps/sim/app/manifest.ts +++ b/apps/sim/app/manifest.ts @@ -2,8 +2,6 @@ import { INTEGRATION_COUNT_LABEL } from '@sim/deployment-config/integration-clai import type { MetadataRoute } from 'next' import { WORKSPACES_PATH } from '@/lib/navigation/paths' -export const dynamic = 'force-dynamic' - export default function manifest(): MetadataRoute.Manifest { return { name: 'Sim — The AI Workspace | Build, Deploy & Manage AI Agents', diff --git a/apps/sim/app/workspace/[workspaceId]/components/invite-modal/invite-modal.tsx b/apps/sim/app/workspace/[workspaceId]/components/invite-modal/invite-modal.tsx index 29c45fa2dd7..f82e3588d01 100644 --- a/apps/sim/app/workspace/[workspaceId]/components/invite-modal/invite-modal.tsx +++ b/apps/sim/app/workspace/[workspaceId]/components/invite-modal/invite-modal.tsx @@ -14,7 +14,6 @@ import { } from '@sim/emcn' import { createLogger } from '@sim/logger' import { useSession } from '@/lib/auth/client' -import { isEnterprise } from '@/lib/billing/plan-helpers' import { useDeploymentShape } from '@/lib/core/config/deployment-shape' import { buildInviteFailureMessage } from '@/lib/invitations/error-messages' import { quickValidateEmail } from '@/lib/messaging/email/validation' @@ -167,11 +166,11 @@ export function InviteModal({ const usedSeats = organizationBillingData?.data?.usedSeats ?? 0 const availableSeats = Math.max(0, totalSeats - usedSeats) /** - * Only Enterprise plans have a fixed seat cap that gates invites. Team seats - * are provisioned when an invitee accepts, and externals never take one. + * Only a fixed seat cap gates invites. Team seats are provisioned when an invitee accepts, a + * self-serve Enterprise contract trues up seats past its baseline, and externals never take one. */ - const isEnterpriseOrg = isEnterprise(organizationBillingData?.data?.subscriptionPlan) - const hasSeatData = canViewOrganizationBilling && isEnterpriseOrg && totalSeats > 0 + const hasFixedSeatCap = organizationBillingData?.data?.seatCapKind === 'fixed' + const hasSeatData = canViewOrganizationBilling && hasFixedSeatCap && totalSeats > 0 /** * Advisory only. The server decides per email and does not charge a seat for * everyone: an existing organization member is granted access directly, and an @@ -184,6 +183,22 @@ export function InviteModal({ const seatLimitReason = mayExceedSeatCapacity ? `Only ${availableSeats} seat${availableSeats === 1 ? '' : 's'} available — invites beyond that may fail. External collaborators and existing members do not use seats.` : null + /** + * Tells the inviter what accepting costs, since the seat is charged then rather than now. An + * organization invite needs the seat model, which only billing admins can read; a personal + * workspace's invitee always joins as a new seat. + */ + const seatCapKind = isOrganizationInvite + ? organizationBillingData?.data?.seatCapKind + : 'on-demand' + const seatChargeHint = + billingEnabled && canInvite && membership !== 'external' + ? seatCapKind === 'baseline' + ? 'New members past your contracted seats are billed at the next seat true-up.' + : seatCapKind === 'on-demand' + ? "Each new member who accepts adds a paid seat, prorated for this period. Existing members don't add one." + : null + : null const validateEmail = useCallback( (email: string): string | null => { @@ -271,7 +286,7 @@ export function InviteModal({ value={emails} onChange={handleEmailsChange} validate={validateEmail} - hint={inviteDisabledReason ?? seatLimitReason} + hint={inviteDisabledReason ?? seatLimitReason ?? seatChargeHint} placeholder={ canInvite ? 'Enter emails' diff --git a/apps/sim/app/workspace/[workspaceId]/home/components/chat-plan-notice/chat-plan-notice.tsx b/apps/sim/app/workspace/[workspaceId]/home/components/chat-plan-notice/chat-plan-notice.tsx new file mode 100644 index 00000000000..dab8bb8de51 --- /dev/null +++ b/apps/sim/app/workspace/[workspaceId]/home/components/chat-plan-notice/chat-plan-notice.tsx @@ -0,0 +1,59 @@ +'use client' + +import { useRouter } from 'next/navigation' +import { CHAT_PLAN_REQUIRED_UPGRADE } from '@/lib/billing/chat-plan' +import { PRO_TRIAL_DAYS } from '@/lib/billing/constants' +import { rememberSettingsReturnUrl } from '@/lib/navigation/settings-return' +import { useChatPlanRequired } from '@/app/workspace/[workspaceId]/home/hooks/use-chat-plan-required' +import { usePlanUpgradeLink } from '@/app/workspace/[workspaceId]/home/hooks/use-plan-upgrade-link' +import { useWorkspaceHostContext } from '@/app/workspace/[workspaceId]/providers/workspace-host-provider' +import { useSubscriptionData } from '@/hooks/queries/subscription' + +/** + * Says up front, above an empty composer, that this workspace's plan does not include Chat, so a + * free payer learns it before typing rather than from the modal a send opens. + */ +export function ChatPlanNotice() { + if (!useChatPlanRequired()) return null + return +} + +function ChatPlanNoticeContent() { + const router = useRouter() + const hostContext = useWorkspaceHostContext() + const { href, opensInNewTab, canManageBilling, unavailableMessage } = usePlanUpgradeLink( + CHAT_PLAN_REQUIRED_UPGRADE + ) + const isPersonalWorkspace = !hostContext.hostOrganizationId + // Only a personal checkout starts the trial, so the offer is the viewer's own. + const { data: viewerBilling } = useSubscriptionData({ + enabled: canManageBilling && isPersonalWorkspace, + }) + const offersTrial = isPersonalWorkspace && viewerBilling?.data?.proTrialEligible === true + + const openUpgrade = () => { + if (opensInNewTab) { + window.open(href, '_blank', 'noopener,noreferrer') + return + } + rememberSettingsReturnUrl(href) + router.push(href) + } + + return ( +

    + Chat with Sim is included with paid plans.{' '} + {canManageBilling ? ( + + ) : ( + unavailableMessage + )} +

    + ) +} diff --git a/apps/sim/app/workspace/[workspaceId]/home/components/chat-plan-notice/index.ts b/apps/sim/app/workspace/[workspaceId]/home/components/chat-plan-notice/index.ts new file mode 100644 index 00000000000..60edaf2cd0a --- /dev/null +++ b/apps/sim/app/workspace/[workspaceId]/home/components/chat-plan-notice/index.ts @@ -0,0 +1 @@ +export { ChatPlanNotice } from './chat-plan-notice' diff --git a/apps/sim/app/workspace/[workspaceId]/home/home.tsx b/apps/sim/app/workspace/[workspaceId]/home/home.tsx index 1e3523389f6..e3b0ad509cb 100644 --- a/apps/sim/app/workspace/[workspaceId]/home/home.tsx +++ b/apps/sim/app/workspace/[workspaceId]/home/home.tsx @@ -21,6 +21,7 @@ import { } from '@/lib/mothership/events' import { captureEvent } from '@/lib/posthog/client' import { persistImportedWorkflow } from '@/lib/workflows/operations/import-export' +import { ChatPlanNotice } from '@/app/workspace/[workspaceId]/home/components/chat-plan-notice' import { ChatResourcePanel } from '@/app/workspace/[workspaceId]/home/components/chat-resource-panel' import { RESOURCE_HEADER_CLASSES } from '@/app/workspace/[workspaceId]/home/components/mothership-view/components/resource-tabs/resource-tab-controls' import { SuggestedActions } from '@/app/workspace/[workspaceId]/home/components/suggested-actions' @@ -441,6 +442,7 @@ function HomeContent({ chatId, userName, userId }: HomeProps) {

    What should we get done{firstName ? `, ${firstName}` : ''}?

    +
    = { void: { variant: 'gray', label: 'Void' }, } +/** A plan's effective monthly price: the annual price spread over twelve months on annual billing. */ +function formatMonthlyPrice(plan: string, billingInterval: string | undefined): string { + const monthly = + getPlanTierDollars(plan) * (billingInterval === 'year' ? 1 - ANNUAL_DISCOUNT_RATE : 1) + return `$${Number.isInteger(monthly) ? monthly : monthly.toFixed(2)}` +} + +function getPeriodEndLabel(isCancelledAtPeriodEnd: boolean, isTrialing: boolean): string { + if (isCancelledAtPeriodEnd) return 'Access until' + if (isTrialing) return 'Free trial ends' + return 'Next billing date' +} + /** Resolve a Stripe invoice status to its badge presentation. */ function getInvoiceStatusBadge(status: string | null): InvoiceStatusBadge { return ( @@ -158,8 +174,12 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps const { data: session } = useSession() const betterAuthSubscription = useSubscription() const openBillingPortal = useOpenBillingPortal() + const endProTrial = useEndProTrial() const organizationBilling = organizationBillingData?.data + const enterpriseSelfServe = isOrganizationScope + ? (organizationBilling?.enterpriseSelfServe ?? null) + : null const upgradeWorkspaceId = isOrganizationScope ? organizationBilling?.upgradeWorkspaceId : subscriptionData?.data?.upgradeWorkspaceId @@ -237,7 +257,7 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps const planIncludedAmount = subscription.isOrgScoped && organizationBilling ? organizationBilling.minimumBillingAmount - : getPlanTierCredits(subscription.plan) / CREDIT_MULTIPLIER + : (subscriptionData?.data?.includedUsage ?? 0) const effectiveUsageLimit = subscription.isOrgScoped && organizationBilling @@ -281,6 +301,10 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps covered, }) + const hasUsablePaidAccess = subscription.isPaid + ? hasUsableSubscriptionAccess(subscription.status, isBlocked) + : false + const permissions = getSubscriptionPermissions( { isFree: subscription.isFree, @@ -289,15 +313,23 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps isEnterprise: subscription.isEnterprise, isPaid: subscription.isPaid, isOrgScoped: subscription.isOrgScoped, + isEnterpriseSelfServe: enterpriseSelfServe !== null, + hasUsableAccess: hasUsablePaidAccess, plan: subscription.plan || 'free', status: subscription.status || 'inactive', }, { isTeamAdmin, userRole: userRole || 'member' } ) - const hasUsablePaidAccess = subscription.isPaid - ? hasUsableSubscriptionAccess(subscription.status, isBlocked) - : false + /** A failed payment or an open dispute pauses the plan's usage. */ + const hasPaymentProblem = subscription.isPaid && !hasUsablePaidAccess + const billingBlockedReason = isOrganizationScope + ? organizationBilling?.billingBlockedReason + : subscriptionData?.data?.billingBlockedReason + const paymentProblemLabel = + billingBlockedReason === 'dispute' + ? 'Usage is paused while a payment dispute is open. Contact support to resolve it' + : 'Payment failed. Update your payment method to resume usage' const isTogglingOnDemand = updateUserLimit.isPending || updateOrgLimit.isPending @@ -337,7 +369,7 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps } const handleOpenBillingPortal = () => { - if (!permissions.canEditUsageLimit) { + if (!permissions.canManageBilling) { toast.error("Can't manage payment method", { description: 'Only organization admins can manage billing.', }) @@ -375,7 +407,7 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps } const handleCancelSubscription = async () => { - if (!permissions.canEditUsageLimit) { + if (!permissions.canManageBilling) { toast.error("Can't cancel subscription", { description: 'Only organization admins can cancel the subscription.', }) @@ -403,7 +435,7 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps } const handleRestoreSubscription = async () => { - if (!permissions.canEditUsageLimit) { + if (!permissions.canManageBilling) { toast.error("Can't restore subscription", { description: 'Only organization admins can restore the subscription.', }) @@ -466,7 +498,7 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps ? 'Choose a new plan for this organization' : subscription.isEnterprise ? 'Custom pricing' - : `$${getPlanTierDollars(subscription.plan)} per user/month, ${billingPeriod}` + : `${formatMonthlyPrice(subscription.plan, billingInterval)}${isOrganizationScope ? ' per user' : ''}/month, ${billingPeriod}` const periodEnd = isOrganizationScope ? (organizationBilling?.billingPeriodEnd ?? null) @@ -475,8 +507,9 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps ? organizationBilling?.cancelAtPeriodEnd === true : subscriptionData?.data?.cancelAtPeriodEnd === true + const isTrialing = isTrialingSubscription(subscription) const weeklyRefreshDollars = - getPlanWeeklyRefreshDollars(subscription.plan) * + getSubscriptionWeeklyRefreshDollars(subscription) * (isOrganizationScope ? subscription.seats || 1 : 1) const invoices = (invoicesData?.invoices ?? []).map((invoice) => ({ @@ -488,20 +521,19 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps url: invoice.hostedInvoiceUrl ?? invoice.invoicePdf, })) - const canManageBilling = permissions.canEditUsageLimit + const canManageBilling = permissions.canManageBilling const canExplorePlans = permissions.showUpgradePlans - const showUsageLimit = subscription.isPaid && !subscription.isEnterprise - const showOnDemand = hasUsablePaidAccess && !subscription.isEnterprise + const hasEditableLimit = !subscription.isEnterprise || enterpriseSelfServe !== null + const showUsageLimit = subscription.isPaid && hasEditableLimit + const showOnDemand = hasUsablePaidAccess && hasEditableLimit && !isTrialing const usageLimitCurrent = subscription.isOrgScoped && organizationBilling ? organizationBilling.totalUsageLimit : usage.limit - const usageLimitMinimum = - subscription.isOrgScoped && organizationBilling - ? organizationBilling.minimumBillingAmount - : getPlanTierDollars(subscription.plan) + // A self-serve Enterprise limit cannot fall below what the contract already covers. + const usageLimitMinimum = enterpriseSelfServe ? covered : planIncludedAmount const explorePlansLabel = isOrganizationScope ? 'Explore organization plans' : 'Explore personal plans' @@ -579,7 +611,7 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps )} @@ -614,7 +646,7 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps {periodEnd && (
    - {isCancelledAtPeriodEnd ? 'Access until' : 'Next billing date'} + {getPeriodEndLabel(isCancelledAtPeriodEnd, isTrialing)} {new Date(periodEnd).toLocaleDateString()} @@ -622,6 +654,28 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
    )} + {isTrialing && !isOrganizationScope && canManageBilling && !isCancelledAtPeriodEnd && ( +
    + + End the trial and start paying today + + + endProTrial.mutate(undefined, { + onSuccess: () => toast.success('Your paid plan has started'), + onError: (error) => + toast.error("Couldn't start your paid plan", { + description: getErrorMessage(error, 'Please try again.'), + }), + }) + } + > + Start paid plan + +
    + )} + {subscription.isPaid && weeklyRefreshDollars > 0 && (
    Weekly refresh @@ -631,15 +685,25 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps
    )} -
    - Payment method - - Manage in Stripe - -
    + {enterpriseSelfServe && billingOrganizationId ? ( + + ) : ( +
    + + {hasPaymentProblem ? paymentProblemLabel : 'Payment method'} + + + Manage in Stripe + +
    + )} {!subscription.isEnterprise && (
    @@ -669,6 +733,13 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps )} + {enterpriseSelfServe && ( + + )} + {isOrganizationScope && ( { + if (!canManage) return 'Managed by organization admins' + if (isError) return 'Unavailable' + if (isPending) return '—' + if (autoPay) return `Auto-pay · ${data?.paymentMethod?.label ?? 'payment method on file'}` + if (isConfirmingAutoPay) return 'Confirming payment method…' + return 'Paid by invoice' + } + + const handleSetUp = () => { + const returnUrl = new URL(window.location.href) + returnUrl.searchParams.delete(AUTO_PAY_RETURN_PARAM) + startAutoPay.mutate( + { organizationId, returnUrl: returnUrl.toString() }, + { + onSuccess: ({ url }) => { + window.location.href = url + }, + onError: (error) => { + logger.error('Failed to start auto-pay setup', { error }) + toast.error("Couldn't open payment setup", { + description: getErrorMessage(error, 'Please try again in a moment.'), + }) + }, + } + ) + } + + return ( +
    +
    + Payment method + +
    + + {autoPay ? 'Update' : 'Set up auto-pay'} + +
    + ) +} diff --git a/apps/sim/app/workspace/[workspaceId]/settings/components/billing/components/enterprise-seats-section/enterprise-seats-section.tsx b/apps/sim/app/workspace/[workspaceId]/settings/components/billing/components/enterprise-seats-section/enterprise-seats-section.tsx new file mode 100644 index 00000000000..25dd01a16e0 --- /dev/null +++ b/apps/sim/app/workspace/[workspaceId]/settings/components/billing/components/enterprise-seats-section/enterprise-seats-section.tsx @@ -0,0 +1,46 @@ +'use client' + +import type { OrganizationBillingSummary } from '@/lib/api/contracts/organization' +import { SettingsSection } from '@/app/workspace/[workspaceId]/settings/components/settings-section/settings-section' + +interface EnterpriseSeatsSectionProps { + terms: NonNullable + billingInterval: 'month' | 'year' +} + +interface SeatRowProps { + label: string + value: string +} + +function SeatRow({ label, value }: SeatRowProps) { + return ( +
    + {label} + {value} +
    + ) +} + +/** + * Self-serve Enterprise seat terms. Additional seats are the open true-up window's peak (a quarter, + * or the month on a monthly contract), which the next true-up bills. + */ +export function EnterpriseSeatsSection({ terms, billingInterval }: EnterpriseSeatsSectionProps) { + const trueUpWindow = billingInterval === 'year' ? 'quarter' : 'month' + return ( + +
    + + + +
    +
    + ) +} diff --git a/apps/sim/app/workspace/[workspaceId]/settings/components/billing/components/usage-limit-field/usage-limit-field.tsx b/apps/sim/app/workspace/[workspaceId]/settings/components/billing/components/usage-limit-field/usage-limit-field.tsx index 1f2cff43577..f074eee95c2 100644 --- a/apps/sim/app/workspace/[workspaceId]/settings/components/billing/components/usage-limit-field/usage-limit-field.tsx +++ b/apps/sim/app/workspace/[workspaceId]/settings/components/billing/components/usage-limit-field/usage-limit-field.tsx @@ -18,13 +18,13 @@ const AUTOSAVE_DELAY_MS = 1000 const USAGE_LIMIT_INFO = ( { - "Max usage to consume per month, set in credits — Sim's usage unit (1,000 credits = $5). By default, it's your plan's included usage, but you can set it beyond." + "Max usage to consume per billing period, set in credits — Sim's usage unit (1,000 credits = $5). By default, it's your plan's included usage (a year's worth on annual billing, or the trial allowance during a trial), but you can set it beyond." } ) interface UsageLimitFieldProps { - /** Current monthly usage limit, in dollars. */ + /** Current usage limit for the billing period, in dollars. */ currentLimit: number /** Lowest limit the plan allows, in dollars. */ minimumLimit: number @@ -37,7 +37,7 @@ interface UsageLimitFieldProps { } /** - * Editable monthly usage-limit field. Seeds from the resolved limit and + * Editable usage-limit field. Seeds from the resolved limit and * auto-saves a debounced, validated value to either the user or the * organization — matching the Subscription tab's edit logic. When the viewer * cannot edit (e.g. a non-admin team member) the resolved value is shown diff --git a/apps/sim/app/workspace/[workspaceId]/settings/components/billing/search-params.ts b/apps/sim/app/workspace/[workspaceId]/settings/components/billing/search-params.ts new file mode 100644 index 00000000000..e2bd92e9733 --- /dev/null +++ b/apps/sim/app/workspace/[workspaceId]/settings/components/billing/search-params.ts @@ -0,0 +1,11 @@ +import { parseAsBoolean } from 'nuqs/server' +import { AUTO_PAY_RETURN_PARAM } from '@/lib/api/contracts/organization' + +/** + * The marker Stripe's setup page returns to: the billing page keeps checking the payment method + * until the webhook has switched the contract to automatic payment. + */ +export const autoPayReturnParam = { + key: AUTO_PAY_RETURN_PARAM, + parser: parseAsBoolean.withDefault(false), +} as const diff --git a/apps/sim/app/workspace/[workspaceId]/settings/components/billing/subscription-permissions.ts b/apps/sim/app/workspace/[workspaceId]/settings/components/billing/subscription-permissions.ts index 94e514d1112..10db3f10b14 100644 --- a/apps/sim/app/workspace/[workspaceId]/settings/components/billing/subscription-permissions.ts +++ b/apps/sim/app/workspace/[workspaceId]/settings/components/billing/subscription-permissions.ts @@ -1,8 +1,15 @@ +import { isTrialingSubscription } from '@/lib/billing/subscriptions/utils' + export interface SubscriptionPermissions { canUpgradeToPro: boolean canUpgradeToTeam: boolean canViewEnterprise: boolean canManageTeam: boolean + /** Manage payment method and cancel or restore the plan. */ + canManageBilling: boolean + /** Save a payment method for automatic payment on a self-serve Enterprise contract. */ + canManageEnterprisePayment: boolean + /** Change the usage limit or on-demand usage; a trial's allowance is fixed. */ canEditUsageLimit: boolean canCancelSubscription: boolean showTeamMemberView: boolean @@ -23,6 +30,10 @@ export interface SubscriptionState { * transferred to an org are org-scoped even though `isTeam` is false. */ isOrgScoped: boolean + /** An Enterprise contract an admin opted into self-serve usage limits, seats, and payment. */ + isEnterpriseSelfServe: boolean + /** Active or trialing and not billing-blocked; a past-due or blocked plan cannot change limits. */ + hasUsableAccess: boolean plan: string status: string } @@ -36,7 +47,8 @@ export function getSubscriptionPermissions( subscription: SubscriptionState, userRole: UserRole ): SubscriptionPermissions { - const { isFree, isPro, isEnterprise, isPaid, isOrgScoped } = subscription + const { isFree, isPro, isEnterprise, isPaid, isOrgScoped, isEnterpriseSelfServe } = subscription + const isTrialing = isTrialingSubscription(subscription) const { isTeamAdmin } = userRole // Non-admin org members see the "team member" view: no edit / no cancel @@ -45,14 +57,22 @@ export function getSubscriptionPermissions( const orgAdminOrSolo = !isOrgScoped || isTeamAdmin const isEnterpriseMember = isEnterprise && !isTeamAdmin + const canManageBilling = (isFree || (isPaid && !isEnterprise)) && orgAdminOrSolo + const canManageEnterprisePayment = isEnterpriseSelfServe && isTeamAdmin const canViewUsageInfo = !isEnterpriseMember return { canUpgradeToPro: isFree, - canUpgradeToTeam: isFree || (isPro && !isOrgScoped), + // A trial becomes a team plan only after it converts. + canUpgradeToTeam: isFree || (isPro && !isOrgScoped && !isTrialing), canViewEnterprise: !isEnterprise && !orgMemberOnly, canManageTeam: isOrgScoped && isTeamAdmin && !isEnterprise, - canEditUsageLimit: (isFree || (isPaid && !isEnterprise)) && orgAdminOrSolo, + canManageBilling, + canManageEnterprisePayment, + canEditUsageLimit: + (canManageBilling || canManageEnterprisePayment) && + !isTrialing && + subscription.hasUsableAccess, canCancelSubscription: isPaid && !isEnterprise && orgAdminOrSolo, showTeamMemberView: orgMemberOnly, showUpgradePlans: diff --git a/apps/sim/app/workspace/[workspaceId]/settings/components/team-management/components/team-seats-overview/team-seats-overview.tsx b/apps/sim/app/workspace/[workspaceId]/settings/components/team-management/components/team-seats-overview/team-seats-overview.tsx index 66f7eac5162..8cc0025297d 100644 --- a/apps/sim/app/workspace/[workspaceId]/settings/components/team-management/components/team-seats-overview/team-seats-overview.tsx +++ b/apps/sim/app/workspace/[workspaceId]/settings/components/team-management/components/team-seats-overview/team-seats-overview.tsx @@ -22,6 +22,8 @@ interface TeamSeatsOverviewProps { usedSeats: number /** Outstanding invites that have not been accepted yet (do not consume a seat). */ pendingSeats?: number + /** A self-serve Enterprise contract, whose members may outgrow its seats and true up. */ + seatsAreBaseline?: boolean } export function TeamSeatsOverview({ @@ -31,6 +33,7 @@ export function TeamSeatsOverview({ totalSeats, usedSeats, pendingSeats = 0, + seatsAreBaseline = false, }: TeamSeatsOverviewProps) { if (isLoadingSubscription) { return null @@ -58,7 +61,7 @@ export function TeamSeatsOverview({ const isEnterprise = checkEnterprisePlan(subscriptionData) const isSeatDataPending = !isEnterprise && totalSeats === 0 - const isOverLimit = totalSeats > 0 && usedSeats > totalSeats + const isOverLimit = !seatsAreBaseline && totalSeats > 0 && usedSeats > totalSeats const pillCount = Math.max(totalSeats, usedSeats, 1) if (isSeatDataPending) { diff --git a/apps/sim/app/workspace/[workspaceId]/settings/components/team-management/team-management.tsx b/apps/sim/app/workspace/[workspaceId]/settings/components/team-management/team-management.tsx index 8e25128c180..803e3710848 100644 --- a/apps/sim/app/workspace/[workspaceId]/settings/components/team-management/team-management.tsx +++ b/apps/sim/app/workspace/[workspaceId]/settings/components/team-management/team-management.tsx @@ -443,6 +443,7 @@ export function TeamManagement({ totalSeats={totalSeats} usedSeats={usedSeats} pendingSeats={pendingSeats} + seatsAreBaseline={organizationBillingData?.data?.seatCapKind === 'baseline'} /> ))} diff --git a/apps/sim/app/workspace/[workspaceId]/upgrade/components/comparison-table/comparison-data.ts b/apps/sim/app/workspace/[workspaceId]/upgrade/components/comparison-table/comparison-data.ts index badb0d3a16f..8c2a081bbf7 100644 --- a/apps/sim/app/workspace/[workspaceId]/upgrade/components/comparison-table/comparison-data.ts +++ b/apps/sim/app/workspace/[workspaceId]/upgrade/components/comparison-table/comparison-data.ts @@ -1,5 +1,10 @@ import { DEFAULT_BILLING_CONCURRENCY_LIMITS } from '@/lib/billing/concurrency-defaults' -import { CREDIT_TIERS, CREDITS_PER_DOLLAR, DEFAULT_FREE_CREDITS } from '@/lib/billing/constants' +import { + CREDIT_TIERS, + CREDITS_PER_DOLLAR, + DEFAULT_FREE_CREDITS, + PRO_TRIAL_DAYS, +} from '@/lib/billing/constants' /** * Looks up a credit tier by name, so a column binds to the right tier even if @@ -84,13 +89,17 @@ export const COMPARISON_SECTIONS: ComparisonSection[] = [ 'Custom', ], }, + { + label: 'Free trial for new subscribers', + values: [false, `${PRO_TRIAL_DAYS} days`, false, false], + }, { label: 'Weekly refresh', values: [ false, `+${formatCredits(PRO_TIER.weeklyRefreshCredits)}/week`, `+${formatCredits(MAX_TIER.weeklyRefreshCredits)}/week`, - 'Custom', + false, ], }, { @@ -104,7 +113,7 @@ export const COMPARISON_SECTIONS: ComparisonSection[] = [ rows: [ { label: 'Workspaces', - values: ['1', '3', 'Unlimited', 'Unlimited'], + values: ['1', '3 (unlimited on Teams)', '10 (unlimited on Teams)', 'Unlimited'], }, { label: 'Invite teammates', @@ -131,15 +140,15 @@ export const COMPARISON_SECTIONS: ComparisonSection[] = [ rows: [ { label: 'Sync executions', - values: ['50', '150', '300', 'Custom'], + values: ['50', '150', '300', '600'], }, { label: 'Async executions', - values: ['200', '1,000', '2,500', 'Custom'], + values: ['200', '1,000', '2,500', '5,000'], }, { label: 'API endpoint', - values: ['30', '100', '200', 'Custom'], + values: ['30', '100', '200', '500'], }, ], }, @@ -148,7 +157,7 @@ export const COMPARISON_SECTIONS: ComparisonSection[] = [ rows: [ { label: 'Sync timeout', - values: ['5 min', '50 min', '50 min', 'Custom'], + values: ['5 min', '50 min', '50 min', '50 min'], }, { label: 'Async timeout', @@ -164,12 +173,12 @@ export const COMPARISON_SECTIONS: ComparisonSection[] = [ values: ['5 GB', '50 GB', '500 GB', 'Custom'], }, { - label: 'Max tables', - values: ['5', '100', '1,000', 'Custom'], + label: 'Tables per workspace', + values: ['5', '100', '1,000', '10,000'], }, { label: 'Max rows per table', - values: ['50,000', '100,000', '500,000', 'Custom'], + values: ['50,000', '100,000', '500,000', '1,000,000'], }, { label: 'Log retention', diff --git a/apps/sim/app/workspace/[workspaceId]/upgrade/plan-configs.ts b/apps/sim/app/workspace/[workspaceId]/upgrade/plan-configs.ts index 9b48675f6eb..1cf18f023b4 100644 --- a/apps/sim/app/workspace/[workspaceId]/upgrade/plan-configs.ts +++ b/apps/sim/app/workspace/[workspaceId]/upgrade/plan-configs.ts @@ -28,6 +28,7 @@ export const ENTERPRISE_PLAN_CREDITS: PlanCredits = { export const PRO_PLAN_FEATURES: readonly string[] = [ 'Chat with Sim', + 'Sim-hosted models & tools', `${DEFAULT_BILLING_CONCURRENCY_LIMITS.pro.toLocaleString('en-US')} concurrent executions`, 'Invite teammates', 'Higher rate limits', @@ -37,6 +38,7 @@ export const PRO_PLAN_FEATURES: readonly string[] = [ export const MAX_PLAN_FEATURES: readonly string[] = [ 'Chat with Sim', + 'Sim-hosted models & tools', `${DEFAULT_BILLING_CONCURRENCY_LIMITS.team.toLocaleString('en-US')} concurrent executions`, 'Invite teammates', 'Sim Mailer, KB Live Sync & Sandboxes', diff --git a/apps/sim/app/workspace/[workspaceId]/upgrade/upgrade.tsx b/apps/sim/app/workspace/[workspaceId]/upgrade/upgrade.tsx index b9579208ea7..92d9e6f4063 100644 --- a/apps/sim/app/workspace/[workspaceId]/upgrade/upgrade.tsx +++ b/apps/sim/app/workspace/[workspaceId]/upgrade/upgrade.tsx @@ -15,6 +15,7 @@ import { type UpgradeCardId, } from '@/lib/billing/client' import { ANNUAL_DISCOUNT_RATE } from '@/lib/billing/constants' +import { formatMonthlyPlanPrice } from '@/lib/billing/plan-helpers' import { DEFAULT_UPGRADE_HEADER, UPGRADE_REASON_COPY } from '@/lib/billing/upgrade-reasons' import { canManageWorkspaceBilling } from '@/lib/billing/workspace-permissions' import { useWorkspaceHostContext } from '@/app/workspace/[workspaceId]/providers/workspace-host-provider' @@ -36,6 +37,7 @@ import { upgradeReasonParam, upgradeUrlKeys, } from '@/app/workspace/[workspaceId]/upgrade/search-params' +import { useSubscriptionData } from '@/hooks/queries/subscription' import { useFullscreenOriginStore } from '@/stores/fullscreen-origin/store' /** The demo form, so a sales booking passes the same spam checks as every other. */ @@ -65,9 +67,14 @@ export function Upgrade({ workspaceId }: UpgradeProps) { ...upgradeUrlKeys, }) const [showAllFeatures, setShowAllFeatures] = useState(false) - const header = reason ? UPGRADE_REASON_COPY[reason].header : DEFAULT_UPGRADE_HEADER const canManageBilling = canManageWorkspaceBilling(hostContext, session?.user?.id) + // The trial is a personal checkout, so only a payer viewing their own workspace can start one. + const isPersonalWorkspace = !hostContext.hostOrganizationId + const { data: viewerBilling } = useSubscriptionData({ + enabled: canManageBilling && isPersonalWorkspace, + }) + const proTrialEligible = isPersonalWorkspace && viewerBilling?.data?.proTrialEligible === true const handleBack = useCallback(() => { router.replace(origin ?? `/workspace/${workspaceId}`) @@ -171,7 +178,10 @@ export function Upgrade({ workspaceId }: UpgradeProps) { } } - return { ...cta, onClick } + // Only a personal Pro checkout starts the trial, so only that card says so. + const startsTrial = + card === 'pro' && cta.intent === 'upgrade' && checkoutTarget === 'pro' && proTrialEligible + return { ...cta, ...(startsTrial ? { label: 'Start free trial' } : {}), onClick } } const proCta = resolveCta('pro') @@ -186,12 +196,8 @@ export function Upgrade({ workspaceId }: UpgradeProps) { const maxBanner = state.isOnMax ? 'Your plan' : undefined const discountPct = Math.round(ANNUAL_DISCOUNT_RATE * 100) - const proPrice = state.isAnnual - ? Math.round(state.proTier.dollars * (1 - ANNUAL_DISCOUNT_RATE)) - : state.proTier.dollars - const maxPrice = state.isAnnual - ? Math.round(state.maxTier.dollars * (1 - ANNUAL_DISCOUNT_RATE)) - : state.maxTier.dollars + const proPrice = formatMonthlyPlanPrice(state.proTier.dollars, state.isAnnual) + const maxPrice = formatMonthlyPlanPrice(state.maxTier.dollars, state.isAnnual) const priceSubtext = state.isAnnual ? 'per user/month, billed annually' : 'per user/month, billed monthly' @@ -220,7 +226,7 @@ export function Upgrade({ workspaceId }: UpgradeProps) {
    { files: { 'workflow.ts': `// read ${sourceReads.length}` }, lock: { version: 1, blocks: {}, variables: {} }, base: { + version: 1, workflowId: WORKFLOW_ID, workspaceId: WORKSPACE_ID, fingerprint: `f${sourceReads.length}`, diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/combobox/combobox.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/combobox/combobox.tsx index 2b6deebe620..ad1b752586f 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/combobox/combobox.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/combobox/combobox.tsx @@ -19,13 +19,13 @@ import { useAccessibleReferencePrefixes } from '@/app/workspace/[workspaceId]/w/ import type { SubBlockConfig } from '@/blocks/types' import { useDebounce } from '@/hooks/use-debounce' import { usePermissionConfig } from '@/hooks/use-permission-config' +import { DEFAULT_BLOCK_MODEL } from '@/providers/default-model' import { useWorkflowRegistry } from '@/stores/workflows/registry/store' import { useSubBlockStore } from '@/stores/workflows/subblock/store' /** * Constants for ComboBox component behavior */ -const DEFAULT_MODEL = 'claude-sonnet-5-5' const ZOOM_FACTOR_BASE = 0.96 const MIN_ZOOM = 0.1 const MAX_ZOOM = 1 @@ -308,7 +308,7 @@ export const ComboBox = memo(function ComboBox({ /** * Determines the default option value to use. - * Priority: explicit defaultValue > DEFAULT_MODEL for model field > first option + * Priority: explicit defaultValue > DEFAULT_BLOCK_MODEL for model field > first option */ const defaultOptionValue = useMemo(() => { if (defaultValue !== undefined) { @@ -322,7 +322,7 @@ export const ComboBox = memo(function ComboBox({ if (subBlockId === 'model') { const defaultModelOption = evaluatedOptions.find( - (opt) => getOptionValue(opt) === DEFAULT_MODEL + (opt) => getOptionValue(opt) === DEFAULT_BLOCK_MODEL ) if (defaultModelOption) { return getOptionValue(defaultModelOption) diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/file-upload/file-upload.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/file-upload/file-upload.tsx index c8457d034f0..4b8cee7c0a1 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/file-upload/file-upload.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/file-upload/file-upload.tsx @@ -28,6 +28,7 @@ import { useActiveCanonicalSubBlockValue } from '@/app/workspace/[workspaceId]/w import { useResourceFolders } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-resource-folders' import { useSubBlockValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-value' import { useActiveSearchTarget } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/providers/active-search-target-provider' +import { findConfiguredModelProvider } from '@/blocks/utils' import { invalidateWorkspaceFileReads } from '@/hooks/queries/utils/workspace-file-cache' import { workspaceFileListParams, @@ -42,7 +43,6 @@ import { } from '@/hooks/queries/workspace-files' import { useSearchFilterValue } from '@/hooks/use-search-filter-value' import { getProviderAttachmentMaxBytes } from '@/providers/attachments' -import { getProviderFromModel } from '@/providers/utils' import { useWorkflowRegistry } from '@/stores/workflows/registry/store' import { useWorkflowStore } from '@/stores/workflows/workflow/store' @@ -322,11 +322,9 @@ export function FileUpload({ const maxSizeInBytes = useMemo(() => { const fallback = maxSize * 1024 * 1024 if (typeof modelValue !== 'string' || !modelValue) return fallback - try { - return Math.max(fallback, getProviderAttachmentMaxBytes(getProviderFromModel(modelValue))) - } catch { - return fallback - } + // sim-auto has no provider until routed, and may route images to an inline-only model. + const provider = findConfiguredModelProvider(modelValue) + return provider ? Math.max(fallback, getProviderAttachmentMaxBytes(provider)) : fallback }, [modelValue, maxSize]) const maxSizeLabel = `${Math.round(maxSizeInBytes / (1024 * 1024))}MB` diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.test.ts b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.test.ts index 79b6e14a8e8..3391c26b06e 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.test.ts +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.test.ts @@ -3,6 +3,7 @@ import type { StoredTool } from '@/app/workspace/[workspaceId]/w/[workflowId]/co import { isAgentToolBlock, isCustomToolAlreadySelected, + supportsToolUsageControlForModel, } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/utils' describe('isAgentToolBlock', () => { @@ -47,3 +48,15 @@ describe('already-selected checks', () => { ).toBe(false) }) }) + +describe('supportsToolUsageControlForModel', () => { + it('offers the control for Auto, which falls back to a provider that supports it', () => { + expect(supportsToolUsageControlForModel('agent', 'sim-auto')).toBe(true) + }) + + it('offers it for a supporting provider and never without a model', () => { + expect(supportsToolUsageControlForModel('agent', 'claude-sonnet-5-5')).toBe(true) + expect(supportsToolUsageControlForModel('agent', '')).toBe(false) + expect(supportsToolUsageControlForModel('mothership', '')).toBe(true) + }) +}) diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.tsx index f19e9af9771..7f007010acc 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.tsx @@ -72,6 +72,7 @@ import { isCustomToolAlreadySelected, isMcpToolAlreadySelected, isWorkflowAlreadySelected, + supportsToolUsageControlForModel, } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/utils' import { getActiveWorkflowSearchHighlight } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/workflow-search-highlight' import { useSubBlockValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-value' @@ -105,8 +106,7 @@ import { useCollaborativeWorkflow } from '@/hooks/use-collaborative-workflow' import { useOperationAccess } from '@/hooks/use-operation-access' import { usePermissionConfig } from '@/hooks/use-permission-config' import { useSettingsNavigation } from '@/hooks/use-settings-navigation' -import { supportsForcedToolUse, supportsToolUsageControl } from '@/providers/models' -import { getProviderFromModel } from '@/providers/utils' +import { supportsForcedToolUse } from '@/providers/models' import type { ActiveSearchTarget } from '@/stores/panel/editor/store' import { useSubBlockStore } from '@/stores/workflows/subblock/store' import { useWorkflowStore } from '@/stores/workflows/workflow/store' @@ -603,9 +603,7 @@ export const ToolInput = memo(function ToolInput({ const modelValue = useSubBlockStore((state) => state.getValue(blockId, 'model')) const model = typeof modelValue === 'string' ? modelValue : '' - const provider = model ? getProviderFromModel(model) : '' - const supportsToolControl = - blockType === 'mothership' || (provider ? supportsToolUsageControl(provider) : false) + const supportsToolControl = supportsToolUsageControlForModel(blockType, model) const supportsForce = blockType === 'mothership' || supportsForcedToolUse(model) const { diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/utils.ts b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/utils.ts index 49a0bb1428b..710674aeea2 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/utils.ts +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/utils.ts @@ -1,6 +1,8 @@ import { stripVersionSuffix } from '@sim/utils/string' import type { StoredTool } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/types' import type { BlockConfig } from '@/blocks/types' +import { resolveModelProviderId } from '@/blocks/utils' +import { supportsToolUsageControl } from '@/providers/models' /** * Core blocks the agent tool picker offers even though they are not @@ -71,3 +73,13 @@ export function isWorkflowAlreadySelected( (tool) => tool.type === 'workflow_input' && tool.params?.workflowId === workflowId ) } + +/** + * Whether the tool picker offers the per-tool usage control (auto, force, none) for the + * block's model. Sim Chat always does; any other block asks its model's provider. + */ +export function supportsToolUsageControlForModel(blockType: string, model: string): boolean { + if (blockType === 'mothership') return true + if (!model) return false + return supportsToolUsageControl(resolveModelProviderId(model)) +} diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/workflow-output-selector/workflow-output-selector.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/workflow-output-selector/workflow-output-selector.tsx index bbe921224b8..a611f6302f5 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/workflow-output-selector/workflow-output-selector.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/workflow-output-selector/workflow-output-selector.tsx @@ -11,6 +11,7 @@ interface WorkflowOutputSelectorProps { previewValue?: string[] | null disabled?: boolean placeholder?: string + outputFilter?: { blockType: string; path: string } } export function WorkflowOutputSelector({ @@ -20,6 +21,7 @@ export function WorkflowOutputSelector({ previewValue, disabled = false, placeholder, + outputFilter, }: WorkflowOutputSelectorProps) { const workflowId = useWorkflowRegistry((state) => state.activeWorkflowId) const [storedValue, setStoredValue] = useSubBlockValue(blockId, subBlockId) @@ -34,6 +36,7 @@ export function WorkflowOutputSelector({ onOutputSelect={setStoredValue} disabled={disabled || isPreview} placeholder={placeholder} + outputFilter={outputFilter} valueMode='public' size='md' className='w-full' diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-value.ts b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-value.ts index 6381ff29cba..6192b33f835 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-value.ts +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-value.ts @@ -4,8 +4,8 @@ import { isEqual } from 'es-toolkit' import { useShallow } from 'zustand/react/shallow' import { useStoreWithEqualityFn } from 'zustand/traditional' import { isMcpRuntimeReference } from '@/lib/mcp/operation-policy' +import { findConfiguredModelProvider } from '@/blocks/utils' import { useCollaborativeWorkflow } from '@/hooks/use-collaborative-workflow' -import { getProviderFromModel } from '@/providers/utils' import { useWorkflowDiffStore } from '@/stores/workflow-diff/store' import { useWorkflowRegistry } from '@/stores/workflows/registry/store' import { useSubBlockStore } from '@/stores/workflows/subblock/store' @@ -193,8 +193,8 @@ export function useSubBlockValue( const currentApiKeyValue = useSubBlockStore.getState().getValue(blockId, 'apiKey') if (currentApiKeyValue && currentApiKeyValue !== '') { const oldModelValue = storeValue as string - const oldProvider = oldModelValue ? getProviderFromModel(oldModelValue) : null - const newProvider = getProviderFromModel(newValue) + const oldProvider = oldModelValue ? findConfiguredModelProvider(oldModelValue) : null + const newProvider = findConfiguredModelProvider(newValue) if (oldProvider !== newProvider) { collaborativeSetSubblockValue(blockId, 'apiKey', '') } diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/sub-block.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/sub-block.tsx index 9607c3b70a5..59658cb5ee4 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/sub-block.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/sub-block.tsx @@ -1152,6 +1152,7 @@ function SubBlockComponent({ previewValue={previewValue as string[] | null | undefined} disabled={isDisabled} placeholder={config.placeholder} + outputFilter={config.outputFilter} /> ) diff --git a/apps/sim/background/schedule-execution.ts b/apps/sim/background/schedule-execution.ts index eeabc810762..62f9ace19b1 100644 --- a/apps/sim/background/schedule-execution.ts +++ b/apps/sim/background/schedule-execution.ts @@ -16,6 +16,7 @@ import { assertBillingAttributionSnapshot, type BillingAttributionSnapshot, } from '@/lib/billing/core/attribution' +import { isHostedKeyPaidPlanFailure } from '@/lib/billing/core/hosted-key-access' import { classifyTransientAdmissionFailure } from '@/lib/core/admission/transient-failure' import type { AsyncExecutionCorrelation } from '@/lib/core/async-jobs/types' import { @@ -98,7 +99,8 @@ function resetScheduleInfraRetryCount(): Pick { + const needsPaidPlan = isHostedKeyPaidPlanFailure(params.failureMessage) + const outcome = await applyScheduleUpdate( + params.scheduleId, + buildScheduleFailureUpdate(params.now, params.nextRunAt, { disable: needsPaidPlan }), + params.requestId, + params.context, + { + expectedLastQueuedAt: params.expectedLastQueuedAt, + disableReason: needsPaidPlan ? 'paid_plan_required' : 'consecutive_failures', + } + ) + return { updated: outcome.updated, disabled: outcome.status === 'disabled' } +} + type RunWorkflowResult = | { status: 'skip' @@ -1192,11 +1223,15 @@ export async function executeScheduleJob( const nextRunAt = calculateNextRunTime(payload, executionResult.blocks) - await updateClaimedSchedule( - buildScheduleFailureUpdate(now, nextRunAt), - `Error updating schedule ${payload.scheduleId} after failure`, - 'consecutive_failures' - ) + await applyScheduleRunFailureUpdate({ + scheduleId: payload.scheduleId, + now, + nextRunAt, + expectedLastQueuedAt: claimedAt, + requestId, + context: `Error updating schedule ${payload.scheduleId} after failure`, + failureMessage: executionResult.executionResult.error, + }) } catch (error: unknown) { logger.error( `Error executing scheduled workflow ${payload.workflowId}`, @@ -1206,11 +1241,15 @@ export async function executeScheduleJob( const nextRunAt = await determineNextRunAfterError(payload, now, requestId) - await updateClaimedSchedule( - buildScheduleFailureUpdate(now, nextRunAt), - `Error updating schedule ${payload.scheduleId} after execution error`, - 'consecutive_failures' - ) + await applyScheduleRunFailureUpdate({ + scheduleId: payload.scheduleId, + now, + nextRunAt, + expectedLastQueuedAt: claimedAt, + requestId, + context: `Error updating schedule ${payload.scheduleId} after execution error`, + failureMessage: toError(error).message, + }) } } catch (error: unknown) { try { @@ -1229,8 +1268,8 @@ export async function executeScheduleJob( ) } catch (recoveryError: unknown) { // A secondary failure during error recovery (e.g. a transient DB blip while - // releasing the claim or scheduling an infra retry) must not fault the run. The - // claim expires on its TTL and the next tick re-claims the schedule. Record the + // releasing the claim or scheduling an infra retry) must not fault the run. A + // tick re-examines the held claim after the claim recheck window. Record the // exception on the span so it stays visible in traces without faulting the run. logger.error( `Failed to recover schedule ${payload.scheduleId} after error`, diff --git a/apps/sim/blocks/blocks/agent.test.ts b/apps/sim/blocks/blocks/agent.test.ts index c701852780e..05936948cfb 100644 --- a/apps/sim/blocks/blocks/agent.test.ts +++ b/apps/sim/blocks/blocks/agent.test.ts @@ -112,4 +112,16 @@ describe('AgentBlock', () => { }) }) }) + + describe('tools.config.tool function', () => { + const toolFunction = AgentBlock.tools.config?.tool + + it('records the provider sim-auto falls back to, since it has none of its own', () => { + expect(toolFunction?.({ model: 'sim-auto' })).toBe('anthropic') + }) + + it('falls back to the same provider when no model is set', () => { + expect(toolFunction?.({})).toBe('anthropic') + }) + }) }) diff --git a/apps/sim/blocks/blocks/agent.ts b/apps/sim/blocks/blocks/agent.ts index 816a7232fe4..8316335b58a 100644 --- a/apps/sim/blocks/blocks/agent.ts +++ b/apps/sim/blocks/blocks/agent.ts @@ -8,10 +8,11 @@ import { getAgentModelOptions, getModelCapabilityCondition, getProviderCredentialSubBlocks, - getSerializedModelProviderId, normalizeFileInput, RESPONSE_FORMAT_WAND_CONFIG, + resolveModelProviderId, } from '@/blocks/utils' +import { DEFAULT_BLOCK_MODEL } from '@/providers/default-model' import { getBaseModelProviders, getEvaluationModels, @@ -24,15 +25,11 @@ import { getReasoningEffortValuesForModel, getThinkingLevelsForModel, getVerbosityValuesForModel, - isAutoModel, supportsTemperature, } from '@/providers/models' const logger = createLogger('AgentBlock') -/** Model the agent block falls back to when `model` is unset or the auto pseudo-model. */ -const AGENT_FALLBACK_MODEL = 'claude-sonnet-5-5' - const MODELS_WITH_REASONING_EFFORT = getModelsWithReasoningEffort() const MODELS_WITH_VERBOSITY = getModelsWithVerbosity() const MODELS_WITH_THINKING = getModelsWithThinking() @@ -130,7 +127,7 @@ Return ONLY the JSON array.`, type: 'combobox', placeholder: 'Type or select a model...', required: true, - defaultValue: 'claude-sonnet-5-5', + defaultValue: DEFAULT_BLOCK_MODEL, options: getAgentModelOptions, commandSearchable: true, }, @@ -428,10 +425,7 @@ Return ONLY the JSON array.`, ], config: { tool: (params: Record) => { - const model = params.model || AGENT_FALLBACK_MODEL - // sim-auto has no provider of its own until the pool resolves it at execution time. - const lookupModel = isAutoModel(model) ? AGENT_FALLBACK_MODEL : model - return getSerializedModelProviderId(lookupModel, AGENT_FALLBACK_MODEL) + return resolveModelProviderId(params.model) }, params: (params: Record) => { const normalizedFiles = normalizeFileInput(params.files) diff --git a/apps/sim/blocks/blocks/api.ts b/apps/sim/blocks/blocks/api.ts index 9c0f51140b2..3159006761a 100644 --- a/apps/sim/blocks/blocks/api.ts +++ b/apps/sim/blocks/blocks/api.ts @@ -103,34 +103,37 @@ Example: }, { id: 'retries', - title: 'Retries', + title: 'Request retries', type: 'short-input', placeholder: '0', description: - 'Number of retry attempts after a timeout, a connection reset, a 429 or a 5xx response (default: 0, no retries). A host that does not resolve or refuses the connection fails without retrying.', + 'Times to resend the HTTP request within one run of this block (default: 0, max: 10), only after a timeout, a connection reset, a 429 or a 5xx response, and only for GET, HEAD, PUT and DELETE unless Retry non-idempotent methods is on. A host that does not resolve or refuses the connection, and any other 4xx, fail at once. Separate from the block retry setting, which reruns the whole block, these request retries included, after any failure.', mode: 'advanced', }, { id: 'retryDelayMs', - title: 'Retry delay (ms)', + title: 'Request retry delay (ms)', type: 'short-input', placeholder: '500', - description: 'Initial retry delay in milliseconds (exponential backoff)', + description: + 'Wait before the first request retry in milliseconds (default: 500); it doubles each retry, with jitter, up to the max request retry delay. Not the block retry wait between tries.', mode: 'advanced', }, { id: 'retryMaxDelayMs', - title: 'Max retry delay (ms)', + title: 'Max request retry delay (ms)', type: 'short-input', placeholder: '30000', - description: 'Maximum delay between retries in milliseconds', + description: + 'Longest wait between request retries in milliseconds (default: 30000). A Retry-After header asking for longer ends the retries.', mode: 'advanced', }, { id: 'retryNonIdempotent', title: 'Retry non-idempotent methods', type: 'switch', - description: 'Allow retries for POST/PATCH requests (may create duplicate requests)', + description: + 'Also resend POST, PATCH and other non-idempotent requests on request retries (may create duplicates).', mode: 'advanced', }, { @@ -169,15 +172,19 @@ Example: body: { type: 'json', description: 'Request body data' }, params: { type: 'json', description: 'URL query parameters' }, timeout: { type: 'number', description: 'Request timeout in milliseconds' }, - retries: { type: 'number', description: 'Number of retry attempts for retryable failures' }, - retryDelayMs: { type: 'number', description: 'Initial retry delay in milliseconds' }, + retries: { + type: 'number', + description: + 'Times to resend the HTTP request after a timeout, connection reset, 429 or 5xx (not the block retry setting)', + }, + retryDelayMs: { type: 'number', description: 'Wait before the first request retry in ms' }, retryMaxDelayMs: { type: 'number', - description: 'Maximum delay between retries in milliseconds', + description: 'Longest wait between request retries in ms', }, retryNonIdempotent: { type: 'boolean', - description: 'Allow retries for non-idempotent methods like POST/PATCH', + description: 'Also resend POST, PATCH and other non-idempotent requests on request retries', }, redirectPolicyVersion: { type: 'string', @@ -193,7 +200,11 @@ Example: }, }, outputs: { - data: { type: 'json', description: 'API response data (JSON, text, or other formats)' }, + data: { + type: 'json', + description: 'API response data (JSON, text, or other formats)', + mayBeText: true, + }, status: { type: 'number', description: 'HTTP status code (200, 404, 500, etc.)' }, headers: { type: 'json', description: 'HTTP response headers as key-value pairs' }, }, diff --git a/apps/sim/blocks/blocks/evaluator.ts b/apps/sim/blocks/blocks/evaluator.ts index 11708998be6..95890acf151 100644 --- a/apps/sim/blocks/blocks/evaluator.ts +++ b/apps/sim/blocks/blocks/evaluator.ts @@ -4,11 +4,12 @@ import { getModelFallbackSubBlock, MODEL_FALLBACK_INPUTS } from '@/blocks/model- import type { BlockConfig, ParamType } from '@/blocks/types' import { BEDROCK_SAVED_CREDENTIAL_INPUTS, - getModelOptions, + getModelOptionsWithAuto, getProviderCredentialSubBlocks, - getSerializedModelProviderId, PROVIDER_CREDENTIAL_INPUTS, + resolveModelProviderId, } from '@/blocks/utils' +import { DEFAULT_BLOCK_MODEL } from '@/providers/default-model' const logger = createLogger('EvaluatorBlock') @@ -168,8 +169,8 @@ export const EvaluatorBlock: BlockConfig = { type: 'combobox', placeholder: 'Type or select a model...', required: true, - defaultValue: 'claude-sonnet-5-5', - options: getModelOptions, + defaultValue: DEFAULT_BLOCK_MODEL, + options: getModelOptionsWithAuto, }, ...getProviderCredentialSubBlocks({ bedrockSavedCredential: true }), getModelFallbackSubBlock(), @@ -236,7 +237,7 @@ export const EvaluatorBlock: BlockConfig = { 'deepseek_reasoner', ], config: { - tool: (params: Record) => getSerializedModelProviderId(params.model), + tool: (params: Record) => resolveModelProviderId(params.model), }, }, inputs: { diff --git a/apps/sim/blocks/blocks/function.ts b/apps/sim/blocks/blocks/function.ts index c5456c532fc..3dde96bf241 100644 --- a/apps/sim/blocks/blocks/function.ts +++ b/apps/sim/blocks/blocks/function.ts @@ -172,7 +172,11 @@ try { }, }, outputs: { - result: { type: 'json', description: 'Structured result emitted by the executed code' }, + result: { + type: 'json', + description: 'Structured result emitted by the executed code', + mayBeText: true, + }, stdout: { type: 'string', description: 'Console log output and debug messages from function execution', @@ -182,4 +186,11 @@ try { description: `Files the code wrote to ${SANDBOX_OUTPUT_DIR}, ready to attach or upload downstream`, }, }, + errorOutputs: { + errorMessage: { + type: 'string', + description: + 'The thrown message alone, without the line and code that error leads with. Use it in a reply to a caller.', + }, + }, } diff --git a/apps/sim/blocks/blocks/microsoft_dynamics_365.test.ts b/apps/sim/blocks/blocks/microsoft_dynamics_365.test.ts index ac0577a9b2e..ce8e159134d 100644 --- a/apps/sim/blocks/blocks/microsoft_dynamics_365.test.ts +++ b/apps/sim/blocks/blocks/microsoft_dynamics_365.test.ts @@ -414,7 +414,7 @@ describe('MicrosoftDynamics365Block tool-call mapping', () => { vi.mocked(getToolMetadata).mockImplementationOnce(lookup).mockImplementationOnce(lookup) function lookup(toolId: string) { const tool = rowTools.find((candidate) => candidate.id === toolId) - return tool && { id: tool.id, params: tool.params } + return tool && { id: tool.id, effect: tool.effect, params: tool.params } } const rowFields = (toolId: string, operation: string) => getSubBlocksForToolInput( diff --git a/apps/sim/blocks/blocks/pi.ts b/apps/sim/blocks/blocks/pi.ts index fed7c3ee8ee..074d0a69ce3 100644 --- a/apps/sim/blocks/blocks/pi.ts +++ b/apps/sim/blocks/blocks/pi.ts @@ -1,5 +1,5 @@ import { PiIcon } from '@/components/icons' -import { getEnv, isTruthy } from '@/lib/core/config/env' +import { getDeploymentShape } from '@/lib/core/config/deployment-shape' import type { BlockConfig } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' import { @@ -164,7 +164,7 @@ export const PiBlock: BlockConfig = { title: 'Mode', type: 'dropdown', /** Cloud modes require E2B and stay hidden when it is disabled. */ - value: () => (isTruthy(getEnv('NEXT_PUBLIC_E2B_ENABLED')) ? 'cloud' : 'local'), + value: () => (getDeploymentShape().e2bEnabled ? 'cloud' : 'local'), options: () => { const options = [ { @@ -173,7 +173,7 @@ export const PiBlock: BlockConfig = { description: 'Edits files on your own machine over SSH', }, ] - if (isTruthy(getEnv('NEXT_PUBLIC_E2B_ENABLED'))) { + if (getDeploymentShape().e2bEnabled) { options.unshift( { label: 'Create PR', diff --git a/apps/sim/blocks/blocks/router.ts b/apps/sim/blocks/blocks/router.ts index a978d261f18..60aa7ef7436 100644 --- a/apps/sim/blocks/blocks/router.ts +++ b/apps/sim/blocks/blocks/router.ts @@ -3,11 +3,12 @@ import { getModelFallbackSubBlock, MODEL_FALLBACK_INPUTS } from '@/blocks/model- import { AuthMode, type BlockConfig } from '@/blocks/types' import { BEDROCK_SAVED_CREDENTIAL_INPUTS, - getModelOptions, + getModelOptionsWithAuto, getProviderCredentialSubBlocks, - getSerializedModelProviderId, PROVIDER_CREDENTIAL_INPUTS, + resolveModelProviderId, } from '@/blocks/utils' +import { DEFAULT_BLOCK_MODEL } from '@/providers/default-model' interface TargetBlock { id: string @@ -161,8 +162,8 @@ export const RouterBlock: BlockConfig = { type: 'combobox', placeholder: 'Type or select a model...', required: true, - defaultValue: 'claude-sonnet-5-5', - options: getModelOptions, + defaultValue: DEFAULT_BLOCK_MODEL, + options: getModelOptionsWithAuto, }, ...getProviderCredentialSubBlocks({ bedrockSavedCredential: true }), getModelFallbackSubBlock(), @@ -194,7 +195,7 @@ export const RouterBlock: BlockConfig = { 'deepseek_reasoner', ], config: { - tool: (params: Record) => getSerializedModelProviderId(params.model), + tool: (params: Record) => resolveModelProviderId(params.model), }, }, inputs: { @@ -253,8 +254,8 @@ export const RouterV2Block: BlockConfig = { type: 'combobox', placeholder: 'Type or select a model...', required: true, - defaultValue: 'claude-sonnet-5-5', - options: getModelOptions, + defaultValue: DEFAULT_BLOCK_MODEL, + options: getModelOptionsWithAuto, }, ...getProviderCredentialSubBlocks({ bedrockSavedCredential: true }), getModelFallbackSubBlock(), @@ -269,7 +270,7 @@ export const RouterV2Block: BlockConfig = { 'deepseek_reasoner', ], config: { - tool: (params: Record) => getSerializedModelProviderId(params.model), + tool: (params: Record) => resolveModelProviderId(params.model), }, }, inputs: { diff --git a/apps/sim/blocks/blocks/slack.ts b/apps/sim/blocks/blocks/slack.ts index 5ff889943bf..b7d9502124a 100644 --- a/apps/sim/blocks/blocks/slack.ts +++ b/apps/sim/blocks/blocks/slack.ts @@ -3551,6 +3551,7 @@ export const SlackV2Block: BlockConfig = { 'Build Slack workflows with messages, conversations, files, reactions, pins, bookmarks, user groups, profiles, Lists, canvases, and Agent Sessions. Operations that need additional app scopes use custom Slack bots. Lists require lists:read/lists:write and a paid Slack plan. Native Sim connections retain their existing permissions. Page through list outputs explicitly.', bestPractices: `${SlackBlock.bestPractices} Native agent-session streaming uses a custom Slack bot and a supported trigger event. Enable streamResponse and select the intended outputs in streamOutputs; Sim Chat (mothership) streams its content output. The trigger owns the streamed reply, so another send needs a separate purpose. +To show an Agent's tool steps without posting its text (for example an analyst whose output a later block reviews), list that Agent in streamTimelineSources while streamOutputs keeps the block that posts the answer (a block cannot be in both), and optionally name its tools in streamToolLabels. The custom-bot manifest's baseline agent scopes are ${SLACK_AGENT_SCOPES.join(', ')}. Selected capabilities add their required scopes and event subscriptions. Verify the installed app's grants, resource access and event configuration; a saved credential or edited manifest alone does not prove access. streamIncludeToolCalls displays tool activity; it does not authorize tool execution. Configure Sim Chat's selected operations and their credentials separately. Choose streamIncludeThinking deliberately for the destination audience. Block Kit messages can contain buttons, selects and forms, but interactions require the app's interactivity request URL and the corresponding interaction trigger. Treat message events, button/select callbacks and modal submissions as separate paths. A control's action_id/value correlates work; runtime actor and state checks authorize it.`, diff --git a/apps/sim/blocks/blocks/table.ts b/apps/sim/blocks/blocks/table.ts index cee3e621c26..0eba39cf6bc 100644 --- a/apps/sim/blocks/blocks/table.ts +++ b/apps/sim/blocks/blocks/table.ts @@ -9,8 +9,11 @@ import { mapperOperation, parseOptionalNumberInput, resolveTableColumnSelection, + TABLE_IGNORED_COLUMNS_OUTPUT, TABLE_OUTPUT_COLUMNS_INPUT, TABLE_OUTPUT_COLUMNS_SUBBLOCK, + TABLE_ROW_OUTPUT, + TABLE_ROWS_OUTPUT, toolCallArg, } from '@/blocks/utils' import { TABLE_ID_PARAM } from '@/tools/table/params' @@ -440,7 +443,7 @@ Return ONLY the data JSON:`, type: 'short-input', canonicalParamId: 'conflictColumn', mode: 'advanced', - placeholder: 'Enter the column id', + placeholder: 'Enter the column name', dependsOn: ['tableId'], condition: { field: 'operation', value: 'upsert_row' }, }, @@ -809,30 +812,19 @@ Return ONLY the sort JSON:`, conflictColumn: { type: 'string', description: - 'Unique column to match on for upsert (required if the table has multiple unique columns)', + 'Unique column (name or id) to match on for upsert (required if the table has multiple unique columns)', }, }, outputs: { success: { type: 'boolean', description: 'Operation success status' }, - row: { - type: 'json', - description: 'Single row data', - condition: { - field: 'operation', - value: ['get_row', 'insert_row', 'upsert_row', 'update_row'], - }, - }, + row: TABLE_ROW_OUTPUT, operation: { type: 'string', description: 'Operation performed (insert or update)', condition: { field: 'operation', value: 'upsert_row' }, }, - rows: { - type: 'array', - description: 'Array of rows', - condition: { field: 'operation', value: ['query_rows', 'batch_insert_rows'] }, - }, + rows: TABLE_ROWS_OUTPUT, rowCount: { type: 'number', description: 'Rows returned (query) or total rows in the table (get schema)', @@ -888,6 +880,7 @@ Return ONLY the sort JSON:`, description: "Max rows per table for the workspace's plan", condition: { field: 'operation', value: 'get_schema' }, }, + ignoredColumns: TABLE_IGNORED_COLUMNS_OUTPUT, message: { type: 'string', description: 'Operation status message' }, }, triggers: { diff --git a/apps/sim/blocks/blocks/table_v2.ts b/apps/sim/blocks/blocks/table_v2.ts index e7e303b2934..7c260cc254e 100644 --- a/apps/sim/blocks/blocks/table_v2.ts +++ b/apps/sim/blocks/blocks/table_v2.ts @@ -16,8 +16,11 @@ import { failToolCallOnError, mapperOperation, resolveTableColumnSelection, + TABLE_IGNORED_COLUMNS_OUTPUT, TABLE_OUTPUT_COLUMNS_INPUT, TABLE_OUTPUT_COLUMNS_SUBBLOCK, + TABLE_ROW_OUTPUT, + TABLE_ROWS_OUTPUT, toolCallArg, } from '@/blocks/utils' import { TABLE_ID_PARAM } from '@/tools/table/params' @@ -412,7 +415,7 @@ Return ONLY the data JSON:`, type: 'short-input', canonicalParamId: 'conflictColumn', mode: 'advanced', - placeholder: 'Enter the column id', + placeholder: 'Enter the column name', dependsOn: ['tableId'], condition: { field: 'operation', value: 'upsert_row' }, }, @@ -604,30 +607,19 @@ Return ONLY the JSON object:`, conflictColumn: { type: 'string', description: - 'Unique column to match on for upsert (required if the table has multiple unique columns)', + 'Unique column (name or id) to match on for upsert (required if the table has multiple unique columns)', }, }, outputs: { success: { type: 'boolean', description: 'Operation success status' }, - row: { - type: 'json', - description: 'Single row data', - condition: { - field: 'operation', - value: ['get_row', 'insert_row', 'upsert_row', 'update_row'], - }, - }, + row: TABLE_ROW_OUTPUT, operation: { type: 'string', description: 'Operation performed (insert or update)', condition: { field: 'operation', value: 'upsert_row' }, }, - rows: { - type: 'array', - description: 'Array of rows', - condition: { field: 'operation', value: ['query_rows', 'batch_insert_rows'] }, - }, + rows: TABLE_ROWS_OUTPUT, rowCount: { type: 'number', description: 'Rows returned (query) or total rows in the table (get schema)', @@ -688,6 +680,7 @@ Return ONLY the JSON object:`, description: "Max rows per table for the workspace's plan", condition: { field: 'operation', value: 'get_schema' }, }, + ignoredColumns: TABLE_IGNORED_COLUMNS_OUTPUT, message: { type: 'string', description: 'Operation status message' }, }, triggers: { diff --git a/apps/sim/blocks/types.ts b/apps/sim/blocks/types.ts index 9741d29939d..54efa034522 100644 --- a/apps/sim/blocks/types.ts +++ b/apps/sim/blocks/types.ts @@ -393,6 +393,8 @@ export interface SubBlockConfig { min?: number max?: number columns?: string[] + /** Limits a `workflow-output-selector` to blocks of one type, each selecting `path`. */ + outputFilter?: { blockType: string; path: string } placeholder?: string /** * Conceals the stored value in the editor until the field is focused. @@ -724,6 +726,13 @@ export interface BlockConfig { url: string } } + /** + * Text outputs the block writes only when it fails into an error edge, beside the `error` + * every failed block writes (`BlockExecutor.handleBlockError`). A reference to one is valid + * exactly where `` is: a successful run resolves it empty, and workflow source + * checks it against the block's `onError` edge as it does `error`. + */ + errorOutputs?: Record hideFromToolbar?: boolean /** * For published custom blocks only: the bound source workflow's id. Discovery diff --git a/apps/sim/blocks/utils.test.ts b/apps/sim/blocks/utils.test.ts index 9d81b8f0d4e..5db6ba4e670 100644 --- a/apps/sim/blocks/utils.test.ts +++ b/apps/sim/blocks/utils.test.ts @@ -1,7 +1,7 @@ import { resetEnvFlagsMock, setEnvFlags } from '@sim/testing' import { oauthUtilsMock } from '@sim/testing/mocks/oauth-utils.mock' import { providersUtilsMock } from '@sim/testing/mocks/providers-utils.mock' -import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest' afterAll(resetEnvFlagsMock) @@ -26,6 +26,9 @@ const { mockProviders } = vi.hoisted(() => ({ litellm: { models: [] as string[], isLoading: false }, openrouter: { models: [] as string[], isLoading: false }, fireworks: { models: [] as string[], isLoading: false }, + 'ollama-cloud': { models: [] as string[], isLoading: false }, + together: { models: [] as string[], isLoading: false }, + baseten: { models: [] as string[], isLoading: false }, }, }, })) @@ -62,16 +65,21 @@ import { evaluateSubBlockCondition } from '@sim/workflow-code/catalog/canonical- import { S3Icon } from '@/components/icons' import type { BlockConfig } from '@/blocks/types' import { + findConfiguredModelProvider, + getAgentModelOptions, getApiKeyCondition, + getModelOptions, + getModelOptionsWithAuto, getProviderCredentialSubBlocks, getSelectedBedrockCredential, - getSerializedModelProviderId, parseOptionalBooleanInput, parseOptionalJsonInput, parseOptionalNumberInput, requiresProviderFamilyCredentials, + resolveModelProviderId, withSavedCredential, } from '@/blocks/utils' +import { DEFAULT_BLOCK_MODEL } from '@/providers/default-model' import { getProviderFromModel } from '@/providers/utils' const BASE_CLOUD_MODELS: Record = { @@ -213,6 +221,9 @@ describe('getApiKeyCondition / shouldRequireApiKeyForModel', () => { litellm: { models: [], isLoading: false }, openrouter: { models: [], isLoading: false }, fireworks: { models: [], isLoading: false }, + 'ollama-cloud': { models: [], isLoading: false }, + together: { models: [], isLoading: false }, + baseten: { models: [], isLoading: false }, } mockGetHostedModels.mockReturnValue([]) mockGetProviderModels.mockReturnValue([]) @@ -323,33 +334,101 @@ describe('parseOptionalBooleanInput', () => { }) }) -describe('getSerializedModelProviderId', () => { +describe('model options', () => { + const ids = (options: { id: string }[]) => options.map(({ id }) => id) + + const empty = { models: [] as string[], isLoading: false } + const originalProviders = mockProviders.value + + beforeEach(() => { + mockProviders.value = { + base: { models: ['gpt-4o'], isLoading: false }, + ollama: empty, + 'ollama-cloud': empty, + vllm: empty, + litellm: empty, + openrouter: empty, + fireworks: empty, + together: empty, + baseten: empty, + } + }) + + afterEach(() => { + mockProviders.value = originalProviders + setEnvFlags({ isHosted: false }) + }) + + it('offers Auto on hosted Sim only to blocks that resolve it through the model router', () => { + setEnvFlags({ isHosted: true }) + + expect(ids(getModelOptions())).toEqual(['gpt-4o']) + expect(ids(getModelOptionsWithAuto())).toEqual(['gpt-4o', 'sim-auto']) + expect(ids(getAgentModelOptions())).toEqual(['gpt-4o', 'sim-auto']) + }) + + it('never offers Auto on self-hosted Sim', () => { + expect(ids(getModelOptionsWithAuto())).toEqual(['gpt-4o']) + expect(ids(getAgentModelOptions())).toEqual(['gpt-4o']) + }) +}) + +describe('resolveModelProviderId', () => { const resolver = vi.mocked(getProviderFromModel) beforeEach(() => { resolver.mockReset() resolver.mockImplementation(((model: string) => { if (model.startsWith('openrouter/')) return 'openrouter' - if (model === 'gpt-4o') return 'openai' - if (model === 'claude-sonnet-5') return 'anthropic' + if (model === DEFAULT_BLOCK_MODEL) return 'anthropic' throw new Error(`No provider found for model: ${model}`) }) as unknown as typeof getProviderFromModel) }) it('resolves a gateway model that the base model map deliberately omits', () => { - expect(getSerializedModelProviderId('openrouter/meta-llama/llama-4-maverick')).toBe( - 'openrouter' - ) + expect(resolveModelProviderId('openrouter/meta-llama/llama-4-maverick')).toBe('openrouter') }) - it('uses the fallback model when the model is still an unresolved reference', () => { - expect(getSerializedModelProviderId('openrouter/')).toBe('openai') + it('uses the default block model when the model is unset or still an unresolved reference', () => { + expect(resolveModelProviderId('openrouter/')).toBe('anthropic') + expect(resolveModelProviderId(undefined)).toBe('anthropic') expect(resolver).not.toHaveBeenCalledWith('openrouter/') }) + it('looks up sim-auto as the model it falls back to, never as itself', () => { + expect(resolveModelProviderId('sim-auto')).toBe('anthropic') + expect(resolveModelProviderId(' SIM-AUTO ')).toBe('anthropic') + expect(resolver).toHaveBeenCalledWith(DEFAULT_BLOCK_MODEL) + expect(resolver).not.toHaveBeenCalledWith('sim-auto') + expect(resolver).not.toHaveBeenCalledWith(' SIM-AUTO ') + }) + it('never throws when the resolver rejects the model', () => { - expect(() => getSerializedModelProviderId('totally-unknown-model')).not.toThrow() - expect(getSerializedModelProviderId('totally-unknown-model')).toBe('openai') + expect(() => resolveModelProviderId('totally-unknown-model')).not.toThrow() + expect(resolveModelProviderId('totally-unknown-model')).toBe('openai') + }) +}) + +describe('findConfiguredModelProvider', () => { + const resolver = vi.mocked(getProviderFromModel) + + beforeEach(() => { + resolver.mockReset() + resolver.mockImplementation(((model: string) => { + if (model.startsWith('openrouter/')) return 'openrouter' + if (model === 'sim-auto') throw new Error('sim-auto has no provider') + if (model === 'blacklisted-model') throw new Error('blacklisted') + return 'anthropic' + }) as unknown as typeof getProviderFromModel) + }) + + it('keeps the explicit namespace of a model reference', () => { + expect(findConfiguredModelProvider('openrouter/')).toBe('openrouter') + }) + + it('names no provider for sim-auto or a blacklisted model', () => { + expect(findConfiguredModelProvider('sim-auto')).toBeNull() + expect(findConfiguredModelProvider('blacklisted-model')).toBeNull() }) }) diff --git a/apps/sim/blocks/utils.ts b/apps/sim/blocks/utils.ts index 60e5a75d7ff..cc0bcff444e 100644 --- a/apps/sim/blocks/utils.ts +++ b/apps/sim/blocks/utils.ts @@ -8,7 +8,13 @@ import type { SelectorKey } from '@/lib/selectors/manifest' import { containsReference } from '@/lib/workflows/sanitization/references' import { getDependsOnFields } from '@/lib/workflows/subblocks/dependencies' import { isTriggerModeSubBlock } from '@/lib/workflows/subblocks/visibility' -import type { BlockConfig, BlockToolParamsContext, SubBlockConfig } from '@/blocks/types' +import type { + BlockConfig, + BlockToolParamsContext, + OutputFieldDefinition, + SubBlockConfig, +} from '@/blocks/types' +import { DEFAULT_BLOCK_MODEL } from '@/providers/default-model' import { findProviderFromModel, getBaseModelProviders, @@ -31,6 +37,7 @@ import { SAVED_CREDENTIAL_OAUTH, type SavedCredentialService, } from '@/tools/shared/saved-credentials' +import { IGNORED_COLUMNS_OUTPUT } from '@/tools/table/types' export const AZURE_MODELS = [ ...getProviderModels('azure-openai'), @@ -232,18 +239,47 @@ function dependOnCredential( } /** - * Returns model options for combobox subblocks, combining all provider sources. + * Model options for a combobox whose block sends the chosen model straight to its provider: + * every provider source, without the sim-auto pseudo-model, which only a block that runs + * the model router can resolve. */ export function getModelOptions() { - return buildModelOptions(false) + return buildModelOptions({ includeEvaluation: false, includeAuto: false }) } -/** Agent supports both conversational and native evaluation models. */ +/** + * {@link getModelOptions} plus Auto (hosted only), for a block whose handler resolves + * sim-auto through the model router before any provider lookup (router, evaluator). + */ +export function getModelOptionsWithAuto() { + return buildModelOptions({ includeEvaluation: false, includeAuto: true }) +} + +/** Agent supports Auto and both conversational and native evaluation models. */ export function getAgentModelOptions() { - return buildModelOptions(true) + return buildModelOptions({ includeEvaluation: true, includeAuto: true }) } -function buildModelOptions(includeEvaluation: boolean) { +/** + * The model-option sources whose values editing validation checks against Sim's model + * catalog, and whether each offers Auto (so accepts sim-auto on hosted Sim). + * + * {@link getAgentModelOptions} is deliberately absent: the agent's model field also takes + * free-typed ids (Bedrock inference profiles, fine-tunes) and retired ids, so validation + * passes its values through unchanged. + */ +export const MODEL_OPTION_SOURCES: ReadonlyMap = new Map([ + [getModelOptions, { auto: false }], + [getModelOptionsWithAuto, { auto: true }], +]) + +function buildModelOptions({ + includeEvaluation, + includeAuto, +}: { + includeEvaluation: boolean + includeAuto: boolean +}) { const providersState = useProvidersStore.getState() const baseModels = orderModelIdsByReleaseDate(providersState.providers.base.models) const ollamaModels = providersState.providers.ollama.models @@ -282,7 +318,7 @@ function buildModelOptions(includeEvaluation: boolean) { // Hosted-only automatic model. Deliberately LAST in the list (limited // visibility for the initial release): available to anyone who scrolls or // searches for it, but never the first thing the dropdown offers. - if (getDeploymentShape().hosted) { + if (includeAuto && getDeploymentShape().hosted) { options.push({ label: 'Auto', id: SIM_AUTO_MODEL_ID, icon: SimAutoIcon }) } @@ -316,12 +352,12 @@ function getProviderFromStore(model: string): string | null { } /** - * Whether an Ollama instance is available. `isOllamaConfigured` reads the + * Whether this browser knows of an Ollama instance. `isOllamaConfigured` reads the * server-only `OLLAMA_URL` env var, which is always undefined in the browser — * there the providers store (populated from the server's model list, which is * non-empty only when Ollama is configured) is the signal. */ -function isOllamaAvailable(): boolean { +function hasOllamaInstance(): boolean { if (isOllamaConfigured) return true return useProvidersStore.getState().providers.ollama.models.length > 0 } @@ -381,7 +417,7 @@ export function shouldRequireApiKeyForModel(model: string): boolean { return false if (storeProvider) return true - if (isOllamaAvailable()) { + if (hasOllamaInstance()) { if (normalizedModel.includes('/')) return true if (normalizedModel in getBaseModelProviders()) return true return false @@ -390,37 +426,35 @@ export function shouldRequireApiKeyForModel(model: string): boolean { return true } -/** Model whose provider is recorded when a block's own `model` cannot be resolved. */ -const SERIALIZATION_FALLBACK_MODEL = 'gpt-4o' - -/** Last-resort provider for when even {@link SERIALIZATION_FALLBACK_MODEL} cannot be resolved. */ +/** Provider recorded when the model's own lookup throws (a blacklisted provider or model). */ const SERIALIZATION_FALLBACK_PROVIDER: ProviderId = 'openai' /** - * Provider id a model-driven block records for `model` during serialization. + * Best-effort provider id for a model a block has not executed yet, for serialization and + * the editor's tool-usage control. Editor decisions about the provider the user configured + * use {@link findConfiguredModelProvider} instead. * * Serialization runs before variable resolution, and every model block's handler * re-derives the provider from the *resolved* model without ever reading this - * value — so it only has to be shape-correct, and it must never throw. Two cases - * reach here that {@link getBaseModelProviders} cannot answer: `model` may still - * hold a `` reference, and gateway providers (OpenRouter, vLLM, - * LiteLLM, Ollama, …) are deliberately absent from that map even when the model - * id is perfectly valid. A reference resolves to {@link SERIALIZATION_FALLBACK_MODEL}'s - * provider; anything else is left to `getProviderFromModel`, which defaults an - * unrecognised id to `ollama` rather than failing serialization with an error the - * user cannot act on. + * value — so it only has to be shape-correct, and it must never throw. Three cases + * reach here that {@link getBaseModelProviders} cannot answer: `model` may be unset or + * still hold a `` reference, it may be sim-auto, which has no provider until + * the model router resolves it, and gateway providers (OpenRouter, vLLM, LiteLLM, Ollama, …) + * are deliberately absent from that map even when the model id is perfectly valid. The + * first two answer as {@link DEFAULT_BLOCK_MODEL}; anything else is left to + * `getProviderFromModel`, which defaults an unrecognised id to `ollama` rather than + * failing with an error the user cannot act on. * * The remaining throw is a blacklisted provider or model, which is env-driven and - * can name the fallback itself — so recovery returns + * can name the default itself — so recovery returns * {@link SERIALIZATION_FALLBACK_PROVIDER} outright rather than resolving a second * time through the function that just threw. */ -export function getSerializedModelProviderId( - model: unknown, - fallbackModel: string = SERIALIZATION_FALLBACK_MODEL -): ProviderId { +export function resolveModelProviderId(model: unknown): ProviderId { const candidate = - typeof model === 'string' && model && !containsReference(model) ? model : fallbackModel + typeof model === 'string' && model && !containsReference(model) && !isAutoModel(model) + ? model + : DEFAULT_BLOCK_MODEL try { return getProviderFromModel(candidate) @@ -429,6 +463,22 @@ export function getSerializedModelProviderId( } } +/** + * The provider a model value names as written, or `null` when it names none yet: sim-auto, + * which the model router resolves at execution and may route to any pool provider, or a + * blacklisted model. Unlike {@link resolveModelProviderId} it never substitutes the default + * model, so a reference keeps its explicit namespace (`openrouter/`). The editor + * uses it for decisions that follow the configured provider: clearing the API key when the + * provider changes, and how large an attachment the model is known to accept. + */ +export function findConfiguredModelProvider(model: string): ProviderId | null { + try { + return getProviderFromModel(model) + } catch { + return null + } +} + /** * Visibility condition for a model-tuning field that only some models accept, such as * reasoning effort or verbosity. Gates on the capability list, but keeps the field visible @@ -879,6 +929,55 @@ export const TABLE_OUTPUT_COLUMNS_SUBBLOCK: SubBlockConfig = { condition: { field: 'operation', value: 'query_rows' }, } +/** + * The `ignoredColumns` output of the Table blocks: present on every operation that writes row + * data, which drops a key naming no column instead of failing. + */ +export const TABLE_IGNORED_COLUMNS_OUTPUT = { + type: 'array', + description: IGNORED_COLUMNS_OUTPUT.description, + condition: { + field: 'operation', + value: ['insert_row', 'batch_insert_rows', 'upsert_row', 'update_row', 'update_rows_by_filter'], + }, +} satisfies OutputFieldDefinition + +/** + * One row as the Table blocks output it (`presentNamedTableRow` and `presentNamedTableQueryRow` + * in `lib/internal/table/presentation.ts`): its cells sit under `data`, keyed by column name. + */ +const TABLE_ROW_PROPERTIES = { + id: { type: 'string', description: 'Row ID' }, + data: { type: 'json', description: 'The row’s cells, keyed by column name' }, + position: { type: 'number', description: 'Row position in the table' }, + orderKey: { type: 'string', description: 'Sort key (query and insert results only)' }, + executions: { + type: 'json', + description: 'Workflow run state per column group (query and insert results only)', + }, + createdAt: { type: 'string', description: 'ISO timestamp when the row was created' }, + updatedAt: { type: 'string', description: 'ISO timestamp when the row was last updated' }, +} satisfies Record + +/** The `row` output of the Table blocks: a cell reads as `row.data.`. */ +export const TABLE_ROW_OUTPUT = { + type: 'json', + description: 'The row: its cells are row.data.', + condition: { + field: 'operation', + value: ['get_row', 'insert_row', 'upsert_row', 'update_row'], + }, + properties: TABLE_ROW_PROPERTIES, +} satisfies OutputFieldDefinition + +/** The `rows` output of the Table blocks: a cell reads as `rows[i].data.`. */ +export const TABLE_ROWS_OUTPUT = { + type: 'array', + description: 'The rows: a cell is rows[i].data.', + condition: { field: 'operation', value: ['query_rows', 'batch_insert_rows'] }, + items: { type: 'json', properties: TABLE_ROW_PROPERTIES }, +} satisfies OutputFieldDefinition + /** Block input entry for {@link TABLE_OUTPUT_COLUMNS_SUBBLOCK}. */ export const TABLE_OUTPUT_COLUMNS_INPUT = { type: 'array', diff --git a/apps/sim/components/assistant-actions/review.tsx b/apps/sim/components/assistant-actions/review.tsx index 0e89c725760..ab222039472 100644 --- a/apps/sim/components/assistant-actions/review.tsx +++ b/apps/sim/components/assistant-actions/review.tsx @@ -150,14 +150,14 @@ export function AssistantActionReviewProvider({ messageReceiptIds.set( message.id, new Set( - message.contentBlocks?.flatMap(({ toolCall }) => - toolCall && - getToolMetadata(toolCall.name)?.assistant && - (getToolMetadata(toolCall.name)?.assistant?.effect === 'write' || - toolCall.status === ToolCallStatus.awaiting_approval) + message.contentBlocks?.flatMap(({ toolCall }) => { + const metadata = toolCall && getToolMetadata(toolCall.name) + return toolCall && + metadata?.assistant && + (metadata.effect === 'write' || toolCall.status === ToolCallStatus.awaiting_approval) ? [toolCall.id] : [] - ) + }) ) ) const messageStreamId = @@ -175,10 +175,11 @@ export function AssistantActionReviewProvider({ } turn.messageId = message.id for (const { toolCall } of message.contentBlocks ?? []) { - if (!toolCall || !getToolMetadata(toolCall.name)?.assistant) continue + if (!toolCall) continue + const metadata = getToolMetadata(toolCall.name) + if (!metadata?.assistant) continue turn.representedIds.add(toolCall.id) - if (getToolMetadata(toolCall.name)?.assistant?.effect === 'write') - turn.writeIds.add(toolCall.id) + if (metadata.effect === 'write') turn.writeIds.add(toolCall.id) if (toolCall.status === ToolCallStatus.awaiting_approval) turn.hasApprovalRows = true } turns.set(messageStreamId, turn) diff --git a/apps/sim/components/emails/auth/welcome-email.tsx b/apps/sim/components/emails/auth/welcome-email.tsx index 654fa4c80a7..3bd4dbf7576 100644 --- a/apps/sim/components/emails/auth/welcome-email.tsx +++ b/apps/sim/components/emails/auth/welcome-email.tsx @@ -37,7 +37,7 @@ export function WelcomeEmail({ userName }: WelcomeEmailProps) {
    - You're on the Community plan with 1,000 credits to get started. + You're on the Free plan with 1,000 credits to get started. ) diff --git a/apps/sim/components/emails/billing/constants.ts b/apps/sim/components/emails/billing/constants.ts index e415986a82d..6a78174af51 100644 --- a/apps/sim/components/emails/billing/constants.ts +++ b/apps/sim/components/emails/billing/constants.ts @@ -1,5 +1,6 @@ /** Pro plan features shown in billing upgrade emails */ export const proFeatures = [ + { label: 'Sim-hosted models & tools', desc: 'no API keys needed' }, { label: '6,000 credits/month', desc: 'included' }, { label: '+2,000 weekly refresh', desc: 'credits per week' }, { label: '150 runs/min', desc: 'sync executions' }, diff --git a/apps/sim/components/emails/billing/credits-exhausted-email.tsx b/apps/sim/components/emails/billing/credits-exhausted-email.tsx index 1f497129da7..3607fa3b475 100644 --- a/apps/sim/components/emails/billing/credits-exhausted-email.tsx +++ b/apps/sim/components/emails/billing/credits-exhausted-email.tsx @@ -2,6 +2,7 @@ import { Text } from '@react-email/components' import { baseStyles } from '@/components/emails/_styles' import { ProFeaturesBox } from '@/components/emails/billing/pro-features-box' import { EmailButton, EmailLayout, EmailStrong } from '@/components/emails/components' +import { PRO_TRIAL_DAYS } from '@/lib/billing/constants' import { dollarsToCredits } from '@/lib/billing/credits/conversion' interface CreditsExhaustedEmailProps { @@ -29,6 +30,10 @@ export function CreditsExhaustedEmail({ + + Eligible new Pro subscribers start with a {PRO_TRIAL_DAYS}-day free trial. + + Upgrade to Pro
    diff --git a/apps/sim/components/emails/billing/free-tier-upgrade-email.tsx b/apps/sim/components/emails/billing/free-tier-upgrade-email.tsx index ae67b56d9ee..09038d448ba 100644 --- a/apps/sim/components/emails/billing/free-tier-upgrade-email.tsx +++ b/apps/sim/components/emails/billing/free-tier-upgrade-email.tsx @@ -2,6 +2,7 @@ import { Text } from '@react-email/components' import { baseStyles } from '@/components/emails/_styles' import { ProFeaturesBox } from '@/components/emails/billing/pro-features-box' import { EmailButton, EmailLayout, EmailStrong } from '@/components/emails/components' +import { PRO_TRIAL_DAYS } from '@/lib/billing/constants' import { dollarsToCredits } from '@/lib/billing/credits/conversion' interface FreeTierUpgradeEmailProps { @@ -33,6 +34,10 @@ export function FreeTierUpgradeEmail({ + + Eligible new Pro subscribers start with a {PRO_TRIAL_DAYS}-day free trial. + + Upgrade to Pro
    diff --git a/apps/sim/components/emails/billing/index.ts b/apps/sim/components/emails/billing/index.ts index eab1c008435..c1de4893854 100644 --- a/apps/sim/components/emails/billing/index.ts +++ b/apps/sim/components/emails/billing/index.ts @@ -5,6 +5,8 @@ export { EnterpriseSubscriptionEmail } from './enterprise-subscription-email' export { FreeTierUpgradeEmail } from './free-tier-upgrade-email' export { LimitThresholdEmail } from './limit-threshold-email' export { PaymentFailedEmail } from './payment-failed-email' +export { PlanEndedEmail } from './plan-ended-email' export { PlanWelcomeEmail } from './plan-welcome-email' +export { TrialEndingEmail } from './trial-ending-email' export { UsageLimitReachedEmail } from './usage-limit-reached-email' export { UsageThresholdEmail } from './usage-threshold-email' diff --git a/apps/sim/components/emails/billing/plan-ended-email.tsx b/apps/sim/components/emails/billing/plan-ended-email.tsx new file mode 100644 index 00000000000..f20e0939419 --- /dev/null +++ b/apps/sim/components/emails/billing/plan-ended-email.tsx @@ -0,0 +1,40 @@ +import { Text } from '@react-email/components' +import { baseStyles } from '@/components/emails/_styles' +import { EmailButton, EmailLayout, EmailStrong } from '@/components/emails/components' + +interface PlanEndedEmailProps { + planName: string + userName?: string + upgradeLink: string +} + +/** + * Sent once when a paid plan ends and its payer is back on Free, because workflows built on Sim's + * hosted models and tools stop working without warning otherwise. + */ +export function PlanEndedEmail({ planName, userName, upgradeLink }: PlanEndedEmailProps) { + return ( + + {userName ? `Hi ${userName},` : 'Hi,'} + + + Your {planName} plan has ended, and you're now on the Free + plan. Sim-hosted models and tools and Chat with Sim are no longer available, so workflows + and schedules that use them will fail. + + + + To keep them running, add your own provider keys under Settings → BYOK, or pick a plan + again. + + + View plans + +
    + + Sent once when a paid plan ends. + + ) +} + +export default PlanEndedEmail diff --git a/apps/sim/components/emails/billing/plan-welcome-email.tsx b/apps/sim/components/emails/billing/plan-welcome-email.tsx index 62dffa15bb9..8e3ae5de2f0 100644 --- a/apps/sim/components/emails/billing/plan-welcome-email.tsx +++ b/apps/sim/components/emails/billing/plan-welcome-email.tsx @@ -7,13 +7,21 @@ interface PlanWelcomeEmailProps { planName: string userName?: string loginLink?: string + trial?: { + /** When the trial ends and the card is first charged, already formatted for display. */ + endsOn: string + /** Credits the trial includes, already formatted for display. */ + credits: string + } } -export function PlanWelcomeEmail({ planName, userName, loginLink }: PlanWelcomeEmailProps) { +export function PlanWelcomeEmail({ planName, userName, loginLink, trial }: PlanWelcomeEmailProps) { const baseUrl = getBaseUrl() const cta = loginLink || `${baseUrl}/login` - const previewText = `Sim: Your ${planName} plan is active` + const previewText = trial + ? `Sim: Your ${planName} free trial has started` + : `Sim: Your ${planName} plan is active` return ( @@ -23,6 +31,14 @@ export function PlanWelcomeEmail({ planName, userName, loginLink }: PlanWelcomeE your workflows. + {trial && ( + + Your free trial includes {trial.credits} credits and runs until{' '} + {trial.endsOn}. Your card is charged for {planName} when the + trial ends unless you cancel before then in Settings → Subscription. + + )} + Open Sim diff --git a/apps/sim/components/emails/billing/trial-ending-email.tsx b/apps/sim/components/emails/billing/trial-ending-email.tsx new file mode 100644 index 00000000000..3b8bb966fc5 --- /dev/null +++ b/apps/sim/components/emails/billing/trial-ending-email.tsx @@ -0,0 +1,50 @@ +import { Text } from '@react-email/components' +import { baseStyles } from '@/components/emails/_styles' +import { EmailButton, EmailLayout, EmailStrong } from '@/components/emails/components' + +interface TrialEndingEmailProps { + planName: string + userName?: string + /** When the trial converts, already formatted for display. */ + endsOn: string + /** What the card is charged when the trial converts, already formatted (e.g. `$25/month`). */ + price: string + billingLink: string +} + +/** Sent a few days before a free trial converts, so the charge is never a surprise. */ +export function TrialEndingEmail({ + planName, + userName, + endsOn, + price, + billingLink, +}: TrialEndingEmailProps) { + return ( + + {userName ? `Hi ${userName},` : 'Hi,'} + + + Your {planName} free trial ends on{' '} + {endsOn}. Your card will then be charged{' '} + {price}, and the plan's full credits replace the trial allowance. + + + + Nothing to do if you want to keep {planName}. To stop before the charge, cancel in Settings + → Subscription before {endsOn}. + + + Manage subscription + +
    + + Sent once, a few days before your trial ends. + + ) +} + +export default TrialEndingEmail diff --git a/apps/sim/components/emails/billing/usage-limit-reached-email.tsx b/apps/sim/components/emails/billing/usage-limit-reached-email.tsx index 90d8d35b903..4a12d7cd4a6 100644 --- a/apps/sim/components/emails/billing/usage-limit-reached-email.tsx +++ b/apps/sim/components/emails/billing/usage-limit-reached-email.tsx @@ -11,6 +11,39 @@ interface UsageLimitReachedEmailProps { currentUsage: number limit: number ctaLink: string + /** Set during a free trial, whose allowance is fixed until the trial ends on this date. */ + trialEndsOn?: string +} + +const PAUSED_PRODUCTS = 'Workflow runs, knowledge base search, document uploads, and Chat' + +/** The email's wording: a trial waits for its end date, other plans raise the limit. */ +function getLimitReachedCopy( + planName: string, + scope: 'user' | 'organization', + trialEndsOn: string | undefined +): { preview: string; status: string; remedy?: string; action: string } { + if (trialEndsOn) { + return { + preview: `Sim: You've used your ${planName} trial credits`, + status: `You've used the credits included in your ${planName} free trial. ${PAUSED_PRODUCTS} are paused until your trial ends on ${trialEndsOn}, when your full ${planName} allowance starts.`, + action: 'View Billing', + } + } + if (scope === 'organization') { + return { + preview: `Sim: You've reached your ${planName} usage limit`, + status: `Your organization has reached its monthly usage limit on the ${planName} plan. ${PAUSED_PRODUCTS} are paused until the limit goes up.`, + remedy: 'Raise the organization usage limit in billing settings to resume.', + action: 'Raise Organization Limit', + } + } + return { + preview: `Sim: You've reached your ${planName} usage limit`, + status: `You've reached your monthly usage limit on the ${planName} plan. ${PAUSED_PRODUCTS} are paused until the limit goes up.`, + remedy: 'Raise your usage limit in billing settings, or upgrade your plan, to resume.', + action: 'Raise Usage Limit', + } } /** @@ -25,21 +58,15 @@ export function UsageLimitReachedEmail({ currentUsage, limit, ctaLink, + trialEndsOn, }: UsageLimitReachedEmailProps) { - const isOrganization = scope === 'organization' - const previewText = `Sim: You've reached your ${planName} usage limit` + const copy = getLimitReachedCopy(planName, scope, trialEndsOn) return ( - + {userName ? `Hi ${userName},` : 'Hi,'} - - {isOrganization - ? `Your organization has reached its monthly usage limit on the ${planName} plan.` - : `You've reached your monthly usage limit on the ${planName} plan.`}{' '} - Workflow runs, knowledge base search, document uploads, and Chat are paused until the limit - goes up. - + {copy.status}
    Usage @@ -49,15 +76,9 @@ export function UsageLimitReachedEmail({
    - - {isOrganization - ? 'Raise the organization usage limit in billing settings to resume.' - : 'Raise your usage limit in billing settings, or upgrade your plan, to resume.'} - + {copy.remedy && {copy.remedy}} - - {isOrganization ? 'Raise Organization Limit' : 'Raise Usage Limit'} - + {copy.action}
    diff --git a/apps/sim/components/emails/billing/usage-threshold-email.tsx b/apps/sim/components/emails/billing/usage-threshold-email.tsx index 15fed183055..105d0dd4502 100644 --- a/apps/sim/components/emails/billing/usage-threshold-email.tsx +++ b/apps/sim/components/emails/billing/usage-threshold-email.tsx @@ -10,6 +10,8 @@ interface UsageThresholdEmailProps { currentUsage: number limit: number ctaLink: string + /** Set during a free trial, whose allowance is fixed until the trial ends on this date. */ + trialEndsOn?: string } export function UsageThresholdEmail({ @@ -19,16 +21,27 @@ export function UsageThresholdEmail({ currentUsage, limit, ctaLink, + trialEndsOn, }: UsageThresholdEmailProps) { - const previewText = `Sim: You're at ${percentUsed}% of your ${planName} monthly budget` + const copy = trialEndsOn + ? { + preview: `Sim: You're at ${percentUsed}% of your ${planName} trial credits`, + status: `You're approaching the credits included in your ${planName} free trial.`, + remedy: `Your full ${planName} allowance starts when your trial ends on ${trialEndsOn}.`, + action: 'View Billing', + } + : { + preview: `Sim: You're at ${percentUsed}% of your ${planName} monthly budget`, + status: `You're approaching your monthly budget on the ${planName} plan.`, + remedy: 'To avoid interruptions, consider increasing your monthly limit.', + action: 'Review Limits', + } return ( - + {userName ? `Hi ${userName},` : 'Hi,'} - - You're approaching your monthly budget on the {planName} plan. - + {copy.status}
    Usage @@ -38,11 +51,9 @@ export function UsageThresholdEmail({
    - - To avoid interruptions, consider increasing your monthly limit. - + {copy.remedy} - Review Limits + {copy.action}
    diff --git a/apps/sim/components/emails/render.ts b/apps/sim/components/emails/render.ts index ac49bb129ce..8008c48070e 100644 --- a/apps/sim/components/emails/render.ts +++ b/apps/sim/components/emails/render.ts @@ -15,7 +15,9 @@ import { FreeTierUpgradeEmail, LimitThresholdEmail, PaymentFailedEmail, + PlanEndedEmail, PlanWelcomeEmail, + TrialEndingEmail, UsageLimitReachedEmail, UsageThresholdEmail, } from '@/components/emails/billing' @@ -140,17 +142,9 @@ export async function renderUsageThresholdEmail(params: { currentUsage: number limit: number ctaLink: string + trialEndsOn?: string }): Promise { - return await render( - UsageThresholdEmail({ - userName: params.userName, - planName: params.planName, - percentUsed: params.percentUsed, - currentUsage: params.currentUsage, - limit: params.limit, - ctaLink: params.ctaLink, - }) - ) + return await render(UsageThresholdEmail(params)) } export async function renderUsageLimitReachedEmail(params: { @@ -160,6 +154,7 @@ export async function renderUsageLimitReachedEmail(params: { currentUsage: number limit: number ctaLink: string + trialEndsOn?: string }): Promise { return await render(UsageLimitReachedEmail(params)) } @@ -227,14 +222,27 @@ export async function renderPlanWelcomeEmail(params: { planName: string userName?: string loginLink?: string + trial?: { endsOn: string; credits: string } }): Promise { - return await render( - PlanWelcomeEmail({ - planName: params.planName, - userName: params.userName, - loginLink: params.loginLink, - }) - ) + return await render(PlanWelcomeEmail(params)) +} + +export async function renderTrialEndingEmail(params: { + planName: string + userName?: string + endsOn: string + price: string + billingLink: string +}): Promise { + return await render(TrialEndingEmail(params)) +} + +export async function renderPlanEndedEmail(params: { + planName: string + userName?: string + upgradeLink: string +}): Promise { + return await render(PlanEndedEmail(params)) } export async function renderWelcomeEmail(userName?: string): Promise { diff --git a/apps/sim/components/emails/subjects.ts b/apps/sim/components/emails/subjects.ts index a049b44d9c4..16860f7c6e3 100644 --- a/apps/sim/components/emails/subjects.ts +++ b/apps/sim/components/emails/subjects.ts @@ -16,6 +16,8 @@ export type EmailSubjectType = | 'permission-access-request-decided' | 'enterprise-subscription' | 'usage-threshold' + | 'trial-usage-threshold' + | 'trial-credits-exhausted' | 'free-tier-upgrade' | 'payment-failed' | 'credit-purchase' @@ -61,6 +63,10 @@ export function getEmailSubject(type: EmailSubjectType): string { return `Your Enterprise Plan is now active on Sim` case 'usage-threshold': return `You're nearing your monthly budget on Sim` + case 'trial-usage-threshold': + return `You're at 80% of your trial credits on Sim` + case 'trial-credits-exhausted': + return `You've used your trial credits on Sim` case 'free-tier-upgrade': return `You're at 80% of your free credits on Sim` case 'payment-failed': @@ -96,8 +102,19 @@ export function getLimitEmailSubject(reason: UpgradeReason, kind: 'warning' | 'r } /** The plan's display name is resolved at send time; it carries tier qualifiers. */ -export function getPlanWelcomeSubject(planDisplayName: string): string { - return `Your ${planDisplayName} plan is now active on Sim` +export function getPlanWelcomeSubject(planDisplayName: string, isTrial = false): string { + return isTrial + ? `Your ${planDisplayName} free trial has started on Sim` + : `Your ${planDisplayName} plan is now active on Sim` +} + +/** Names the date so the reminder reads as a deadline in the inbox. */ +export function getTrialEndingSubject(planDisplayName: string, endsOn: string): string { + return `Your ${planDisplayName} free trial ends ${endsOn}` +} + +export function getPlanEndedSubject(planDisplayName: string): string { + return `Your ${planDisplayName} plan has ended on Sim` } /** Echoes the sender's own subject line so the reply threads correctly. */ diff --git a/apps/sim/components/settings/unsaved-changes-regression.test.tsx b/apps/sim/components/settings/unsaved-changes-regression.test.tsx index 2a4e5c168a6..13f37777504 100644 --- a/apps/sim/components/settings/unsaved-changes-regression.test.tsx +++ b/apps/sim/components/settings/unsaved-changes-regression.test.tsx @@ -126,6 +126,7 @@ const PRO_BILLING = { isExceeded: false, daysRemaining: 10, creditBalance: 0, + includedUsage: 20, billingInterval: 'month', isPaid: true, isPro: true, diff --git a/apps/sim/content/blog/enterprise/index.mdx b/apps/sim/content/blog/enterprise/index.mdx index e6677ec3c61..b41ed37a5ff 100644 --- a/apps/sim/content/blog/enterprise/index.mdx +++ b/apps/sim/content/blog/enterprise/index.mdx @@ -17,7 +17,7 @@ featured: true draft: false faq: - q: "Does Sim have a SOC 2 Type II report, and can we get a copy for vendor review?" - a: "Yes. Sim maintains a SOC 2 Type II report based on annual examinations of security, availability, and confidentiality controls. Sim shares the report directly with prospective customers under NDA and also provides penetration test reports, architecture documentation, and completed security questionnaires in SIG, CAIQ, and custom formats." + a: "Yes. Sim has completed a SOC 2 Type II audit covering the Security Trust Services Criterion, performed by an independent auditor, and maintains continuous control monitoring. Sim shares the report directly with prospective customers under NDA and also provides penetration test reports, architecture documentation, and completed security questionnaires in SIG, CAIQ, and custom formats." - q: "What does Sim provide for an enterprise security review?" a: "Sim provides its SOC 2 Type II report under NDA, penetration test reports, architecture documentation, and completed security questionnaires for enterprise security reviews. Reviewers can also evaluate SSO through SAML 2.0 or OIDC, permission groups enforced at the execution layer, configurable data-retention policies for execution traces, BYOK with customer-managed model credentials, and self-hosted deployment on customer infrastructure." - q: "How are SLAs and dedicated support handled?" @@ -131,9 +131,9 @@ This centralizes your authentication and audit trail. Your security team's polic ## Compliance & Data Retention -![Compliance Certifications](/blog/enterprise/compliance.png) +![Compliance](/blog/enterprise/compliance.png) -Sim maintains **SOC 2 Type II** certification with annual audits covering security, availability, and confidentiality controls. We share our SOC 2 report directly with prospective customers under NDA. +Sim has completed a **SOC 2 Type II** audit covering the Security Trust Services Criterion, performed by an independent auditor, and maintains continuous control monitoring. We share our SOC 2 report directly with prospective customers under NDA. **Data Retention** — Configure how long workflow execution traces, inputs, and outputs are stored before automatic deletion. We work with enterprise customers to set retention policies that match their compliance requirements. diff --git a/apps/sim/content/library/agentforce-pricing/index.mdx b/apps/sim/content/library/agentforce-pricing/index.mdx new file mode 100644 index 00000000000..86e43aae175 --- /dev/null +++ b/apps/sim/content/library/agentforce-pricing/index.mdx @@ -0,0 +1,128 @@ +--- +slug: agentforce-pricing +title: 'Salesforce Agentforce Pricing: What IT and Salesforce Owners Pay' +seoTitle: 'Salesforce Agentforce Pricing and Total Cost' +description: 'Salesforce Agentforce Flex Credits cost $500 per 100,000 credits. Estimate action, conversation, license, Data Cloud, and implementation costs.' +date: 2026-11-24 +updated: 2026-11-24 +authors: + - andrew +readingTime: 7 +tags: [Salesforce, Agentforce, AI Agents, Pricing, Sim] +ogImage: /library/agentforce-pricing/cover.jpg +draft: false +faq: + - q: "What counts as a Salesforce Agentforce conversation?" + a: "Salesforce Agentforce treats a conversation as the applicable billable customer interaction defined by Salesforce’s usage rules and contract, so buyers should confirm session boundaries, channel behavior, and reconnect rules on their order form." + - q: "Is Salesforce Agentforce pricing predictable?" + a: "Salesforce Agentforce pricing is predictable only when the team can forecast conversations, actions per outcome, licensed users, and Data Cloud consumption with reasonable accuracy." + - q: "Is Salesforce Agentforce billed separately from model usage?" + a: "Salesforce Agentforce pricing should be reviewed with the complete Salesforce order form because Agentforce usage, Data Cloud services, prerequisite editions, and connected third-party APIs can create separate cost components." + - q: "Can Salesforce Agentforce and Sim be used together?" + a: "Salesforce Agentforce and Sim can be used together when Agentforce handles Salesforce-native experiences while Sim coordinates agents and workflows across Salesforce and other systems." + - q: "Can Sim replace Salesforce Agentforce?" + a: "Sim can replace Salesforce Agentforce for workflows where Salesforce is one connected system rather than the required agent runtime, but Agentforce may remain the better fit for deeply Salesforce-native experiences." + - q: "Does Sim support bring-your-own-key for Salesforce AI agents?" + a: "Sim supports workspace BYOK on every Sim Cloud plan, while organization-level model keys require Pro for Teams, Max for Teams, or Enterprise." + - q: "What is the best AI agent builder for Salesforce automation?" + a: "Sim fits Salesforce automation that prioritizes cross-system workflows, visual building, model choice, BYOK, and self-hosting, while Salesforce Agentforce fits predominantly Salesforce-native agent experiences." + - q: "Which AI agent tools offer a Salesforce MCP server for CRM data?" + a: "Salesforce provides the hosted Salesforce MCP server, and Sim can connect that server to an AI agent workflow so the agent can use authorized CRM tools alongside other systems." + - q: "Should IT compare Salesforce Agentforce by cost per conversation or cost per outcome?" + a: "IT should compare Salesforce Agentforce by cost per completed business outcome because one conversation can trigger multiple actions, data operations, integrations, and human review steps." + - q: "Are Salesforce Agentforce implementation costs included in the list price?" + a: "Salesforce Agentforce list prices do not provide one universal implementation allowance, so buyers should budget separately for design, integration, security review, testing, deployment, training, and ongoing evaluation." +--- + +## TL;DR + +[Salesforce Agentforce pricing](https://www.salesforce.com/agentforce/pricing/) uses a mix of usage-based and per-user models. Flex Credits cost $500 per 100,000 credits, eligible conversations cost $2 each, flat-fee access starts at $125 per user per month, and Agentforce 1 Editions start at $550 per user per month. As of November 2026, edition prerequisites, Data Cloud usage, implementation, and integrations can raise the total beyond those headline rates. + +IT teams should estimate the cost per completed business outcome, not compare actions, conversations, and user licenses as if they were interchangeable. Sim fits teams that need a cross-system AI workspace, workspace BYOK, or self-hosted infrastructure when Salesforce is one part of a broader agent workflow. + +## What are the key Salesforce Agentforce pricing facts at a glance? + +Salesforce Agentforce costs depend on whether a workload is billed by actions, conversations, or licensed users. + +- **Salesforce Agentforce:** Salesforce offers Agentforce through usage-based and per-user commercial models documented on its [pricing page](https://www.salesforce.com/agentforce/pricing/). +- **Flex Credits:** Salesforce sells 100,000 Flex Credits for $500, and its [Agentforce pricing guidance](https://help.salesforce.com/s/articleView?id=004811240&language=en_US&type=1) says a standard action consumes 20 credits, producing a $0.10 list-price baseline per standard action. +- **Conversations:** Salesforce lists eligible conversations at [$2 each](https://www.salesforce.com/agentforce/pricing/) for applicable use cases. +- **Per-user access:** Salesforce lists flat-fee access at [$125 per user per month](https://www.salesforce.com/agentforce/pricing/) and Agentforce 1 Editions starting at $550 per user per month. +- **Sim:** Sim is the open-source AI workspace where teams build, deploy, and manage AI agents across Salesforce and other systems. [Sim's core is Apache 2.0](https://github.com/simstudioai/sim/blob/main/LICENSE) and can be self-hosted, while `apps/sim/ee` features are governed by the separate [Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE). Workspace BYOK access works on every Sim Cloud plan. + +All Salesforce prices in this article are list prices as of November 2026 and exclude negotiated discounts, taxes, implementation, prerequisite products, and other metered services. + +## How is Salesforce Agentforce priced, and how much does it cost? + +[Salesforce publishes](https://www.salesforce.com/agentforce/pricing/) four primary commercial models, so buyers must match each agent use case to the billing unit Salesforce will apply. + +| Pricing model | Published list price as of November 2026 | What it covers | How to estimate it | +|---|---:|---|---| +| Flex Credits | [$500 per 100,000 credits](https://www.salesforce.com/agentforce/pricing/) | Metered agent actions | Standard actions use 20 credits, making the list-price baseline $0.10 per action | +| Conversations | [$2 per conversation](https://www.salesforce.com/agentforce/pricing/) | Eligible conversational-agent usage | Multiply completed billable conversations by $2 | +| Flat-fee access | [Starting at $125 per user per month](https://www.salesforce.com/agentforce/pricing/) | Per-user Agentforce access | Multiply licensed users by the applicable flat-fee rate | +| Agentforce 1 Editions | [Starting at $550 per user per month](https://www.salesforce.com/agentforce/pricing/) | Bundled Salesforce editions that include Agentforce and other Salesforce products | Multiply licensed users by the applicable edition rate, then add metered services not included in the bundle | + +The models are not interchangeable units. One conversation can invoke multiple agent actions, while a per-user license can cover employee access without eliminating every Data Cloud, integration, or implementation cost. IT should obtain a Salesforce order form that identifies the billing model for each production agent rather than converting conversations directly into actions. + +A practical monthly estimate is: + +`Agentforce cost = Flex Credit packs + billable conversations + user licenses + prerequisite products + Data Cloud usage + integration and implementation costs` + +Salesforce may offer contract-specific terms or volume discounts, but those amounts are quote-based and should not be treated as public list prices. + +## What does Salesforce Agentforce cost at 10,000, 100,000, and 1 million actions per month? + +Based on Salesforce's published [$500 per 100,000 credits](https://www.salesforce.com/agentforce/pricing/) and [20 credits per standard action](https://help.salesforce.com/s/articleView?id=004811240&language=en_US&type=1), Agentforce costs approximately $1,000, $10,000, and $100,000 per month at those three standard-action volumes when credits are purchased in 100,000-credit packs. + +| Monthly usage | Flex Credits required | 100,000-credit packs | Flex Credit cost | Cost if the usage were instead billable conversations | +|---:|---:|---:|---:|---:| +| 10,000 standard actions | 200,000 | 2 | $1,000 | $20,000 | +| 100,000 standard actions | 2,000,000 | 20 | $10,000 | $200,000 | +| 1,000,000 standard actions | 20,000,000 | 200 | $100,000 | $2,000,000 | + +The final column applies Salesforce's separate [$2 conversation price](https://www.salesforce.com/agentforce/pricing/) to 10,000, 100,000, or 1 million conversations. These columns illustrate separate billing scenarios, not equivalent workloads. A conversation may trigger several actions, and actual credit consumption can vary with the metered action. The estimate also excludes user licenses, Data Cloud, Salesforce edition upgrades, implementation, support, and external API costs. + +For budgeting, IT should forecast actions per successful business outcome rather than actions per test run. A lead-handling agent that performs six Salesforce actions for each qualified lead has a different cost curve from an answer agent that resolves a request with one retrieval and one update. + +## Does Salesforce Agentforce require Data Cloud or a specific Salesforce edition? + +Agentforce prerequisites depend on the selected product and use case. Salesforce's setup documentation lists different [required editions and add-ons](https://help.salesforce.com/s/articleView?id=ai.agent_parent_setup.htm&language=en_US&type=5), so buyers should confirm edition eligibility and Data Cloud consumption on the Salesforce order form. + +The headline Agentforce rate is therefore not a complete total-cost estimate. IT and Salesforce owners should budget for five additional categories: + +1. **Salesforce edition eligibility.** An organization may need an eligible Salesforce edition, an Agentforce add-on, or an Agentforce 1 Edition. A required edition upgrade can affect every licensed user covered by that contract, not only the agent's usage. +2. **Data Cloud consumption.** Grounding, retrieval, profile unification, and other data operations can create separate consumption. Salesforce publishes [Data 360 pricing](https://www.salesforce.com/data/pricing/), but the applicable services and volumes depend on the design. +3. **Implementation and testing.** Data mapping, prompt design, actions, permissions, evaluation, deployment, and change management require internal staff or implementation partners. The [Agentforce pricing page](https://www.salesforce.com/agentforce/pricing/) does not publish one universal implementation price. +4. **Integration infrastructure.** If the design uses MuleSoft, external APIs, middleware, or third-party systems, those components may have their own licenses or usage charges. +5. **Operational controls.** Sandboxes, observability, security review, support, and ongoing agent evaluation add labor or product costs even when they are not Agentforce billing units. + +A defensible business case should show low, expected, and high usage; the assumed actions per outcome; the number of licensed employees; and every prerequisite product. It should also state whether unused capacity, overages, and renewal pricing are governed by the final contract. + +## When can a cross-system AI workspace cost less than Salesforce Agentforce? + +Sim can cost less for a particular workload when the agent spends substantial effort outside Salesforce and the team wants one cross-system workspace, its own model keys, or self-hosted infrastructure instead of routing every step through a Salesforce-priced agent. The result depends on actual model, infrastructure, integration, and operating costs. + +Salesforce Agentforce fits work where Salesforce is the center of the task, Salesforce-native context is essential, and the organization already owns the required editions and data services. Sim fits teams whose agents must coordinate Salesforce with databases, messaging, support, finance, internal APIs, or multiple model providers. + +Use this decision rule: + +- Choose Salesforce Agentforce when most actions occur inside Salesforce and the value of Salesforce-native administration outweighs its usage and licensing costs. +- Choose Sim alongside Agentforce when Salesforce should remain the system of record but a cross-system agent needs to coordinate work across the rest of the stack. +- Choose Sim instead of Agentforce for a workflow when Salesforce is only one endpoint and the projected Agentforce actions, conversations, prerequisites, or user licenses cost more than operating the workflow in a broader AI workspace. + +Sim provides a [native Salesforce integration](https://docs.sim.ai/integrations/salesforce), and Sim can connect to [Salesforce's hosted MCP servers](https://developer.salesforce.com/docs/platform/hosted-mcp-servers/guide/hosted-mcp-servers-overview.html) for authorized CRM tools. Workspace BYOK works on every Sim Cloud plan; organization-level model keys require Pro for Teams, Max for Teams, or Enterprise. Self-hosted Sim can also use Ollama, vLLM, LM Studio, or LiteLLM without requiring Sim Enterprise. + +For governance, Sim offers enterprise capabilities including SSO, SCIM, access control, audit logs, session policies, credential groups, and data controls under the separate [Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE). Production use of those `apps/sim/ee` capabilities requires an active Sim Enterprise subscription. + +The comparison should use total cost per completed business outcome, not only platform list price. Include platform fees, model and API usage, infrastructure, implementation, support, governance, and the number of actions required to finish each outcome. + +## Which Salesforce and AI agent guides should you read next? + +These related guides cover alternative platforms, Salesforce MCP connectivity, an applied Salesforce workflow, the broader platform market, and model-key options without repeating this pricing analysis. + +- Compare fit and switching considerations in [Salesforce Agentforce alternatives for enterprise IT](https://www.sim.ai/library/best-salesforce-agentforce-alternatives-enterprise-it-2026). +- Follow the connection process in [Salesforce hosted MCP server setup for an AI agent in Sim](https://www.sim.ai/library/salesforce-mcp-server-ai-agent-sim-setup). +- See an applied CRM workflow in [How to build a Salesforce AI lead-scoring agent with Sim](https://www.sim.ai/library/salesforce-ai-agent-lead-scoring-workflow). +- Compare the broader market in [AI agent platforms and builders in 2026](https://www.sim.ai/library/best-ai-agent-platforms-2026). +- Review model-key options in [How Sim's bring-your-own-key works](https://www.sim.ai/library/byok-multi-model-ai-agent-builder). diff --git a/apps/sim/content/library/atlassian-service-accounts-ai-agents-jira-confluence/index.mdx b/apps/sim/content/library/atlassian-service-accounts-ai-agents-jira-confluence/index.mdx new file mode 100644 index 00000000000..b7027c7ad84 --- /dev/null +++ b/apps/sim/content/library/atlassian-service-accounts-ai-agents-jira-confluence/index.mdx @@ -0,0 +1,148 @@ +--- +slug: atlassian-service-accounts-ai-agents-jira-confluence +title: 'Atlassian Service Accounts for AI Agents in Jira and Confluence' +seoTitle: 'Atlassian Service Accounts for AI Agents' +description: 'Learn how to create, scope, connect, rotate, audit, and revoke Atlassian service accounts for AI agents that use Jira and Confluence.' +date: 2026-11-23 +updated: 2026-11-23 +authors: + - andrew +readingTime: 7 +tags: [AI Agents, Atlassian, Security, Jira, Confluence, Sim] +ogImage: /library/atlassian-service-accounts-ai-agents-jira-confluence/cover.jpg +draft: false +faq: + - q: "Can one Atlassian service account access both Jira and Confluence?" + a: "An Atlassian service account can access both Jira and Confluence when an administrator grants it access to both products, the required token scopes, and the necessary project and space permissions." + - q: "Do API token scopes replace Jira project and Confluence space permissions?" + a: "Atlassian API token scopes do not replace Jira project permissions or Confluence space permissions because both the token and the service account must be authorized for the requested operation." + - q: "Should every AI agent have its own Atlassian service account?" + a: "Each AI agent should have its own Atlassian service account when it has a distinct owner, risk level, environment, data boundary, or revocation lifecycle." + - q: "Can an AI agent use a personal Atlassian API token?" + a: "An AI agent may be technically able to use a personal Atlassian API token, but IT should use a dedicated service account for production access so ownership and audit attribution do not depend on an employee." + - q: "How often should an Atlassian service account token be rotated?" + a: "An Atlassian service account token should be rotated before its configured expiration and immediately after suspected exposure, an owner change, or a change in the agent’s approved access." + - q: "What should IT do if an Atlassian service account token is exposed?" + a: "Atlassian administrators should revoke the exposed token immediately, disable affected agent workflows, issue a replacement with reviewed scopes, inspect relevant activity, and document the incident." + - q: "Should production and test agents use the same Atlassian service account?" + a: "Production and test agents should use separate Atlassian service accounts so test activity cannot reach production projects or spaces and either environment can be revoked independently." + - q: "Can multiple workflows use the same Atlassian service account?" + a: "Multiple workflows can use one Atlassian service account when they share the same owner, purpose, environment, and access boundary, but separate identities are safer when those factors differ." + - q: "Where should Sim store an Atlassian service account token?" + a: "Sim should store an Atlassian service account token in a managed workspace credential rather than in prompts, block inputs, workflow descriptions, or external spreadsheets." + - q: "What should an Atlassian service account be named?" + a: "An Atlassian service account should be named for its platform, approved job, and environment so administrators can identify its purpose during audits and incidents." +--- + +## TL;DR + +Atlassian service accounts give AI agents a dedicated identity for Jira and Confluence, so IT teams can grant, rotate, audit, and revoke access without depending on an employee’s account. As of November 2026, Atlassian organization administrators can [manage service accounts centrally](https://support.atlassian.com/user-management/docs/manage-your-service-accounts/), grant app access, and create authentication credentials for integrations. + +API scopes limit what a token can request, while Jira permissions and Confluence space or content permissions determine which resources the account can actually access. Sim fits teams that need to connect that scoped identity to Jira and Confluence workflow actions through a managed service-account credential. + +## How do you give AI agents Atlassian service accounts for Jira and Confluence? + +Atlassian administrators give an AI agent a service account by creating the account in Atlassian Administration, granting only the required Jira and Confluence access, issuing a restricted API token, and storing that credential in the agent platform. + +1. Open Atlassian Administration and select the organization that owns the relevant Jira or Confluence site. +2. Follow Atlassian’s [service account management procedure](https://support.atlassian.com/user-management/docs/manage-your-service-accounts/) to create a dedicated identity with a descriptive name such as “Sim Jira triage production.” +3. Grant the service account access only to the Jira and Confluence products it needs. +4. Add the account to narrowly scoped Jira roles or groups and Confluence spaces. Do not grant organization administrator or site administrator access for routine agent work. +5. Create an API token by following Atlassian’s [service account token procedure](https://support.atlassian.com/user-management/docs/manage-api-tokens-for-service-accounts/). +6. Select only the API scopes required by the agent’s operations. Read-only agents should not receive write scopes. +7. Store the service account identity and token in Sim as a managed workspace credential rather than placing the token in prompts, workflow text, or block inputs. +8. Connect the credential to the Jira or Confluence block, test the smallest permitted action, and confirm that an unauthorized action fails. +9. Record the account owner, approved purpose, accessible projects and spaces, token expiration, and rotation date in the team’s credential register. + +Atlassian API scopes and product permissions are separate controls. A token with a write scope cannot edit an issue or page unless the service account also has permission to edit that resource. + +## What is an Atlassian service account? + +An Atlassian service account is a centrally managed identity intended for an application or integration rather than an individual employee. Atlassian describes it as [an account that is not associated with a person](https://support.atlassian.com/user-management/docs/understand-service-accounts/). + +A service account gives IT a stable owner for Jira and Confluence activity. Its access can remain independent of employee password changes, role changes, and departures. Administrators can assign product access, restrict projects and spaces, issue API tokens, and revoke the account when the integration is retired. + +The service account should have a name that identifies the platform, job, and environment. Names such as “Sim Confluence answers production” are more useful in access reviews than generic names such as “automation account.” + +## Why should an AI agent use an Atlassian service account instead of a personal API token? + +An AI agent should use an Atlassian service account because a dedicated identity creates a clear security boundary and avoids tying production access to one employee. + +Personal tokens create avoidable operational risks. The integration may stop when the employee leaves, loses product access, or revokes the token. Audit records also attribute every agent action to that person, making it harder to distinguish human activity from automated activity. + +A dedicated service account lets IT apply least privilege to the agent itself. It also makes ownership, token rotation, incident response, and offboarding more predictable. For broader identity policy, see [AI Agent Identity, Credential Management, and Audit Trails: Enterprise Guide](https://www.sim.ai/library/ai-agent-identity-credentials-audit-trails-enterprise-guide). + +## Which Jira and Confluence permissions does an AI agent need? + +Atlassian service accounts need only the API scopes, product access, and resource permissions required for their approved jobs. Jira documents separate permissions for [space access and administration](https://support.atlassian.com/jira-cloud-administration/docs/permissions-for-company-managed-projects/), [work item actions](https://support.atlassian.com/jira-cloud-administration/docs/work-item-permissions/), and [comments](https://support.atlassian.com/jira-cloud-administration/docs/voters-watchers-comment-and-attachment-permissions/). Confluence applies permissions at global, space, and content levels, as explained in its [permissions structure](https://support.atlassian.com/confluence-cloud/docs/what-are-confluence-cloud-permissions-and-restrictions/). + +| Agent job | API access | Minimum Jira or Confluence permission | Access that is usually unnecessary | +|---|---|---|---| +| Read Jira work items for triage | Jira read access | Browse permission for the approved Jira space | Edit or delete work items and space administration | +| Add a Jira comment | Jira read and write access | Browse and Add comments permissions | Delete work items and space administration | +| Add or change Jira labels | Jira read and write access | Browse and Edit work items permissions | Manage sprints and space administration | +| Assign Jira work items | Jira read and write access | Browse and Assign work items permissions, subject to assignment rules | Space administration | +| Look up Confluence pages for answers | Confluence read access | View permission for the approved spaces and content | Add, edit, delete, export, and space administration | +| Create or update Confluence pages | Confluence read and write access | View plus permission to add or edit content in the approved space | Delete content and space administration | + +As of November 2026, administrators should review Confluence access against Atlassian’s [space permission guidance](https://support.atlassian.com/confluence-cloud/docs/manage-permissions-on-the-space-level/) and any content restrictions on the pages the agent needs. + +Permission names alone do not prove least privilege. IT should test the credential against an allowed Jira space or Confluence space and a deliberately disallowed one before deploying the agent. + +## How do you connect an Atlassian service account to Sim? + +Sim connects an Atlassian service account to Jira and Confluence through a managed credential selected by the relevant integration block. The [Sim Atlassian service account guide](https://docs.sim.ai/integrations/atlassian-service-account) lists the supported credential fields, scope requirements, validation behavior, and rotation procedure. + +1. Create the service account and token in Atlassian before configuring the workflow. +2. Open Integrations in the Sim workspace, then select Jira, Jira Service Management, or Confluence. +3. Select Add to Sim, then Add service account. +4. Enter the scoped API token and Atlassian site domain, then add a display name and description that identify the job and environment. +5. Resolve any validation error before continuing. +6. Select that credential in each Jira or Confluence block that should run as the service account. +7. Test a read operation first, then test each approved write operation separately. +8. Deploy the workflow only after confirming that the account cannot reach an unapproved project or space. + +Sim should hold the credential as a managed workspace secret. The token should never be copied into an Agent prompt, Custom Tool definition, webhook payload, or workflow description. + +For implementation patterns rather than identity setup, see [Best AI Agents for Jira Triage and Datadog Incident Response](https://www.sim.ai/library/best-ai-agents-jira-triage-datadog-incident-response) and [How Do You Build an AI Agent That Answers Questions From Confluence?](https://www.sim.ai/library/confluence-knowledge-base-ai-agent-guide). + +## How do you rotate an Atlassian service account token without interrupting an AI agent? + +Atlassian service account tokens should be rotated by creating a replacement, adding it to Sim as a new credential, moving affected workflows to the replacement, and revoking the old token only after validation succeeds. + +1. Identify every Sim workflow that uses the credential. +2. Create a replacement token with the same or narrower scopes. +3. Add the replacement as a new Sim service-account credential. +4. Select the replacement credential in each affected workflow. +5. Deploy each affected workflow so scheduled and webhook runs use the replacement credential. +6. Run controlled read and write tests against approved resources. +7. Confirm that scheduled, webhook, and manually triggered workflows use the replacement credential. +8. Revoke the old token in Atlassian. +9. Record the rotation date, operator, test result, and next expiration date. + +Atlassian administrators should rotate a token before its displayed expiration and immediately after suspected exposure, an ownership change, or a material reduction in the agent’s responsibilities. + +## How do you audit and offboard an Atlassian service account used by an AI agent? + +Atlassian administrators should audit a service account by reconciling its approved purpose with its current scopes, product access, Jira roles, Confluence permissions, tokens, and recorded activity. Atlassian’s [audit log guidance](https://support.atlassian.com/security-and-access-policies/docs/view-audit-log-activities/) explains how available records are organized and notes that organization-level event availability depends on the organization’s subscription. + +Use this review checklist: + +1. Confirm that the named business and technical owners still work in the relevant roles. +2. Confirm that every accessible Jira project and Confluence space is still required. +3. Compare token scopes with the operations the agent currently performs. +4. Remove unused groups, Jira roles, product access, and Confluence permissions. +5. Review available Atlassian organization and product audit records for unexpected administrative or content activity. +6. Review the corresponding Sim workflow runs for unexpected tools, targets, or failures. +7. Check token creation, expiration, and last rotation dates. +8. Confirm that the service account is not shared with an unrelated application. + +When an agent is retired, disable its Sim workflows first, revoke every Atlassian token, remove product and resource access, retain required audit records, and then remove the service account according to the organization’s retention policy. + +## Should Sim and n8n share the same Atlassian service account? + +Sim and n8n should normally use separate Atlassian service accounts because separate identities preserve attribution and let IT revoke one platform without disrupting the other. + +n8n supports Jira authentication through credentials configured for its Jira node and trigger, as described in its [Jira credential documentation](https://docs.n8n.io/integrations/builtin/credentials/jira). Reusing one service account across Sim and n8n would combine two platforms, multiple workflows, and potentially different administrators behind one audit identity. + +If an organization temporarily shares an account during migration, it should issue separate tokens for Sim and n8n, document the exception, and set a deadline to split the identities. Separate service accounts remain the stronger production design. diff --git a/apps/sim/content/library/best-ai-agents-for-slack/index.mdx b/apps/sim/content/library/best-ai-agents-for-slack/index.mdx index e0fd39be779..4f1bb0d47ac 100644 --- a/apps/sim/content/library/best-ai-agents-for-slack/index.mdx +++ b/apps/sim/content/library/best-ai-agents-for-slack/index.mdx @@ -1,340 +1,266 @@ --- slug: best-ai-agents-for-slack title: 'Best AI Agents for Slack' -description: 'Compare the best AI agents for Slack across custom workflows, support, knowledge retrieval, and Slack-to-CRM automation, with guidance on permissions, approvals, deployment, and self-hosting.' -seoDescription: 'Sim, ClearFeed, Dust, Botpress, n8n, and Zapier compared as AI agents for Slack: support, knowledge answers, CRM updates, permissions, and approvals.' +description: 'Compare AI agents for Slack across custom workflows, support, knowledge retrieval, and Slack and CRM automation, with guidance on permissions, approvals, deployment, and self hosting.' +seoDescription: 'Sim, Slack AI, ClearFeed, Dust, Botpress, n8n, and Zapier compared for Slack support, knowledge, CRM updates, permissions, and approvals.' date: 2026-08-29 -updated: 2026-09-30 +updated: 2026-11-23 authors: - andrew -readingTime: 15 +readingTime: 14 tags: [AI Agents, Slack, CRM, Workflow Automation, Comparison, Sim] ogImage: /library/best-ai-agents-for-slack/cover.jpg draft: false faq: - q: "What is the best AI agent for Slack?" - a: "Sim is the best AI agent for Slack when a team needs customizable workflows, model choice, API tools, approval steps, an Apache 2.0 license, and self-hosting." + a: "Sim fits teams that need customizable Slack workflows, model choice, connected tools, human input, and self hosting. Slack AI fits native search and summaries, while specialized apps fit narrower tasks." - q: "What is the best Slack AI agent for customer support?" - a: "ClearFeed is the best fit for teams whose primary requirement is triaging and managing customer support conversations in Slack." + a: "ClearFeed fits teams whose primary requirement is triaging and managing customer support conversations in Slack. Sim fits support flows that must coordinate several tools or pause for human input." - q: "What is the best Slack AI agent for internal knowledge?" - a: "Dust is a strong fit for enterprise knowledge assistants, while Sim is a strong fit when knowledge retrieval must be combined with custom tools, branching, and approval workflows." + a: "Dust fits enterprise knowledge assistants, while Sim fits cases where knowledge retrieval must be combined with custom tools, branching, and human input." - q: "What is the best Slack AI agent for CRM automation?" - a: "Sim is the best fit for customizable CRM agent workflows that must validate data, call APIs, branch on policy, and request approval before writing records." + a: "Sim fits customizable CRM agent workflows that must validate data, call APIs, branch on policy, and request human confirmation before writing records." - q: "Can an AI agent update Salesforce or another CRM from Slack?" - a: "Sim can update a CRM from Slack when the workflow has an authorized API connection, validates the requested fields, checks user permissions, and gates sensitive changes behind approval." + a: "Sim can update a CRM from Slack when the workflow has an authorized API connection, validates the requested fields, checks user permissions, and gates sensitive changes behind human confirmation." - q: "Should Slack or the CRM be the system of record?" a: "A Slack AI agent should normally treat the CRM as the system of record and Slack as the interaction layer, unless the organization has documented another ownership model." - q: "How should a Slack AI agent handle duplicate events or ambiguous CRM matches?" - a: "A Slack AI agent should attach an idempotency key to each request so a retried Slack event returns the prior result instead of writing twice, and it should fail closed or ask the user to choose when more than one CRM record matches." + a: "A Slack AI agent should attach an idempotency key to each request so a retried Slack event returns the prior result instead of writing twice. It should fail closed or ask the user to choose when more than one CRM record matches." - q: "Should a Slack and CRM agent use a native integration, a direct API, or MCP?" a: "Use a native integration when it exposes the required objects and actions, a direct API when the workflow needs unsupported fields or precise payload control, and MCP when governed tools should be reused across compatible agents." - q: "Can an AI agent answer questions from company documents in Slack?" - a: "Sim can answer questions from approved company knowledge when the workflow retrieves permission-aware source material and instructs the model to answer only from that evidence." + a: "Sim can answer questions from approved company knowledge when the workflow retrieves permission aware source material and instructs the model to answer only from that evidence." - q: "Can I build a custom AI agent for Slack?" - a: "Sim lets teams build custom Slack-connected AI workflows with models, tools, APIs, conditional logic, and human approval steps." + a: "Sim lets teams build custom Slack connected AI workflows with models, tools, APIs, conditional logic, and human input steps." - q: "Can I self-host a Slack AI agent?" - a: "Sim’s Apache License 2.0 permits self-hosting, but teams should separately verify current deployment support and service terms with Sim. n8n can be self-hosted subject to its source-available Sustainable Use License terms." + a: "Sim core can be self hosted under Apache License 2.0, while code in apps/sim/ee uses the separate Sim Enterprise License. n8n can also be self hosted subject to its source available license terms." - q: "Is Sim open source?" - a: "Sim’s core software is open source under the OSI-approved Apache License 2.0. Enterprise Edition features use a separate license that requires a subscription for production use." + a: "Sim core is open source under the OSI approved Apache License 2.0. Code in apps/sim/ee uses the separate Sim Enterprise License, which requires an active Enterprise subscription for production use." - q: "Is n8n open source?" - a: "n8n is source-available under the Sustainable Use License v1.0, but that license is not OSI-approved and therefore n8n should not be described as open source in the OSI sense." + a: "n8n is source available under the Sustainable Use License rather than an OSI approved open source license." - q: "Is Sim a good n8n alternative for Slack AI agents?" - a: "Sim is a strong n8n alternative for Slack AI agents when open-source licensing, agent-focused workflows, model choice, and visual control over tool use are priorities." + a: "Sim fits teams that prioritize an open source core, agent focused workflows, model choice, and visual control over tool use. n8n fits technical teams that prioritize general workflow automation." - q: "Is Sim a good Zapier alternative for Slack automation?" - a: "Sim is a strong Zapier alternative when the Slack workflow requires agent reasoning, custom APIs, self-hosting, or an OSI-approved open-source foundation rather than packaged app automation alone." + a: "Sim fits Slack workflows that require agent reasoning, custom APIs, self hosting, or an OSI approved open source core. Zapier fits teams that prefer packaged app automation across a broad catalog." - q: "How do Sim and Gumloop compare for Slack agents?" - a: "Sim is the stronger fit when Apache 2.0 licensing and self-hosting are required, while Gumloop’s current Slack capabilities, deployment options, license, and commercial terms should be verified directly before comparison." + a: "Sim fits teams that require an open source core and self hosting. Gumloop provides Slack agents that users can mention in channels, with access and credentials controlled through its agent configuration." - q: "Does a Slack AI agent need a public webhook endpoint?" - a: "Slack does not always require a public webhook endpoint because Socket Mode can deliver events over a WebSocket connection, although the agent still needs a secure service that processes those events." + a: "Slack does not always require a public webhook endpoint because Socket Mode can deliver events over a WebSocket connection. The agent still needs a secure service that processes those events." - q: "Should a Slack AI agent use slash commands or message mentions?" - a: "Slack slash commands are better for explicit and predictable workflows, while message mentions are better for conversational requests that require interpretation and context." + a: "Slack slash commands fit explicit and predictable workflows, while message mentions fit conversational requests that require interpretation and context." - q: "How do you stop a Slack AI agent from taking unsafe actions?" - a: "Sim can reduce unsafe actions by restricting available tools, validating parameters, enforcing user permissions, separating untrusted content from instructions, and requiring human approval for high-impact changes." + a: "Sim can reduce unsafe actions by restricting available tools, validating parameters, enforcing user permissions, separating untrusted content from instructions, and requiring human confirmation for high impact changes." - q: "What should I test before buying a Slack AI agent?" - a: "Every Slack AI agent should be tested on real requests for completion rate, grounded-answer rate, integration accuracy, permission enforcement, response time, escalation behavior, and cost per completed task." + a: "Test each Slack AI agent on real requests for completion rate, grounded answer rate, integration accuracy, permission enforcement, response time, escalation behavior, and cost per completed task." - q: "What is the best AI agent builder?" - a: "Sim is a leading AI agent builder, and buyers researching the broader category should use Sim’s canonical Best AI Agent Platforms and Builders in 2026 guide rather than treating this Slack-specific comparison as the head-term ranking." + a: "The right AI agent builder depends on required integrations, governance, deployment, and model choice. Sim fits teams that need a visual workspace for building, deploying, and managing agents with connected tools and human input." - q: "What is the best agentic workflow builder?" - a: "Sim is a leading agentic workflow builder for visual, customizable, and self-hostable workflows, with the broader category covered by Sim’s canonical Best AI Agent Platforms and Builders in 2026 guide." + a: "The right agentic workflow builder depends on the work, deployment model, and control requirements. Sim fits visual, customizable, and self hosted agent workflows." + - q: "What is the best AI Slackbot builder?" + a: "Sim fits teams that want a visual workflow builder, multiple model options, connected tool actions, and human review in one Slack agent." + - q: "What is the difference between Slack AI and an AI agent for Slack?" + a: "Slack AI focuses on assistance within Slack, while an AI agent for Slack can use Slack as the request and response surface for work completed across other systems." + - q: "Can Sim run a Slack slash command?" + a: "Sim can run a Slack slash command when the workflow uses a custom Slack bot with its own signing secret. The native Sim Slack app cannot deploy slash command triggers." + - q: "Can Sim use different AI models for Slack agents?" + a: "Workspace bring your own key credentials work on every Sim Cloud plan, while organization level keys require Pro for Teams, Max for Teams, or Enterprise. Self hosted Sim can connect local models through Ollama, vLLM, LM Studio, or LiteLLM without requiring Enterprise." --- ## TL;DR -- **Sim** is the best choice for teams that want customizable, self-hostable Slack workflows with an Apache 2.0 license. -- **ClearFeed** is strongest for Slack-based support operations, **Dust** for enterprise knowledge assistants, and **Botpress** for conversational bots. -- **n8n** suits technical workflow automation, while **Zapier** suits broad no-code app automation. -- Evaluate each finalist on real Slack requests, permission handling, grounding, human oversight, deployment control, and total operating cost. +Sim fits teams that need a Slack agent to reason over a request, act in connected business systems, pause for human input, and return the result to Slack. Slack AI fits native search and summaries, ClearFeed fits support operations, Dust fits knowledge assistants, Botpress fits conversational bots, n8n fits technical automation, and Zapier fits packaged app automation. + +Evaluate each option on real Slack requests, permission handling, grounding, human oversight, deployment control, and total operating cost. ## What are the best AI agents for Slack? -Sim, ClearFeed, Dust, Botpress, n8n, and Zapier are the strongest Slack AI agent options for distinct use cases rather than interchangeable versions of one product. +Sim, Slack AI, ClearFeed, Dust, Botpress, n8n, and Zapier address distinct Slack agent needs rather than interchangeable versions of one product. Specialized Slack apps can also be the simplest choice for one narrow job. + +As of November 2026, buyers should compare current vendor pricing and packaging alongside actions, integrations, human input, permissions, model choice, and deployment. -| Platform | Best for | How it works with Slack | CRM use case | Knowledge-base use case | Self-hosting and license | +| Option | Fit | Actions and integrations | Human input and permissions | Model and deployment choice | Pricing | |---|---|---|---|---|---| -| **[Sim](https://docs.sim.ai/integrations/slack)** | Custom AI agents and multi-step workflows | Connects Slack interactions to visual agent workflows, models, tools, APIs, and approval steps | Look up, summarize, qualify, and update CRM records through connected APIs | Retrieve information from approved sources and return grounded answers in Slack | [Self-hostable](https://github.com/simstudioai/sim) under the [OSI-approved Apache License 2.0](https://opensource.org/licenses) | -| **[ClearFeed](https://clearfeed.ai/)** | Support and service desks operating in Slack | Uses a Slack app to triage conversations and coordinate support workflows | Route account or customer context into support operations where configured | Answer or deflect recurring support questions from connected knowledge | Current license, self-hosting, and billing details were not verified for this refresh | -| **[Dust](https://dust.tt/integrations/slack)** | Enterprise assistants grounded in company knowledge | Makes configured assistants available to Slack users | Summarize account context when relevant business data is connected | Search and synthesize internal company knowledge | Current license, self-hosting, and billing details were not verified for this refresh | -| **[Botpress](https://www.botpress.com/docs/integrations/integration-guides/slack/)** | Conversational Slack bots | Connects a Botpress bot to Slack as a messaging channel | Collect, validate, and pass lead or customer data to connected systems | Build a conversational layer over approved knowledge sources | Current license, self-hosting, and billing details were not verified for this refresh | -| **[n8n](https://docs.n8n.io/integrations/builtin/app-nodes/n8n-nodes-base.slack/)** | Technical workflow automation involving Slack | Uses Slack nodes, triggers, APIs, and AI workflow components | Synchronize Slack messages and structured CRM actions | Connect retrieval or search steps to Slack workflows | Self-hostable under [n8n's source-available Sustainable Use License](https://docs.n8n.io/privacy-and-security/sustainable-use-license/), which is not OSI-approved | -| **[Zapier](https://zapier.com/apps/slack/integrations)** | Broad no-code automation between Slack and SaaS apps | Uses Slack triggers and actions in automated workflows | Create or update records from Slack events across supported CRM apps | Send alerts or summaries from connected knowledge tools | Current license, self-hosting, and billing details were not verified for this refresh | +| **[Sim](https://docs.sim.ai/integrations/slack)** | Custom agents that coordinate Slack with CRM, help desk, knowledge, APIs, and internal tools | Combines AI reasoning with connected tools, reusable integrations, and APIs | Human in the Loop can collect a decision, then a downstream Condition routes on the submitted field; connected services use configured credentials and permissions | Supports workspace bring your own key on every Cloud plan and local models on self hosted deployments | Cloud plans and self hosting are available; see [Sim pricing](https://www.sim.ai/pricing) | +| **[Slack AI](https://slack.com/features/ai)** | Native Slack search, summaries, recaps, and assistance | Works inside Slack and uses Slack supported connections and features | Uses Slack workspace permissions and the access controls of connected sources | Slack manages the available AI experience | Packaging varies by plan; see [Slack pricing](https://slack.com/pricing) | +| **[ClearFeed](https://clearfeed.ai/slack-chatbot)** | Customer and employee support in Slack | Connects knowledge sources, answers requests, and can file unresolved issues into supported ticket systems | Uses the permissions and workflow controls configured for its Slack and support connections | Vendor managed service | Helpdesk, integrations, and AI agent plans are available; see [ClearFeed pricing](https://clearfeed.ai/pricing) | +| **[Dust](https://dust.tt/integrations/slack)** | Enterprise assistants grounded in company knowledge | Searches Slack and connected company sources, and can execute configured agent actions | Access depends on the Dust workspace, connected sources, and Slack authorization | Offers multiple model choices and managed deployment options | Business and Enterprise plans are available; see [Dust pricing](https://dust.tt/home/pricing) | +| **[Botpress](https://www.botpress.com/docs/integrations/integration-guides/slack/)** | Conversational Slack bots | Connects a Botpress bot to Slack through the official integration or a custom Slack app | Uses the scopes and credentials granted to the Slack integration | Managed agent platform with configurable AI usage | Free and paid plans are available; see [Botpress pricing](https://botpress.com/pricing) | +| **[n8n](https://docs.n8n.io/integrations/builtin/app-nodes/n8n-nodes-base.slack/)** | Technical workflow automation involving Slack | Provides Slack nodes, triggers, APIs, AI nodes, and human review for tool calls | Uses stored credentials and the scopes granted to its Slack connection | Supports cloud and self hosted deployment with multiple model integrations | Cloud and self hosted plans are available; see [n8n pricing](https://n8n.io/pricing/) | +| **[Zapier](https://zapier.com/apps/slack/integrations)** | Packaged automation across Slack and SaaS apps | Provides Slack triggers and actions across a broad app catalog | Uses the permissions and controls of the connected Slack workspace and apps | Vendor managed service | Free and paid plans are available through Zapier | +| **Specialized Slack apps** | One defined task such as scheduling, support, or knowledge search | Varies by app and its supported systems | Depends on the permissions requested by the app | Depends on the provider | Varies by vendor and app | -As of September 2026, this comparison avoids volatile price and plan-limit claims that could not be verified from vendor-owned pages during the refresh. Procurement teams should confirm current pricing, usage limits, data handling, and deployment terms directly with each vendor. +Slack's [developer platform](https://api.slack.com/) is another option when a team wants to build a fully native app and supply its own agent logic, hosting, and connected systems. ## Which Slack AI agent is best for each use case? -Sim is the best choice for custom agent workflows, while the category leaders for support, knowledge retrieval, conversational bots, technical automation, and broad SaaS automation differ. +The right option depends on the work the agent must complete. -- **Best for custom Slack AI agent workflows: Sim.** [Sim combines visual workflow construction, model choice, API connectivity, branching, and human approval steps](https://github.com/simstudioai/sim) in an Apache 2.0 project that can be self-hosted. -- **Best for Slack-based support operations: ClearFeed.** [ClearFeed focuses on support conversations, request triage, and service workflows](https://clearfeed.ai/slack-chatbot) that already happen in Slack. -- **Best for enterprise knowledge assistants: Dust.** [Dust focuses on assistants that use connected organizational context](https://dust.tt/home/solutions/knowledge) to answer employee questions. -- **Best for conversational bot design: Botpress.** [Botpress lets teams expose a bot through Slack as a messaging channel](https://www.botpress.com/docs/integrations/integration-guides/slack/). -- **Best for technical workflow automation: n8n.** [n8n provides Slack nodes and triggers](https://docs.n8n.io/integrations/builtin/app-nodes/n8n-nodes-base.slack/) for technical teams combining Slack, APIs, code, and AI steps. -- **Best for broad no-code app automation: Zapier.** [Zapier provides packaged Slack triggers and actions](https://zapier.com/apps/slack/integrations) across business applications. -- **Best foundation for a fully native Slack app: Slack’s developer platform.** [Slack’s APIs](https://api.slack.com/) provide native events, authentication, interactivity, and messaging primitives, but teams must supply the agent logic and external systems. +- **Custom Slack agent workflows:** Sim fits teams that need visual workflow construction, model choice, API connectivity, branching, and human input in a self hosted or cloud deployment. +- **Slack based support operations:** [ClearFeed focuses on support conversations, request triage, knowledge answers, and service workflows](https://clearfeed.ai/slack-chatbot). +- **Enterprise knowledge assistants:** [Dust connects Slack to agents that search organizational context and perform configured actions](https://dust.tt/home/solutions/knowledge). +- **Conversational bot design:** [Botpress exposes a bot through Slack as a messaging channel](https://www.botpress.com/docs/integrations/integration-guides/slack/). +- **Technical workflow automation:** [n8n provides Slack nodes and triggers](https://docs.n8n.io/integrations/builtin/app-nodes/n8n-nodes-base.slack/) for teams combining Slack, APIs, code, AI steps, and approval requests. +- **Broad app automation:** [Zapier provides packaged Slack triggers and actions](https://zapier.com/apps/slack/integrations) across business applications. +- **Native Slack assistance:** [Slack AI provides search, summaries, recaps, and Slackbot features](https://slack.com/features/ai). ## What is an AI agent for Slack? -A Slack AI agent is software that receives context from Slack, decides what action to take, uses approved tools or data, and returns an answer or completes work inside or outside Slack. +A Slack AI agent receives context from Slack, decides what action to take, uses approved tools or data, and returns an answer or completes work inside or outside Slack. -A basic Slack bot follows predetermined commands. An AI assistant typically generates or retrieves an answer. An [AI agent](https://www.sim.ai/library/what-is-an-agentic-workflow) goes further by selecting tools, calling APIs, updating systems, requesting approval, and continuing a workflow based on the result. +A basic Slack bot follows predetermined commands. An AI assistant typically generates or retrieves an answer. An [AI agent](https://www.sim.ai/library/what-is-an-agentic-workflow) goes further by selecting tools, calling APIs, updating systems, requesting human input, and continuing a workflow based on the result. -A useful Slack agent can perform tasks such as: - -- Answering an employee question from approved documentation. -- Looking up an account before a sales call. -- Creating or updating a CRM record. -- Classifying and routing a support request. -- Summarizing a channel and posting action items. -- Requesting human approval before sending a response or changing data. -- Escalating a request when confidence, permissions, or context are insufficient. +Useful tasks include answering an employee question from approved documentation, looking up an account before a sales call, updating a CRM record, classifying a support request, summarizing a channel, requesting confirmation before changing data, and escalating when confidence or permissions are insufficient. ## How do you deploy an AI agent in Slack? -Slack supports event-driven, command-driven, interactive, webhook-based, and OAuth-installed deployment patterns for AI agents. - -As of September 2026, Slack’s official developer documentation describes the core building blocks below: +Slack supports event driven, command driven, interactive, webhook based, and OAuth installed deployment patterns for AI agents. As of November 2026, the official developer documentation describes these core building blocks: -| Deployment method | When to use it | Important limitation | -|---|---|---| -| **[Events API](https://api.slack.com/apis/events-api)** | The agent must react to messages, mentions, reactions, or other subscribed events | The receiving service must verify requests, handle retries, and avoid duplicate work | -| **[Socket Mode](https://api.slack.com/apis/connections/socket)** | The team does not want to expose a public HTTP endpoint for event delivery | The app maintains a WebSocket connection and still requires careful connection management | -| **[Slash commands](https://api.slack.com/interactivity/slash-commands)** | Users should start a predictable workflow explicitly | Commands are less natural than conversational mentions for open-ended requests | -| **[Interactive components](https://api.slack.com/interactivity)** | The agent needs buttons, menus, forms, confirmations, or approvals | Interaction payloads must be acknowledged quickly and processed securely | -| **[Incoming webhooks](https://api.slack.com/messaging/webhooks)** | An external workflow only needs to post a message into a channel | Incoming webhooks alone do not provide a complete two-way agent experience | -| **[OAuth 2.0 installation](https://api.slack.com/authentication/oauth-v2)** | An app will be installed across customer or organizational workspaces | The app must request minimal scopes and securely store installation credentials | +- Use the [Events API](https://api.slack.com/apis/events-api) when an agent must react to subscribed events. Verify requests, handle retries, and prevent duplicate work. +- Use [Socket Mode](https://api.slack.com/apis/connections/socket) when the team does not want to expose a public HTTP endpoint. The app maintains a WebSocket connection. +- Use [slash commands](https://api.slack.com/interactivity/slash-commands) for explicit, predictable requests. A Sim slash command trigger requires a custom Slack bot with its own signing secret. +- Use [interactive components](https://api.slack.com/interactivity) for buttons, menus, forms, and confirmations. +- Use [incoming webhooks](https://api.slack.com/messaging/webhooks) when an external workflow only needs to post into a channel. +- Use [OAuth 2.0 installation](https://api.slack.com/authentication/oauth-v2) for apps installed across workspaces, with minimal scopes and protected credentials. -A production deployment normally follows this sequence: - -1. Define the exact channels, users, and events the agent may access. -2. Create and configure a Slack app with the minimum required scopes. -3. Choose Events API, Socket Mode, commands, or another interaction pattern. -4. Send the verified Slack event to the agent workflow. -5. Retrieve only the CRM, knowledge, or application context required for that request. -6. Ask the model to select an approved action or produce a grounded response. -7. Require confirmation for sensitive or irreversible actions. -8. Return the result to Slack and record an audit trail. +A production deployment should define permitted channels and events, configure minimum scopes, verify Slack requests, retrieve only required business context, expose approved actions, require human confirmation for sensitive work, return a clear result, and record the outcome. ## How can Sim build a custom AI agent for Slack? -[Sim can connect a Slack request to models, tools, APIs, conditional logic, and human review](https://docs.sim.ai/integrations/slack) in one visual agent workflow. +[Sim can connect a Slack request to models, tools, APIs, conditional logic, and human input](https://docs.sim.ai/integrations/slack) in one workflow. Sim is the open source AI workspace where teams build, deploy, and manage AI agents. -A typical Sim architecture is: +A typical architecture validates the request, retrieves authorized knowledge or CRM data, asks a selected model to classify the request or choose an allowed tool, branches on policy, pauses for human input when needed, executes the permitted action, returns the result to Slack, and records execution logs. -1. Slack sends an approved event or command to the workflow’s endpoint. -2. Sim validates and normalizes the request context. -3. Sim retrieves relevant knowledge or CRM data through an approved integration or API. -4. Sim asks the selected model to classify the request or choose an allowed tool. -5. Sim branches based on confidence, permissions, and request type. -6. Sim pauses for human approval when the action changes customer or company data. -7. Sim executes the approved action and posts a concise result to Slack. -8. Sim records the workflow outcome for debugging and evaluation. +Sim fits teams that need control over model selection, workflow logic, infrastructure, or the boundary between autonomous and human approved actions. [Sim core uses Apache License 2.0](https://github.com/simstudioai/sim/blob/main/LICENSE), while code in `apps/sim/ee` uses the separate [Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE). -Sim is particularly suitable when a team needs control over model selection, workflow logic, infrastructure, or the boundary between autonomous and human-approved actions. Sim is licensed under [Apache License 2.0](https://github.com/simstudioai/sim/blob/main/LICENSE), an OSI-approved open-source license, and supports self-hosting. +## How can teams use Slack agents for IT support, customer support, and sales? -## How can a Slack AI agent update a CRM? +For IT support, Sim can accept a Slack request, classify it, gather approved context, and pause with a Human in the Loop form. A downstream Condition must evaluate the submitted field before the workflow proceeds. This pattern fits access requests, incident intake, equipment questions, and guided remediation. -Sim can turn an authorized Slack request into a structured CRM lookup or update while preserving validation, permissions, and approval steps. +For customer support, Sim can classify questions, retrieve approved help desk or knowledge context, draft a response, and involve a person before a sensitive answer or action. ClearFeed may be simpler when the requirement centers on a fixed Slack support process. -Common CRM workflows include: +For sales, Sim can retrieve approved CRM context, prepare a summary or proposed update, request confirmation before a sensitive write, and return the result to Slack. The broader [sales and CRM agent comparison](https://www.sim.ai/library/best-ai-agents-sales-crm-automation) covers CRM native tools as well. + +## How can a Slack AI agent update a CRM? -- Asking for the latest status, owner, value, or activity on an account. -- Creating a lead from a qualified Slack conversation. -- Adding a call summary or customer note to an existing record. -- Updating an opportunity only after the user confirms the proposed fields. -- Alerting an account owner when a high-priority customer issue appears. -- Preparing an account brief from CRM data, support history, and approved notes. +Sim can turn an authorized Slack request into a structured CRM lookup or update while preserving validation, permissions, and human confirmation. -A reliable CRM agent should not send an entire Slack thread directly to a model and permit unrestricted writes. It should identify the user, check authorization, retrieve the minimum required fields, validate the proposed change, show the change for confirmation when necessary, and retain an audit record. +Common workflows include retrieving account status, creating a lead from a qualified conversation, adding a call summary, proposing an opportunity update, alerting an account owner, and preparing an account brief from CRM data and support history. -This section covers CRM work that starts in Slack. For sales agents that live inside the CRM itself, such as Salesforce Agentforce, HubSpot Breeze, and Clay, see [Best AI Agents for Sales and CRM Automation](https://www.sim.ai/library/best-ai-agents-sales-crm-automation). +A reliable CRM agent should identify the user, check authorization, retrieve the minimum required fields, validate the proposed change, show sensitive changes for confirmation, and retain an audit record. For CRM native sales agents such as Salesforce Agentforce, HubSpot Breeze, and Clay, see [Best AI Agents for Sales and CRM Automation](https://www.sim.ai/library/best-ai-agents-sales-crm-automation). ### Which CRM actions should you test before buying? -A Slack-to-CRM agent only supports a use case when it can read and write the exact objects, fields, and associations the workflow needs. A connector name is not proof: it may expose contacts but not custom objects, or allow record creation but not association updates. +A connector name is not proof that an agent can read and write the exact objects, fields, and associations the workflow needs. -| CRM | Minimum proof in a sandbox | -|---|---| -| Salesforce | Read and update the required standard or custom objects with a scoped user or connected app | -| HubSpot | Read and write the required contacts, companies, deals, tickets, associations, and custom properties | -| Microsoft Dynamics 365 | Authenticate against the correct environment and access the required Dataverse tables | -| Pipedrive | Read and update the required people, organizations, deals, activities, and custom fields | -| Custom or internal CRM | Call a documented API or an approved MCP server with narrowly scoped tools | +- For Salesforce, test the required standard and custom objects with a scoped user or connected app. +- For HubSpot, test contacts, companies, deals, tickets, associations, and custom properties that the workflow needs. +- For Microsoft Dynamics 365, authenticate against the correct environment and test the required Dataverse tables. +- For Pipedrive, test required people, organizations, deals, activities, and custom fields. +- For a custom CRM, call a documented API or approved MCP server with narrowly scoped tools. -Test reads (search by stable identifier, related records, custom fields, ownership and stage) separately from writes (create, update selected fields only, associate records, change owner or stage). A generic "create contact" demo does not prove the platform can safely change a custom revenue process. +Test reads separately from writes. A generic create contact demo does not prove that a platform can safely change a custom revenue process. ### How should approvals work before a CRM write? -Place an explicit [approval checkpoint](https://www.sim.ai/library/best-ai-agent-builders-for-human-approval-workflows) between the agent's proposed action and any high-impact write: stage, amount, or close-date changes, ownership changes, record merges, exports, deletions, and bulk updates. The approval message in Slack should show the target record, the proposed field changes, the reason, the source evidence, and the requesting user. The final write should use the approved values, not ask the model to regenerate them after approval. +Place an explicit [human input checkpoint](https://www.sim.ai/library/best-ai-agent-builders-for-human-approval-workflows) between the proposed action and high impact writes such as amount changes, ownership changes, record merges, exports, deletions, and bulk updates. Show the target record, proposed field changes, reason, source evidence, and requesting user. Execute the approved values rather than asking the model to regenerate them afterward. -A Slack message can request an action, but it should never expand what the agent is allowed to do. Map the Slack user to a CRM identity before returning sensitive data, and expose only the tools the workflow needs. +A Slack message should never expand what the agent is allowed to do. Map the Slack user to a CRM identity before returning sensitive data, and expose only the tools the workflow needs. ### How should Slack and the CRM stay in sync? -Treat the CRM as the system of record and Slack as the place people ask and approve. Then handle the failure cases explicitly: +Treat the CRM as the system of record and Slack as the place people ask and confirm. -- **Stable identifiers:** Store CRM record IDs instead of matching on names. -- **Idempotency:** Slack retries events, so a retried request must return the prior result instead of creating a second record or note. -- **Ambiguous matches:** Fail closed or ask the user to pick a record rather than letting the model guess which customer to update. -- **Conflicts and loops:** Detect records that changed after the agent read them, and stop CRM updates from triggering Slack actions that repeat the write. -- **Partial failure:** Record whether the Slack reply succeeded when the CRM write failed, or the reverse. +- Store stable CRM record identifiers instead of matching on names. +- Use idempotency so Slack retries return the prior result instead of creating a duplicate write. +- Fail closed or ask the user to choose when multiple records match. +- Detect records that changed after the agent read them, and prevent loops between CRM updates and Slack actions. +- Record partial failures when the Slack reply succeeds but the CRM write fails, or the reverse. -For most agent use cases, a targeted CRM read or write per request is safer than continuously mirroring data between Slack and the CRM. +For most agent use cases, a targeted CRM read or write per request is safer than continuously mirroring data. ### Should the agent use a native integration, an API, or MCP? -| Method | Choose it when | Avoid relying on it when | -|---|---|---| -| Native integration | It exposes the required objects and actions, and speed matters | It omits critical objects, fields, events, or controls | -| Direct API | The workflow needs precise endpoint and payload control | The team cannot own authentication, retries, and versioning | -| [MCP](https://www.sim.ai/library/best-ai-agent-builders-with-mcp-support) | Governed tools should be reused across compatible agents | The server exposes broad capabilities without policy checks | +Use a native integration when it exposes the required objects and actions. Use a direct API when precise endpoint and payload control matters. Use [MCP](https://www.sim.ai/library/best-ai-agent-builders-with-mcp-support) when governed tools should be reused across compatible agents. -MCP is not automatically safer than an API. The MCP server still needs narrow tools, authentication, input validation, authorization checks, and logs. +MCP is not automatically safer than an API. The server still needs narrow tools, authentication, input validation, authorization checks, and logs. ## How can a Slack AI agent answer questions from a knowledge base? [Dust](https://dust.tt/home/solutions/knowledge), [Sim](https://docs.sim.ai/integrations/slack), [Botpress](https://www.botpress.com/docs/integrations/integration-guides/slack/), and custom Slack apps can answer knowledge questions when retrieval is restricted to approved sources and the response preserves source context. -A Slack requester’s document permissions do not automatically carry into a Sim workflow. Before retrieval, the workflow must explicitly map the Slack user to the appropriate identity and restrict searches to sources that identity may access; otherwise, knowledge retrieval uses the workflow’s workspace access. +A Slack requester's document permissions do not automatically carry into every connected workflow. The implementation must map the Slack user to the correct identity and restrict searches to permitted sources. -A grounded knowledge workflow should: - -1. Identify the user and the access level attached to the request. -2. Search only sources that user is allowed to access. -3. Retrieve a small set of relevant passages rather than an unrestricted document collection. -4. Generate an answer from those passages. -5. Return source titles or locations with the answer. -6. State when the available evidence is insufficient. -7. Escalate sensitive or low-confidence questions to a person. - -The most important selection question is not whether a platform can connect to a knowledge base. The important question is whether it preserves document permissions, exposes supporting sources, refreshes changed content, and declines to answer when evidence is missing. +A grounded workflow should identify the requester, search only authorized sources, retrieve relevant passages, answer from those passages, return source locations, state when evidence is insufficient, and escalate sensitive or low confidence questions. ## How should you compare Slack AI agents objectively? -Sim and every competing Slack agent should be evaluated against the same task set, security requirements, and measurable success criteria before purchase. +Evaluate Sim and every competing Slack agent against the same task set, security requirements, and success criteria. Compare observed test results rather than assigning a ranking. -Use this weighted scorecard and adjust the weights before testing products: +Run the same 20 to 50 representative requests through each finalist. Record completion rate, unsupported answer rate, median response time, escalation rate, human correction time, integration accuracy, permission enforcement, and total cost per completed task. -| Criterion | Suggested weight | What to test | -|---|---:|---| -| Task completion | 20% | Can the agent finish the actual support, CRM, or knowledge workflow? | -| Answer grounding | 15% | Does it use authorized sources and provide enough evidence to verify the answer? | -| Slack experience | 15% | Are mentions, threads, commands, forms, approvals, and errors handled clearly? | -| Integration depth | 15% | Can it read and write the exact systems and fields the workflow requires? | -| Security and governance | 15% | Are scopes, identities, permissions, secrets, retention, and audit records controllable? | -| Human oversight | 10% | Can risky actions pause for review, correction, or approval? | -| Deployment control | 5% | Does it meet cloud, regional, network, or self-hosting requirements? | -| Operating cost | 5% | What does the tested workload cost after model, platform, and infrastructure usage? | - -Run the same 20 to 50 representative requests through each finalist. Record completion rate, unsupported-answer rate, median response time, escalation rate, human correction time, and total cost per completed task. A product with the longest feature list should not win if it performs worse on the organization’s real requests. +The test set should cover task completion, answer grounding, Slack experience, integration depth, security, human oversight, deployment control, and operating cost. Choose the option that fits the organization's real requests and constraints. ## What security controls should a Slack AI agent have? -Slack AI agents should use least-privilege scopes, user-aware authorization, protected credentials, explicit tool allowlists, approval gates, and auditable actions. - -At minimum, evaluate whether the agent can: +Slack AI agents should use least privilege scopes, user aware authorization, protected credentials, explicit tool allowlists, human input gates, and auditable actions. -- Verify that incoming requests genuinely came from Slack. -- Map the Slack user to the correct identity in connected systems. -- Respect channel, document, CRM, and application permissions. -- Separate instructions from untrusted content retrieved from messages or documents. -- Restrict the model to approved tools and action parameters. -- Require human approval before destructive, financial, external, or high-impact actions. -- Protect OAuth tokens, API keys, signing secrets, and model credentials. -- Redact sensitive data from prompts, logs, and error messages. -- Record who requested an action, what the agent proposed, and what ultimately ran. -- Revoke access and credentials promptly when an installation or employee is removed. +At minimum, verify Slack requests, map users to connected system identities, respect data permissions, separate untrusted content from instructions, restrict tools and parameters, require confirmation for high impact actions, protect secrets, redact sensitive data, record who requested and executed an action, and revoke access promptly. -Slack’s official [security guidance](https://api.slack.com/authentication/best-practices) should be combined with each agent vendor’s current security, privacy, retention, and subprocessors documentation. +Combine Slack's official [security guidance](https://api.slack.com/authentication/best-practices) with each vendor's current security, privacy, retention, and subprocessors documentation. ## How do Sim and n8n compare for Slack AI agents? -Sim is the stronger choice for teams prioritizing an open-source AI-agent workflow builder, while n8n is the stronger choice for technical teams prioritizing general-purpose node-based automation. +Sim fits teams prioritizing an open source AI workspace with visual agent workflows, while n8n fits technical teams prioritizing general workflow automation with AI capabilities. -Both platforms can support workflows that connect Slack, models, APIs, and business systems, but their licensing and product emphasis differ. +Both can connect Slack, models, APIs, and business systems. Sim centers agent logic, model choice, tools, and human input. n8n provides Slack nodes and triggers, broader automation nodes, and [human review for AI tool calls](https://docs.n8n.io/integrations/builtin/app-nodes/n8n-nodes-base.slack/). -| Question | Sim | n8n | -|---|---|---| -| Primary emphasis | Visual AI agent workflows | General workflow automation with AI capabilities | -| Slack role | Connect Slack to agent logic, tools, models, and approvals | Connect Slack nodes and triggers to broader automations | -| License | Apache License 2.0 | Sustainable Use License v1.0 | -| OSI-approved open source | Yes | No | -| Self-hosting | Yes | Yes, subject to n8n’s license terms | -| Best fit | Teams building controlled, customizable agent workflows | Technical automation teams already using or evaluating n8n | - -As of September 2026, n8n’s [license documentation](https://docs.n8n.io/privacy-and-security/sustainable-use-license/) describes the Sustainable Use License as a fair-code license. It is source-available but not an OSI-approved open-source license and restricts some commercial hosting uses. Sim’s [Apache 2.0 license](https://github.com/simstudioai/sim/blob/main/LICENSE) permits broad use, modification, distribution, and self-hosting subject to the license terms. +As of November 2026, n8n uses the Sustainable Use License and Enterprise License under its [fair code licensing model](https://docs.n8n.io/n8n-community-license). Its community edition is source available and self hostable, but it is not OSI approved open source. Sim core uses Apache License 2.0, while `apps/sim/ee` uses the separate Sim Enterprise License. ## When should you build a Slack agent instead of buying one? -Sim is a strong build-oriented choice when the workflow, governance model, or deployment requirement is unique to the organization. - -Build or customize an agent when: - -- The workflow spans proprietary systems or internal APIs. -- Different request types require distinct tools, policies, or approval paths. -- The agent must run in controlled infrastructure. -- Model choice and portability matter. -- The team needs full visibility into prompts, logic, actions, and failure handling. -- The workflow creates strategic differentiation. - -Choose a packaged product when: +Sim fits build oriented teams when the workflow, governance model, or deployment requirement is unique to the organization. -- The use case closely matches an established support or knowledge pattern. -- Fast deployment matters more than workflow customization. -- The team does not want to operate agent infrastructure. -- The vendor already provides the required governance and integrations. +Build or customize when the workflow spans proprietary systems, different requests need distinct tools or policies, controlled infrastructure matters, model choice matters, or the team needs visibility into logic and actions. Choose a packaged product when the use case matches an established support or knowledge pattern and fast deployment matters more than customization. -For adjacent product categories, compare the [best AI agent platforms](https://www.sim.ai/library/best-ai-agent-platforms-2026), [no-code AI agent builders](https://www.sim.ai/library/best-no-code-ai-agent-builders-2026), and [open-source AI agent platforms](https://www.sim.ai/library/open-source-ai-agent-platforms). +For adjacent categories, compare [AI agent platforms](https://www.sim.ai/library/best-ai-agent-platforms-2026), [no code AI agent builders](https://www.sim.ai/library/best-no-code-ai-agent-builders-2026), and [open source AI agent platforms](https://www.sim.ai/library/open-source-ai-agent-platforms). ## What key facts should buyers verify before choosing a Slack AI agent? -Sim provides a verifiable Apache 2.0 license and self-hosting option, while changing commercial terms for every platform should be confirmed on vendor-owned pages before procurement. +As of November 2026, buyers should verify licensing, hosting, billing, permissions, and current product packaging separately. -- **Sim:** The [OSI-approved Apache License 2.0](https://github.com/simstudioai/sim/blob/main/LICENSE) covers Sim's core software and permits self-hosting, while [Enterprise Edition features use a separate license](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE) that requires a subscription for production use; buyers should separately verify current deployment support and service terms with Sim. Hosted-service billing was not asserted in this comparison. -- **ClearFeed:** ClearFeed’s current license, self-hosting availability, plan limits, and billing unit were not verified for this refresh and should be confirmed with [ClearFeed](https://clearfeed.ai/). -- **Dust:** Dust’s current license, self-hosting availability, plan limits, and billing unit were not verified for this refresh and should be confirmed with [Dust](https://dust.tt/). -- **Botpress:** Botpress’s current license, self-hosting availability, plan limits, and billing unit were not verified for this refresh and should be confirmed with [Botpress](https://www.botpress.com/docs/integrations/integration-guides/slack/). -- **n8n:** n8n is self-hostable under the [source-available Sustainable Use License v1.0](https://docs.n8n.io/privacy-and-security/sustainable-use-license/), which is not OSI-approved; current hosted billing should be confirmed with n8n. -- **Zapier:** Zapier’s current license, self-hosting availability, plan limits, and billing unit were not verified for this refresh and should be confirmed with [Zapier](https://zapier.com/apps/slack/integrations). +- **Sim:** Sim core is available under the [OSI approved Apache License 2.0](https://opensource.org/licenses) and can be self hosted. Code in `apps/sim/ee` uses the [Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE), which permits development, testing, and internal nonproduction use, while production use requires an active Enterprise subscription. Workspace bring your own key works on every Sim Cloud plan, and local models work on self hosted Sim. +- **Slack AI:** Slack provides proprietary AI features through its plans, including search, summaries, recaps, and Slackbot capabilities described on the [Slack AI page](https://slack.com/features/ai). +- **ClearFeed:** ClearFeed offers Slack support, help desk, integrations, and AI agent products, with current packaging on its [first party site](https://clearfeed.ai/). +- **Dust:** Dust offers Slack connected agents and Business and Enterprise plans, with product and packaging details on the [Dust site](https://dust.tt/). +- **Botpress:** Botpress provides an [official Slack integration](https://www.botpress.com/docs/integrations/integration-guides/slack/) and managed pricing based on its current plans. +- **n8n:** n8n provides cloud and self hosted deployment under its [fair code licensing model](https://docs.n8n.io/n8n-community-license). +- **Zapier:** Zapier provides [Slack triggers and actions](https://zapier.com/apps/slack/integrations) across its managed automation service. ## Which related AI agent comparisons should buyers read? -Sim’s Slack guide owns the Slack-specific selection and deployment lane, while the broader best AI agent builder comparison remains the canonical guide for head-term research. +This guide covers Slack selection, deployment, CRM work, knowledge retrieval, and governance. For the broader category, read [Best AI Agent Platforms and Builders in 2026](https://www.sim.ai/library/best-ai-agent-platforms-2026). For CRM native sales agents and prospecting tools, read [Best AI Agents for Sales and CRM Automation](https://www.sim.ai/library/best-ai-agents-sales-crm-automation). -- For the broader category, read [Best AI Agent Platforms and Builders in 2026](https://www.sim.ai/library/best-ai-agent-platforms-2026). -- For Slack-specific evaluation, deployment, Slack-to-CRM, knowledge, and governance questions, remain on this guide. -- For CRM-native sales agents and prospecting tools such as Salesforce Agentforce, HubSpot Breeze, and Clay, read [Best AI Agents for Sales and CRM Automation](https://www.sim.ai/library/best-ai-agents-sales-crm-automation). -- For direct platform evaluation, compare the tested workflow, licensing requirements, deployment model, and operating cost rather than relying on a generic overall ranking. +Compare the tested workflow, licensing requirements, deployment model, permissions, and operating cost rather than relying on a generic ranking. ## Where can buyers verify the platform claims in this guide? -Sim and the compared vendors provide first-party product or documentation pages that buyers should recheck because features, limits, and commercial terms can change. +The following first party sources support the changing product, pricing, hosting, integration, and license claims in this comparison as of November 2026: - [Sim GitHub repository](https://github.com/simstudioai/sim) -- [Sim Apache 2.0 license](https://github.com/simstudioai/sim/blob/main/LICENSE) +- [Sim core license](https://github.com/simstudioai/sim/blob/main/LICENSE) +- [Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE) +- [Sim bring your own key documentation](https://docs.sim.ai/platform/costs#bring-your-own-key-byok) +- [Sim self hosting documentation](https://docs.sim.ai/platform/self-hosting) - [Slack developer platform](https://api.slack.com/) +- [Slack AI](https://slack.com/features/ai) +- [Slack pricing](https://slack.com/pricing) - [ClearFeed](https://clearfeed.ai/) +- [ClearFeed Slack chatbot](https://clearfeed.ai/slack-chatbot) +- [Dust](https://dust.tt/) - [Dust Slack integration](https://dust.tt/integrations/slack) - [Botpress Slack integration documentation](https://www.botpress.com/docs/integrations/integration-guides/slack/) - [n8n Slack node documentation](https://docs.n8n.io/integrations/builtin/app-nodes/n8n-nodes-base.slack/) -- [n8n Sustainable Use License documentation](https://docs.n8n.io/privacy-and-security/sustainable-use-license/) +- [n8n community license documentation](https://docs.n8n.io/n8n-community-license) +- [n8n pricing](https://n8n.io/pricing/) - [Zapier Slack integrations](https://zapier.com/apps/slack/integrations) +- [Gumloop Slack agent documentation](https://docs.gumloop.com/core-concepts/agents_slack) diff --git a/apps/sim/content/library/best-free-ai-agent-builders-2026/index.mdx b/apps/sim/content/library/best-free-ai-agent-builders-2026/index.mdx index 1f428f99bb4..d49bd09d476 100644 --- a/apps/sim/content/library/best-free-ai-agent-builders-2026/index.mdx +++ b/apps/sim/content/library/best-free-ai-agent-builders-2026/index.mdx @@ -168,4 +168,5 @@ Before you commit, run one real task end to end on the free plan, including a de - [Best no-code AI agent builders](https://www.sim.ai/library/best-no-code-ai-agent-builders-2026) if nobody on your team writes code - [Best open-source AI agent platforms](https://www.sim.ai/library/open-source-ai-agent-platforms) if self-hosting is a requirement +- [Cheapest AI agent builders for startups](https://www.sim.ai/library/cheapest-ai-agent-builders-for-startups-2026) if you are comparing paid entry prices as well as free plans - [Best AI agent platforms and builders in 2026](https://www.sim.ai/library/best-ai-agent-platforms-2026) for the broader category diff --git a/apps/sim/content/library/best-glean-alternatives-pricing-2026/index.mdx b/apps/sim/content/library/best-glean-alternatives-pricing-2026/index.mdx new file mode 100644 index 00000000000..d89009fd960 --- /dev/null +++ b/apps/sim/content/library/best-glean-alternatives-pricing-2026/index.mdx @@ -0,0 +1,220 @@ +--- +slug: best-glean-alternatives-pricing-2026 +title: 'What Are the Best Glean Alternatives, and How Much Does Glean Cost?' +description: 'Compare Glean alternatives for enterprise search, knowledge management, workplace assistants, and governed AI agents, plus Glean pricing details.' +seoTitle: 'Glean Alternatives and Pricing in 2026' +date: 2026-11-24 +updated: 2026-11-24 +authors: + - andrew +readingTime: 10 +tags: [AI Agents, Enterprise Search, Knowledge Management, Sim] +ogImage: /library/best-glean-alternatives-pricing-2026/cover.jpg +draft: false +faq: + - q: "Is Glean an enterprise search platform or an AI agent platform?" + a: "Glean is primarily an enterprise search and work-assistant platform that also offers agent capabilities around connected organizational knowledge." + - q: "What is the difference between enterprise search and an AI agent workspace?" + a: "Glean and Coveo focus on finding and presenting relevant information, while Sim focuses on building agents that can retrieve context, make decisions, and execute governed steps across tools." + - q: "Which Glean competitors can be self-hosted?" + a: "Sim and n8n document self-hosted deployment options. Buyers should confirm deployment terms directly with every vendor in their shortlist." + - q: "Which Glean alternative is open source?" + a: "Sim's core is open source under the OSI-approved Apache 2.0 license, while Sim enterprise code has a separate license. n8n uses the source-available Sustainable Use License rather than an OSI-approved open-source license." + - q: "Can Glean alternatives search the web and internal documents together?" + a: "Sim can be configured to combine retrieval from connected knowledge sources with web-search tools in one agent. Other products' support depends on their connectors, search products, and agent configuration." + - q: "Which Glean alternative supports human approval before an agent takes action?" + a: "Sim supports a Human in the Loop step that pauses a run and resumes with submitted form fields. A downstream Condition can then route the workflow based on an approval or rejection field." + - q: "Is n8n a direct replacement for Glean?" + a: "n8n is not a direct replacement for Glean because n8n provides workflow execution components rather than a turnkey permissions-aware enterprise search experience." + - q: "Can Sim replace Glean for company-wide enterprise search?" + a: "Sim fits teams whose main requirement is building action-oriented agents, because Sim is not a drop-in company-wide enterprise search engine." + - q: "Which Glean alternative fits Microsoft 365 organizations?" + a: "Microsoft 365 Copilot fits organizations whose documents, communications, identity, and permissions already reside primarily in Microsoft 365." + - q: "Which Glean alternative fits teams that need actions across business tools?" + a: "Sim fits teams building governed agents that combine retrieved context with API calls, application tools, logic, and human input." + - q: "What should a CIO include in a Glean proof of concept?" + a: "A Glean proof of concept should test representative data sources, permission-sensitive queries, retrieval quality, stale content, connector reliability, administrative controls, adoption, implementation effort, and total contract cost." + - q: "What should a CIO include in a Glean alternative proof of concept?" + a: "A Glean alternative proof of concept should add action accuracy, credential isolation, approval behavior, failure handling, auditability, deployment requirements, and operational ownership to the enterprise-search tests." +--- + +## TL;DR + +The right Glean alternative depends on the job. [Coveo](https://www.coveo.com/en/solutions/digital-workplace) fits search-led digital workplace experiences, [Microsoft 365 Copilot](https://www.microsoft.com/en-us/copilot/pricing/enterprise) fits Microsoft-centric organizations, [Guru](https://www.getguru.com/features/verification) fits knowledge maintenance, [Dust](https://dust.tt/home/product) fits configurable workplace agents, [n8n](https://n8n.io/pricing/) fits technical workflow automation, and Sim fits teams that need governed agents to retrieve context and act across tools. + +[Glean](https://www.glean.com/enterprise-search) remains a strong option for permissions-aware enterprise search. Sim is not a pure enterprise search engine. Sim is the open-source AI workspace where teams build, deploy, and manage AI agents that combine knowledge retrieval with tool use and multi-step execution. + +All pricing and licensing references in this guide are current as of November 2026 and link to first-party vendor sources. + +## What are the best Glean alternatives? + +Sim, Coveo, Microsoft 365 Copilot, Guru, Dust, and n8n address distinct enterprise requirements rather than serving as interchangeable replacements. + +1. **Sim:** Fits governed agents that search for context and act across systems. +2. **[Coveo](https://www.coveo.com/en/pricing/):** Fits enterprise search across digital workplace, service, commerce, and website experiences. +3. **[Microsoft 365 Copilot](https://learn.microsoft.com/en-us/microsoft-365/copilot/extensibility/copilot-apis-overview):** Fits organizations centered on Microsoft 365 and Microsoft Graph. +4. **[Guru](https://www.getguru.com/features/verification):** Fits teams maintaining and delivering verified internal knowledge in employees' existing tools. +5. **[Dust](https://dust.tt/home/product):** Fits configurable workplace agents that use company context. +6. **[n8n](https://n8n.io/pricing/):** Fits technical teams building workflow automation around APIs, databases, and AI models. + +[Glean is compelling](https://www.glean.com/enterprise-search) when permissions-aware search and a unified employee assistant are the primary requirements. Buyers should consider alternatives when deployment control, action depth, ecosystem alignment, knowledge-maintenance workflows, or automation flexibility matters more than turnkey enterprise search. + +## How did we compare Glean alternatives? + +This comparison uses practical buying questions rather than scores or rankings: + +- Can the product retrieve useful context from systems employees already use? +- Does it preserve source-system permissions when returning search results? +- Can it take governed actions, or does it mainly answer questions? +- What deployment options does the vendor document? +- What identity, access, audit, and administrative controls are available? +- Is the pricing model public enough for buyers to estimate cost before procurement? + +Enterprise search, knowledge management, workplace agents, and agent workspaces are different categories with overlapping use cases. A tool can be a credible Glean alternative for one buying need without matching Glean feature for feature. + +## How do Glean alternatives compare? + +Glean fits buyers seeking turnkey permissions-aware enterprise search. Sim fits buyers whose primary requirement is building agents that retrieve context and execute governed work across systems. + +| Platform | Primary fit | Search and context | Actions | Deployment and pricing | +|---|---|---|---|---| +| **Glean** | Permissions-aware enterprise search and assistance | Glean says its search spans 100+ tools and returns permission-aware results | Glean also offers governed agent capabilities around enterprise context | Glean documents per-user licensing, with usage models that vary between its Core Suite and Enterprise Flex offerings | +| **Sim** | Governed, action-oriented agents | Agents can combine retrieval, models, APIs, and connected tools | Visual workflows support tools, logic, human input, and multi-step execution | Sim Cloud has published plans, and Sim's core can be self-hosted | +| **Coveo** | Search-led workplace, service, website, and commerce experiences | Coveo offers a secure unified index and AI search across enterprise knowledge | The product is oriented around search and digital experiences | Coveo publishes product packaging and asks buyers to request pricing | +| **Microsoft 365 Copilot** | Microsoft-centered organizations | Microsoft 365 Copilot works with Microsoft 365 data and its identity model | Copilot Studio extends the environment with custom agents and actions | Microsoft publishes enterprise and Copilot Studio licensing options | +| **Guru** | Knowledge governance and verification | Guru combines enterprise knowledge access with human verification workflows | Its focus is trusted answers and knowledge maintenance | Guru now scopes pricing around each organization's scale and knowledge requirements | +| **Dust** | Configurable workplace agents | Dust connects company knowledge, tools, and teams | Custom agents can use knowledge, tools, schedules, and triggers | Dust publishes a Business plan and custom Enterprise options | +| **n8n** | Technical workflow automation | Teams can assemble retrieval from integrations, databases, vector stores, and models | n8n provides flexible API and workflow execution | n8n offers cloud and self-hosted editions, with cloud pricing based on workflow executions | + +Sources for the table include [Glean Enterprise Search](https://www.glean.com/enterprise-search), [Glean Core Suite licensing](https://docs.glean.com/glean-core-suite-pricing), [Sim pricing](https://www.sim.ai/pricing), [Coveo pricing](https://www.coveo.com/en/pricing/), [Microsoft Copilot enterprise pricing](https://www.microsoft.com/en-us/copilot/pricing/enterprise), [Guru pricing](https://www.getguru.com/pricing), [Dust pricing](https://dust.tt/home/pricing), and [n8n pricing](https://n8n.io/pricing/). + +## What key facts should enterprise buyers know at a glance? + +Licensing, deployment, and billing differ materially across these products, so procurement teams should compare implementation scope as well as subscription terms. + +- **Glean:** Its [Core Suite](https://docs.glean.com/glean-core-suite-pricing) uses per-user, per-month licensing, while [Enterprise Flex](https://docs.glean.com/glean-enterprise-flex-pricing) combines per-user licensing with pooled usage credits. +- **Sim:** [Sim's core is Apache 2.0](https://github.com/simstudioai/sim/blob/main/LICENSE) and can be self-hosted. Code in `apps/sim/ee` is covered by the separate [Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE), and production use of that enterprise code requires an active Sim Enterprise subscription. +- **Coveo:** Coveo's [pricing page](https://www.coveo.com/en/pricing/) describes packages for service, website, workplace, and commerce use cases and directs buyers to request pricing. +- **Microsoft 365 Copilot:** Microsoft publishes [enterprise Copilot plans](https://www.microsoft.com/en-us/copilot/pricing/enterprise), with separate options for [Copilot Studio](https://www.microsoft.com/en-us/copilot/pricing/copilot-studio). +- **Guru:** Guru's [pricing page](https://www.getguru.com/pricing) says pricing is tailored to organizational scale, knowledge complexity, and AI maturity. +- **Dust:** Dust publishes [Business and Enterprise plan details](https://dust.tt/home/pricing), including credits, connectors, governance, and support differences. +- **n8n:** n8n's self-hosted Community Edition uses the [Sustainable Use License](https://docs.n8n.io/n8n-community-license/community-license/license-faq), while its [pricing](https://n8n.io/pricing/) covers cloud and paid self-hosted plans. + +## How much does Glean cost? + +Glean does not publish a universal dollar list price in its public pricing documentation as of November 2026. Its [Core Suite documentation](https://docs.glean.com/glean-core-suite-pricing) describes per-user, per-month licensing, while [Enterprise Flex](https://docs.glean.com/glean-enterprise-flex-pricing) combines per-user seats with pooled credits for advanced AI usage. + +Buyers should request a written quote that separates these cost drivers: + +- Number of licensed or active users +- Included data sources and connectors +- Search, assistant, and agent capabilities +- Identity, governance, security, and support requirements +- Implementation and connector setup +- Contract length and minimum commitment +- Usage allowances and overage terms for the proposed package + +A useful total-cost estimate covers both subscription fees and implementation work. Third-party estimates should not be treated as authoritative purchase terms. + +## Is Sim a good Glean alternative? + +Sim fits teams that need to build governed agents that retrieve context and then take action across APIs and business tools. + +**Fit:** CIOs, Heads of AI, platform teams, and developers that want an extensible agent workspace rather than a preconfigured enterprise search product. + +**Pricing and deployment:** [Sim publishes cloud plan details](https://www.sim.ai/pricing), and workspace BYOK keys work on any Sim Cloud plan. Organization-level model keys require Pro for Teams, Max for Teams, or Enterprise, according to the [Sim cost and BYOK documentation](https://docs.sim.ai/platform/costs#bring-your-own-key-byok). [Self-hosted Sim](https://docs.sim.ai/platform/self-hosting) can use local model services such as Ollama, vLLM, LM Studio, or LiteLLM without requiring Sim Enterprise. + +**Strengths:** Sim provides a visual workflow builder for combining models, retrieval, APIs, conditions, human input, and application actions. Sim Cloud reduces operational work, while self-hosting supports infrastructure control and local models. Enterprise code covers SSO, SCIM, access control, audit logs, data retention, session policies, and related controls. + +**Limitations:** Sim is not a drop-in enterprise search engine. Teams must design data ingestion, retrieval, permissions, credentials, and action policies for each agent. Organizations seeking an immediately deployed company-wide search layer may prefer Glean or Coveo. + +For adjacent comparisons, see [Glean vs Dust](https://www.sim.ai/library/glean-vs-dust-enterprise-ai) and [AI agents for internal knowledge search](https://www.sim.ai/library/best-ai-agents-internal-knowledge-search). + +## Is Coveo a good Glean alternative? + +Coveo fits organizations prioritizing enterprise search, relevance, and search-driven digital experiences. + +**Fit:** Enterprises that need search across employee, customer-service, commerce, or website experiences and want relevance tooling around those experiences. + +**Pricing:** As of November 2026, [Coveo's pricing page](https://www.coveo.com/en/pricing/) describes product-specific packaging and asks buyers to request pricing. + +**Strengths:** Coveo specializes in secure, unified search and relevance across several enterprise use cases. Its [digital workplace product](https://www.coveo.com/en/solutions/digital-workplace) connects enterprise systems and surfaces knowledge in employees' flow of work. + +**Limitations:** Coveo is oriented around search and digital experiences rather than a general-purpose agent workspace. Buyers whose main goal is arbitrary multi-step execution across APIs should compare its action model with Sim or n8n. + +## Is Microsoft 365 Copilot a good Glean alternative? + +Microsoft 365 Copilot fits organizations whose knowledge, identity, collaboration, and productivity estate centers on Microsoft 365. + +**Fit:** Enterprises that primarily use Teams, SharePoint, Outlook, Word, Excel, and other Microsoft services. + +**Pricing:** As of November 2026, Microsoft publishes [commercial enterprise Copilot licensing](https://www.microsoft.com/en-us/copilot/pricing/enterprise), while agent-building capacity has separate [Copilot Studio options](https://www.microsoft.com/en-us/copilot/pricing/copilot-studio). + +**Strengths:** Microsoft documents that its Copilot APIs use the same authentication and authorization model as other Microsoft Graph APIs, with organizational controls enforced through Microsoft Entra ID and Microsoft 365. [Microsoft's security documentation](https://learn.microsoft.com/en-us/microsoft-365/copilot/extensibility/copilot-apis-security-authentication) explains those permission boundaries. + +**Limitations:** Microsoft 365 Copilot is most compelling inside the Microsoft ecosystem. Enterprises with heterogeneous data estates should assess external connectors, non-Microsoft actions, licensing dependencies, and implementation effort. + +## Is Guru a good Glean alternative? + +Guru fits teams that need governed knowledge creation, verification, and delivery inside employees' existing work surfaces. + +**Fit:** Operations, enablement, support, and people teams that need employees to find trusted internal answers and keep knowledge current. + +**Pricing:** As of November 2026, [Guru's pricing page](https://www.getguru.com/pricing) says the vendor scopes an engagement based on organizational scale, knowledge complexity, and AI maturity rather than listing standard per-user tiers. + +**Strengths:** Guru combines knowledge discovery with workflows for capturing, organizing, and verifying internal information. Its [verification feature](https://www.getguru.com/features/verification) assigns verification status, timestamps, and responsible subject-matter experts to knowledge. + +**Limitations:** Guru is not a general-purpose self-hosted agent workspace. Buyers needing complex API execution or custom multi-step agents should compare Guru with Sim or n8n. + +## Is Dust a good Glean alternative? + +Dust fits teams that want configurable workplace agents grounded in company context. + +**Fit:** Enterprises creating role-specific agents for knowledge work without making enterprise search the only interface. + +**Pricing:** As of November 2026, [Dust publishes a Business plan and custom Enterprise options](https://dust.tt/home/pricing). + +**Strengths:** Dust says its agents can use company knowledge, tools, schedules, triggers, and multiple models. Its [product overview](https://dust.tt/home/product) emphasizes shared knowledge, tools, skills, and governed human-agent collaboration. + +**Limitations:** Buyers should assess Dust's connector coverage, source permissions, action depth, administration, deployment options, and contract terms against their requirements. + +## Is n8n a good Glean alternative? + +n8n fits technical teams that primarily need workflow execution, but it is not a direct replacement for turnkey permissions-aware enterprise search. + +**Fit:** Technical automation teams assembling API workflows, retrieval pipelines, model calls, and application actions. + +**Pricing:** As of November 2026, [n8n pricing](https://n8n.io/pricing/) is based on monthly workflow executions and includes hosted and paid self-hosted plans. n8n also documents a free [self-hosted Community Edition](https://docs.n8n.io/deploy/host-n8n/community-edition-features). + +**Strengths:** n8n provides integrations, workflow logic, AI nodes, and cloud or self-hosted deployment. Teams can construct knowledge-retrieval workflows by combining data sources, vector stores, models, and application nodes. + +**Limitations:** Teams must build and operate the search, indexing, retrieval, and permission behavior that Glean packages as an enterprise product. n8n's [Sustainable Use License](https://docs.n8n.io/n8n-community-license/community-license/license-faq) is source-available rather than OSI-approved open source. + +## Which Glean alternative should CIOs choose? + +Choose according to the primary requirement: + +- Choose **[Glean](https://www.glean.com/enterprise-search)** when company-wide, permissions-aware enterprise search is the main purchase. +- Choose **Sim** when agents need to do more than return an answer, teams want a visual builder for models, tools, logic, and human input, or self-hosting and local-model support matter. +- Choose **[Coveo](https://www.coveo.com/en/solutions/digital-workplace)** when search relevance and search-driven digital experiences are central requirements. +- Choose **[Microsoft 365 Copilot](https://learn.microsoft.com/en-us/microsoft-365/copilot/extensibility/copilot-apis-overview)** when Microsoft Graph and Microsoft 365 define the enterprise knowledge layer. +- Choose **[Guru](https://www.getguru.com/features/verification)** when trusted knowledge maintenance is the main problem. +- Choose **[Dust](https://dust.tt/home/product)** when configurable workplace agents are the desired interface. +- Choose **[n8n](https://n8n.io/pricing/)** when a technical team wants to construct the surrounding automation itself. + +A proof of concept should use representative data, permission-sensitive queries, stale content, realistic actions, approval paths, failures, and administrative review. Procurement should evaluate operational ownership and implementation effort alongside subscription pricing. + +## Where can buyers compare Glean, Dust, and internal knowledge-search agents in more detail? + +These related guides separate direct product comparison, internal-search use cases, and broader enterprise-agent evaluation: + +- [Glean vs Dust: Which Enterprise AI Platform Should You Choose?](https://www.sim.ai/library/glean-vs-dust-enterprise-ai) covers direct head-to-head evaluation. +- [Best AI Agents for Internal Knowledge Search Across Docs and Tools](https://www.sim.ai/library/best-ai-agents-internal-knowledge-search) focuses on internal-search use cases. +- [Best Enterprise AI Agent Platforms in 2026](https://www.sim.ai/library/best-ai-agent-platforms-for-enterprise-teams-2026) compares governance capabilities such as SSO, SCIM, access control, and audit logs. +- [Best AI Agent Platforms and Builders in 2026](https://www.sim.ai/library/best-ai-agent-platforms-2026) covers the wider AI agent platform market. + +## What else should enterprise buyers know about Glean alternatives? + +Glean alternatives should be evaluated as different product categories with overlapping use cases, not as feature-identical substitutes. Enterprise search products package indexing, retrieval, relevance, and permission handling, while agent workspaces and automation products give teams more responsibility for designing context, credentials, actions, approvals, and operational safeguards. + +The final choice should follow the workload. Start with the employee question or business action the system must support, identify the source permissions and audit evidence required, and then test the smallest realistic deployment before signing a broad contract. diff --git a/apps/sim/content/library/best-self-hosted-ai-workflow-automation-platforms-2026/index.mdx b/apps/sim/content/library/best-self-hosted-ai-workflow-automation-platforms-2026/index.mdx index 1c24b275e71..577538d8f81 100644 --- a/apps/sim/content/library/best-self-hosted-ai-workflow-automation-platforms-2026/index.mdx +++ b/apps/sim/content/library/best-self-hosted-ai-workflow-automation-platforms-2026/index.mdx @@ -333,7 +333,7 @@ The selection therefore depends on both product capabilities and the team that w This example routes a sample request using its priority. It uses two blocks in Sim and two nodes in n8n, with no model calls or external integrations. You can use the same inputs to check a successful run and find the failed step on each platform. 1. In Sim, download the [Sim workflow JSON](/library/best-self-hosted-ai-workflow-automation-platforms-2026/support-routing-sim.json). [Import it into a test workspace](https://docs.sim.ai/cli/workflows#import-workflow), [deploy it](https://docs.sim.ai/workflows/deployment), then [call the execution API](https://docs.sim.ai/api-reference/getting-started#quick-start) with `{"input":{"priority":"urgent"}}`. Read the routing decision at `data.output.result.queue`. -2. In n8n, download the [n8n workflow JSON](/library/best-self-hosted-ai-workflow-automation-platforms-2026/support-routing-n8n.json). [Import the workflow](https://docs.n8n.io/deploy/host-n8n/configure-n8n/use-the-command-line.md#import-workflows-and-credentials), publish it on a local test instance, and POST `{"priority":"urgent"}` to the [Webhook node's production URL](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.webhook#webhook-urls). Read the decision at `queue`. The bundled webhook is for local testing. Configure authentication before exposing it to a network. +2. In n8n, download the [n8n workflow JSON](/library/best-self-hosted-ai-workflow-automation-platforms-2026/support-routing-n8n.json). [Import the workflow](https://docs.n8n.io/deploy/host-n8n/configure-n8n/use-the-command-line#import-workflows-and-credentials), publish it on a local test instance, and POST `{"priority":"urgent"}` to the [Webhook node's production URL](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.webhook#webhook-urls). Read the decision at `queue`. The bundled webhook is for local testing. Configure authentication before exposing it to a network. 3. Repeat with `"normal"` and `"invalid"`. On Sim, inspect `data.status` and the **Route request** block in Logs. On n8n, open the matching run under **Executions** and inspect the **Route request** node. We ran these inputs on local Docker installations of Sim v0.9.62 and n8n 2.48.5. diff --git a/apps/sim/content/library/cheapest-ai-agent-builders-for-startups-2026/index.mdx b/apps/sim/content/library/cheapest-ai-agent-builders-for-startups-2026/index.mdx new file mode 100644 index 00000000000..9f5e552dff0 --- /dev/null +++ b/apps/sim/content/library/cheapest-ai-agent-builders-for-startups-2026/index.mdx @@ -0,0 +1,196 @@ +--- +slug: cheapest-ai-agent-builders-for-startups-2026 +title: 'Cheapest AI Agent Builders for Startups in 2026: Free Tiers and Entry Prices Compared' +description: 'Compare free tiers and entry prices for Sim, n8n, Zapier, Make, Dify, Gumloop, Lindy, and Relevance AI to find a low-cost AI agent builder for a small team.' +seoTitle: 'Cheapest AI Agent Builders for Startups in 2026' +date: 2026-11-24 +authors: + - sim +readingTime: 8 +tags: [AI Agents, Pricing, Open Source, Sim] +ogImage: /library/cheapest-ai-agent-builders-for-startups-2026/cover.jpg +draft: false +faq: + - q: "What is the cheapest AI agent platform with solid features?" + a: "The lowest cash cost is a self-hosted open-source builder such as Sim, n8n's Community Edition, or Dify's Community Edition, where you pay only for your server and models; among hosted paid plans, Zapier Professional starts at $19.99 a month, n8n Starter at €20 a month billed annually, and Sim Pro at $25 per user per month." + - q: "Which AI agent builder is the best value for the price?" + a: "It depends on the unit you are billed in: n8n bills per workflow execution with unlimited steps, Zapier bills per task, and Sim, Make, Gumloop, and Lindy bill in credits, so the best value is the plan whose unit matches how many steps and model calls your agent makes." + - q: "Which AI agent builder has the best free tier for testing before buying?" + a: "For a recurring hosted allowance, Make's Free plan offers up to 1,000 credits a month and Zapier's Free plan 100 tasks a month, while Sim's Free plan gives 1,000 one-time credits with all integrations and no credit card, and n8n Cloud offers a 14-day trial with no credit card." + - q: "What is the best low-cost or free AI agent platform for a startup with a tiny budget?" + a: "A startup with no budget can self-host Sim, n8n, or Dify for no license fee and bring its own model keys, or start on a hosted free plan and move to a paid tier only when the agent runs every day." + - q: "What is the best AI agent builder for a small startup team?" + a: "For a team rather than a solo builder, check which plan lets you invite teammates before comparing prices: in Sim, Pro at $25 per user per month adds teammate invites and three workspaces to what the Free plan includes." + - q: "Do I need a credit card to try an AI agent builder?" + a: "Not always: Sim's Free plan and n8n Cloud's 14-day trial both start without a credit card." + - q: "Is Sim free?" + a: "Yes, Sim's Free plan costs $0 with 1,000 one-time credits, one workspace, and all 280+ integrations on your own model keys, and Sim's Apache 2.0 core can be self-hosted for no license fee." + - q: "How much does Sim cost after the free plan?" + a: "Sim Pro is $25 per user per month with 6,000 credits a month plus a weekly refresh of 2,000 more, Max is $100 per user per month with 25,000 credits a month plus a weekly refresh of 4,000, and annual billing costs 15% less." + - q: "Can I self-host an AI agent builder for free?" + a: "Yes, Sim's Apache 2.0 core, n8n's Community Edition, and Dify's Community Edition can be self-hosted without a license fee, but you still pay for the server, the models, and the time to maintain them." + - q: "Do AI agent builders offer startup discounts?" + a: "n8n lists a Startup plan for companies with fewer than 20 employees that qualify, so ask each vendor's sales team before paying list price." + - q: "Does bringing my own model API keys lower the cost?" + a: "Usually yes: in Sim, model calls on your own provider keys add no Sim usage charge beyond the 1-credit base charge per run, so you pay the model provider directly at its own rates." +--- + +The cheapest way to run an AI agent in 2026 is to self-host an open-source builder such as Sim, n8n's Community Edition, or Dify's Community Edition and pay only for a server and model usage. If you would rather not run infrastructure, the lowest hosted entry prices are Zapier Professional from $19.99 a month, n8n Starter at €20 a month billed annually, and Sim Pro at $25 per user per month, and several builders have a free plan or trial to test on first. + +This article is published by Sim, and Sim is one of the eight products covered. Prices were checked against each vendor's pricing page on November 24, 2026, except Make, whose page could not be loaded for this review; its figures come from a capture used in our [guide to free AI agent builders](https://www.sim.ai/library/best-free-ai-agent-builders-2026). Prices change, so confirm them before you commit. + +> **Choose self-hosting when** you have someone who can run a server and you want the lowest cash cost. +> +> **Choose a hosted free plan when** you want to test an agent on real work this week without a card. +> +> **Choose Sim when** you want to build visually, in Chat, or with code on an Apache 2.0 core, use your own model keys without a markup, and add teammates on the same agents when you are ready. + +## What is the cheapest AI agent platform with solid features? + +There are two kinds of cheap, and they cost different things. + +- **Self-hosted, no license fee.** Sim, n8n, and Dify publish editions you can run yourself. The software costs nothing, but a server, model usage, updates, and security are on you. +- **Hosted, low entry price.** Zapier, n8n, and Sim have paid plans from about $20 to $25 a month for one builder. You trade a monthly fee for not running anything. + +For a startup, the deciding cost is usually not the plan price but the unit the plan meters. An agent that runs ten steps and three model calls per run burns through a per-task or per-credit allowance much faster than one that runs a single step. + +## How do free tiers and entry prices compare? + +| Builder | Free option | Lowest listed paid price | Billed in | +| --- | --- | --- | --- | +| **Sim** | Free plan, 1,000 one-time credits, no card; or self-host the Apache 2.0 core | Pro, $25 per user per month | Credits | +| **n8n** | Self-hosted Community Edition; 14-day Cloud trial, no card | Starter, €20 a month billed annually | Workflow executions | +| **Zapier** | Free plan, 100 tasks a month, two-step Zaps | Professional, from $19.99 a month | Tasks | +| **Make** | Free plan, up to 1,000 credits a month | Priced by credit volume | Credits | +| **Dify** | Sandbox, 200 message credits; or self-deploy the Community Edition | Professional, $590 per workspace a year | Message credits | +| **Gumloop** | 14-day trial of Pro | Pro, $37 a month | Credits | +| **Lindy** | $50 in credits that last 7 days | From $49.99 per user per month | Credits | +| **Relevance AI** | Try for free | No self-serve price published | Custom | + +## Which builder has the best free tier for testing before you buy? + +The best free tier for testing is one that lets you run the exact agent you plan to buy, with your real integrations, for long enough to see a week of results. + +- **Recurring hosted allowances** suit agents that run on a schedule. Make offers up to 1,000 credits a month, and Zapier 100 tasks a month with two-step Zaps. +- **One-time allowances and trials** suit a focused evaluation. Sim's Free plan gives 1,000 one-time credits with all 280+ integrations and no card. n8n Cloud offers 14 days with no card. Gumloop offers 14 days of Pro. Lindy's $50 in credits last 7 days. +- **Self-hosted editions** have no time limit at all, so they suit long evaluations if you can run a server. + +On Sim's Free plan, models and tools run on your own provider keys, and each run carries a base charge of 1 credit. If every model call in an agent uses your keys, the 1,000 credits cover up to 1,000 runs, with sandboxed code and hosted tools costing extra. + +## What does each platform cost a small startup team? + +Sim, the publisher, is listed first; the others follow in order of entry price, with the trade-off for each stated plainly. + +### 1. Sim + +**Best for:** Small teams that want to build visually, in Chat, or with code, bring their own model keys, and keep the option to self-host. + +**What it costs:** The Free plan is $0 with 1,000 one-time credits, one workspace, two concurrent executions, and all 280+ integrations on your own keys. Pro is $25 per user per month with 6,000 credits a month plus a weekly refresh of 2,000 more, three workspaces, teammate invites, and Sim-hosted models. Max is $100 per user per month with 25,000 credits a month plus a weekly refresh of 4,000. Annual billing costs 15% less. One credit is $0.005, and model calls on your own keys add no Sim usage charge beyond the 1-credit base charge per run. + +**Limitations:** The Free plan's credits do not renew and it does not include teammate invites, so a team that runs agents every day will need Pro or a self-hosted deployment. Enterprise features such as SSO and access control need a license when self-hosted. + +**Sources:** [Sim pricing](https://www.sim.ai/pricing), [Sim repository license](https://github.com/simstudioai/sim/blob/main/LICENSE). + +### 2. Zapier + +**Best for:** Teams whose agents are short, simple automations between popular apps. + +**What it costs:** The Free plan is $0 with 100 tasks a month and two-step Zaps. Professional starts at $19.99 a month, and Team starts at $69 a month. + +**Limitations:** Zapier bills per task, so a multi-step agent that runs often moves up the task tiers quickly. For how that adds up, see [Zapier pricing at scale](https://www.sim.ai/library/zapier-pricing-at-scale). + +**Sources:** [Zapier pricing](https://zapier.com/pricing), [Sim vs Zapier](https://www.sim.ai/comparisons/zapier). + +### 3. n8n + +**Best for:** Technical teams that want per-execution billing or are happy to self-host. + +**What it costs:** The self-hosted Community Edition has no license fee. n8n Cloud's 14-day trial needs no credit card. Starter is €20 a month billed annually for 2,500 workflow executions, and Pro is €50 a month billed annually for 10,000. n8n also lists a Startup plan for qualifying companies with fewer than 20 employees. + +**Limitations:** n8n is fair-code under the Sustainable Use License rather than OSI-approved open source, and self-hosting means running updates and security yourself. For the full breakdown, see [n8n pricing for Cloud, self-hosted, and Enterprise](https://www.sim.ai/library/n8n-pricing-cloud-self-hosted-enterprise). + +**Sources:** [n8n pricing](https://n8n.io/pricing/), [Sim vs n8n](https://www.sim.ai/comparisons/n8n). + +### 4. Make + +**Best for:** Teams that want a recurring hosted free allowance and detailed visual control. + +**What it costs:** Make's Free plan offers up to 1,000 credits a month. Paid plans are priced by monthly credit volume. + +**Limitations:** Each module action consumes credits, so a multi-step agent uses the allowance faster than the headline number suggests. + +**Sources:** [Make pricing](https://www.make.com/en/pricing), [Sim vs Make](https://www.sim.ai/comparisons/make). + +### 5. Gumloop + +**Best for:** Teams that want a hosted builder and are ready to pay after a trial. + +**What it costs:** Pro is $37 a month with 20,000 credits a month, after a 14-day free trial. Enterprise pricing is custom. + +**Limitations:** There is no permanent free plan, so evaluation is limited to the trial window. + +**Sources:** [Gumloop pricing](https://www.gumloop.com/pricing), [Sim vs Gumloop](https://www.sim.ai/comparisons/gumloop). + +### 6. Lindy + +**Best for:** Teams that want a hosted AI assistant they can hand everyday tasks to. + +**What it costs:** You start with $50 in free credits that last 7 days. Paid plans start at $49.99 a month for 5,000 credits per active user, and every active user in the workspace is billed. + +**Limitations:** Per-user billing raises the cost as the team grows, and the free credits expire after a week. + +**Sources:** [Lindy pricing](https://www.lindy.ai/pricing). + +### 7. Dify + +**Best for:** Developers building LLM apps who want a hosted sandbox or a self-deployed edition. + +**What it costs:** The Sandbox plan is free with 200 message credits. Professional is $590 per workspace a year with 5,000 message credits a month, and Team is $1,590 per workspace a year. The Community Edition can be self-deployed under the Dify Open Source License. + +**Limitations:** Paid plans are billed per workspace per year, and the Sandbox credits are sized for trying the product rather than running an agent daily. + +**Sources:** [Dify pricing](https://dify.ai/pricing), [Sim vs Dify](https://www.sim.ai/comparisons/dify). + +### 8. Relevance AI + +**Best for:** Sales and go-to-market teams buying an AI agent workforce through a sales process. + +**What it costs:** Relevance AI offers a free start, but its pricing page publishes no self-serve plan prices; Enterprise is priced through sales. + +**Limitations:** Without a listed price, a startup cannot compare it on cost until it talks to sales. + +**Sources:** [Relevance AI pricing](https://relevanceai.com/pricing), [Sim vs Relevance AI](https://www.sim.ai/comparisons/relevance-ai). + +## How do credits, tasks, and executions change the real price? + +The same agent can cost very different amounts depending on what the plan counts. + +- **Per execution (n8n).** One workflow run counts once, however many steps it has, so long agents are cheaper per run. +- **Per task (Zapier).** Each action step counts, so cost grows with the number of steps. +- **Per credit (Sim, Make, Gumloop, Lindy).** Credits are spent on runs, steps, or model calls depending on the vendor, so check what one credit buys. + +Model usage is often the largest cost of all. Builders that let you bring your own model keys, as Sim does, let you pay the model provider directly instead of a resold rate. For a full cost model, see [how much it costs to build and run an AI agent](https://www.sim.ai/library/how-much-does-it-cost-to-build-and-run-an-ai-agent). + +## When is self-hosting the cheapest option? + +Self-hosting is cheapest when someone on the team can run a server and the agent runs often enough that a hosted plan would move up its tiers. The license fee is zero for Sim's Apache 2.0 core, n8n's Community Edition, and Dify's Community Edition, but you still pay for: + +- **A server.** Sizing depends on the workload, so test with your real agents. +- **Models.** Hosted model APIs bill per token, unless you run a local model. +- **Time.** Updates, backups, and security are your team's job. + +For a side-by-side view of licenses and hosting, see [open-source AI agent platforms](https://www.sim.ai/library/open-source-ai-agent-platforms). + +## How should a startup on a tiny budget choose? + +1. **Write down one agent you need this month,** with its steps, its integrations, and how often it runs. +2. **Build it on a free plan or trial** and count how many credits, tasks, or executions one run uses. +3. **Multiply by a month of runs** and compare that against each vendor's lowest paid tier. +4. **Decide who runs it.** If nobody can maintain a server, pick a hosted plan even if self-hosting looks cheaper on paper. +5. **Ask about startup pricing** before paying list price. + +## Where can you compare more AI agent builders? + +- [The best free AI agent builders in 2026](https://www.sim.ai/library/best-free-ai-agent-builders-2026) +- [The best AI agent platforms in 2026](https://www.sim.ai/library/best-ai-agent-platforms-2026) +- [Bring your own keys to a multi-model AI agent builder](https://www.sim.ai/library/byok-multi-model-ai-agent-builder) diff --git a/apps/sim/content/library/greenhouse-ai-agent-recruiting-operations/index.mdx b/apps/sim/content/library/greenhouse-ai-agent-recruiting-operations/index.mdx new file mode 100644 index 00000000000..8a6e650c40a --- /dev/null +++ b/apps/sim/content/library/greenhouse-ai-agent-recruiting-operations/index.mdx @@ -0,0 +1,192 @@ +--- +slug: greenhouse-ai-agent-recruiting-operations +title: 'How Do You Build a Governed AI Agent for Greenhouse Recruiting Operations?' +description: 'Build a governed Greenhouse AI agent for application summaries, stage alerts, scorecard reminders, scheduling handoffs, and approved Workday transfers.' +seoTitle: 'Greenhouse AI Agent for Recruiting Operations' +date: 2026-11-23 +updated: 2026-11-23 +authors: + - andrew +readingTime: 8 +tags: [AI Agents, Greenhouse, Recruiting Operations, HR Automation, Sim] +ogImage: /library/greenhouse-ai-agent-recruiting-operations/cover.jpg +draft: false +faq: + - q: "Can AI summarize resumes in Greenhouse?" + a: "Greenhouse data can be summarized by a Sim agent when the workflow retrieves only necessary job-related information, labels the result as a model-generated summary, and leaves hiring decisions with people." + - q: "Can Greenhouse send stage changes to Slack?" + a: "Greenhouse stage changes can reach Slack through a Sim workflow that receives a documented event or polls an approved endpoint, filters the event, and posts a minimal update to an authorized private channel." + - q: "Can Greenhouse sync accepted offers to Workday?" + a: "Greenhouse accepted offer data can be prepared for Workday by Sim, but a governed workflow should validate fields and require human approval before creating or changing an employee record." + - q: "How do you connect Greenhouse to Claude for a recruiting team?" + a: "Sim can connect approved Greenhouse data to a Claude model step by using a stored provider credential, minimizing candidate fields, and routing the model output through validation and human review before any consequential action." + - q: "Can an AI agent schedule Greenhouse interviews?" + a: "A Greenhouse agent can prepare scheduling options and internal handoffs, but candidate-facing invitations and material schedule changes should require recruiter approval unless the organization has separately validated and authorized autonomous scheduling." + - q: "Does the Greenhouse Harvest API contain candidate PII?" + a: "Greenhouse recruiting records can contain personal information, so Harvest API access should be treated as sensitive and limited by endpoint permission, field selection, purpose, retention policy, and authorized user access." + - q: "Should Greenhouse agents make hiring decisions?" + a: "Greenhouse agents should not make final hiring decisions because models can omit context, reproduce bias, and generate unsupported conclusions; Sim should support administrative work and human review instead." + - q: "Can n8n automate Greenhouse recruiting operations?" + a: "n8n can support Greenhouse automation through available integrations and HTTP-based API workflows, but recruiting teams must design their own least-privilege access, candidate data controls, approvals, and failure handling." + - q: "Is Sim open source?" + a: "Sim's core is open source under Apache 2.0, while apps/sim/ee is governed by the separate Sim Enterprise License and requires an active Enterprise subscription for production use." + - q: "Do Sim Cloud workspaces support BYOK?" + a: "Sim Cloud supports workspace bring-your-own-key credentials on every cloud plan, while organization-level keys require Pro for Teams, Max for Teams, or Enterprise." +--- + +## TL;DR + +Greenhouse and Sim can support governed recruiting operations by summarizing new applications, routing internal scheduling handoffs, sending stage alerts to Slack, reminding interviewers about scorecards, and preparing accepted offer data for Workday with human approval before sensitive actions. + +Sim is the open-source AI workspace where teams build, deploy, and manage AI agents. The [Greenhouse integration](https://www.sim.ai/integrations/greenhouse) lets recruiting operations teams connect Greenhouse data to governed workflows without turning an AI model into an unsupervised hiring decision-maker. + +## What can an AI agent safely automate in Greenhouse? + +Greenhouse agents can safely automate administrative coordination and internal decision support when candidate-facing communication, hiring decisions, and sensitive record changes remain under human control. + +Good automation candidates include application summaries for recruiters, internal scheduling handoffs, stage change notifications, overdue scorecard reminders, and approved data transfers to an HR system. The agent should summarize evidence already present in Greenhouse rather than infer protected characteristics, rank people from hidden signals, or make final hiring decisions. + +A practical boundary is simple: let the agent collect, transform, and route information, but require a person to approve candidate-facing messages and consequential record changes. The [AI Agents for Recruiting guide](https://www.sim.ai/library/best-ai-agents-for-recruiting-teams) explains how this governed approach compares with broader recruiting tools. + +## What should recruiting operations teams know before connecting Greenhouse to an AI agent? + +Greenhouse access should be limited to the smallest set of objects and actions required for each workflow. + +As of November 2026, Greenhouse documents its Recruiting APIs, including the Harvest API and recruiting webhooks, in the [Greenhouse developer documentation](https://developers.greenhouse.io/). Greenhouse administrators should create a dedicated integration credential, grant only the required endpoint permissions, and keep that credential in the workflow platform credential store rather than in prompts or workflow text. + +Recruiting operations, People Ops, IT, security, and legal teams should agree on four controls before deployment: + +1. Define which Greenhouse fields the agent may read and which fields must never enter a model prompt. + +2. Define whether model providers may retain submitted data and select an approved provider configuration. + +3. Require human approval before candidate-facing communication, rejection, offer changes, or transfers into downstream systems. + +4. Define retention, access review, incident response, and audit requirements for workflow runs. + +[Sim's Human in the Loop block](https://docs.sim.ai/workflows/blocks/human-in-the-loop) pauses a run and collects form fields. An approval field must be evaluated by a downstream Condition before the workflow continues. [Sim Guardrails](https://docs.sim.ai/workflows/blocks/guardrails) report whether a check passed or failed, so a downstream Condition must also route the workflow based on that result. + +## Which Greenhouse API objects should the agent read or write? + +Greenhouse agents should read only the recruiting objects required for the task and should receive write access only when a reviewed workflow has a specific reason to change a record. + +The following access pattern is a conservative starting point based on the recruiting data available through the [Greenhouse developer resources](https://developers.greenhouse.io/) as of November 2026. + +| Greenhouse object | Typical workflow use | Recommended agent access | +| --- | --- | --- | +| Candidate | Identify the candidate associated with an application | Read only and limit retrieved fields | +| Application | Read status, job association, and current stage | Read by default; allow stage changes only in a separately approved workflow | +| Job | Provide role context for an application summary | Read only | +| Scheduled interview | Prepare internal scheduling handoffs and reminders | Read only unless an approved scheduling workflow requires more | +| Scorecard | Detect missing interview feedback | Read completion state without generating interviewer feedback | +| Offer | Detect an accepted offer and prepare an HR system handoff | Read only for the handoff workflow | + +Field availability and endpoint permissions can vary by Greenhouse configuration. The production workflow should use the exact object names, events, and permissions shown in the organization's Greenhouse developer settings and current official documentation. + +## How do you build a new application summary for a Slack hiring channel? + +Sim can turn a new Greenhouse application into a concise internal summary and send it to an authorized Slack hiring channel without making a hiring decision. + +1. Start the workflow from a documented Greenhouse event or an approved polling process. + +2. Retrieve only the candidate, application, and job fields needed for the summary. + +3. Remove unnecessary contact details and other personal information before the model step. + +4. Ask the model to summarize job-related evidence, stated experience, open questions, and missing information without assigning a hiring score. + +5. Run the output through a Guardrails check, then use a Condition to stop or reroute failed output. + +6. Send the approved format to a private Slack channel with links back to the source record for recruiter review. + +The Slack message should distinguish candidate-supplied facts from model-generated summaries. The agent should not infer age, health, ethnicity, religion, family status, disability, or other protected characteristics from names, dates, addresses, photographs, or writing style. + +## How do you send Greenhouse stage change alerts to Slack? + +Sim can route documented Greenhouse stage changes to Slack so interview teams receive timely internal updates without exposing the entire candidate record. + +1. Configure a relevant Greenhouse event using the current [Greenhouse webhook documentation](https://docs.greenhouse.io/webhooks.html), or use an approved polling pattern when an event is unavailable. + +2. Retrieve the application identifier, job, previous stage, current stage, and responsible recruiting contact. + +3. Apply an allowlist so only approved jobs, departments, or stages can produce a message. + +4. Post a short update to the appropriate private Slack channel. + +5. Record the workflow result and route delivery failures to recruiting operations. + +A stage alert should include only the information the channel needs. Teams handling candidate information in Slack should also follow the access and retention controls in the [Slack AI Agent Security guide](https://www.sim.ai/library/slack-ai-agent-security-permissions-guide). + +## How do you automate Greenhouse scorecard reminders? + +Sim can identify incomplete Greenhouse scorecards and send internal reminders while leaving interview feedback entirely with the interviewer. + +1. Run the workflow on an approved schedule. + +2. Read recently completed interviews and their associated scorecard completion state. + +3. Compare the interview completion time with the organization's reminder policy. + +4. Notify only the responsible interviewer or recruiting coordinator through an approved Slack destination. + +5. Stop reminders when the scorecard is completed or when the application reaches an excluded state. + +The model may help produce a concise reminder, but it should never draft evaluative scorecard content on behalf of an interviewer. Interviewers must provide their own evidence and assessment. + +## How do you hand an accepted Greenhouse offer to Workday? + +Sim can prepare an accepted Greenhouse offer for Workday onboarding while requiring a person to approve the transfer before any employee record is created or changed. + +1. Start from the documented Greenhouse event or offer status used by the organization. + +2. Retrieve only the approved candidate, job, start date, location, manager, and offer fields required by the Workday process. + +3. Validate required fields and route incomplete records to People Ops. + +4. Pause the run with Human in the Loop and collect an explicit approval or rejection field. + +5. Use a Condition to continue only when the reviewer approved the transfer. + +6. Send the approved fields through a configured [Sim Workday action](https://docs.sim.ai/integrations/workday) and return the result to People Ops. + +The workflow should use a stable identifier to prevent duplicate employee creation when a run is retried. The [governed Workday AI agent guide](https://www.sim.ai/library/workday-ai-agent-employee-onboarding-offboarding) covers governance on the Workday side of this handoff. + +## How should Greenhouse agents handle permissions, PII, and auditability? + +Greenhouse agents should combine least-privilege credentials, data minimization, human approval, and reviewable execution records. + +[Greenhouse recruiting data](https://developers.greenhouse.io/) can include candidate, application, interview, scorecard, offer, and attachment information that teams should treat as sensitive. A workflow should retrieve only the fields needed for its declared purpose and should avoid placing complete resumes or complete candidate profiles into prompts when a smaller field set will work. + +Use separate credentials for development and production. Restrict Slack destinations to private channels with approved membership. Review Greenhouse, Slack, Workday, model provider, and Sim access whenever a recruiter, coordinator, administrator, or integration owner changes roles. The [agentic AI security controls guide](https://www.sim.ai/library/agentic-ai-security-risks-controls) provides a broader framework for permissions, approvals, and incident handling. + +As of November 2026, [Sim's core is licensed under Apache 2.0](https://github.com/simstudioai/sim/blob/main/LICENSE), while code in `apps/sim/ee` is governed by the separate [Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE). Enterprise capabilities such as audit logs, access control, data retention, and credential groups are located in `apps/sim/ee`, and production use of that code requires an active Sim Enterprise subscription. + +## Should recruiting teams use Sim or n8n for Greenhouse automation? + +Sim fits recruiting teams that want a visual agent workflow with model steps, governed human review, and explicit routing around AI output. n8n fits teams centered on general-purpose workflow automation. + +As of November 2026, Sim's core uses the OSI-approved Apache 2.0 license, while enterprise code uses the separate Sim Enterprise License. Sim Cloud workspaces can use [their own model provider keys](https://docs.sim.ai/platform/costs) on any cloud plan. + +As of November 2026, n8n is self-hostable under the [Sustainable Use License](https://github.com/n8n-io/n8n/blob/master/LICENSE.md), which is source-available rather than OSI-approved open source. n8n's hosted plans use workflow executions as a billing measure according to the vendor's [pricing page](https://n8n.io/pricing/). + +The choice should follow the operating model. Sim is designed for teams building, deploying, and managing AI agents. n8n is established for broad integration automation and can connect services through its [HTTP Request node](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.httprequest), but the recruiting team must still design its approval, PII, and hiring governance controls. + +## What should teams test before deploying a Greenhouse agent? + +Sim Greenhouse workflows should pass functional, privacy, security, and failure recovery tests before production deployment. + +1. Test records with missing resumes, missing job data, multiple applications, withdrawn applications, and duplicate webhook delivery. + +2. Confirm that prompts receive only approved fields and that logs do not expose secrets or unnecessary candidate data. + +3. Confirm that Guardrails failures reach a downstream Condition and cannot continue through the success path. + +4. Confirm that Human in the Loop rejection reaches a downstream Condition and prevents the Workday or candidate-facing action. + +5. Test expired Greenhouse credentials, Slack permission failures, model timeouts, Workday validation errors, and workflow retries. + +6. Compare summaries with source records and measure unsupported claims, omitted qualifications, and prohibited inferences. + +7. Assign an owner who reviews failures, credential permissions, model changes, and access at a defined interval. + +A production agent should fail closed for sensitive writes. If approval, identity, or required data is missing, the workflow should stop and route the case to a person. diff --git a/apps/sim/content/library/iso-42001-nist-ai-rmf-ai-agent-governance-controls/index.mdx b/apps/sim/content/library/iso-42001-nist-ai-rmf-ai-agent-governance-controls/index.mdx new file mode 100644 index 00000000000..adc566134fe --- /dev/null +++ b/apps/sim/content/library/iso-42001-nist-ai-rmf-ai-agent-governance-controls/index.mdx @@ -0,0 +1,170 @@ +--- +slug: iso-42001-nist-ai-rmf-ai-agent-governance-controls +title: 'How Do You Map AI Agent Governance Controls to ISO 42001 and the NIST AI RMF?' +description: 'Map AI agent governance controls to ISO 42001 and the NIST AI RMF, with practical evidence requirements for oversight, risk, monitoring, and change.' +seoTitle: 'ISO 42001 and NIST AI RMF Agent Governance' +date: 2026-11-24 +updated: 2026-11-24 +authors: + - andrew +readingTime: 9 +tags: [AI Agents, AI Governance, Compliance, Risk Management, Sim] +ogImage: /library/iso-42001-nist-ai-rmf-ai-agent-governance-controls/cover.jpg +draft: false +faq: + - q: "Does ISO 42001 apply to AI agents?" + a: "ISO/IEC 42001 can apply to organizations that develop, provide, or use AI agents when those agents fall within the organization’s AI management system scope. The organization determines and documents that scope, then applies the standard’s management-system requirements and relevant controls to the agents, their supporting processes, and their lifecycle." + - q: "Can an AI agent be ISO 42001 certified?" + a: "ISO/IEC 42001 certification applies to an organization’s AI management system within a defined scope, not to a standalone AI agent as an isolated product badge. An agent may be included within the certified scope, but describing the individual agent as certified can misrepresent what was assessed." + - q: "Is the NIST AI RMF mandatory for AI agents?" + a: "The NIST AI RMF is a voluntary framework unless a law, regulator, contract, customer, or internal policy makes its use a requirement for a particular organization. Its Govern, Map, Measure, and Manage functions can still provide a practical structure for agent risk management when formal adoption is not required." + - q: "Is NIST AI RMF compliance a certification?" + a: "The NIST AI RMF does not establish a NIST certification for organizations, platforms, or AI agents. Organizations should describe specific alignment, implementation, or assessment activities instead of claiming NIST certification." + - q: "Does SOC 2 prove alignment with ISO 42001 or the NIST AI RMF?" + a: "SOC 2 does not by itself prove alignment with ISO/IEC 42001 or the NIST AI RMF because the frameworks have different scopes and objectives. SOC 2 evidence may support controls such as access management, change management, logging, and incident response, but organizations still need AI-specific governance, impact assessment, oversight, evaluation, and lifecycle evidence." + - q: "What is the difference between ISO 42001 and the NIST AI RMF for AI agents?" + a: "ISO/IEC 42001 specifies requirements for an organizational AI management system, while the NIST AI RMF provides voluntary outcomes for governing, mapping, measuring, and managing AI risk. Organizations often use ISO/IEC 42001 to structure the management system and the NIST AI RMF to deepen operational risk activities." + - q: "Do audit logs make an AI agent compliant?" + a: "Audit logs alone do not make an AI agent or organization compliant with ISO/IEC 42001 or aligned with the NIST AI RMF. Logs are evidence for selected controls, but effective governance also requires ownership, risk assessment, access control, testing, human oversight, monitoring, incident response, and corrective action." + - q: "How often should AI agent risk assessments be updated?" + a: "AI agent risk assessments should be updated on a defined schedule and whenever a material change or incident alters the agent’s context or risk. Triggers should include changes to models, prompts, tools, permissions, data sources, autonomy, affected users, deployment environments, providers, or intended use." + - q: "What counts as a material change to an AI agent?" + a: "A material change to an AI agent is any modification that could alter its behavior, access, impact, risk, or evidence requirements. Common examples include changing the model, system instructions, tools, credentials, data sources, approval logic, user population, deployment environment, or permitted actions." + - q: "Can Sim guarantee ISO 42001 or NIST AI RMF compliance?" + a: "Sim cannot guarantee an organization’s ISO/IEC 42001 certification or NIST AI RMF alignment because those outcomes depend on the organization’s full management system, scope, configuration, processes, people, and evidence. Sim can provide technical capabilities that support selected controls when they are configured and operated within an appropriate governance program." +--- + +## TL;DR + +ISO/IEC 42001 and the NIST AI Risk Management Framework ask organizations running AI agents to establish accountable governance, assess risks, maintain human oversight, document system changes, monitor performance, and retain evidence. ISO/IEC 42001 defines a certifiable AI management system, while the NIST AI RMF organizes voluntary risk management around Govern, Map, Measure, and Manage. + +The practical goal is not to label an agent “compliant.” It is to operate an AI agent program with controls that produce reviewable evidence throughout each agent’s lifecycle. + +> This guide is an operational mapping, not an official ISO-to-NIST crosswalk or legal advice. Organizations should validate their implementation with qualified auditors, counsel, and risk professionals. + +## What are the key facts about ISO 42001 and the NIST AI RMF? + +ISO/IEC 42001 and the NIST AI RMF provide complementary ways to govern AI agents: ISO/IEC 42001 specifies management-system requirements, while the NIST AI RMF provides a voluntary risk-management structure. + +- **ISO/IEC 42001:** [ISO/IEC 42001:2023](https://www.iso.org/standard/42001) is an AI management system standard covering organizational context, leadership, planning, support, operation, performance evaluation, improvement, and AI-specific control themes. +- **NIST AI RMF:** The [NIST AI Risk Management Framework](https://www.nist.gov/itl/ai-risk-management-framework) is a voluntary framework organized around Govern, Map, Measure, and Manage. +- **Certification:** Organizations can seek accredited certification against ISO/IEC 42001, but [ISO itself does not certify organizations](https://www.iso.org/conformity-assessment.html). The NIST AI RMF is not a certification standard. +- **Agent governance:** Neither framework is an agent-builder checklist. Organizations must translate framework outcomes into controls for agent inventory, ownership, risk assessment, access, approvals, logs, releases, monitoring, and incident response. +- **Evidence:** Policies alone are insufficient. Assessors need records showing that controls operated, including approvals, access reviews, test results, version records, execution logs, exceptions, incidents, and remediation. + +As of November 2026, ISO/IEC 42001:2023 remains the published ISO AI management system standard, and NIST continues to provide the AI RMF 1.0 and its supporting [AI RMF Playbook](https://airc.nist.gov/airmf-resources/playbook/). + +## How do you map AI agent governance controls to ISO 42001 and the NIST AI RMF? + +An AI agent governance program maps operational controls to both frameworks by connecting each control to an owner, a risk outcome, and retained evidence. + +| AI agent control | ISO/IEC 42001 area | NIST AI RMF function | What the control should do | Evidence an assessor may request | +|---|---|---|---|---| +| Agent inventory | Resources; AI system lifecycle; information for interested parties | Govern; Map | Record every production agent, purpose, owner, model, tools, data sources, deployment, users, and risk tier | Registry export, architecture record, data-flow record, owner attestation, retirement status | +| Accountable ownership | Leadership; roles and responsibilities; internal organization | Govern | Assign business, technical, risk, and operational accountability for each agent | Responsibility matrix, approval record, access review, escalation contacts | +| Risk and impact assessment | Planning; AI system impact assessment | Map; Measure | Assess intended use, affected people, data sensitivity, autonomy, failure modes, security threats, and impact severity before deployment | Completed assessment, threat model, test plan, residual-risk acceptance, review date | +| Human oversight | Internal organization; lifecycle processes; information provided to users | Govern; Manage | Define when a person must review, approve, reject, pause, or override an agent action | Approval logs, reviewer identity, decision record, exception record, escalation test | +| Role-based access and credential control | Resources; data controls; third-party relationships | Govern; Manage | Restrict who can create, modify, deploy, run, or administer agents and their credentials | Role assignments, access-review history, credential inventory, revocation evidence | +| Execution logging and traceability | Lifecycle processes; data controls; performance evaluation | Measure; Manage | Record agent runs, tool calls, relevant inputs and outputs, errors, approvals, and administrative events at an appropriate level | Run logs, audit events, trace exports, retention settings, investigation records | +| Testing and evaluation | Operational planning; lifecycle processes; performance evaluation | Map; Measure | Test task quality, safety boundaries, security, reliability, and foreseeable misuse before release and after material changes | Evaluation suite, test results, acceptance thresholds, failed-test disposition | +| Change control and rollback | Lifecycle processes; operational control; improvement | Govern; Manage | Review material changes to prompts, models, tools, permissions, data, and workflow logic, with a recovery path | Version record, change request, reviewer approval, deployment record, rollback test | +| Production monitoring | Performance evaluation; lifecycle processes; improvement | Measure; Manage | Monitor failures, unsafe outcomes, latency, cost, drift indicators, override rates, and control effectiveness | Dashboards, alerts, periodic review, threshold rationale, corrective-action record | +| Incident and exception management | Nonconformity and corrective action; improvement | Manage; Govern | Triage incidents, contain harm, preserve evidence, notify owners, and track remediation | Incident ticket, timeline, impact analysis, corrective action, closure approval | +| Third-party and model-provider governance | Supplier, customer, and third-party relationships | Govern; Map; Manage | Assess model providers, hosting vendors, tools, integrations, subprocessors, and contract dependencies | Due-diligence review, contract controls, provider inventory, service-change review | +| Decommissioning | Lifecycle processes; data and resource controls | Govern; Manage | Disable retired agents, revoke credentials, preserve required records, and remove obsolete access paths | Retirement approval, credential revocation, retention record, inventory update | + +This mapping should be tailored to the organization’s scope and risk profile. The official [NIST AI RMF 1.0 publication](https://nvlpubs.nist.gov/nistpubs/ai/NIST.AI.100-1.pdf) provides the authoritative NIST outcomes, while the licensed ISO standard provides the authoritative ISO/IEC 42001 requirements and controls. + +## What evidence should an AI agent governance program retain? + +An AI agent governance program should retain evidence that identifies the agent, reconstructs important decisions, and demonstrates that required controls operated over time. + +A minimum evidence package for each production agent should include: + +1. **System record:** Purpose, owner, risk tier, deployment environment, users, model providers, tools, integrations, and data categories. +2. **Risk record:** Initial impact assessment, security review, test results, residual risks, accepted exceptions, and reassessment dates. +3. **Authorization record:** Deployment approval, role assignments, credential ownership, human-approval requirements, and access reviews. +4. **Change record:** Versions, material changes, reviewer decisions, release dates, rollback procedures, and post-change validation. +5. **Operational record:** Relevant execution logs, errors, human decisions, monitoring alerts, incidents, and corrective actions. +6. **Retirement record:** Decommissioning approval, credential revocation, retained evidence, and inventory status. + +Retention should be risk-based. A low-impact internal summarization agent may not require the same evidence depth as an agent that changes customer records, initiates payments, handles health information, or modifies production infrastructure. + +## How should human oversight work for AI agents? + +Human oversight for AI agents should place an identified person at a defined decision point with enough context and authority to approve, reject, modify, pause, or escalate the action. + +A human-in-the-loop control is stronger when it specifies: + +- Which actions require review +- Who is authorized to review them +- What information the reviewer receives +- What approve, reject, and escalation decisions mean +- How long the agent may wait +- What happens when nobody responds +- How the decision and reviewer identity are logged +- How the organization tests that the control cannot be bypassed + +In Sim, the Human in the Loop block pauses a run and resumes it with submitted form fields. An approve-or-reject choice is a field, so a downstream Condition must evaluate that field and route the workflow accordingly. This design makes the decision point explicit instead of treating the pause itself as an approval. + +For a deeper treatment, see [What Is Human-in-the-Loop in AI Agents?](https://www.sim.ai/library/what-is-human-in-the-loop-in-ai-agents). + +## How can Sim support evidence for ISO 42001 and NIST AI RMF alignment? + +Sim can support an organization’s governance evidence through controlled access, audit records, human decision points, execution records, retention controls, and operational data exports, but Sim does not make an organization ISO/IEC 42001 certified or NIST AI RMF compliant. + +Sim is the open-source AI workspace where teams build, deploy, and manage AI agents. Sim Enterprise includes access control, access requests, audit logs, data retention, data drains, credential groups, and session policies under the separate [Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE). These capabilities can support evidence collection when the organization configures them within a documented governance process. + +| Governance need | How Sim can support it | Evidence to retain | +|---|---|---| +| Access governance | Sim Enterprise access control and access requests can separate authoring, administration, and approval responsibilities | Role assignments, access requests, approvals, periodic access-review records | +| Administrative accountability | Sim Enterprise audit logs can record relevant workspace activity | Audit-log exports, investigation records, retention configuration | +| Human oversight | Sim’s Human in the Loop block can pause a run, collect a reviewer’s decision, and pass the result to a downstream Condition | Reviewer identity, submitted fields, workflow route, execution record | +| Operational visibility | Sim execution records, Enterprise data drains, and retention controls can support centralized review and evidence preservation | Run records, exported events, alert records, retention settings | +| Credential governance | Sim Enterprise credential groups can support controlled credential access | Credential ownership, group membership, access-review and revocation records | +| Change governance | Teams can combine platform version records with release approvals, tests, and rollback procedures | Version identifier, change ticket, test results, approval, recovery test | + +Platform evidence is only one layer of an AI management system. Organizations also need policies, assigned accountability, impact assessments, legal analysis, workforce training, supplier governance, incident procedures, internal reviews, and corrective-action processes. + +Related implementation guides include [How Do Enterprises Build an Internal AI Agent Registry?](https://www.sim.ai/library/internal-ai-agent-registry-enterprise-guide) and [AI Agent Version Control and Rollback: Platforms, Process, and Enterprise Checklist](https://www.sim.ai/library/ai-agent-version-control-rollback-platforms). + +## What should you require from an AI agent platform vendor? + +An AI agent platform vendor should demonstrate how its controls create exportable evidence rather than relying on broad claims about enterprise readiness or compliance. + +Require the vendor to demonstrate: + +- A complete inventory of deployed agents and responsible owners +- Roles that separate building, administration, approval, and deployment where required +- Credential scoping, rotation, revocation, and ownership +- Logs for administrative events and relevant agent executions +- Human-approval steps that cannot be bypassed by an unreviewed route +- Version identification and reviewable change history +- Tested rollback or recovery procedures +- Monitoring and export options for security and operations teams +- Configurable retention aligned with legal and audit requirements +- Incident investigation and evidence-preservation workflows +- Documentation for hosting, subprocessors, data handling, and deletion +- Clear boundaries between platform controls and customer responsibilities + +The proof of concept should test these controls directly. Ask Sim, n8n, and any other shortlisted platform to perform the same governance scenarios, then compare the evidence each platform exports rather than comparing feature labels alone. + +Useful scenarios include attempting an unauthorized deployment, revoking a credential, requiring approval for a high-impact action, tracing a failed run, changing a model or tool, restoring a prior version, exporting audit evidence, and decommissioning an agent. + +For broader platform security and deployment requirements, see [Enterprise AI Agent Compliance and Deployment Guide: HIPAA, GDPR, Data Residency, On-Prem, and VPC](https://www.sim.ai/library/enterprise-ai-agent-compliance-deployment-guide) and [AI Agent Identity, Credential Management, and Audit Trails: Enterprise Guide](https://www.sim.ai/library/ai-agent-identity-credentials-audit-trails-enterprise-guide). + +## How should organizations implement this mapping? + +Organizations should implement the ISO/IEC 42001 and NIST AI RMF mapping as a lifecycle process that begins with scope and ownership, then adds controls according to agent risk. + +1. Inventory every production agent and assign accountable owners. +2. Define risk tiers using autonomy, data sensitivity, affected parties, action impact, and reversibility. +3. Map required controls and evidence to each risk tier. +4. Assess every agent before deployment and after material changes. +5. Configure access, credentials, approvals, logging, retention, and monitoring. +6. Test both the agent and its governance controls. +7. Review evidence periodically and after incidents or significant changes. +8. Track exceptions with an owner, rationale, compensating controls, and expiration date. +9. Retire agents through a documented process that revokes access and preserves required records. + +The result should be a living control system, not a one-time spreadsheet. Agent inventories, risks, models, tools, permissions, and operating conditions change, so the evidence must change with them. diff --git a/apps/sim/content/library/n8n-alternatives/index.mdx b/apps/sim/content/library/n8n-alternatives/index.mdx index 3a7351e440e..6af3de3da4b 100644 --- a/apps/sim/content/library/n8n-alternatives/index.mdx +++ b/apps/sim/content/library/n8n-alternatives/index.mdx @@ -1,86 +1,84 @@ --- slug: n8n-alternatives -title: '12 Best n8n Alternatives and Competitors for AI Agents in 2026' -description: 'The 12 best n8n alternatives and competitors in 2026 for AI agent workflows, compared on pricing, license, and hosting: Sim, Dify, Activepieces, Make, Zapier, and more.' -seoTitle: 'n8n Alternatives: 12 Best n8n Competitors in 2026' -seoDescription: 'The 12 best n8n alternatives and competitors for 2026, compared on pricing, free plans, license, and self-hosting: Sim, Dify, Activepieces, Make, Zapier.' +title: '14 n8n Alternatives and Competitors: Choosing an n8n Alternative in 2026' +description: 'Compare 14 n8n alternatives and n8n competitors for AI agents, pricing, licensing, managed cloud, and self-hosting in 2026.' +seoTitle: 'n8n Alternatives: 14 Competitors for AI Agents' +seoDescription: 'Compare 14 n8n alternatives and competitors for AI agents, pricing, licensing, managed cloud, and self-hosting in 2026.' date: 2026-07-13 -updated: 2026-10-20 +updated: 2026-11-23 authors: - andrew -readingTime: 17 +readingTime: 25 tags: [n8n Alternatives, Workflow Automation, AI Agents, Sim] ogImage: /library/n8n-alternatives/cover.jpg draft: false faq: - - q: "What is the best free alternative to n8n?" - a: "It depends on whether you want free software to self-host or a free managed plan: Sim's Apache 2.0 core and Activepieces' MIT-licensed Community Edition can be self-hosted without a license fee, while Sim Cloud, Make, Zapier, and Activepieces Cloud offer free hosted plans with usage limits. Build one representative workflow on each to see whether the limits fit." - q: "Which n8n alternative is best for AI agent workflows?" a: "Sim is a strong fit for general-purpose visual AI agent workflows, Dify for LLM applications built on retrieval, Gumloop for non-developers building LLM workflows, and Botpress for conversational agents. Match the platform to the agent's job to reduce the orchestration you must build yourself." - - q: "Is Make better than n8n?" - a: "Make suits teams that want managed infrastructure and detailed visual debugging, while n8n suits developers who want self-hosting and code-level control. Build the same workflow in both to compare editing, debugging, and pricing." - q: "What is the best open-source n8n alternative?" a: "Sim's core is licensed under the OSI-approved Apache 2.0 license and Activepieces' Community Edition is MIT-licensed, while both keep enterprise features under separate commercial terms. Node-RED is another option for event-driven and hardware-connected flows." + - q: "What should I look for in an n8n alternative?" + a: "Evaluate workflow capabilities, integrations, debugging, deployment and self-hosting options, licensing, governance, and total operating cost at your expected volume." + - q: "What is the best n8n alternative?" + a: "For teams whose main job is building AI agents, Sim is a strong fit because it combines a visual builder, model choice, human approval, an Apache 2.0 core, and managed or self-hosted deployment. For plain SaaS automation, Make or Zapier may fit better." + - q: "Is Sim better than n8n for AI agents?" + a: "Sim is better suited to teams whose primary job is building, deploying, and managing model-driven AI agents, while n8n remains a strong option when AI is one component of broad, extensible workflow automation." + - q: "What is the best free alternative to n8n?" + a: "Sim, Activepieces, and other alternatives differ depending on whether you want free software to self-host or a free managed plan: Sim's Apache 2.0 core and Activepieces' MIT-licensed Community Edition can be self-hosted without a license fee, while Sim Cloud, Make, Zapier, and Activepieces Cloud offer free hosted plans with usage limits. Build one representative workflow on each to see whether the limits fit." + - q: "Is Make better than n8n?" + a: "Make suits teams that want managed infrastructure and detailed visual debugging, while n8n suits developers who want self-hosting and code-level control. Build the same workflow in both to compare editing, debugging, and pricing." - q: "How hard is it to migrate from n8n to another tool?" - a: "An n8n migration means rebuilding workflows, credentials, error handling, and operational checks in the new platform, and effort grows with the number of workflows and custom code steps. Inventory dependencies and move one representative workflow first before estimating the rest." + a: "n8n migrations mean rebuilding workflows, credentials, error handling, and operational checks in the new platform, and effort grows with the number of workflows and custom code steps. Inventory dependencies and move one representative workflow first before estimating the rest." - q: "What is an AI agent workflow builder?" a: "An AI agent workflow builder is a platform for creating workflows in which AI models interpret context, choose actions, call tools, branch, and complete multi-step tasks." - q: "Can n8n build AI agents?" - a: "Yes. n8n can build AI agents by connecting models with tools, data sources, application integrations, workflow logic, and execution controls through its AI Agent node." + a: "n8n can build AI agents by connecting models with tools, data sources, application integrations, workflow logic, and execution controls through its AI Agent node." - q: "Is n8n open source?" - a: "No. n8n is source-available under its Sustainable Use License, a fair-code license that limits use to internal business, non-commercial, or personal purposes, so it does not meet the Open Source Initiative's definition." + a: "n8n is source-available under its Sustainable Use License, a fair-code license that limits use to internal business, non-commercial, or personal purposes, so it does not meet the Open Source Initiative's definition." - q: "Is Sim free?" a: "Sim's core can be self-hosted under Apache 2.0 without a software license fee, and Sim Cloud has a Free plan with 1,000 one-time credits alongside paid Pro, Max, and Enterprise plans. Code in apps/sim/ee has separate enterprise terms." - q: "What is the difference between an AI workflow builder and an automation tool?" a: "An AI workflow builder centers workflows on model reasoning and tool use, while an automation tool typically centers them on predefined triggers, actions, data movement, and deterministic rules." - q: "What should I test before replacing n8n?" - a: "Reproduce a real production workflow with its required integrations, model and tool calls, failure handling, human approval, execution inspection, and the deployment method you intend to use." + a: "An n8n replacement should be tested with a real production workflow, including its required integrations, model and tool calls, failure handling, human approval, execution inspection, and intended deployment method." - q: "Is Sim a drop-in replacement for n8n?" - a: "No. Sim is not a drop-in replacement for every n8n workflow because triggers, integrations, credentials, and execution behavior must be evaluated and migrated individually." - - q: "What should I look for in an n8n alternative?" - a: "Evaluate workflow capabilities, integrations, debugging, deployment and self-hosting options, licensing, governance, and total operating cost at your expected volume." + a: "Sim is not a drop-in replacement for every n8n workflow because triggers, integrations, credentials, and execution behavior must be evaluated and migrated individually." - q: "Which n8n alternative should I choose if I need self-hosting?" a: "Sim is a strong self-hosted fit for AI agent workflows when an Apache 2.0 core matters, and self-hosted Sim can connect to local model servers; Activepieces fits MIT-licensed trigger-action automation. Account separately for enterprise-licensed code in both." - q: "Which n8n alternative should I choose if I need human approval steps?" - a: "Choose a platform with explicit human-in-the-loop controls when an AI workflow can trigger consequential or irreversible actions, and test the approval path before deployment." + a: "An n8n alternative should provide explicit human-in-the-loop controls when an AI workflow can trigger consequential or irreversible actions, and test the approval path before deployment." - q: "Do AI agent workflow builders replace traditional automation tools?" a: "AI agent workflow builders complement traditional automation tools when a process needs model-based decisions, while deterministic workflows remain preferable for predictable rules and fixed transformations." - - q: "What is the best n8n alternative?" - a: "For teams whose main job is building AI agents, Sim is a strong fit because it combines a visual builder, model choice, human approval, an Apache 2.0 core, and managed or self-hosted deployment. For plain SaaS automation, Make or Zapier may fit better." - - q: "What is the best n8n alternative for teams that don't want to self host?" - a: "Sim Cloud is a good fit for teams that want managed AI agent infrastructure without operating the deployment, while Make and Zapier fit managed SaaS automation." - q: "What does n8n's fair-code license allow?" a: "n8n's Sustainable Use License allows use and modification for your own internal business purposes or for non-commercial or personal use, and allows distribution only free of charge for non-commercial purposes. Check your exact use against the license text." - q: "Is Sim open source?" a: "Sim's core is open source under Apache 2.0, while code in apps/sim/ee is governed by the separate Sim Enterprise License and requires an active Enterprise subscription for production use." - q: "Can Sim be self-hosted?" - a: "Yes. Anyone can self-host Sim's Apache 2.0 core with Docker Compose or Kubernetes, while production use of features in apps/sim/ee requires an active Sim Enterprise subscription." + a: "Sim's Apache 2.0 core can be self-hosted with Docker Compose or Kubernetes, while production use of features in apps/sim/ee requires an active Sim Enterprise subscription." - q: "Can Sim use local models when self-hosted?" - a: "Yes. Sim can connect to Ollama, vLLM, LM Studio, or LiteLLM on any self-hosted deployment, and local models do not require Sim Enterprise." + a: "Sim can connect to Ollama, vLLM, LM Studio, or LiteLLM on any self-hosted deployment, and local models do not require Sim Enterprise." - q: "Does Sim support bring your own model keys?" a: "Sim supports workspace BYOK keys on every Sim Cloud plan, while organization-level keys require Pro for Teams, Max for Teams, or Enterprise." - - q: "Is Sim better than n8n for AI agents?" - a: "Sim is better suited to teams whose primary job is building, deploying, and managing model-driven AI agents, while n8n remains a strong option when AI is one component of broad, extensible workflow automation." - q: "Is n8n better than Zapier?" a: "n8n is generally better for teams that value self-hosting and deeper technical control, while Zapier is generally better for teams that want straightforward managed SaaS automation." - q: "Is Sim better than Zapier for AI agents?" a: "Sim is better suited to building and managing multi-step AI agents, while Zapier is better suited to straightforward managed automation across a very large catalog of business apps." - q: "Do I need to self host an n8n alternative?" - a: "No. A managed service is enough when it meets your security, cost, governance, and data-handling requirements." + a: "Managed n8n alternatives are sufficient when they meet your security, cost, governance, and data-handling requirements." - q: "Is self-hosting cheaper than managed hosting?" - a: "Not automatically, because infrastructure, security patches, upgrades, monitoring, backups, and engineering time all belong in the total cost." + a: "Self-hosting is not automatically cheaper because infrastructure, security patches, upgrades, monitoring, backups, and engineering time all belong in the total cost." - q: "Can I migrate n8n workflows to Sim?" - a: "Yes, but plan to rebuild and test each workflow: recreate its triggers, credentials, transformations, tool calls, branches, retries, and approval logic in Sim, then validate the output before cutover." + a: "Sim migrations require rebuilding and testing each workflow: recreate its triggers, credentials, transformations, tool calls, branches, retries, and approval logic in Sim, then validate the output before cutover." - q: "Does Sim support human approval workflows?" - a: "Yes. Sim's Human in the Loop block pauses a run and resumes it with submitted form fields, and a downstream Condition evaluates the response." + a: "Sim's Human in the Loop block pauses a run and resumes it with submitted form fields, and a downstream Condition evaluates the response." - q: "Do Sim Guardrails automatically stop a workflow?" - a: "No. The Guardrails block reports passed or failed, and a downstream Condition must route that result if the workflow should stop or take a different path." + a: "Sim's Guardrails block reports passed or failed, and a downstream Condition must route that result if the workflow should stop or take a different path." - q: "Which guide compares Sim, n8n, and OpenAI AgentKit?" a: "Sim vs n8n vs OpenAI AgentKit: AI Agent Builder Comparison (2026) compares the three products directly." - q: "Which guide compares self-hosted AI workflow platforms?" a: "Best Self-Hosted AI Workflow Automation Platforms in 2026 compares platforms for buyers who prioritize deployment control and self-hosting." - q: "Which guide explains Apache 2.0 versus fair-code licensing?" - a: "Apache 2.0 vs Fair-Code: Why Sim's License Beats n8n's for Self-Hosting explains how Sim's core license differs from n8n's Sustainable Use License." + a: "Apache 2.0 vs Fair-Code: Why Sim's Core License Differs From n8n's for Self Hosting explains how Sim's core license differs from n8n's Sustainable Use License." - q: "What is the difference between Sim and n8n?" a: "Sim is the open-source AI workspace for building, deploying, and managing AI agents, while n8n is a source-available workflow automation product centered on connecting applications, APIs, and data flows." - q: "Which n8n alternative supports local AI models?" @@ -98,12 +96,12 @@ faq: - q: "Which n8n alternative has the most integrations?" a: "Zapier lists 9,000+ apps and Make 3,000+, and Workato's site cites 14,000+ apps, while Sim's 270+ integrations focus on orchestrating AI agents with tools and APIs rather than maximizing connector count." - q: "Which n8n alternative is cheapest?" - a: "None is universally cheapest because Sim, n8n, Zapier, Make, Dify, and the others bill against different units, and self-hosting shifts cost toward infrastructure and operations." + a: "n8n alternatives do not have one universally cheapest option because Sim, n8n, Zapier, Make, Dify, and the others bill against different units, and self-hosting shifts cost toward infrastructure and operations." --- -The best n8n alternatives in 2026 are Sim for AI agent workflows, Dify for LLM applications, Activepieces for MIT-licensed self-hosting, Make and Zapier for managed SaaS automation, and LangGraph or CrewAI for code-first agents. This guide is published by Sim, and Sim is one of the 12 n8n competitors covered, so each entry, including Sim, lists real limitations and links its sources. +The best n8n alternatives depend on the workload: Sim fits visual AI agent workflows, Dify and Langflow fit LLM applications, Activepieces and Node-RED fit permissively licensed self-hosting, Make and Zapier fit managed application automation, and LangGraph or CrewAI fit code-first agents. This guide compares 14 n8n competitors, and every profile lists limitations and official sources. -Sim, the open-source AI workspace for building, deploying, and managing AI agents, is a strong fit when your n8n workflows are turning into AI agent workflows. n8n remains a strong choice for technical workflow automation. The difference is focus: n8n is broad automation with AI steps inside it, while Sim puts building, deploying, and managing agents at the center, visually, conversationally, or with code. +Sim, the open-source AI workspace for building, deploying, and managing AI agents, fits teams whose n8n workflows are becoming AI agent workflows. n8n remains a strong choice for technical workflow automation. The difference is focus: n8n covers broad automation with AI steps, while Sim puts building, deploying, and managing agents at the center through a visual builder, Chat, or code. > **Choose n8n when** your workflows are mostly deterministic app-to-app automation, your team already runs a reliable n8n estate, and the [Sustainable Use License](https://docs.n8n.io/privacy-and-security/sustainable-use-license/) fits your use. > @@ -115,7 +113,7 @@ For a feature-by-feature breakdown of the two products, see [Sim vs n8n](https:/ ## What should you look for in an n8n alternative? -Look at the operating requirements of the whole AI agent workflow, not at integration counts alone. Teams usually start looking for n8n alternatives for three reasons: +An n8n alternative should be evaluated against the operating requirements of the whole AI agent workflow, not integration counts alone. Teams usually start looking for n8n alternatives for three reasons: - **Self-hosting overhead.** Running n8n yourself means provisioning compute and a database, applying security and version updates, and maintaining backups, TLS certificates, and uptime monitoring. - **Execution-based pricing.** [n8n Cloud](https://n8n.io/pricing/) prices plans by monthly workflow executions "regardless of complexity", so high-frequency triggers can push you into a larger plan. @@ -132,15 +130,53 @@ Use these criteria to compare the alternatives below: - **License:** Is the software OSI-approved open source, source-available, or proprietary? - **Operational fit:** Is it built for AI agent development, general business automation, or code-first orchestration? -## What are the 12 best n8n alternatives in 2026? +## Best n8n alternatives for teams that don't want to self-host + +[Sim Cloud](https://www.sim.ai/pricing), [Zapier](https://zapier.com/pricing), [Make](https://www.make.com/en/pricing), [Gumloop](https://www.gumloop.com/pricing), [Workato](https://www.workato.com/free), [Microsoft Power Automate](https://www.microsoft.com/en-us/power-platform/products/power-automate/pricing), [Botpress](https://botpress.com/pricing), [Dify Cloud](https://dify.ai/pricing/dify-cloud), and hosted [CrewAI](https://crewai.com/pricing) or [LangSmith](https://www.langchain.com/pricing) services fit teams that do not want to operate the full platform themselves. Sim Cloud preserves a path to self-hosting if requirements change, and [workspace BYOK keys are available on every Sim Cloud plan](https://docs.sim.ai/platform/costs#bring-your-own-key-byok), while organization-level keys require Pro for Teams, Max for Teams, or Enterprise. + +Managed-service buyers should compare identity controls, credential management, execution history, model access, human review, support, and billing units. Make and Zapier focus on managed application automation, Gumloop focuses on managed AI automation, and Workato or Microsoft Power Automate fit organizations with enterprise integration or Microsoft ecosystem requirements. + +## What's a good n8n alternative for building AI agents? + +Sim is a good n8n alternative for visual AI agent workflows because it combines model choice, tool connections, deployment, and run management in one open-source AI workspace. [Self-hosted Sim](https://docs.sim.ai/platform/self-hosting) can connect to Ollama, vLLM, LM Studio, or LiteLLM without requiring Sim Enterprise. + +[Dify](https://dify.ai/pricing) fits teams focused on LLM applications and retrieval, [Langflow](https://www.langflow.org/) fits visual composition of models and retrieval components, and [LangGraph](https://www.langchain.com/pricing) or [CrewAI](https://crewai.com/pricing) fit developers who want agent behavior in code. For a direct product comparison, see [Sim versus n8n](https://www.sim.ai/comparisons/n8n). + +## n8n alternative that handles ai agents better + +Sim fits teams whose primary job is coordinating models, tools, structured logic, and human input, while n8n fits broad application automation that includes AI steps. Sim's Guardrails block reports passed or failed for a downstream Condition to route, and Human in the Loop pauses a run and resumes it with submitted form fields for downstream logic to evaluate. + +n8n remains a capable choice when a team already has extensive n8n workflows or mainly needs deterministic application integration. Teams should test the same agent workflow in each platform rather than assuming that one product fits every workload. + +## What should teams leaving n8n Cloud compare? -The 12 are Sim, Dify, Activepieces, LangGraph, Make, CrewAI, Zapier, Microsoft Power Automate, Botpress, Workato, Gumloop, and Lindy. n8n is the baseline, not one of the 12. Prices below were checked on vendor pages on October 20, 2026. +n8n Cloud customers should compare workflow fit, managed operations, migration effort, billing, and governance before switching. Inventory triggers, credentials, custom code, community nodes, model calls, execution volume, retry behavior, and approval steps because no alternative reproduces every n8n workflow automatically. + +A team leaving n8n Cloud should answer five questions: + +1. Does the replacement provide every essential trigger and action? +2. Can credentials be moved without exposing secrets? +3. Will custom JavaScript or Python need to be rewritten? +4. How does the platform count executions, tasks, credits, or other usage? +5. Can the team test failure handling and output quality before switching production traffic? + +As of November 2026, n8n publishes cloud plan prices and execution allowances on its [official pricing page](https://n8n.io/pricing/). Compare current figures using the same workflow volume and retry assumptions instead of comparing entry prices alone. + +## n8n is fair-code and has license restrictions, what open source options are truly permissive + +Sim core and Node-RED are permissively licensed under Apache 2.0, while Activepieces Community Edition, LangGraph, and CrewAI use the MIT license. n8n describes its Sustainable Use License as fair code in its [community license documentation](https://docs.n8n.io/n8n-community-license), and the license is source available rather than OSI approved open source. + +[Sim core uses Apache 2.0](https://github.com/simstudioai/sim/blob/main/LICENSE). Code in `apps/sim/ee` uses the separate [Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE), is free for development, testing, and internal nonproduction use, and requires an active Sim Enterprise subscription for production use; modification and redistribution are not permitted. For more detail, read [Apache 2.0 vs Fair Code: Why Sim's Core License Differs From n8n's for Self Hosting](https://www.sim.ai/library/apache-2-0-vs-fair-code). + +## What are the 14 best n8n alternatives in 2026? + +The 14 alternatives are Sim, Dify, Activepieces, Langflow, LangGraph, Make, CrewAI, Zapier, Microsoft Power Automate, Botpress, Workato, Gumloop, Lindy, and Node-RED. n8n is the baseline, not one of the 14. Prices below were checked on official vendor pages in November 2026. ### 1. Sim Sim, the open-source AI workspace for building, deploying, and managing AI agents, is a strong fit for teams that want visual AI agent workflows with flexible hosting. Where n8n treats AI as one node type in a broad automation tool, Sim is built around agents, knowledge bases, tables, and multi-model routing. -**Best for:** Teams building AI agent workflows that need multi-model orchestration, memory, human approval, and real-time collaboration. +**Fits:** Teams building AI agent workflows that need multi-model orchestration, memory, human approval, and real-time collaboration. **Pricing:** The Free plan includes 1,000 one-time credits (worth $5 on Sim Cloud). Pro is $25 per user per month, Max is $100 per user per month, and Enterprise is custom, all on [credit-based billing](https://www.sim.ai/pricing). [Workspace BYOK keys work on every Sim Cloud plan](https://docs.sim.ai/platform/costs#bring-your-own-key-byok). Self-hosting the core carries no license fee. @@ -159,7 +195,7 @@ Sim, the open-source AI workspace for building, deploying, and managing AI agent Dify is a strong n8n alternative when the main job is building LLM applications with prompts, retrieval, datasets, and agent behavior. Compared with Sim, Dify centers on LLM apps and knowledge retrieval, while Sim covers broader agent workflows across 270+ integrations. -**Best for:** Teams centered on LLM applications and retrieval that want managed or self-hosted deployment. +**Fits:** Teams centered on LLM applications and retrieval that want managed or self-hosted deployment. **Pricing:** Dify Cloud has a free Sandbox plan with 200 message credits. [Professional is $59 per workspace per month and Team is $159 per workspace per month](https://dify.ai/pricing/dify-cloud), with discounts for annual billing ($590 and $1,590 per workspace per year). @@ -177,9 +213,9 @@ Dify is a strong n8n alternative when the main job is building LLM applications Activepieces is a strong pick for teams that want visual trigger-and-action automation with an MIT-licensed self-hosted option. Compared with Sim, Activepieces maps more closely to n8n's trigger-action model, while Sim is the better fit when the workflow is an AI agent. -**Best for:** Teams that want a self-hostable n8n alternative under a permissive license, plus cloud plans with published allowances. +**Fits:** Teams that want a self-hostable n8n alternative under a permissive license, plus cloud plans with published allowances. -**Pricing:** [Activepieces Cloud](https://www.activepieces.com/pricing) has a Free plan with 1,000 credits a month for up to five users, Plus at $20 flat per month (10,000 credits a month), Team at $200 flat per month with 25 users, and a sales-led Ultimate plan. Usage over the allowance costs $0.007 per credit on Plus and Team. The self-hosted Community Edition has no license fee. +**Pricing:** [Activepieces Cloud](https://www.activepieces.com/pricing) has a Free plan with 1,000 credits a month, and its current pricing page advertises paid access from $16 per month. The self-hosted Community Edition has no license fee, while enterprise and cloud-edition features use commercial terms. **Strengths:** @@ -191,11 +227,29 @@ Activepieces is a strong pick for teams that want visual trigger-and-action auto **Sources:** [Activepieces pricing](https://www.activepieces.com/pricing), [Activepieces license](https://www.activepieces.com/docs/about/license). -### 4. LangGraph +### 4. Langflow + +Langflow fits teams that want a visual environment for composing models, retrieval components, tools, agents, and MCP servers. Compared with Sim, Langflow is oriented toward developer-built AI applications, while Sim combines agent building with broader workspace and run-management features. + +**Fits:** Developers prototyping and deploying visual agent and retrieval flows. + +**Pricing:** The [Langflow project](https://www.langflow.org/) can be self-hosted, so teams pay for their own infrastructure and model usage. Managed deployment costs depend on the service used to host it. + +**Strengths:** + +- **Visual AI composition:** Drag-and-drop flows connect models, vector databases (databases that find related information by meaning), tools, and custom Python components. +- **Deployment choice:** The [deployment documentation](https://docs.langflow.org/deployment-overview) covers local, containerized, and remote self-hosting options. +- **Developer control:** Python components support customization beyond the visual flow. + +**Limitations:** Langflow is not a replacement for every conventional trigger-action automation, and production teams still need to plan hosting, authentication, monitoring, and upgrades. + +**Sources:** [Langflow product](https://www.langflow.org/), [Langflow deployment](https://docs.langflow.org/deployment-overview). + +### 5. LangGraph LangGraph is a strong n8n alternative for software teams that want to define stateful agent execution in code. Compared with Sim, LangGraph gives engineers finer control, but the open-source framework has no shared visual builder for mixed teams. -**Best for:** Developers who want explicit control over agent state, nodes, transitions, and persistence. +**Fits:** Developers who want explicit control over agent state, nodes, transitions, and persistence. **Pricing:** The framework is free under the [MIT license](https://github.com/langchain-ai/langgraph/blob/main/LICENSE). LangSmith, the separate hosted service, lists a [Developer plan at $0 per seat and Plus at $39 per seat per month](https://www.langchain.com/pricing), both with pay-as-you-go usage, plus Enterprise. @@ -209,11 +263,11 @@ LangGraph is a strong n8n alternative for software teams that want to define sta **Sources:** [LangGraph license](https://github.com/langchain-ai/langgraph/blob/main/LICENSE), [LangSmith pricing](https://www.langchain.com/pricing), [Sim vs LangChain](https://www.sim.ai/comparisons/langchain). -### 5. Make (formerly Integromat) +### 6. Make (formerly Integromat) Make is a strong choice for teams that want managed visual automation with detailed control over deterministic scenarios. Compared with Sim, Make has a far larger app catalog, while Sim offers deeper agent orchestration and a self-hosting option. -**Best for:** Teams that want managed visual automation with detailed inspection of routes, filters, and intermediate values. +**Fits:** Teams that want managed visual automation with detailed inspection of routes, filters, and intermediate values. **Pricing:** [Make's pricing page](https://www.make.com/en/pricing) lists a Free plan with 1,000 credits a month and paid plans from $9 per month billed annually (Core) at 10,000 credits, followed by Pro and Teams. Each module action counts as one credit, and [some AI features use credits based on tokens](https://help.make.com/credits). @@ -227,11 +281,11 @@ Make is a strong choice for teams that want managed visual automation with detai **Sources:** [Make pricing](https://www.make.com/en/pricing), [Make credits](https://help.make.com/credits), [Sim vs Make](https://www.sim.ai/comparisons/make). -### 6. CrewAI +### 7. CrewAI CrewAI is a strong n8n alternative for Python developers designing systems around agents, tasks, crews, and flows. Compared with Sim, CrewAI is framework-first, with a visual Studio on its hosted platform, while Sim lets mixed teams build, deploy, and manage agents in one workspace. -**Best for:** Developer-led projects that represent multi-agent behavior in code, with an optional visual editor on the hosted platform. +**Fits:** Developer-led projects that represent multi-agent behavior in code, with an optional visual editor on the hosted platform. **Pricing:** The framework is [MIT-licensed](https://github.com/crewAIInc/crewAI/blob/main/LICENSE). The hosted platform has a [free Basic plan with Studio (visual editor) and 50 workflow executions a month, and a custom-priced Enterprise plan](https://crewai.com/pricing). Teams running the framework themselves pay for their own infrastructure and model usage. @@ -245,13 +299,13 @@ CrewAI is a strong n8n alternative for Python developers designing systems aroun **Sources:** [CrewAI pricing](https://crewai.com/pricing), [CrewAI license](https://github.com/crewAIInc/crewAI/blob/main/LICENSE), [Sim vs CrewAI](https://www.sim.ai/comparisons/crewai). -### 7. Zapier +### 8. Zapier Zapier is a strong pick for non-technical teams that prioritize fast setup and a very large managed integration catalog. Compared with Sim, Zapier connects more apps, while Sim gives more control over multi-step agent behavior and can be self-hosted. -**Best for:** Non-technical teams that need a broad app catalog and a fast path to a first working automation. +**Fits:** Non-technical teams that need a broad app catalog and a fast path to a first working automation. -**Pricing:** [Zapier](https://zapier.com/pricing) has a Free plan with 100 tasks per month, Professional from $19.99 per month billed annually ($29.99 billed monthly), Team from $69 per month billed annually ($103.50 billed monthly), and custom Enterprise pricing. Higher task tiers cost more. +**Pricing:** [Zapier](https://zapier.com/pricing) has a Free plan with 100 tasks per month, Professional from $19.99 per month billed annually, and custom pricing that varies by plan and task allowance. Higher task tiers cost more. **Strengths:** @@ -263,11 +317,11 @@ Zapier is a strong pick for non-technical teams that prioritize fast setup and a **Sources:** [Zapier pricing](https://zapier.com/pricing), [Zapier home](https://zapier.com/), [Sim vs Zapier](https://www.sim.ai/comparisons/zapier). -### 8. Microsoft Power Automate +### 9. Microsoft Power Automate Microsoft Power Automate is the natural pick for organizations standardized on Microsoft 365, Dynamics, Azure, and desktop automation. Compared with Sim, it reaches deeper into Microsoft systems and legacy desktops, while Sim is model-agnostic and not tied to one vendor's stack. -**Best for:** Organizations standardized on Microsoft 365, Dynamics, and the broader Microsoft ecosystem. +**Fits:** Organizations standardized on Microsoft 365, Dynamics, and the broader Microsoft ecosystem. **Pricing:** [Microsoft lists](https://www.microsoft.com/en-us/power-platform/products/power-automate/pricing) a 30-day free trial, Power Automate Premium at $15.00 per user per month, Power Automate Process at $150.00 per bot per month, and Hosted Process at $215.00 per bot per month, all paid yearly. @@ -281,11 +335,11 @@ Microsoft Power Automate is the natural pick for organizations standardized on M **Sources:** [Power Automate pricing](https://www.microsoft.com/en-us/power-platform/products/power-automate/pricing), [Sim vs Power Automate](https://www.sim.ai/comparisons/power-automate). -### 9. Botpress +### 10. Botpress Botpress is a strong pick for teams building conversational agents for support and sales across chat and voice. Compared with Sim, Botpress specializes in conversations, while Sim handles back-office and data workflows as well as chat agents. -**Best for:** Customer support bots, conversational sales agents, and multi-turn dialogue. +**Fits:** Customer support bots, conversational sales agents, and multi-turn dialogue. **Pricing:** [Botpress](https://botpress.com/pricing) has a Free plan with 100 conversations, Plus at $150 per month billed annually with 250 conversations a month, Team at $750 per month billed annually with 1,500 conversations a month, and custom Enterprise. AI usage is included on every plan. @@ -299,13 +353,13 @@ Botpress is a strong pick for teams building conversational agents for support a **Sources:** [Botpress pricing](https://botpress.com/pricing). -### 10. Workato +### 11. Workato Workato fits large organizations that need governed enterprise integration and contractual support. Compared with Sim, Workato brings enterprise connector depth (its site cites [14,000+ apps](https://www.workato.com/free)) and procurement-ready contracts, while Sim offers an open-source core and self-hosting. -**Best for:** Enterprise teams that need SLAs, compliance documentation, and governance controls. +**Fits:** Enterprise teams that need SLAs, compliance documentation, and governance controls. -**Pricing:** Workato uses [usage-based billing in Workato credits](https://docs.workato.com/en/pricing). [Self-service plans](https://docs.workato.com/en/pricing/self-service/self-service) include Workato Free with a one-time 50,000-credit grant and Workato Pro from $75 per month for 2,500 credits up to $1,275 per month for 50,000 credits. Enterprise editions are quoted by sales. +**Pricing:** Workato uses [usage-based billing in Workato credits](https://docs.workato.com/en/pricing). [Self-service documentation](https://docs.workato.com/en/pricing/self-service/self-service) lists Workato Free with a one-time 50,000-credit grant and Pro tiers from $75 per month for 2,500 credits up to $1,275 per month for 50,000 credits, while Workato's [current signup page](https://www.workato.com/free) advertises a $100 Pro option with 3,500 monthly credits. Enterprise editions are quoted by sales. **Strengths:** @@ -317,11 +371,11 @@ Workato fits large organizations that need governed enterprise integration and c **Sources:** [Workato billing docs](https://docs.workato.com/en/pricing), [Workato self-service plans](https://docs.workato.com/en/pricing/self-service/self-service), [Sim vs Workato](https://www.sim.ai/comparisons/workato). -### 11. Gumloop +### 12. Gumloop Gumloop fits non-developers assembling hosted, AI-powered business processes visually. Compared with Sim, Gumloop is hosted only and narrower on traditional connectors, while Sim adds self-hosting and Apache 2.0 licensing. -**Best for:** Non-developer teams building hosted AI agents; Gumloop now labels its older workflow builder as Legacy on its pricing page. +**Fits:** Non-developer teams building hosted AI agents; Gumloop now labels its older workflow builder as Legacy on its pricing page. **Pricing:** [Gumloop](https://www.gumloop.com/pricing) Pro starts at $37 per month after a 14-day free trial and includes 20,000 credits (7,400 plus 12,600 bonus). Credits are indexed at $0.005 each, and Enterprise is custom. @@ -335,11 +389,11 @@ Gumloop fits non-developers assembling hosted, AI-powered business processes vis **Sources:** [Gumloop pricing](https://www.gumloop.com/pricing), [Sim vs Gumloop](https://www.sim.ai/comparisons/gumloop). -### 12. Lindy +### 13. Lindy Lindy fits teams that want ready-made agents for defined email, meeting, and sales tasks. Compared with Sim, Lindy is quicker to start for those tasks, while Sim is more configurable for workflows that do not fit a template. -**Best for:** Less technical teams that want agents for email triage, meeting scheduling, and sales outreach with minimal setup. +**Fits:** Less technical teams that want agents for email triage, meeting scheduling, and sales outreach with minimal setup. **Pricing:** [Lindy](https://www.lindy.ai/pricing) starts new users with $50 in free credits that last 7 days, then bills every active user from $29.99 a month for 3,000 credits, though some visitors see $49.99 for 5,000 credits; its [billing docs](https://docs.lindy.ai/teammate/lindy-teammate-billing) describe seat-based Plus, Pro, and Max plans. @@ -353,28 +407,48 @@ Lindy fits teams that want ready-made agents for defined email, meeting, and sal **Sources:** [Lindy pricing](https://www.lindy.ai/pricing), [Lindy billing docs](https://docs.lindy.ai/teammate/lindy-teammate-billing). +### 14. Node-RED + +Node-RED fits technical teams that want event-driven flows on infrastructure they control. Compared with Sim, Node-RED provides a general low-code runtime for events and devices, while Sim centers model-driven AI agents and managed run operations. + +**Fits:** Engineering-led event processing, device integration, and edge automation. + +**Pricing:** Node-RED has no software license fee under its [Apache 2.0 license](https://nodered.org/about/license/), while teams pay for infrastructure and operations. + +**Strengths:** + +- **Permissive license:** Apache 2.0 permits commercial use, modification, and redistribution under its terms. +- **Self-hosting:** Official [getting-started documentation](https://nodered.org/docs/getting-started/) covers local, Docker, device, and cloud infrastructure deployments. +- **Event-oriented runtime:** Node.js and a large community node catalog support device, messaging, and data-flow use cases. + +**Limitations:** Node-RED does not provide a first-party managed platform equivalent to Sim Cloud or n8n Cloud, so teams own production hosting, security, upgrades, and monitoring. + +**Sources:** [Node-RED product](https://nodered.org/), [Node-RED license](https://nodered.org/about/license/), [Node-RED deployment](https://nodered.org/docs/getting-started/). + ## How do these n8n alternatives compare? -The list is ordered for AI agent workflows, set by the publisher; it is not a verdict on overall product quality. - -| # | Tool | Best fit | License and hosting | Entry paid price (Oct 2026) | -| --- | --- | --- | --- | --- | -| 1 | Sim | Visual AI agent workflows | Apache 2.0 core; cloud or self-hosted | Pro $25/user/mo | -| 2 | Dify | LLM apps and retrieval | Modified Apache 2.0; cloud or self-hosted | $59/workspace/mo | -| 3 | Activepieces | Open-source trigger-action automation | MIT core; cloud or self-hosted | $20/mo | -| 4 | LangGraph | Stateful agents in code | MIT framework; self-managed or LangSmith | LangSmith Plus $39/seat/mo | -| 5 | Make | Managed visual SaaS automation | Proprietary; cloud only | Core $9/mo billed annually | -| 6 | CrewAI | Multi-agent systems in code | MIT framework; hosted platform | Enterprise custom | -| 7 | Zapier | Simple SaaS automation | Proprietary; cloud only | $19.99/mo billed annually | -| 8 | Power Automate | Microsoft-centric organizations | Proprietary; cloud plus desktop | $15/user/mo | -| 9 | Botpress | Chat and voice agents | Proprietary; managed | $150/mo billed annually | -| 10 | Workato | Governed enterprise integration | Proprietary; managed | $75/mo | -| 11 | Gumloop | Hosted AI agents for non-developers | Proprietary; cloud only | $37/mo | -| 12 | Lindy | Template-led business agents | Proprietary; cloud only | $29.99 or $49.99/user/mo | +The 14 n8n alternatives in this decision table separate managed cloud from full-platform self-hosting so teams can filter by operating model before comparing workflow fit. The table follows the same sequence as the profiles for easier cross-reference. + +| Platform | Best fit | Managed cloud | Self hosting | License or distribution model | Entry paid price (Nov 2026) | +| --- | --- | --- | --- | --- | --- | +| [Sim](https://www.sim.ai/pricing) | Visual AI agent workflows | Yes | Yes | Apache 2.0 core; `apps/sim/ee` uses the Sim Enterprise License | Pro $25/user/mo | +| [Dify](https://dify.ai/pricing) | LLM apps and retrieval | Yes | Yes | Modified Apache 2.0 terms | $59/workspace/mo | +| [Activepieces](https://www.activepieces.com/pricing) | Trigger-action automation | Yes | Yes | MIT core; commercial enterprise features | From $16/mo | +| [Langflow](https://docs.langflow.org/deployment-overview) | Visual AI application composition | Available through managed hosting | Yes | Open-source project with separately operated hosting | Hosting dependent | +| [LangGraph](https://www.langchain.com/pricing) | Stateful agents in code | Yes, through LangSmith | Yes | MIT framework; commercial LangSmith service | LangSmith Plus $39/seat/mo | +| [Make](https://www.make.com/en/pricing) | Managed visual application automation | Yes | No | Proprietary service | Core $9/mo billed annually | +| [CrewAI](https://crewai.com/pricing) | Multi-agent systems in code | Yes | Yes | MIT framework; commercial platform | Enterprise custom | +| [Zapier](https://zapier.com/pricing) | Managed application automation | Yes | No | Proprietary service | $19.99/mo billed annually | +| [Microsoft Power Automate](https://www.microsoft.com/en-us/power-platform/products/power-automate/pricing) | Microsoft-centered automation | Yes | No full platform self-hosting | Proprietary service with desktop and gateway components | $15/user/mo | +| [Botpress](https://botpress.com/pricing) | Chat and voice agents | Yes | No | Proprietary service | $150/mo billed annually | +| [Workato](https://www.workato.com/pricing) | Governed enterprise integration | Yes | No full platform self-hosting | Proprietary service with on-premises connectivity agents | $75/mo self-service tier | +| [Gumloop](https://www.gumloop.com/pricing) | Hosted AI automation | Yes | No | Proprietary service | $37/mo | +| [Lindy](https://www.lindy.ai/pricing) | Template-led business agents | Yes | No | Proprietary service | $29.99 or $49.99/user/mo | +| [Node-RED](https://nodered.org/docs/getting-started/) | Engineering-led event flows | No first-party managed platform | Yes | Apache 2.0 | Infrastructure cost | ## How do n8n and Sim compare on licensing and pricing? -n8n is source-available but not open source, while Sim's core is OSI-approved open source under Apache 2.0. n8n states that it "uses the Sustainable Use License and n8n Enterprise License", which it describes as fair-code. Under the [license text](https://github.com/n8n-io/n8n/blob/master/LICENSE.md), you "may use or modify the software only for your own internal business purposes or for non-commercial or personal use", and may distribute it only "free of charge for non-commercial purposes". Files with `.ee.` in their name or `.ee` in their directory name need an n8n Enterprise License. Agencies, consultancies, and SaaS companies should get legal advice before offering n8n functionality to customers. For the clause-by-clause view, see [Apache 2.0 vs fair-code](https://www.sim.ai/library/apache-2-0-vs-fair-code). +n8n is source available but not OSI approved open source, while Sim's core is OSI-approved open source under Apache 2.0. n8n states in its [community license documentation](https://docs.n8n.io/n8n-community-license) that it uses the Sustainable Use License and n8n Enterprise License under a fair-code model. Under the [license text](https://github.com/n8n-io/n8n/blob/master/LICENSE.md), you "may use or modify the software only for your own internal business purposes or for non-commercial or personal use", and may distribute it only "free of charge for non-commercial purposes". Files with `.ee.` in their name or `.ee` in their directory name need an n8n Enterprise License. Agencies, consultancies, and SaaS companies should get legal advice before offering n8n functionality to customers. For the clause-by-clause view, see [Apache 2.0 vs fair-code](https://www.sim.ai/library/apache-2-0-vs-fair-code). [Sim's core is licensed under Apache 2.0](https://github.com/simstudioai/sim/blob/main/LICENSE), which anyone can self-host, modify, and redistribute. Code in `apps/sim/ee` is under the separate [Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE): production use requires an active Sim Enterprise subscription, and modification and redistribution are not permitted. Activepieces follows a similar split, with an MIT core and commercially licensed enterprise features. @@ -388,7 +462,7 @@ Before choosing any alternative, ask these licensing questions: 6. Do self-hosting rights change when the software is customer-facing? 7. Which entity and license version govern the code you deploy? -On price, [n8n's pricing page](https://n8n.io/pricing/) says "All plans include unlimited users & workflows and every integration" and bills on monthly executions. On October 20, 2026 it listed, in euros and billed annually: +On price, [n8n's pricing page](https://n8n.io/pricing/) says "All plans include unlimited users & workflows and every integration" and bills on monthly executions. As of November 2026, it lists these base allowances in euros and billed annually: | n8n plan | Price | Executions | | --- | --- | --- | @@ -410,22 +484,25 @@ Sim bills in credits instead of executions: Free (1,000 one-time credits), Pro $ ## How should you choose an n8n alternative? -Choose by the dominant workload and hosting model, not by whether a product has an AI label. A workflow that mostly moves data between SaaS apps with one model call has different needs from an agent that repeatedly picks tools, checks results, and asks for approval. +An n8n alternative should be chosen by the dominant workload and hosting model, not by whether a product has an AI label. A workflow that mostly moves data between SaaS apps with one model call has different needs from an agent that repeatedly picks tools, checks results, and asks for approval. - **Choose Sim if** AI agents, model flexibility, approvals, and a choice between managed and self-hosted deployment are the core requirements. -- **Choose Dify if** retrieval and LLM application development dominate. +- **Choose Dify or Langflow if** retrieval and visual LLM application development dominate. - **Choose Activepieces if** you want trigger-action automation under an MIT license you can self-host. - **Choose LangGraph or CrewAI if** developers want to own agent behavior in code. - **Choose Make if** you want managed visual automation with detailed scenario debugging. - **Choose Zapier if** you want a fast managed setup across a very large app catalog. - **Choose Power Automate if** the organization runs on Microsoft 365 and Azure. -- **Choose Botpress, Workato, Gumloop, or Lindy if** you need conversational agents, governed enterprise integration, no-code LLM workflows, or template-led business agents respectively. +- **Choose Botpress, Workato, Gumloop, or Lindy if** you need conversational agents, governed enterprise integration, managed AI automation, or template-led business agents respectively. +- **Choose Node-RED if** you need engineering-led event flows under Apache 2.0 and can operate the runtime yourself. - **Stay with n8n if** current workflows are reliable, the license fits your use, and migration would not add enough AI agent benefit to justify its cost. Before switching, build the same representative workflow in two or three candidates. Include at least one model call, one tool call, one conditional branch, one failure or retry, and one human approval so the test shows operational differences. Then migrate gradually: inventory triggers, credentials, API calls, transformations, retries, and approval steps; rebuild one workflow; test it with production-like inputs; compare output and operating cost; and retire the original only after the new one runs cleanly. Sim, Make, Zapier, Activepieces, and Dify all have free tiers that can cover a first test. ## What should you read next? +Sim's related comparisons and library guides cover narrower licensing, deployment, and product-selection questions: + - [Sim vs n8n](https://www.sim.ai/comparisons/n8n): features, pricing, security, and deployment side by side. - [Sim vs n8n vs OpenAI AgentKit](https://www.sim.ai/library/openai-vs-n8n-vs-sim): agent-first, automation-first, and OpenAI-native architectures compared. - [Apache 2.0 vs fair-code](https://www.sim.ai/library/apache-2-0-vs-fair-code): what each license allows for self-hosting and commercial products. diff --git a/apps/sim/content/library/n8n-pricing-cloud-self-hosted-enterprise/index.mdx b/apps/sim/content/library/n8n-pricing-cloud-self-hosted-enterprise/index.mdx new file mode 100644 index 00000000000..ef07f43defd --- /dev/null +++ b/apps/sim/content/library/n8n-pricing-cloud-self-hosted-enterprise/index.mdx @@ -0,0 +1,126 @@ +--- +slug: n8n-pricing-cloud-self-hosted-enterprise +title: 'n8n Pricing: Cloud, Self-Hosted, and Enterprise Costs Explained' +description: 'Compare n8n Cloud, self-hosted, and Enterprise pricing, execution limits, licensing, infrastructure costs, and where Sim fits.' +seoTitle: 'n8n Pricing: Cloud, Self-Hosted & Enterprise' +date: 2026-11-24 +updated: 2026-11-24 +authors: + - andrew +readingTime: 7 +tags: [n8n, Pricing, Self-Hosting, AI Agents, Sim] +ogImage: /library/n8n-pricing-cloud-self-hosted-enterprise/cover.jpg +draft: false +faq: + - q: "Is n8n free?" + a: "n8n Community Edition can be self-hosted without a subscription fee when the intended use complies with the Sustainable Use License, but infrastructure, maintenance, external APIs, and employee time still cost money. As of November 2026, n8n’s managed Cloud service starts at €20 per month when billed annually." + - q: "Is n8n open source?" + a: "n8n is source-available under the Sustainable Use License, not open source under an OSI-approved license. The license permits many internal and noncommercial uses but imposes restrictions that permissive licenses such as Apache 2.0 do not." + - q: "What counts as an n8n execution?" + a: "n8n counts one execution when a workflow runs, regardless of how many standard steps the workflow contains. As of November 2026, execution allowances are a primary difference among n8n plans, although special workflow structures and product terms should be checked against n8n’s current documentation." + - q: "Does n8n charge per user?" + a: "n8n advertises unlimited users across its public plans as of November 2026, so the main published meter is workflow executions rather than seats. Enterprise identity, governance, and administration requirements can still affect which plan a team needs." + - q: "Does n8n charge for failed executions?" + a: "A failed production run is still a workflow execution, so teams should include failures and retries when forecasting monthly execution volume. Current billing terms should be checked for the team’s specific plan and workflow structure." + - q: "Which n8n plan includes SSO?" + a: "n8n includes SSO in its self-hosted Business and custom Enterprise offerings as of November 2026, while Starter and Pro do not include it. Teams should confirm the supported identity protocol and deployment model in their current n8n terms." + - q: "How much does n8n Enterprise cost?" + a: "n8n Enterprise uses custom pricing as of November 2026. The quote depends on factors such as execution volume, hosting model, scaling, security controls, support, and negotiated commercial terms." + - q: "n8n is fair code and has license restrictions, what open source options are truly permissive" + a: "Sim’s core is a permissively licensed alternative because it uses the OSI-approved Apache 2.0 license. Sim’s enterprise directory is a documented exception under the separate Sim Enterprise License, so buyers should distinguish the Apache-licensed core from enterprise-only production features." +--- + +n8n starts at €20 per month for Starter and €50 per month for Pro when billed annually, while the self-hosted Business plan starts at €667 per month and Enterprise uses custom pricing. As of November 2026, [n8n bases these plans primarily on monthly workflow executions](https://n8n.io/pricing/) rather than workflow steps. + +## TL;DR + +- **n8n Cloud:** [Starter costs €20 per month and Pro costs €50 per month](https://n8n.io/pricing/) when billed annually as of November 2026. Pricing is based primarily on monthly workflow executions. +- **Self-hosted n8n:** Community Edition has no subscription fee for uses allowed by the [Sustainable Use License](https://docs.n8n.io/n8n-community-license/), while the Business plan starts at €667 per month when billed annually, before infrastructure and operations costs. +- **n8n Enterprise:** Pricing is custom for Cloud or self-hosted deployments, with terms based on deployment, scale, security, support, and commercial requirements. +- **Sim:** Sim is the open-source AI workspace. [Sim’s core is licensed under Apache 2.0](https://github.com/simstudioai/sim/blob/main/LICENSE), while [apps/sim/ee is governed by the separate Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE). Self-hosted Sim can use local models, and workspace bring your own key (BYOK), which lets teams use their own model-provider keys, is available on every Sim Cloud plan. + +## What are the key n8n and Sim pricing facts at a glance? + +n8n and Sim differ most clearly in their billing models, self-hosting costs, and software licenses. + +- **n8n:** As of November 2026, [n8n offers hosted Cloud plans, a paid self-hosted Business plan, and quote-based Enterprise deployment](https://n8n.io/pricing/). Plans are primarily metered by monthly workflow executions. n8n is distributed under its source-available Sustainable Use License, which does not appear on the [OSI list of approved licenses](https://opensource.org/licenses). +- **Sim:** Sim is the open-source AI workspace, and [Sim’s core is licensed under Apache 2.0](https://github.com/simstudioai/sim/blob/main/LICENSE), while [apps/sim/ee is governed by the separate Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE). Self-hosted Sim can use local models, and workspace BYOK is available on every Sim Cloud plan. + +## How do n8n Cloud, self-hosted, and Enterprise plans compare? + +[n8n offers two public Cloud tiers, one public paid self-hosted tier, and a custom Enterprise tier](https://n8n.io/pricing/) as of November 2026. + +The following prices and limits come from [n8n’s official pricing page](https://n8n.io/pricing/) and reflect its public euro pricing for annual billing as of November 2026. Local currency, taxes, monthly billing, add-ons, and negotiated terms can change the total. + +| n8n plan | Hosting | Starting price | Included executions per month | Active workflows | Users | Single sign-on (SSO) | Notable features | +|---|---|---:|---:|---:|---:|---|---| +| Starter | n8n Cloud | €20/month, billed annually | 2,500 | Unlimited | Unlimited | No | Hosted service, integrations, and the workflow builder | +| Pro | n8n Cloud | €50/month, billed annually | 10,000 | Unlimited | Unlimited | No | Higher execution allowance and added collaboration and administration features | +| Business | Self-hosted | €667/month, billed annually | 40,000 | Unlimited | Unlimited | Yes | Environments, source-control features, scaling options, and administration controls | +| Enterprise | n8n Cloud or self-hosted | Custom quote | Custom | Unlimited | Unlimited | Yes | Security, governance, scaling, support, and deployment terms agreed with n8n | + +[n8n counts executions instead of charging for every individual step in a workflow](https://n8n.io/pricing/). That can make a long workflow economical, but a frequently triggered workflow can still move a team into a higher plan even if each run is simple. + +The advertised subscription is not always the final cost. Teams may also pay for AI model APIs, third-party services, data storage, additional infrastructure, implementation, support, and the engineering time required to operate self-hosted deployments. + +## What does self-hosting n8n really cost? + +Self-hosted n8n can remove the managed-cloud component, but it does not remove infrastructure, operations, licensing, or execution-based plan costs. + +A realistic monthly estimate includes: + +1. **n8n subscription:** [Community Edition has no subscription fee for uses permitted by the Sustainable Use License](https://docs.n8n.io/n8n-community-license/community-license/license-faq), while [Business starts at €667 per month when billed annually and Enterprise is quote-based](https://n8n.io/pricing/) as of November 2026. +2. **Compute and storage:** The deployment needs application servers, a database, persistent storage, backups, and network services. +3. **Scaling infrastructure:** Larger or highly available deployments may require workers, caching or queue infrastructure, load balancing, monitoring, and additional database capacity. +4. **Operations:** A team must patch n8n, test upgrades, monitor runs, investigate failures, restore backups, and manage secrets. +5. **External services:** AI models, email providers, databases, observability tools, and other APIs can bill separately. +6. **Security and compliance:** Private networking, log retention, identity management, vulnerability handling, and audit requirements can add software and labor costs. + +The simplest cost model is: + +> Total self-hosted cost = n8n license or subscription + infrastructure + external APIs + operations labor + security and compliance tooling + +Self-hosting is usually most economical when a team already operates reliable application infrastructure and the Community Edition satisfies its feature and license requirements. Managed n8n Cloud is usually simpler when the team would otherwise need to create a new operational function solely for the automation service. + +## What does the n8n Sustainable Use License allow? + +The n8n Sustainable Use License allows many internal, personal, noncommercial, educational, and consulting uses, but it does not grant the broad rights associated with an OSI-approved open-source license. + +As of November 2026, n8n describes its standard license as a [Sustainable Use License](https://docs.n8n.io/n8n-community-license/). It is source-available and often permits a business to run n8n internally. Its restrictions matter when a company wants to sell hosted n8n access, white-label the product, or use it as the core of a competing commercial service. + +A paid n8n Business or Enterprise agreement can also be necessary when a team needs capabilities reserved for those editions, regardless of whether its basic internal use would otherwise fit the Sustainable Use License. Teams should review n8n’s current license text and commercial terms for their exact deployment rather than treating self-hosted availability as an unrestricted license grant. + +For a fuller license comparison, read [Apache 2.0 vs Fair-Code: Why Sim’s Core License Differs From n8n’s for Self-Hosting](https://www.sim.ai/library/apache-2-0-vs-fair-code). + +## How does monthly n8n cost change at 2,500, 10,000, and 40,000 executions? + +[n8n’s public annual-billing prices](https://n8n.io/pricing/) rise from €20 at 2,500 included executions to €50 at 10,000, while the published 40,000-execution Business tier costs €667 and requires self-hosting as of November 2026. + +| Monthly execution volume | Public plan that includes the volume | Published base subscription | Additional cost to consider | +|---:|---|---:|---| +| 2,500 | Starter on n8n Cloud | €20/month, billed annually | AI models and other metered APIs | +| 10,000 | Pro on n8n Cloud | €50/month, billed annually | AI models, other APIs, and optional services | +| 40,000 | Business, self-hosted | €667/month, billed annually | Compute, database, storage, backups, monitoring, and operations labor | + +These are plan examples rather than universal total-cost estimates. A team that needs 40,000 executions but wants n8n to host the deployment should request current Cloud or Enterprise terms instead of assuming the self-hosted Business price applies. Likewise, a team exceeding a plan allowance should compare n8n’s available execution tiers or add-ons against the next plan rather than extrapolating an unofficial per-execution rate. + +## When does Sim fit compared with n8n? + +Sim can fit teams that need a permissively licensed AI workspace, want to self-host the core without a core software license fee, or plan to use their own model keys or local models. + +[Sim’s core Apache 2.0 license](https://github.com/simstudioai/sim/blob/main/LICENSE) permits use, modification, and redistribution subject to the license terms. The exception is [apps/sim/ee](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE), which includes enterprise capabilities such as single sign-on (SSO), System for Cross-domain Identity Management (SCIM) for automated user provisioning, access control, audit logs, data retention, and credential groups. That code is free for development, testing, and internal non-production use, but production use requires an active Sim Enterprise subscription, and modification and redistribution are not permitted. + +[Self-hosted Sim](https://docs.sim.ai/platform/self-hosting) can connect to Ollama, vLLM, LM Studio, or LiteLLM without requiring Sim Enterprise. Infrastructure and model costs still remain, so Apache 2.0 does not mean a production deployment has zero total cost. + +[Sim Cloud supports workspace BYOK on every plan](https://docs.sim.ai/platform/costs), allowing teams to pay model providers directly. Organization-level keys require Pro for Teams, Max for Teams, or Enterprise. + +Sim fits teams that specifically need Apache 2.0 rights for the core. n8n fits teams that prioritize its automation ecosystem, execution-based billing, and existing operational familiarity over a permissive open-source license. + +## Where can you compare n8n with Sim and other alternatives? + +Sim’s existing guides separate direct product comparison, alternative selection, and licensing analysis so buyers can examine each decision in detail. + +- [Sim vs n8n vs OpenAI AgentKit: AI Agent Builder Comparison (2026)](https://www.sim.ai/library/openai-vs-n8n-vs-sim) compares product capabilities and deployment choices. +- [14 n8n Alternatives and Competitors: Choosing an n8n Alternative in 2026](https://www.sim.ai/library/n8n-alternatives) covers broader replacement options. +- [Apache 2.0 vs Fair-Code: Why Sim’s Core License Differs From n8n’s for Self-Hosting](https://www.sim.ai/library/apache-2-0-vs-fair-code) explains the licensing distinction in depth. +- [n8n vs Zapier vs Make: Which Automation Platform Is Best in 2026?](https://www.sim.ai/library/n8n-vs-zapier-vs-make) compares three established automation products. diff --git a/apps/sim/content/library/servicenow-ai-agent-it-service-requests/index.mdx b/apps/sim/content/library/servicenow-ai-agent-it-service-requests/index.mdx new file mode 100644 index 00000000000..b14783c93c8 --- /dev/null +++ b/apps/sim/content/library/servicenow-ai-agent-it-service-requests/index.mdx @@ -0,0 +1,247 @@ +--- +slug: servicenow-ai-agent-it-service-requests +title: 'How Do You Build a Governed AI Agent for ServiceNow IT Service Requests?' +description: 'Learn how to build a governed ServiceNow AI agent with scoped access, structured decisions, human approval, execution evidence, and safe escalation.' +seoTitle: 'ServiceNow AI Agent for IT Service Requests' +date: 2026-11-23 +updated: 2026-11-23 +authors: + - andrew +readingTime: 11 +tags: [AI Agents, ServiceNow, ITSM, Governance, Sim] +ogImage: /library/servicenow-ai-agent-it-service-requests/cover.jpg +draft: false +faq: + - q: "What are the top AI agent platforms for IT helpdesk teams automating ticket resolution?" + a: "ServiceNow fits native ITSM automation, Sim fits governed agents that must coordinate ServiceNow with external systems, and n8n is a practical source-available option for teams that want general workflow automation." + - q: "Can Sim connect ServiceNow to Slack or Microsoft Teams?" + a: "Sim can coordinate ServiceNow actions with supported Slack or Microsoft Teams actions so an approved workflow can send ticket updates to the appropriate channel." + - q: "Should an AI agent close ServiceNow incidents automatically?" + a: "ServiceNow incidents should close automatically only for narrowly defined outcomes with reliable evidence, while ambiguous, privileged, or high-impact cases should require human approval." + - q: "Can n8n automate ServiceNow tickets?" + a: "n8n provides a ServiceNow node for general workflow automation, but IT leaders should evaluate its source-available Sustainable Use License, governance requirements, and approval design before production deployment." + - q: "Does Sim require Enterprise for self hosting or local models?" + a: "Sim does not require Enterprise for self hosting or local models because any self-hosted Sim deployment can connect to Ollama, vLLM, LM Studio, or LiteLLM, although production use of features in apps/sim/ee requires an active Sim Enterprise subscription." + - q: "Can a ServiceNow AI agent use CMDB data?" + a: "A ServiceNow AI agent can use CMDB data that its integration identity is permitted to read, and the workflow should retrieve only the attributes needed for the current incident." + - q: "How should IT teams measure a ServiceNow AI agent pilot?" + a: "IT teams should measure a ServiceNow AI agent pilot with routing accuracy, reassignment rate, approval rate, resolution time, reopen rate, unauthorized action count, and the percentage of runs escalated safely." + - q: "Is Sim open source?" + a: "Sim's core is Apache 2.0 open source, while enterprise features in apps/sim/ee use the separate Sim Enterprise License and require an active Enterprise subscription for production use." +--- + +## TL;DR + +Sim fits teams that need governed AI agents to classify ServiceNow incidents, gather relevant context, prepare routine service actions, pause for human approval, update tickets, and notify collaboration channels without giving a language model unrestricted control of the ITSM system. + +The safest design separates probabilistic analysis from deterministic execution. The model can interpret a request and propose a structured decision, while explicit Conditions, scoped credentials, approval steps, and ServiceNow access controls determine whether any record is changed. + +## What can AI agents safely do inside ServiceNow today? + +ServiceNow AI agents can safely perform bounded tasks when every read and write is constrained by permissions, structured outputs, deterministic rules, and escalation paths. + +Good production candidates include: + +1. Classifying an incident by category, subcategory, urgency, and likely assignment group. +2. Retrieving approved ticket, asset, service, and CMDB context before producing a summary. +3. Preparing routine service request actions and waiting for an authorized person to approve them. +4. Updating work notes or status fields after a confirmed external action. +5. Sending sanitized progress notifications to Slack or Microsoft Teams. +6. Escalating low-confidence, sensitive, or exceptional cases without making a change. + +An agent should not receive broad administrator access, invent missing configuration data, or treat a plausible answer as proof that work was completed. ServiceNow's [Table API](https://www.servicenow.com/docs/r/xanadu/api-reference/rest-apis/c_TableAPI.html) supports create, read, update, and delete operations on tables, but the integration identity and ServiceNow access controls should determine which operations are available. + +## How should a governed ServiceNow agent be designed in Sim? + +Sim can orchestrate a ServiceNow agent as a sequence of narrow reads, structured decisions, policy checks, approvals, writes, and notifications. + +A practical architecture has seven stages: + +1. **Trigger:** Receive a new or updated ServiceNow record through an approved event or polling pattern. +2. **Retrieve:** Use the ServiceNow block to fetch only the record fields and related context required for the task. +3. **Analyze:** Ask the model for a structured classification, confidence score, rationale, and proposed action. +4. **Validate:** Use deterministic Conditions to check allowed categories, confidence thresholds, required fields, and protected request types. +5. **Approve:** Pause sensitive actions with Sim's Human in the Loop block and collect an explicit approve or reject field. +6. **Execute:** Use a downstream Condition to inspect the approval field before allowing the ServiceNow update or external action. +7. **Record:** Write the outcome and relevant evidence to the ticket, then send a limited status message to the chosen collaboration channel. + +Sim's Human in the Loop block pauses a run and resumes it with submitted form fields. Approval is not automatic enforcement. The workflow must use a downstream Condition to check the approve or reject field before executing the proposed action. + +For model output controls, define a compact schema such as: + +```json +{ + "category": "network", + "assignment_group": "network_operations", + "confidence": 0.94, + "risk_level": "low", + "proposed_action": "route", + "evidence": ["vpn_error_in_description", "affected_service_matches"] +} +``` + +The ServiceNow write should use mapped values from an approved set rather than unconstrained model text wherever possible. + +## How do you classify and route ServiceNow incidents with an AI agent? + +Sim can classify and route ServiceNow incidents by combining ticket context with a controlled taxonomy and allowing deterministic logic to make the final assignment decision. + +A lean workflow is: + +1. Retrieve the incident description, affected service, caller context, current category, and current assignment group. +2. Remove secrets or unnecessary personal information before sending context to the model. +3. Give the model the approved category list and assignment group mapping. +4. Require a structured response with category, group, confidence, evidence, and a short summary. +5. Route high-confidence matches to an allowed assignment group. +6. Send low-confidence or conflicting results to the service desk queue for review. +7. Add a work note explaining the evidence used for the recommendation. + +Use historical tickets for evaluation, not as unconditional instructions. A previous routing decision may reflect an old team structure or a human mistake. The workflow's current allowlist should remain authoritative. + +Routing accuracy alone is not enough. Track reassignment rate, time to first owner, false high-confidence decisions, and the share of incidents safely escalated. The same design principles apply to broader [AI support ticket triage](https://www.sim.ai/library/best-ai-agents-support-ticket-triage), where classification quality must be paired with safe handoff behavior. + +## How do you enrich a ServiceNow ticket with logs and CMDB context? + +Sim can enrich a ServiceNow ticket by retrieving a small set of relevant records from approved systems and attaching a concise, evidence-based summary to the incident. + +The workflow should begin with identifiers already present in the ticket, such as the affected configuration item, service, user, host, or alert ID. It can then retrieve permitted attributes from ServiceNow and approved observability sources before asking the model to summarize relationships. + +Useful enrichment can include: + +1. The affected service and configuration item. +2. Recent approved changes related to that item. +3. Ownership and support group information. +4. A small window of relevant error events. +5. Related open incidents. +6. A concise chronology with source identifiers. + +The agent should cite record IDs or event IDs in its work note so a technician can inspect the evidence. It should distinguish observed facts from model-generated hypotheses and should not copy unrestricted logs into ServiceNow or a collaboration channel. + +For alert-focused workflows that need a formal approval boundary, see [How Do AI Agents Triage Security Alerts With Human Approval?](https://www.sim.ai/library/ai-agents-security-alert-triage-human-approval). + +## How do you fulfill routine ServiceNow requests with human approval? + +Sim can prepare and execute routine ServiceNow service requests safely when the permitted request types, approvers, action parameters, and completion evidence are defined before the model runs. + +Password resets, access changes, software requests, and device actions do not carry equal risk. Start with a narrow request type whose downstream system exposes a reversible and auditable operation. + +A governed fulfillment sequence is: + +1. Retrieve the request and verify that it belongs to an approved request type. +2. Extract structured parameters such as the target user, requested resource, duration, and business justification. +3. Validate required fields and reject values outside the policy allowlist. +4. Determine the required approver from policy rather than allowing the model to choose one freely. +5. Pause the run with Human in the Loop and display the proposed action, target, evidence, and risk. +6. Route on the submitted approval field with a downstream Condition. +7. Execute the action only on the approved branch. +8. Verify the external system response before updating ServiceNow as fulfilled. +9. Record rejection, failure, or incomplete evidence without claiming success. + +The workflow should use idempotency controls where the downstream operation supports them. A resumed or retried run must not grant access twice, create duplicate requests, or post contradictory completion notes. + +For a device management example, see [How Do You Build a Governed AI Agent for Microsoft Intune Device Management?](https://www.sim.ai/library/ai-agents-microsoft-intune-device-management). + +## How do you post ServiceNow status updates to Slack or Microsoft Teams? + +Sim can post ServiceNow status updates to Slack or Microsoft Teams after the workflow confirms the ticket state and removes information that should remain inside the ITSM system. + +A useful channel message contains the ticket identifier, a short status, the owning team, and a link supplied by the organization's approved configuration. It should omit secrets, full logs, sensitive user details, and internal model reasoning. + +Send notifications only after a confirmed state transition. For example, the workflow can notify a channel after ServiceNow accepts the assignment update, after an approver submits a decision, or after the downstream system returns evidence of completion. + +Channel selection should be deterministic. Map services, business units, or assignment groups to approved destinations instead of asking the model to invent a channel name. + +## How should ServiceNow AI agents be governed? + +ServiceNow and Sim should govern IT service agents through dedicated identities, least-privilege access, explicit approval boundaries, execution records, and regular evaluation. + +### What permissions should a ServiceNow integration identity receive? + +A ServiceNow integration identity should receive only the roles and record access required for the specific tables, fields, and operations in the workflow. + +Use separate credentials for development and production. Avoid sharing a human administrator account. Keep read and write permissions distinct where practical, and deny access to unrelated records even if they are technically reachable through an API. + +ServiceNow [Access Control Lists](https://www.servicenow.com/docs/r/platform-security/access-control/access-control-rules.html) restrict access to data through defined requirements and should remain the enforcement layer for records and fields. Sim credentials should be stored as managed credentials rather than placed in prompts or workflow text. + +### Where should human approval be required? + +Sim should require human approval before privileged, high-impact, ambiguous, or difficult-to-reverse actions. + +Approval is especially important for access grants, account changes, security configuration, device actions, financial commitments, sensitive user data, and any operation with incomplete evidence. Low-risk classification or enrichment can often run without approval if it only proposes or records bounded information. + +The approval form should show the target, exact proposed action, relevant evidence, risk level, and expected result. The approver should not need to reconstruct the action from a generic summary. + +### What should the audit record contain? + +Sim and ServiceNow should preserve enough execution evidence to reconstruct what triggered the run, what data was used, what decision was proposed, who approved it, and what action result was returned. + +At minimum, record the workflow version, ticket identifier, timestamps, model and prompt version where available, structured decision, approval response, ServiceNow response, external action response, and final state. Avoid placing secrets or unnecessary raw personal data in logs. + +Sim's enterprise audit log features are in `apps/sim/ee` under the separate [Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE), which requires an active Sim Enterprise subscription for production use. + +## How does Sim compare with ServiceNow AI agents and n8n for IT service requests? + +Sim, ServiceNow, and n8n fit different IT service automation boundaries. ServiceNow fits native ITSM work, Sim fits governed cross-system agents, and n8n fits general workflow automation. + +| Platform | Fit | ServiceNow role | Governance approach | +|---|---|---|---| +| ServiceNow AI Agents | Work that remains primarily inside ServiceNow | Native access to ServiceNow processes and data according to the purchased product and configured permissions | ServiceNow roles, access controls, and product governance | +| Sim | Governed agents that coordinate ServiceNow with models, collaboration tools, device systems, observability tools, and custom APIs | ServiceNow remains the system of record while Sim coordinates reasoning, approval, and cross-system execution | Structured outputs, Conditions, Human in the Loop, managed credentials, deployment controls, and enterprise controls where licensed | +| n8n | General integrations and deterministic automation with optional AI steps | The ServiceNow node can read and change supported records within configured credentials | Workflow logic, credentials, deployment controls, and organization-specific review processes | + +ServiceNow describes agents that use tools such as flow actions, subflows, scripts, and skills on its [AI Agents product page](https://www.servicenow.com/products/ai-agents.html). Native ServiceNow agents fit when the task, data, approvals, and actions all remain in ServiceNow. + +Sim fits when ServiceNow must coordinate with systems such as Intune, observability platforms, internal APIs, Slack, or Microsoft Teams, and the team wants one visual workflow for model reasoning, deterministic checks, approval, and execution. + +n8n is another option for broad automation. Its [ServiceNow node documentation](https://docs.n8n.io/integrations/builtin/app-nodes/n8n-nodes-base.servicenow) lists operations for incidents, configuration items, table records, users, and other resources. n8n uses the source-available [Sustainable Use License](https://docs.n8n.io/n8n-community-license), not an OSI-approved open-source license. + +## What are the key platform facts as of November 2026? + +Sim, ServiceNow, and n8n differ in licensing, deployment, and billing, so IT teams should compare those facts separately from workflow features. + +1. **Sim:** Sim's core uses the OSI-approved Apache 2.0 license, while code in `apps/sim/ee` uses the separate [Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE). Any [self-hosted Sim deployment](https://docs.sim.ai/platform/self-hosting) can use local models through Ollama, vLLM, LM Studio, or LiteLLM, and [workspace BYOK](https://docs.sim.ai/platform/costs#bring-your-own-key-byok) is available on any Sim Cloud plan. +2. **ServiceNow:** ServiceNow's [ITSM pricing page](https://www.servicenow.com/lpgp/pricing-itsm.html) directs buyers to request a quote based on their requirements rather than publishing one universal workflow execution price. +3. **n8n:** n8n's self-hosted Community edition uses its [Sustainable Use License](https://docs.n8n.io/n8n-community-license/community-license/license-faq), while [n8n Cloud pricing](https://n8n.io/pricing/) uses monthly workflow executions as its primary usage unit. + +These facts are current as of November 2026. Buyers should confirm current terms on each vendor's official pages during procurement. + +## When should an IT team choose ServiceNow, Sim, or n8n? + +IT teams should choose based on the system boundary, governance model, deployment needs, and licensing requirements of the use case. + +Choose ServiceNow's native agents when: + +1. Most relevant context and actions live in ServiceNow. +2. The organization wants native ServiceNow administration and product governance. +3. Existing ServiceNow licensing and implementation resources cover the use case. + +Choose Sim when: + +1. The agent must coordinate ServiceNow with several external systems. +2. The team needs explicit separation between model reasoning and deterministic execution. +3. Human approval must be visible inside a multi-step workflow. +4. The team wants model choice, workspace BYOK, or local models on a self-hosted deployment. +5. IT wants Sim's core Apache 2.0 codebase while evaluating features under the separate [Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE) where needed. + +Choose n8n when: + +1. The task is primarily general integration automation. +2. The required ServiceNow operations are supported by its node or can be implemented through approved API calls. +3. The organization accepts the Sustainable Use License and can implement the required governance around its workflows. + +For a broader fit-based comparison, see [AI Agents for IT Helpdesk Teams: 6 Platforms Compared](https://www.sim.ai/library/best-ai-agents-for-it-helpdesk-teams). + +## How should CIOs pilot a ServiceNow AI agent? + +A team can begin a ServiceNow pilot with one high-volume, low-risk request type and a written policy for data access, confidence thresholds, approvals, and rollback. + +A four-phase pilot reduces operational risk: + +1. **Replay:** Run historical tickets without writing to ServiceNow and compare the agent's decisions with reviewed outcomes. +2. **Recommend:** Let the agent prepare classifications or actions while humans make every final change. +3. **Approve:** Permit bounded writes only after an authorized person approves the exact action. +4. **Automate selectively:** Remove approval only for outcomes that demonstrate reliable evidence, low impact, and safe recovery. + +Set exit criteria before the pilot begins. A production candidate should meet agreed thresholds for routing accuracy, reassignment rate, resolution time, reopen rate, policy violations, and safe escalation. Any unauthorized action should trigger investigation rather than being averaged into an overall success score. + +A ServiceNow agent is ready for broader use only when the organization can explain its permissions, reproduce its decisions, identify its approvers, and stop or reverse its actions safely. diff --git a/apps/sim/content/library/workato-pricing-ai-agents-cost/index.mdx b/apps/sim/content/library/workato-pricing-ai-agents-cost/index.mdx new file mode 100644 index 00000000000..77ce77bc481 --- /dev/null +++ b/apps/sim/content/library/workato-pricing-ai-agents-cost/index.mdx @@ -0,0 +1,200 @@ +--- +slug: workato-pricing-ai-agents-cost +title: 'Workato Pricing: Costs, Cost Drivers, and When AI Agents Cost Less' +description: 'Understand Workato pricing, usage credits, enterprise quote drivers, and when an AI workspace such as Sim can have a lower annual cost.' +seoTitle: 'Workato Pricing and AI Agent Costs' +date: 2026-11-24 +updated: 2026-11-24 +authors: + - andrew +readingTime: 8 +tags: [Workato, Pricing, AI Agents, BYOK, Sim] +ogImage: /library/workato-pricing-ai-agents-cost/cover.jpg +draft: false +faq: + - q: "Does Workato publish standard list prices?" + a: "Workato publishes self-service Free and Pro options, but its enterprise pricing page does not publish standard dollar prices. Enterprise buyers must contact Workato for a tailored quote." + - q: "Does Workato offer a free plan?" + a: "Workato offers a self-service Free plan with a one-time allocation of Workato credits as of November 2026." + - q: "Are Workato recipes and tasks the same thing?" + a: "Workato recipes and tasks are not the same thing: a recipe defines an automation, while Tasks represent action steps performed when recipes execute." + - q: "Can Sim use bring-your-own model keys?" + a: "Sim supports workspace bring-your-own model keys on every Sim Cloud plan, while Sim organization-level keys require Pro for Teams, Max for Teams, or Enterprise as of November 2026." + - q: "Does BYOK make AI model usage free?" + a: "Sim BYOK does not make model usage free because the model provider still charges for usage. Sim BYOK lets the team pay that provider directly instead of using Sim-hosted model keys." + - q: "Can Sim run local models when self-hosted?" + a: "Sim can connect a self-hosted deployment to local models through Ollama, vLLM, LM Studio, or LiteLLM without requiring Sim Enterprise." + - q: "Is Sim free to self-host?" + a: "Sim’s Apache 2.0 core can be self-hosted, but production use of features under the separate Sim Enterprise License requires an active Sim Enterprise subscription. Infrastructure, model, and third-party service costs can still apply." + - q: "Is n8n open source?" + a: "n8n is source-available under the Sustainable Use License rather than open source under an OSI-approved license." + - q: "Which is better for enterprise integration, Workato or Sim?" + a: "Workato suits broad enterprise integration programs, while Sim fits teams that need to build, deploy, and manage AI agents with model choice and BYOK." + - q: "Which is cheaper, Workato or Sim?" + a: "Sim can cost less for focused AI-agent workloads with BYOK and a limited integration footprint, but buyers must compare a current Workato quote with complete annual costs for the same requirements." +--- + +## TL;DR + +- Workato offers [self-service Free and Pro options](https://docs.workato.com/en/pricing/self-service/self-service), while its [enterprise editions use quote-based pricing](https://www.workato.com/pricing). Enterprise buyers need an itemized quote to establish the actual annual cost. +- Workato uses a [usage-based billing model](https://docs.workato.com/pricing) for current plans. Usage across capabilities is converted into Workato credits, although some older contracts use different measurements. +- The main cost drivers are the selected edition, usage capacity, connectors, environments, AI capabilities, support, implementation, and internal operating labor. Workato’s enterprise pricing page shows how included capabilities vary by edition. +- Sim fits teams that primarily need to build, deploy, and manage AI agents. BYOK and self-hosting can change the cost structure, but model, infrastructure, implementation, and operating costs still count. + +Workato pricing has two distinct paths as of November 2026. Workato provides [self-service Free and Pro plans](https://docs.workato.com/en/pricing/self-service/self-service), while the company’s [enterprise pricing page](https://www.workato.com/pricing) asks buyers to contact sales for Standard, Business MCP, and Enterprise MCP pricing. + +For a useful comparison, calculate Workato’s complete annual cost, including usage, environments, support, add-ons, and implementation. Then compare it with the subscription, model, hosting, and operating costs of an AI workspace such as Sim. + +## How much does Workato cost? + +Workato does not publish one standard price that answers how much every customer will pay. Its [self-service documentation](https://docs.workato.com/en/pricing/self-service/self-service) describes a Free plan with a one-time 50,000-credit grant and Pro options with recurring monthly credit allocations. [Enterprise editions](https://www.workato.com/pricing) remain quote-based. + +That means there is no defensible public “typical Workato price” for a 20-person startup, a 200-person operations team, or a global enterprise. Enterprise quotes can differ because the required edition, capacity, applications, environments, governance features, support, and implementation scope differ. + +Buyers should ask Workato for an itemized annual quote rather than treating an initial platform figure as total cost. The quote should state: + +- The platform edition and included capabilities +- The contracted usage or credit allowance +- How excess usage is measured and charged +- Which connectors and recipes are included +- The number of development, test, and production environments +- AI or agent-related entitlements +- Support and service levels +- One-time implementation or partner fees +- Renewal terms and expected price changes + +## How does Workato pricing work? + +Workato describes its current approach as a [usage-based billing model](https://docs.workato.com/pricing). For customers on that model, usage across different capabilities is converted into Workato credits. Workato notes that customers who joined before February 2024 may use a different model, so the order form remains the source of truth for a specific account. + +A recipe is Workato’s term for an automated workflow. For workflow recipes measured in Tasks, [Workato defines a Task](https://docs.workato.com/recipes/tasks) as one action step that a recipe executes. Triggers and control-flow steps do not count as Tasks, and some plans measure workflow usage differently. + +This distinction matters. The number of recipes describes how many automations a team operates, while usage reflects how often and how extensively those automations perform work. A team with a few high-volume recipes can therefore need more capacity than a team with many rarely used recipes. + +## What drives Workato cost? + +Workato cost is primarily driven by the selected edition, usage capacity, deployment requirements, add-ons, support, and implementation scope. The [Workato pricing page](https://www.workato.com/pricing) lists different capabilities across its enterprise editions but leaves exact contract prices to the sales process. + +| Cost driver | How it can affect Workato’s total cost | What buyers should request | +|---|---|---| +| Platform edition | Establishes the contracted capabilities and commercial foundation | An itemized list of included platform capabilities | +| Recipes | Represents the automations the organization builds and operates | Recipe entitlements and any contractual limits | +| Usage capacity | Reflects operations across recipes and other Workato capabilities | Included credits or other capacity, measurement rules, and excess-usage terms | +| Connectors | Determines which business systems recipes can access | Included connectors and charges for premium or custom connectivity | +| Environments | Supports separation between development, testing, and production | Included environments and the price of additional environments | +| AI capabilities | Adds agent, model, document, or AI-related usage | Included capabilities, usage allowances, and external model charges | +| Governance and security | Adds controls required by larger or regulated organizations | Exact capabilities included in the selected edition or add-ons | +| Support | Changes response commitments and access to vendor assistance | Support tier, service levels, and annual charge | +| Implementation | Covers solution design, migration, testing, and enablement | Separate estimates for Workato, partner, and internal labor | + +Workato buyers should also model growth. A quote that fits a pilot may not represent the cost of running the same recipes across more departments, records, customers, or events. + +## What do mid-size teams typically pay for Workato? + +Workato’s [enterprise pricing page](https://www.workato.com/pricing) does not publish enough dollar data to calculate a reliable typical price for mid-size teams. Any universal estimate that is not tied to a current Workato quote risks combining different editions, capacities, add-ons, and service arrangements. + +A mid-size team can still produce a decision-ready estimate by requesting three scenarios: + +1. **Pilot:** The smallest production configuration that supports the first use case. +2. **Expected year-one use:** The anticipated recipes, runs, data volume, environments, and users. +3. **Growth case:** Higher usage plus the governance, support, and additional environments likely to be needed after rollout. + +The useful number is annual total cost, not just subscription cost: + +**Workato annual total cost = platform and capacity charges + usage charges + add-ons + support + implementation + partner fees + internal operating labor** + +This method avoids presenting an unsupported market average as if it were an official Workato price. + +## When is Workato worth the cost? + +Workato is worth considering when an organization needs enterprise integration, broad business-system connectivity, centralized governance, and coordinated automation across multiple departments. Its [enterprise editions](https://www.workato.com/pricing) include combinations of application integration, process automation, environment management, access controls, Model Context Protocol (MCP) capabilities for connecting AI systems with tools, data integration, API management, and other services, depending on the selected edition. + +Workato may be the right call when: + +- Multiple departments need a shared integration and automation program +- Existing enterprise applications require coordinated data movement +- Central IT needs formal administration and lifecycle controls +- The organization has staff or partners available for implementation +- The negotiated quote remains economical under expected usage growth + +The decision should depend on requirements rather than company size alone. A smaller regulated business may need enterprise controls, while a large team with only a narrow AI use case may not need a broad integration suite. + +## Is Workato overkill for a 20-person startup that just needs AI agents connected to a few SaaS tools? + +Workato can be more platform than a 20-person startup needs when the team only wants a few AI agents connected to a small set of SaaS tools. An enterprise integration suite can be harder to justify when the main requirements are visual agent building, model access, selected integrations, and direct control over model spending. + +Workato may still make sense if the startup has unusually complex integration, compliance, or governance requirements. Otherwise, an AI-focused workspace can reduce platform scope and procurement effort. + +A startup should compare the options using its actual workload: + +- Number of production agents +- Agent runs per month +- Model tokens consumed per run +- SaaS actions performed per run +- Required approval and governance controls +- Engineering time needed for deployment and maintenance +- Expected workload growth over the next 12 months + +For a broader product comparison, see [6 Best Workato Alternatives for AI Agents in 2026](https://www.sim.ai/library/best-workato-alternatives-ai-agents-2026). Teams deciding whether to operate their own infrastructure can also review [AI Agent Hosting: Where Should IT Run Production Agents?](https://www.sim.ai/library/ai-agent-hosting-models-production-agents). + +## When do AI agents cost less than Workato? + +Sim can cost less than Workato when a team primarily needs AI agents, uses a focused set of integrations, brings its own model-provider keys, and does not require the full scope of an enterprise integration suite. The result depends on the customer’s Workato quote and actual AI usage, so the break-even point must be calculated rather than assumed. + +Sim supports workspace BYOK on every Sim Cloud plan. Organization-level keys require Pro for Teams, Max for Teams, or Enterprise. With BYOK, the model provider bills the customer directly, as explained in Sim’s [cost and BYOK documentation](https://docs.sim.ai/platform/costs#bring-your-own-key-byok). + +Use these formulas: + +**Sim Cloud annual total cost = Sim subscription + usage charges beyond included credits + direct model-provider charges + implementation labor + operating labor** + +Sim’s [cost documentation](https://docs.sim.ai/platform/costs) notes that BYOK avoids the model or tool charge for provider calls it covers, but the workflow base charge and unrelated hosted-tool or sandbox usage still apply. Paid usage beyond included credits can be billed as overage when on-demand usage is enabled. + +**Self-hosted Sim annual total cost = infrastructure + direct model-provider charges + implementation labor + operating labor + any required enterprise-feature subscription** + +**Workato annual total cost = Workato subscription or quote + usage charges outside the included allowance + add-ons + support + implementation labor + operating labor** + +Sim costs less only when the relevant Sim total is below the complete Workato total for the same production requirements. BYOK can strengthen the case for model-heavy workloads because the team pays the model provider directly, but it does not eliminate provider usage charges. + +The [AI agent development company versus in-house guide](https://www.sim.ai/library/ai-agent-development-company-vs-building-in-house) explains how implementation and staffing choices affect the budget beyond software fees. + +## What are the key pricing and deployment facts about Workato, Sim, and n8n? + +Workato, Sim, and n8n use materially different packaging, deployment, and licensing models that affect total cost. + +- **Workato:** Workato is a proprietary product with [self-service](https://docs.workato.com/en/pricing/self-service/self-service) and [enterprise sales](https://www.workato.com/pricing) paths. Its [usage documentation](https://docs.workato.com/pricing) says current plans convert successful operations across capabilities into Workato credits, while some older contracts use different measurements. +- **Sim:** Sim is the open-source AI workspace where teams build, deploy, and manage AI agents. Sim’s core is Apache 2.0 and can be [self-hosted](https://docs.sim.ai/platform/self-hosting), while code in `apps/sim/ee` is governed by the separate [Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE), which requires an active Enterprise subscription for production use. +- **n8n:** n8n offers hosted and self-hosted plans, and its [pricing page](https://n8n.io/pricing/) says pricing is based on monthly workflow executions. Its [Sustainable Use License](https://github.com/n8n-io/n8n/blob/master/LICENSE.md) is source-available rather than an OSI-approved open-source license. + +n8n belongs in the cost comparison because teams may evaluate it for workflow automation and AI agents. Sim fits teams whose primary job is building and operating AI agents with model choice and BYOK. Workato suits programs centered on enterprise integration breadth and centralized automation. + +For a deeper licensing comparison, read [Apache 2.0 vs Fair-Code: Why Sim’s Core License Differs From n8n’s for Self-Hosting](https://www.sim.ai/library/apache-2-0-vs-fair-code). + +## How should buyers compare a Workato quote with an AI workspace? + +Buyers should compare Workato and an AI workspace against the same workload, service level, and governance requirements. Comparing a broad Workato enterprise quote with a small AI-workspace subscription, or ignoring model, hosting, and labor costs, produces a misleading result. + +Use this process: + +1. Define three representative production workflows or agents. +2. Estimate monthly runs, SaaS actions, model calls, and token use. +3. List required environments, approval controls, support, and security capabilities. +4. Obtain a written Workato quote for the same scenario. +5. Calculate Sim Cloud and self-hosted Sim costs separately where both are viable. +6. Include implementation and ongoing operating labor for every option. +7. Recalculate the totals at expected year-two volume. + +The lower-cost choice is the option that meets every required capability at the lowest risk-adjusted annual total, not automatically the product with the lowest advertised entry price. + +## Sources + +Use current primary sources when updating a budget or preparing a vendor comparison: + +- [Workato enterprise pricing and editions](https://www.workato.com/pricing) +- [Workato billing and usage documentation](https://docs.workato.com/pricing) +- [Workato self-service billing documentation](https://docs.workato.com/en/pricing/self-service/self-service) +- [Workato Tasks documentation](https://docs.workato.com/recipes/tasks) +- [Sim costs and BYOK documentation](https://docs.sim.ai/platform/costs#bring-your-own-key-byok) +- [Sim self-hosting documentation](https://docs.sim.ai/platform/self-hosting) +- [Sim Enterprise License](https://github.com/simstudioai/sim/blob/main/apps/sim/ee/LICENSE) +- [n8n pricing](https://n8n.io/pricing/) +- [n8n Sustainable Use License](https://github.com/n8n-io/n8n/blob/master/LICENSE.md) diff --git a/apps/sim/ee/access-control/utils/permission-check.test.ts b/apps/sim/ee/access-control/utils/permission-check.test.ts index 3b7c907a599..fccff74d9bb 100644 --- a/apps/sim/ee/access-control/utils/permission-check.test.ts +++ b/apps/sim/ee/access-control/utils/permission-check.test.ts @@ -349,6 +349,26 @@ describe('validateModelProvider', () => { ).rejects.toBeInstanceOf(ModelNotAllowedError) }) + it('lets sim-auto through a provider allowlist, since the router gates each pool candidate', async () => { + queueGroupResolution([{ config: { allowedModelProviders: ['anthropic'] } }]) + mockGetProviderFromModel.mockReturnValue('ollama') + + await expect( + validateModelProvider('user-123', 'workspace-1', 'sim-auto') + ).resolves.toBeUndefined() + expect(mockGetProviderFromModel).not.toHaveBeenCalledWith('sim-auto') + }) + + it('refuses sim-auto when the denylist names it, even under a provider allowlist', async () => { + queueGroupResolution([ + { config: { allowedModelProviders: ['anthropic'], deniedModels: ['sim-auto'] } }, + ]) + + await expect( + validateModelProvider('user-123', 'workspace-1', 'sim-auto') + ).rejects.toBeInstanceOf(ModelNotAllowedError) + }) + it('enforces the denylist even when no provider allowlist is set', async () => { queueGroupResolution([{ config: { allowedModelProviders: null, deniedModels: ['gpt-4'] } }]) mockGetProviderFromModel.mockReturnValue('openai') diff --git a/apps/sim/ee/access-control/utils/permission-check.ts b/apps/sim/ee/access-control/utils/permission-check.ts index 03c35cd1e31..7cda2581a5f 100644 --- a/apps/sim/ee/access-control/utils/permission-check.ts +++ b/apps/sim/ee/access-control/utils/permission-check.ts @@ -30,6 +30,7 @@ import { mergeEnvAllowlist, } from '@/lib/permission-groups/resolve.server' import type { ExecutionContext } from '@/executor/types' +import { isAutoModel } from '@/providers/models' import { getProviderFromModel } from '@/providers/utils' /** @@ -309,7 +310,11 @@ function assertModelAllowed( model: string, subject: PermissionSubject ): void { - if (config.allowedModelProviders !== null) { + /** + * sim-auto has no provider to allowlist: the model router gates every pool candidate + * through this check before it resolves to one. Naming it outright still refuses it. + */ + if (config.allowedModelProviders !== null && !isAutoModel(model)) { const providerId = getProviderFromModel(model) if (!config.allowedModelProviders.includes(providerId)) { diff --git a/apps/sim/ee/access-requests/lib/application/flow.integration.ts b/apps/sim/ee/access-requests/lib/application/flow.integration.ts index a6929e6da06..73df87e5953 100644 --- a/apps/sim/ee/access-requests/lib/application/flow.integration.ts +++ b/apps/sim/ee/access-requests/lib/application/flow.integration.ts @@ -87,7 +87,7 @@ beforeAll(async () => { period_start timestamp, period_end timestamp, cancel_at_period_end boolean, cancel_at timestamp, canceled_at timestamp, ended_at timestamp, seats integer, trial_start timestamp, trial_end timestamp, billing_interval text, - stripe_schedule_id text, metadata json, last_closed_period_start timestamp + stripe_schedule_id text, metadata json, last_closed_period_start timestamp, allowance_period_start timestamp, allowance_seats integer, allowance_seat_months numeric ); CREATE TABLE workspace ( id text PRIMARY KEY, name text NOT NULL, owner_id text REFERENCES "user"(id), diff --git a/apps/sim/ee/access-requests/lib/catalog-registry.ts b/apps/sim/ee/access-requests/lib/catalog-registry.ts index bb45379fac7..cdb35a5b375 100644 --- a/apps/sim/ee/access-requests/lib/catalog-registry.ts +++ b/apps/sim/ee/access-requests/lib/catalog-registry.ts @@ -3,9 +3,8 @@ import { env } from '@/lib/core/config/env' import { getAllowedIntegrationsFromEnv, getBlacklistedProvidersFromEnv, - isHosted, } from '@/lib/core/config/env-flags' -import { isOllamaUrlConfigured } from '@/lib/core/utils/urls' +import { isOllamaReachable } from '@/lib/core/utils/urls' import { isScopedCredentialGroupsAvailable } from '@/lib/credential-groups/scoped-availability' import { isIntegrationDeploymentAvailableForVisibility, @@ -37,7 +36,7 @@ export interface AccessRequestCatalogContext { } function isProviderDeploymentAvailable(providerId: string): boolean { - if (providerId === 'ollama') return !isHosted || isOllamaUrlConfigured() + if (providerId === 'ollama') return isOllamaReachable() if (providerId === 'vllm') return Boolean(env.VLLM_BASE_URL?.trim()) if (providerId === 'litellm') return Boolean(env.LITELLM_BASE_URL?.trim()) return true diff --git a/apps/sim/ee/access-requests/lib/catalog.test.ts b/apps/sim/ee/access-requests/lib/catalog.test.ts index d73504d5745..271c027a7bb 100644 --- a/apps/sim/ee/access-requests/lib/catalog.test.ts +++ b/apps/sim/ee/access-requests/lib/catalog.test.ts @@ -17,7 +17,7 @@ import { providersModelsMockFns, } from '@sim/testing/mocks/providers-models.mock' import { providersUtilsMock, providersUtilsMockFns } from '@sim/testing/mocks/providers-utils.mock' -import { resetUrlsMock, urlsMockFns } from '@sim/testing/mocks/urls.mock' +import { resetUrlsMock } from '@sim/testing/mocks/urls.mock' import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest' vi.mock('@/lib/core/config/block-visibility', () => blockVisibilityMock) @@ -111,7 +111,7 @@ setEnvFlags({ isSandboxesEnabled: false, isSsoEnabled: false, }) -urlsMockFns.mockIsOllamaUrlConfigured.mockReturnValue(false) +setEnv({ OLLAMA_URL: undefined }) afterAll(() => { resetEnvMock() diff --git a/apps/sim/ee/organization-usage/components/usage-consumers.tsx b/apps/sim/ee/organization-usage/components/usage-consumers.tsx index 347bef20b2b..129ce5aa90f 100644 --- a/apps/sim/ee/organization-usage/components/usage-consumers.tsx +++ b/apps/sim/ee/organization-usage/components/usage-consumers.tsx @@ -35,6 +35,7 @@ import { OpenAIIcon, OpenRouterIcon, SakanaIcon, + SimAutoIcon, TogetherIcon, TypeSafeIcon, VertexIcon, @@ -101,6 +102,8 @@ const PROVIDER_ICONS: Readonly> 'lockManualMembership')::boolean, false) = true + and ${lockedSetting()} )` } +function lockedSetting(): SQL { + return sql`coalesce((${qualifiedColumn(scimConnection.settings)} ->> 'lockManualMembership')::boolean, false) = true` +} + /** * Drizzle removes Column qualifiers from single-table SELECT expressions, * including nested SQL. Explicit identifiers preserve this subquery's joins @@ -104,7 +116,7 @@ async function refuseIfDirectoryManaged( throw new ForbiddenOperationError('SCIM_MANAGED_MEMBERSHIP', message) } -/** Refuses an invitation to someone the directory already provisions, while the directory can still sync. */ +/** Refuses an invitation that would add someone the directory provisions to the organization. */ export async function assertInviteeNotScimManaged(params: { organizationId: string managed: boolean | null | undefined @@ -113,6 +125,58 @@ export async function assertInviteeNotScimManaged(params: { if (!(await isScimEntitledForOrganization(params.organizationId))) return throw new ForbiddenOperationError( 'SCIM_MANAGED_MEMBERSHIP', - 'This person is provisioned by the organization’s identity provider, so Sim will not grant them access separately. They already have access, or will once the next directory sync runs.' + 'This person is provisioned by the organization’s identity provider, which manages their organization membership. Add them to the organization there.' + ) +} + +/** + * Refuses a manual change to workspace access the directory owns: access that + * reconciliation sets because one of the user's groups in this organization's + * locked connection is mapped to the workspace, or that it applied and has not + * yet withdrawn. Derived from the same rows reconciliation reads, so the two + * cannot disagree. + */ +export async function assertWorkspaceAccessNotScimManaged(params: { + organizationId: string + userId: string + workspaceIds: readonly string[] + executor: DbOrTx +}): Promise { + if (!isScimDeploymentEnabled() || params.workspaceIds.length === 0) return + const [provisioned] = await params.executor + .select({ scimUserId: scimUser.id }) + .from(scimUser) + .innerJoin(scimConnection, eq(scimConnection.id, scimUser.connectionId)) + .where( + and( + eq(scimUser.userId, params.userId), + eq(scimConnection.organizationId, params.organizationId), + eq(scimConnection.status, 'active'), + lockedSetting() + ) + ) + .limit(1) + if (!provisioned) return + /** + * Owned while a mapping calls for the grant, and until reconciliation has + * withdrawn one it still tracks: a mapping removal commits before its members + * are reconciled, and a manual change in that gap would be undone by the + * pending withdrawal. + */ + const mapped = resolveDesiredGrants( + await loadMappingRows(params.executor, provisioned.scimUserId) + ) + const tracked = await currentGrants(params.executor, provisioned.scimUserId) + const requested = new Set(params.workspaceIds) + const owned = [...mapped, ...tracked].some( + (grant) => grant.targetKind === 'workspace' && requested.has(grant.targetId) + ) + if (!owned) return + /** Read only once an owned workspace is found, so the common case costs nothing. */ + if (!(await isScimEntitledForOrganization(params.organizationId, params.executor))) return + const target = params.workspaceIds.length === 1 ? 'this workspace' : 'a selected workspace' + throw new ForbiddenOperationError( + 'SCIM_MANAGED_MEMBERSHIP', + `This person’s access to ${target} is managed by the organization’s identity provider through a directory group mapping. Change their group membership there, or remove the mapping and let the next directory sync finish.` ) } diff --git a/apps/sim/ee/scim/lib/projection/directory-grants.ts b/apps/sim/ee/scim/lib/projection/directory-grants.ts new file mode 100644 index 00000000000..8d947af9385 --- /dev/null +++ b/apps/sim/ee/scim/lib/projection/directory-grants.ts @@ -0,0 +1,59 @@ +import { scimGroupMapping, scimGroupMember, scimProjectionGrant } from '@sim/db/schema' +import { eq } from 'drizzle-orm' +import type { DbOrTx } from '@/lib/db/types' +import type { + MappingRow, + ProjectionGrant, + ProjectionGrantOrigin, + ProjectionTargetKind, +} from '@/ee/scim/lib/projection/grants' + +/** + * What reconciliation reads for one directory user: the grants their groups' + * mappings call for, and the grants it has already applied and still tracks. + * Shared with the managed-membership guard so both agree on what the directory owns. + */ + +/** + * The mapping rows this user reaches through their groups. + * + * Deliberately independent of whether the user is active. A deactivation blocks + * sign-in and API keys through suspension; it does not withdraw grants, because + * withdrawing a workspace grant reassigns the workflows the person owns there, + * and that cannot be undone by reactivating them. Grants change only when group + * membership or mappings change, or when the user is deprovisioned outright. + */ +export async function loadMappingRows(tx: DbOrTx, scimUserId: string): Promise { + return tx + .select({ + targetKind: scimGroupMapping.targetKind, + permissionGroupId: scimGroupMapping.permissionGroupId, + workspaceId: scimGroupMapping.workspaceId, + permissionType: scimGroupMapping.permissionType, + role: scimGroupMapping.role, + }) + .from(scimGroupMember) + .innerJoin(scimGroupMapping, eq(scimGroupMapping.groupId, scimGroupMember.groupId)) + .where(eq(scimGroupMember.scimUserId, scimUserId)) +} + +/** The grants reconciliation applied for this user and has not yet withdrawn. */ +export async function currentGrants(tx: DbOrTx, scimUserId: string): Promise { + const rows = await tx + .select({ + targetKind: scimProjectionGrant.targetKind, + targetId: scimProjectionGrant.targetId, + permissionType: scimProjectionGrant.permissionType, + origin: scimProjectionGrant.origin, + baselinePermission: scimProjectionGrant.baselinePermission, + }) + .from(scimProjectionGrant) + .where(eq(scimProjectionGrant.scimUserId, scimUserId)) + return rows.map((row) => ({ + targetKind: row.targetKind as ProjectionTargetKind, + targetId: row.targetId, + origin: row.origin as ProjectionGrantOrigin, + baselinePermission: row.baselinePermission ?? null, + ...(row.permissionType ? { permissionType: row.permissionType } : {}), + })) +} diff --git a/apps/sim/ee/scim/lib/projection/reconcile-user.ts b/apps/sim/ee/scim/lib/projection/reconcile-user.ts index cfbc77b3549..21e28b6ecd9 100644 --- a/apps/sim/ee/scim/lib/projection/reconcile-user.ts +++ b/apps/sim/ee/scim/lib/projection/reconcile-user.ts @@ -4,8 +4,6 @@ import { permissionGroupMember, permissions, scimConnection, - scimGroupMapping, - scimGroupMember, scimProjectionGrant, scimUser, workspace, @@ -38,11 +36,9 @@ import { revokeWorkspaceAccessTx, stopRunsWithoutWorkspaceAccessTx, } from '@/lib/workspaces/access/workspace-access' +import { currentGrants, loadMappingRows } from '@/ee/scim/lib/projection/directory-grants' import { - type MappingRow, type ProjectionGrant, - type ProjectionGrantOrigin, - type ProjectionTargetKind, planGrantChanges, resolveDesiredGrants, } from '@/ee/scim/lib/projection/grants' @@ -86,49 +82,6 @@ function addChanges(total: ProjectionChanges, changes: ProjectionChanges): void /** Users per transaction when projecting outside a request's own transaction; the organization lock is held for the batch. */ export const PROJECTION_BATCH_SIZE = 25 -/** - * The mapping rows this user reaches through their groups. - * - * Deliberately independent of whether the user is active. A deactivation blocks - * sign-in and API keys through suspension; it does not withdraw grants, because - * withdrawing a workspace grant reassigns the workflows the person owns there, - * and that cannot be undone by reactivating them. Grants change only when group - * membership or mappings change, or when the user is deprovisioned outright. - */ -async function loadMappingRows(tx: DbOrTx, scimUserId: string): Promise { - return tx - .select({ - targetKind: scimGroupMapping.targetKind, - permissionGroupId: scimGroupMapping.permissionGroupId, - workspaceId: scimGroupMapping.workspaceId, - permissionType: scimGroupMapping.permissionType, - role: scimGroupMapping.role, - }) - .from(scimGroupMember) - .innerJoin(scimGroupMapping, eq(scimGroupMapping.groupId, scimGroupMember.groupId)) - .where(eq(scimGroupMember.scimUserId, scimUserId)) -} - -async function currentGrants(tx: DbOrTx, scimUserId: string): Promise { - const rows = await tx - .select({ - targetKind: scimProjectionGrant.targetKind, - targetId: scimProjectionGrant.targetId, - permissionType: scimProjectionGrant.permissionType, - origin: scimProjectionGrant.origin, - baselinePermission: scimProjectionGrant.baselinePermission, - }) - .from(scimProjectionGrant) - .where(eq(scimProjectionGrant.scimUserId, scimUserId)) - return rows.map((row) => ({ - targetKind: row.targetKind as ProjectionTargetKind, - targetId: row.targetId, - origin: row.origin as ProjectionGrantOrigin, - baselinePermission: row.baselinePermission ?? null, - ...(row.permissionType ? { permissionType: row.permissionType } : {}), - })) -} - /** Reads access independently of provenance so a reconcile can repair real drift. */ async function actualGrants( tx: DbOrTx, diff --git a/apps/sim/executor/constants.ts b/apps/sim/executor/constants.ts index 8d7ec391cf5..84f12e5e297 100644 --- a/apps/sim/executor/constants.ts +++ b/apps/sim/executor/constants.ts @@ -5,6 +5,7 @@ import { import { getMaxExecutionTimeout } from '@/lib/core/execution-limits' import type { LoopType, ParallelType } from '@/lib/workflows/types' import { isCustomBlockType } from '@/blocks/custom/build-config' +import { DEFAULT_BLOCK_MODEL } from '@/providers/default-model' /** * Runtime-injected keys for trigger blocks that should be hidden from logs/display. @@ -227,7 +228,7 @@ export const HTTP = { } as const export const AGENT = { - DEFAULT_MODEL: 'claude-sonnet-5-5', + DEFAULT_MODEL: DEFAULT_BLOCK_MODEL, get DEFAULT_FUNCTION_TIMEOUT() { return getMaxExecutionTimeout() }, @@ -242,13 +243,13 @@ export const MCP = { } as const export const ROUTER = { - DEFAULT_MODEL: 'claude-sonnet-5-5', + DEFAULT_MODEL: DEFAULT_BLOCK_MODEL, DEFAULT_TEMPERATURE: 0, INFERENCE_TEMPERATURE: 0.1, } as const export const EVALUATOR = { - DEFAULT_MODEL: 'claude-sonnet-5-5', + DEFAULT_MODEL: DEFAULT_BLOCK_MODEL, DEFAULT_TEMPERATURE: 0.1, RESPONSE_SCHEMA_NAME: 'evaluation_response', JSON_INDENT: 2, diff --git a/apps/sim/executor/errors/child-workflow-error.ts b/apps/sim/executor/errors/child-workflow-error.ts index a5505acfbd3..4fc22d1deb1 100644 --- a/apps/sim/executor/errors/child-workflow-error.ts +++ b/apps/sim/executor/errors/child-workflow-error.ts @@ -8,6 +8,8 @@ interface ChildWorkflowErrorOptions { childTraceSpans?: TraceSpan[] executionResult?: ExecutionResult childWorkflowSnapshotId?: string + /** The deployment version a deployed workflow-block child ran; unset for draft and custom-block children. */ + childDeploymentVersionId?: string childWorkflowInstanceId?: string /** Child workflow names from this invocation down to the failing run, outermost first. */ workflowChain?: string[] @@ -38,6 +40,7 @@ export class ChildWorkflowError extends Error { readonly childWorkflowName: string readonly executionResult?: ExecutionResult readonly childWorkflowSnapshotId?: string + readonly childDeploymentVersionId?: string /** Per-invocation unique ID used to correlate child block events with this workflow block. */ readonly childWorkflowInstanceId?: string /** @@ -59,6 +62,7 @@ export class ChildWorkflowError extends Error { this.childTraceSpans = options.childTraceSpans ?? [] this.executionResult = options.executionResult this.childWorkflowSnapshotId = options.childWorkflowSnapshotId + this.childDeploymentVersionId = options.childDeploymentVersionId this.childWorkflowInstanceId = options.childWorkflowInstanceId this.workflowChain = options.workflowChain ?? [options.childWorkflowName] this.rootErrorMessage = options.rootErrorMessage ?? options.message diff --git a/apps/sim/executor/execution/block-executor.test.ts b/apps/sim/executor/execution/block-executor.test.ts index aba897999ee..d6d86217225 100644 --- a/apps/sim/executor/execution/block-executor.test.ts +++ b/apps/sim/executor/execution/block-executor.test.ts @@ -14,6 +14,8 @@ import { clearLargeValueCacheForTests } from '@/lib/execution/payloads/cache' import { createLargeArrayManifest } from '@/lib/execution/payloads/large-array-manifest' import { isLargeValueRef } from '@/lib/execution/payloads/large-value-ref' import { buildTraceSpans } from '@/lib/logs/execution/trace-spans/trace-spans' +import { FunctionBlock } from '@/blocks/blocks/function' +import { getBlock } from '@/blocks/registry' import { validateBlockType } from '@/ee/access-control/utils/permission-check' import { BlockType, EDGE } from '@/executor/constants' import type { DAGNode } from '@/executor/dag/builder' @@ -21,7 +23,7 @@ import { ChildWorkflowError } from '@/executor/errors/child-workflow-error' import { BlockExecutor } from '@/executor/execution/block-executor' import { ExecutionState } from '@/executor/execution/state' import type { BlockHandler, ExecutionContext } from '@/executor/types' -import { attachTrustedExecutionCost } from '@/executor/utils/errors' +import { attachErrorOutputs, attachTrustedExecutionCost } from '@/executor/utils/errors' import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' import { VariableResolver } from '@/executor/variables/resolver' import type { SerializedBlock, SerializedWorkflow } from '@/serializer/types' @@ -39,6 +41,13 @@ if (!blockExecutorBaseLogger) throw new Error('BlockExecutor logger mock was not vi.mock('@/ee/access-control/utils/permission-check', () => permissionCheckMock) +/** The Function block's real config, whose declared error outputs every failure writes. */ +const registryGetBlock = vi.mocked(getBlock) +const stubGetBlock = registryGetBlock.getMockImplementation() +registryGetBlock.mockImplementation((type: string) => + type === 'function' ? FunctionBlock : stubGetBlock?.(type) +) + vi.mock('@/lib/uploads', () => uploadsMock) vi.mock('@/lib/guardrails/mask-client', () => maskClientMock) @@ -490,7 +499,7 @@ describe('BlockExecutor', () => { expect(thrown.message).toBe(`Function: ${message}`) expect(thrown.cause.cause).toBe(databaseError) expect(handler.execute).not.toHaveBeenCalled() - expect(state.getBlockOutput(block.id)).toEqual({ error: message }) + expect(state.getBlockOutput(block.id)).toEqual({ error: message, errorMessage: message }) expect(ctx.blockLogs[0]?.error).toBe(message) const surfaced = JSON.stringify([state.getBlockOutput(block.id), ctx.blockLogs]) expect(surfaced).not.toContain('Failed query') @@ -529,13 +538,14 @@ describe('BlockExecutor', () => { const wrapped = new Error(`Failed to upload file: ${databaseError.message}`, { cause: databaseError, }) + attachErrorOutputs(wrapped, { errorMessage: wrapped.message }) vi.mocked(validateBlockType).mockRejectedValueOnce(wrapped) const message = 'An internal error occurred while executing the block. Please try again.' const thrown = await executor.execute(ctx, createNode(block), block).catch((error) => error) expect(thrown.message).toBe(`Function: ${message}`) - expect(state.getBlockOutput(block.id)).toEqual({ error: message }) + expect(state.getBlockOutput(block.id)).toEqual({ error: message, errorMessage: message }) const surfaced = JSON.stringify([thrown.message, state.getBlockOutput(block.id), ctx.blockLogs]) expect(surfaced).not.toContain('Failed query') expect(surfaced).not.toContain('owner-secret-id') @@ -726,6 +736,44 @@ describe('BlockExecutor', () => { ) }) + it.each([ + [BlockType.WORKFLOW_INPUT, 'dv-7'], + ['custom_block_abc', undefined], + ])( + 'records the child deployment version on a failed %s block only when it is a workflow block', + async (blockType, expected) => { + const block = { ...createBlock(), metadata: { id: blockType, name: 'Child' } } + const state = new ExecutionState() + const workflow: SerializedWorkflow = { + version: '1', + blocks: [block], + connections: [], + loops: {}, + parallels: {}, + } + const handler: BlockHandler = { + canHandle: () => true, + execute: async () => { + throw new ChildWorkflowError({ + message: '"Child" failed: boom', + childWorkflowName: 'Child', + childDeploymentVersionId: 'dv-7', + }) + }, + } + const executor = new BlockExecutor( + [handler], + new VariableResolver(workflow, {}, state), + {}, + state + ) + + await executor.execute(createContext(state), createNode(block), block).catch(() => undefined) + + expect(state.getBlockOutput(block.id)?.childDeploymentVersionId).toBe(expected) + } + ) + it('does not soft-succeed non-agent blocks on user AbortError', async () => { const block = createBlock() const workflow: SerializedWorkflow = { @@ -1529,6 +1577,7 @@ describe('BlockExecutor retry', () => { expect(execute).toHaveBeenCalledTimes(3) expect(ctx.blockLogs[0]?.output).toEqual({ error: 'provider unavailable', + errorMessage: 'provider unavailable', cost: { input: 0, output: 0, total: 0.375 }, }) diff --git a/apps/sim/executor/execution/block-executor.ts b/apps/sim/executor/execution/block-executor.ts index 8bd78562d48..96dcc1f1061 100644 --- a/apps/sim/executor/execution/block-executor.ts +++ b/apps/sim/executor/execution/block-executor.ts @@ -23,6 +23,7 @@ import { } from '@/lib/uploads/utils/user-file-base64.server' import { sanitizeInputFormat, sanitizeTools } from '@/lib/workflows/comparison/normalize' import { isCustomBlockType } from '@/blocks/custom/build-config' +import { getBlock } from '@/blocks/registry' import { validateBlockType } from '@/ee/access-control/utils/permission-check' import { BlockType, @@ -64,6 +65,7 @@ import { attachTrustedExecutionCost, buildBlockExecutionError, normalizeError, + readErrorOutputs, readTrustedExecutionCost, type TrustedExecutionCost, } from '@/executor/utils/errors' @@ -737,6 +739,7 @@ export class BlockExecutor { const trustedExecutionCost = readTrustedExecutionCost(error) ?? completedHandlerCost const errorOutput: NormalizedBlockOutput = { error: errorMessage, + ...declaredErrorOutputs(block, isDatabaseError ? undefined : error, errorMessage), ...(trustedExecutionCost ? { cost: trustedExecutionCost } : {}), } @@ -757,6 +760,9 @@ export class BlockExecutor { if (error.childWorkflowSnapshotId) { errorOutput.childWorkflowSnapshotId = error.childWorkflowSnapshotId } + if (error.childDeploymentVersionId) { + errorOutput.childDeploymentVersionId = error.childDeploymentVersionId + } } // A custom block's consumer gets a machine-readable failure class and an // opaque handle to the failed run — enough to branch on and to quote in a @@ -1462,3 +1468,20 @@ function stripThinkingContentFromOutput(output: unknown): void { } } } + +/** + * The block's declared error outputs (`BlockConfig.errorOutputs`), each the value its handler + * attached to `error` (a Function's thrown message without its line and code), or `message` when + * none was attached: a failure the handler never reported has nothing narrower to say. A database + * failure passes no `error`, so its masked message is all any output carries. + */ +function declaredErrorOutputs( + block: SerializedBlock, + error: unknown, + message: string +): Record { + const declared = block.metadata?.id ? getBlock(block.metadata.id)?.errorOutputs : undefined + if (!declared) return {} + const attached = readErrorOutputs(error) + return Object.fromEntries(Object.keys(declared).map((key) => [key, attached?.[key] || message])) +} diff --git a/apps/sim/executor/execution/function-error-message.test.ts b/apps/sim/executor/execution/function-error-message.test.ts new file mode 100644 index 00000000000..d81ca5d82d1 --- /dev/null +++ b/apps/sim/executor/execution/function-error-message.test.ts @@ -0,0 +1,143 @@ +import { permissionCheckMock } from '@sim/testing/mocks/permission-check.mock' +import { toolsMock, toolsMockFns } from '@sim/testing/mocks/tools.mock' +import type { Mock } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { FunctionBlock } from '@/blocks/blocks/function' +import { ResponseBlock } from '@/blocks/blocks/response' +import { getBlock } from '@/blocks/registry' +import { DAGExecutor } from '@/executor/execution/executor' +import { hasExecutionResult } from '@/executor/utils/errors' +import type { SerializedConnection, SerializedWorkflow } from '@/serializer/types' + +vi.mock('@/lib/execution/cancellation', () => ({ + subscribeToExecutionCancellation: vi.fn(async () => () => {}), + isExecutionCancelled: vi.fn(async () => false), +})) +vi.mock('@/ee/access-control/utils/permission-check', () => permissionCheckMock) +vi.mock('@/tools', () => toolsMock) + +const REAL_BLOCKS: Record = { function: FunctionBlock, response: ResponseBlock } +const registryGetBlock = getBlock as Mock +const stubGetBlock = registryGetBlock.getMockImplementation() +registryGetBlock.mockImplementation((type: string) => REAL_BLOCKS[type] ?? stubGetBlock?.(type)) + +const LINE_ERROR = "Line 4: `throw new Error('invalid phone: 555')` - invalid phone: 555" + +/** What `executeTool` returns when the Function route reports a thrown error. */ +function failedFunction(output: Record = { errorMessage: 'invalid phone: 555' }) { + return { success: false, error: LINE_ERROR, output } +} + +/** Start → Parse (a Function), and Parse → Reply, a Response echoing Parse's error outputs. */ +function workflow(parseToReply: SerializedConnection['sourceHandle']): SerializedWorkflow { + return { + version: '1', + blocks: [ + { + id: 'start', + position: { x: 0, y: 0 }, + config: { tool: 'start_trigger', params: {} }, + inputs: {}, + outputs: {}, + metadata: { id: 'start_trigger', name: 'Start', category: 'triggers' }, + enabled: true, + }, + { + id: 'parse', + position: { x: 0, y: 0 }, + config: { tool: 'function_execute', params: { code: 'return 1' } }, + inputs: {}, + outputs: {}, + metadata: { id: 'function', name: 'Parse' }, + enabled: true, + }, + { + id: 'reply', + position: { x: 0, y: 0 }, + config: { + tool: 'response', + params: { + dataMode: 'json', + data: '{"message": "", "error": ""}', + }, + }, + inputs: {}, + outputs: {}, + metadata: { id: 'response', name: 'Reply' }, + enabled: true, + }, + ], + connections: [ + { source: 'start', target: 'parse' }, + { source: 'parse', target: 'reply', sourceHandle: parseToReply }, + ], + loops: {}, + parallels: {}, + } +} + +async function run(parseToReply: SerializedConnection['sourceHandle']) { + const executor = new DAGExecutor({ + workflow: workflow(parseToReply), + contextExtensions: { workspaceId: 'ws', executionId: 'exec', userId: 'u' }, + }) + return executor.execute('wf').then( + (result) => ({ result, thrown: undefined }), + (thrown: unknown) => ({ result: undefined, thrown }) + ) +} + +function blockLog(logs: Array<{ blockId: string; output?: unknown }> | undefined, id: string) { + return logs?.find((log) => log.blockId === id) +} + +describe('a failed Function block', () => { + beforeEach(() => { + toolsMockFns.mockExecuteTool.mockReset() + }) + + it("hands an error edge's target the thrown message alone, and error unchanged", async () => { + toolsMockFns.mockExecuteTool.mockResolvedValueOnce(failedFunction()) + + const { result } = await run('error') + + expect(result?.output.data).toEqual({ message: 'invalid phone: 555', error: LINE_ERROR }) + expect(blockLog(result?.logs, 'parse')?.output).toEqual({ + error: LINE_ERROR, + errorMessage: 'invalid phone: 555', + }) + }) + + it('repeats error when the route reported no thrown message of its own', async () => { + toolsMockFns.mockExecuteTool.mockResolvedValueOnce(failedFunction({})) + + const { result } = await run('error') + + expect(result?.output.data).toEqual({ message: LINE_ERROR, error: LINE_ERROR }) + }) + + it('records errorMessage on the failed block when no error edge catches it', async () => { + toolsMockFns.mockExecuteTool.mockResolvedValueOnce(failedFunction()) + + const { thrown } = await run('source') + + expect(hasExecutionResult(thrown)).toBe(true) + if (!hasExecutionResult(thrown)) return + expect(blockLog(thrown.executionResult.logs, 'parse')?.output).toEqual({ + error: LINE_ERROR, + errorMessage: 'invalid phone: 555', + }) + }) + + it('resolves its error outputs empty after a successful run, as error does', async () => { + toolsMockFns.mockExecuteTool.mockResolvedValueOnce({ + success: true, + output: { result: 1, stdout: '', files: [] }, + }) + + const { result, thrown } = await run('source') + + expect(thrown).toBeUndefined() + expect(result?.output.data).toEqual({ message: '', error: '' }) + }) +}) diff --git a/apps/sim/executor/handlers/agent/handler.test.ts b/apps/sim/executor/handlers/agent/handler.test.ts index 198a68d5b9f..7216c58c843 100644 --- a/apps/sim/executor/handlers/agent/handler.test.ts +++ b/apps/sim/executor/handlers/agent/handler.test.ts @@ -3540,6 +3540,34 @@ describe('AgentBlockHandler', () => { }) }) + it('keeps a custom tool titled like the workflow tool from claiming a child version', async () => { + mockExecuteProviderRequest.mockResolvedValueOnce({ + content: 'done', + model: 'mock-model', + tokens: { input: 10, output: 20, total: 30 }, + toolCalls: [ + { name: 'custom_workflow_executor', result: { childDeploymentVersionId: 'forged' } }, + { name: 'workflow_executor', result: { childDeploymentVersionId: 'dv-7' } }, + { name: 'custom_lookup', result: { childDeploymentVersionId: 'user-data' } }, + ], + cost: 0.001, + timing: { total: 100 }, + }) + + const result = await handler.execute(mockContext, mockBlock, { + model: 'gpt-4o', + userPrompt: 'Score it', + apiKey: 'test-api-key', + }) + + const [custom, workflow, otherCustom] = ( + result as { toolCalls: { list: Array<{ result: Record }> } } + ).toolCalls.list + expect(custom.result).not.toHaveProperty('childDeploymentVersionId') + expect(workflow.result.childDeploymentVersionId).toBe('dv-7') + expect(otherCustom.result.childDeploymentVersionId).toBe('user-data') + }) + it('uses a secret-backed skillId for lookup without carrying it into output provenance', async () => { const skillId = 'x' mockContext.workspaceId = 'workspace-1' diff --git a/apps/sim/executor/handlers/agent/handler.ts b/apps/sim/executor/handlers/agent/handler.ts index 183ae88d95f..90c44d3e588 100644 --- a/apps/sim/executor/handlers/agent/handler.ts +++ b/apps/sim/executor/handlers/agent/handler.ts @@ -63,7 +63,13 @@ import { validateBlockType, validateModelProvider, } from '@/ee/access-control/utils/permission-check' -import { AGENT, BlockType, DEFAULTS, stripCustomToolPrefix } from '@/executor/constants' +import { + AGENT, + BlockType, + DEFAULTS, + isCustomTool, + stripCustomToolPrefix, +} from '@/executor/constants' import { getMemoryMessageAppendKey, getMemoryMessageTurnId, @@ -3227,6 +3233,7 @@ export class AgentBlockHandler implements BlockHandler { private formatToolCall(tc: any) { const toolName = stripCustomToolPrefix(tc.name) + const result = tc.result || tc.output return { ...tc, @@ -3235,7 +3242,12 @@ export class AgentBlockHandler implements BlockHandler { endTime: tc.endTime, duration: tc.duration, arguments: tc.arguments || tc.input || {}, - result: tc.result || tc.output, + // The span factory trusts this key only on a `workflow_executor` call. Stripping the prefix + // would let a custom tool titled `workflow_executor` claim a child version it never ran. + result: + isCustomTool(tc.name) && toolName === 'workflow_executor' && isRecordLike(result) + ? omit(result, ['childDeploymentVersionId']) + : result, } } } diff --git a/apps/sim/executor/handlers/api/handler.test.ts b/apps/sim/executor/handlers/api/handler.test.ts index a53ad1fb459..da0fe944624 100644 --- a/apps/sim/executor/handlers/api/handler.test.ts +++ b/apps/sim/executor/handlers/api/handler.test.ts @@ -50,6 +50,7 @@ describe('ApiBlockHandler', () => { name: 'HTTP Request Tool', description: 'Makes an HTTP request', version: '1.0', + effect: 'write', params: { url: { type: 'string', required: true }, method: { type: 'string', default: 'GET' }, diff --git a/apps/sim/executor/handlers/function/handler.ts b/apps/sim/executor/handlers/function/handler.ts index 0244263f51d..c142e49fd47 100644 --- a/apps/sim/executor/handlers/function/handler.ts +++ b/apps/sim/executor/handlers/function/handler.ts @@ -13,7 +13,7 @@ import { normalizeSecretMountPolicy } from '@/lib/mothership/secret-mount-policy import { BlockType } from '@/executor/constants' import type { BlockHandler, ExecutionContext } from '@/executor/types' import { collectBlockData } from '@/executor/utils/block-data' -import { attachTrustedExecutionCost } from '@/executor/utils/errors' +import { attachErrorOutputs, attachTrustedExecutionCost } from '@/executor/utils/errors' import { FUNCTION_BLOCK_CONTEXT_VARS_KEY, FUNCTION_BLOCK_DISPLAY_CODE_KEY, @@ -119,6 +119,7 @@ export class FunctionBlockHandler implements BlockHandler { ? new NonRetryableExecutionError(result.error || 'Function execution is indeterminate') : new Error(result.error || 'Function execution failed') attachTrustedExecutionCost(error, result.output?.cost) + attachErrorOutputs(error, { errorMessage: result.output?.errorMessage }) throw adoptToolFailure(error, result) } diff --git a/apps/sim/executor/handlers/generic/handler.test.ts b/apps/sim/executor/handlers/generic/handler.test.ts index 2a88fe9339e..bf832d82722 100644 --- a/apps/sim/executor/handlers/generic/handler.test.ts +++ b/apps/sim/executor/handlers/generic/handler.test.ts @@ -73,6 +73,7 @@ describe('GenericBlockHandler', () => { name: 'Some Custom Tool', description: 'Does something custom', version: '1.0', + effect: 'write', params: { param1: { type: 'string' } }, request: { url: 'https://example.com/api', diff --git a/apps/sim/executor/handlers/workflow/handler.test.ts b/apps/sim/executor/handlers/workflow/handler.test.ts index 2f0cbad2274..095e8c499c4 100644 --- a/apps/sim/executor/handlers/workflow/handler.test.ts +++ b/apps/sim/executor/handlers/workflow/handler.test.ts @@ -358,6 +358,86 @@ describe('WorkflowBlockHandler', () => { }) }) + describe('child deployment version', () => { + const inputs = { workflowId: 'child-workflow-id' } + const deployedCtx = () => + ({ + ...mockContext, + workspaceId: 'workspace-parent', + isDeployedContext: true, + }) as unknown as ExecutionContext + + beforeEach(() => { + mockReadWorkflowDefinitionAsExecutor.mockResolvedValue({ + workflow: { id: 'child-workflow-id', name: 'Score', variables: {} }, + workspaceId: 'workspace-parent', + state: { + blocks: {}, + edges: [], + loops: {}, + parallels: {}, + deploymentVersionId: 'dv-7', + }, + }) + mockResolveSnapshot.mockResolvedValue({ id: 'snapshot-1', workflowId: 'w', stateHash: 'h' }) + }) + + it('records the version a deployed child ran', async () => { + mockExecutorExecute.mockResolvedValue({ success: true, output: { data: 'ok' } }) + + const output = await handler.execute(deployedCtx(), mockBlock, inputs) + + expect(output).toMatchObject({ childDeploymentVersionId: 'dv-7' }) + }) + + it('records the version on a deployed child that reports a failure', async () => { + mockExecutorExecute.mockResolvedValue({ success: false, error: 'boom', output: {} }) + + const failure = await handler.execute(deployedCtx(), mockBlock, inputs).catch((e) => e) + + expect(failure).toMatchObject({ childDeploymentVersionId: 'dv-7' }) + }) + + it('records the version on a deployed child that throws', async () => { + mockExecutorExecute.mockRejectedValue(new Error('engine blew up')) + + const failure = await handler.execute(deployedCtx(), mockBlock, inputs).catch((e) => e) + + expect(failure).toMatchObject({ childDeploymentVersionId: 'dv-7' }) + }) + + it('records no version for a deployed child refused by the workspace check', async () => { + mockReadWorkflowDefinitionAsExecutor.mockResolvedValue({ + workflow: { id: 'child-workflow-id', name: 'Score', variables: {} }, + workspaceId: 'workspace-other', + state: { blocks: {}, edges: [], loops: {}, parallels: {}, deploymentVersionId: 'dv-7' }, + }) + + const failure = await handler.execute(deployedCtx(), mockBlock, inputs).catch((e) => e) + + expect(failure.message).toContain('belongs to a different workspace') + expect(failure).not.toHaveProperty('childDeploymentVersionId', 'dv-7') + }) + + it('records no version for a draft child', async () => { + mockReadWorkflowDefinitionAsExecutor.mockResolvedValue({ + workflow: { id: 'child-workflow-id', name: 'Score', variables: {} }, + workspaceId: 'workspace-parent', + state: { blocks: {}, edges: [], loops: {}, parallels: {} }, + }) + mockExecutorExecute.mockResolvedValue({ success: true, output: { data: 'ok' } }) + + const output = await handler.execute( + { ...mockContext, workspaceId: 'workspace-parent' } as unknown as ExecutionContext, + mockBlock, + inputs + ) + + expect(output).toMatchObject({ childWorkflowId: 'child-workflow-id' }) + expect(output).not.toHaveProperty('childDeploymentVersionId') + }) + }) + describe('workspace containment', () => { const inputs = { workflowId: 'child-workflow-id' } diff --git a/apps/sim/executor/handlers/workflow/handler.ts b/apps/sim/executor/handlers/workflow/handler.ts index 62b37772388..a2d8bc4cf4c 100644 --- a/apps/sim/executor/handlers/workflow/handler.ts +++ b/apps/sim/executor/handlers/workflow/handler.ts @@ -1,7 +1,7 @@ import { createLogger } from '@sim/logger' import { findCause, getErrorMessage, toError } from '@sim/utils/errors' import { generateId } from '@sim/utils/id' -import { isRecordLike } from '@sim/utils/object' +import { filterUndefined, isRecordLike } from '@sim/utils/object' import type { Variable, WorkflowState } from '@sim/workflow-types/workflow' import { resolveBillingAttribution } from '@/lib/billing/core/attribution' import { DelegatedWorkspaceAuthorizationError } from '@/lib/core/application' @@ -350,6 +350,8 @@ export class WorkflowBlockHandler implements BlockHandler { } let childWorkflowSnapshotId: string | undefined + /** Unset for draft children, and for custom blocks so the consumer learns nothing of the source. */ + let childDeploymentVersionId: string | undefined /** Set for custom blocks only: the child's own execution id / log row. */ let childExecutionId: string | undefined let childSession: LoggingSession | undefined @@ -444,6 +446,9 @@ export class WorkflowBlockHandler implements BlockHandler { // skipped or every custom-block invocation from another workspace throws. if (!isCustomBlock) { this.assertChildWorkflowInWorkspace(workflowId, childWorkflow.workspaceId, ctx.workspaceId) + // Recorded only once the child is known to be this workspace's, so a refusal never names + // another workspace's version. + childDeploymentVersionId = childWorkflow.deploymentVersionId } childWorkflowName = childWorkflow.name || 'Unknown Workflow' @@ -999,7 +1004,7 @@ export class WorkflowBlockHandler implements BlockHandler { childWorkflowName, instanceId, childTraceSpans, - childWorkflowSnapshotId, + { childWorkflowSnapshotId, childDeploymentVersionId }, { executionId: ctx.executionId, blockId: block.id } ) @@ -1097,6 +1102,7 @@ export class WorkflowBlockHandler implements BlockHandler { childTraceSpans, executionResult, childWorkflowSnapshotId, + childDeploymentVersionId, childWorkflowInstanceId: instanceId, cause: error instanceof Error ? error : undefined, }) @@ -1587,7 +1593,7 @@ export class WorkflowBlockHandler implements BlockHandler { childWorkflowName: string, instanceId: string, childTraceSpans?: WorkflowTraceSpan[], - childWorkflowSnapshotId?: string, + childRun: { childWorkflowSnapshotId?: string; childDeploymentVersionId?: string } = {}, parent?: { executionId?: string; blockId: string } ): BlockOutput { const success = childResult.success !== false @@ -1606,7 +1612,7 @@ export class WorkflowBlockHandler implements BlockHandler { workflowChain: chain, rootErrorMessage, childTraceSpans: childTraceSpans || [], - childWorkflowSnapshotId, + ...childRun, childWorkflowInstanceId: instanceId, }) /** The warning above is this failure's log line. */ @@ -1618,7 +1624,7 @@ export class WorkflowBlockHandler implements BlockHandler { success: true, childWorkflowName, childWorkflowId, - ...(childWorkflowSnapshotId ? { childWorkflowSnapshotId } : {}), + ...filterUndefined(childRun), result, childTraceSpans: childTraceSpans || [], _childWorkflowInstanceId: instanceId, diff --git a/apps/sim/executor/types.ts b/apps/sim/executor/types.ts index f54c45e6528..75cc34c5811 100644 --- a/apps/sim/executor/types.ts +++ b/apps/sim/executor/types.ts @@ -258,6 +258,8 @@ export interface NormalizedBlockOutput { status?: number headers?: Record error?: string + /** A failed Function's thrown message alone, without the line and code `error` leads with. */ + errorMessage?: string childTraceSpans?: TraceSpan[] childWorkflowName?: string _pauseMetadata?: PauseMetadata diff --git a/apps/sim/executor/utils/block-data.ts b/apps/sim/executor/utils/block-data.ts index e3fb8a03130..6459c71d100 100644 --- a/apps/sim/executor/utils/block-data.ts +++ b/apps/sim/executor/utils/block-data.ts @@ -41,11 +41,16 @@ function getRegistrySchema(block: SerializedBlock): OutputSchema | undefined { const blockConfig = getBlock(blockType) const isTriggerCapable = blockConfig ? hasTriggerCapability(blockConfig) : false const triggerMode = Boolean(isTriggerBehavior(block) && isTriggerCapable) - const outputs = getEffectiveBlockOutputs(blockType, subBlocks, { - triggerMode, - preferToolOutputs: !triggerMode, - includeHidden: true, - }) as OutputSchema + // A block's error outputs resolve empty after a successful run, as the implicit `error` does + // (`IMPLICIT_ERROR_OUTPUT_SCHEMA`); an output the block declares under the same name wins. + const outputs: OutputSchema = { + ...blockConfig?.errorOutputs, + ...(getEffectiveBlockOutputs(blockType, subBlocks, { + triggerMode, + preferToolOutputs: !triggerMode, + includeHidden: true, + }) as OutputSchema), + } if (!outputs || Object.keys(outputs).length === 0) { return undefined diff --git a/apps/sim/executor/utils/errors.ts b/apps/sim/executor/utils/errors.ts index 6dd532b6355..1f3fc3f1615 100644 --- a/apps/sim/executor/utils/errors.ts +++ b/apps/sim/executor/utils/errors.ts @@ -104,6 +104,30 @@ export function readTrustedExecutionCost(subject: unknown): TrustedExecutionCost return isRecordedThrown(subject) ? trustedExecutionCosts.get(subject) : undefined } +/** + * The values of a block's declared error outputs (`BlockConfig.errorOutputs`, a Function's + * `errorMessage`), keyed by the error its handler throws. A side table like + * {@link trustedExecutionCosts}, so only the executor's deliberate copy of a declared key puts a + * value into block output. + */ +const attachedErrorOutputs = new WeakMap>>() + +/** Attaches the values a handler reports for its block's declared error outputs to its error. */ +export function attachErrorOutputs(error: unknown, outputs: Record): void { + if (!isRecordedThrown(error)) return + const values = Object.fromEntries( + Object.entries(outputs).filter( + (entry): entry is [string, string] => typeof entry[1] === 'string' + ) + ) + if (Object.keys(values).length > 0) attachedErrorOutputs.set(error, values) +} + +/** Reads the error-output values a handler attached, if it attached any. */ +export function readErrorOutputs(error: unknown): Readonly> | undefined { + return isRecordedThrown(error) ? attachedErrorOutputs.get(error) : undefined +} + function normalizeTrustedExecutionCost(cost: unknown): TrustedExecutionCost | undefined { if (!cost || typeof cost !== 'object' || Array.isArray(cost)) return undefined diff --git a/apps/sim/executor/utils/file-tool-processor.test.ts b/apps/sim/executor/utils/file-tool-processor.test.ts index 93ed62eb033..530f21fa552 100644 --- a/apps/sim/executor/utils/file-tool-processor.test.ts +++ b/apps/sim/executor/utils/file-tool-processor.test.ts @@ -50,6 +50,7 @@ const toolConfig = { name: 'Test File Output', description: 'Test file output', version: '1.0.0', + effect: 'write', params: {}, request: { url: () => 'https://example.com', @@ -249,6 +250,7 @@ describe('copilot tool execution context', () => { name: 'Test attachments', description: 'Downloads message attachments', version: '1.0.0', + effect: 'read', params: {}, request: { url: 'https://example.com/messages', method: 'GET' }, outputs: { files: { type: 'file[]' } }, @@ -397,6 +399,7 @@ describe('file output aliases', () => { name: 'Alias Test', description: 'File aliases', version: '1.0.0', + effect: 'write', params: {}, outputs: { file: { type: 'file', description: 'Stored file' } }, } diff --git a/apps/sim/executor/utils/run-from-block.test.ts b/apps/sim/executor/utils/run-from-block.test.ts index cdabe5ec2ed..ac8552e80e7 100644 --- a/apps/sim/executor/utils/run-from-block.test.ts +++ b/apps/sim/executor/utils/run-from-block.test.ts @@ -1,7 +1,11 @@ import { describe, expect, it } from 'vitest' import type { DAG, DAGNode } from '@/executor/dag/builder' import type { DAGEdge, NodeMetadata } from '@/executor/dag/types' -import { computeExecutionSets, validateRunFromBlock } from '@/executor/utils/run-from-block' +import { + computeExecutionSets, + findRerunStartBlockId, + validateRunFromBlock, +} from '@/executor/utils/run-from-block' import type { SerializedLoop, SerializedParallel } from '@/serializer/types' /** @@ -862,3 +866,38 @@ describe('upstream block addition/deletion scenarios', () => { expect(result.valid).toBe(true) }) }) + +describe('findRerunStartBlockId', () => { + const blocks = { + start: { data: {} }, + loop: { data: {} }, + inLoop: { data: { parentId: 'loop' } }, + parallel: { data: { parentId: 'loop' } }, + deep: { data: { parentId: 'parallel' } }, + orphan: { data: { parentId: 'gone' } }, + a: { data: { parentId: 'b' } }, + b: { data: { parentId: 'a' } }, + } + + it('starts a top-level block, including a container, at itself', () => { + expect(findRerunStartBlockId('start', blocks)).toBe('start') + expect(findRerunStartBlockId('loop', blocks)).toBe('loop') + }) + + it('starts a block inside a loop or parallel at the outermost container, however deep', () => { + expect(findRerunStartBlockId('inLoop', blocks)).toBe('loop') + expect(findRerunStartBlockId('parallel', blocks)).toBe('loop') + expect(findRerunStartBlockId('deep', blocks)).toBe('loop') + }) + + it('reads a parallel branch id as the block it clones', () => { + expect(findRerunStartBlockId('deep₍2₎', blocks)).toBe('loop') + }) + + it('names no start for a block or container missing from the workflow, or a parent cycle', () => { + expect(findRerunStartBlockId('missing', blocks)).toBeUndefined() + expect(findRerunStartBlockId('orphan', blocks)).toBeUndefined() + expect(findRerunStartBlockId('a', blocks)).toBeUndefined() + expect(findRerunStartBlockId('constructor', blocks)).toBeUndefined() + }) +}) diff --git a/apps/sim/executor/utils/run-from-block.ts b/apps/sim/executor/utils/run-from-block.ts index 1f7e18eb3c0..68adf1fb373 100644 --- a/apps/sim/executor/utils/run-from-block.ts +++ b/apps/sim/executor/utils/run-from-block.ts @@ -1,4 +1,4 @@ -import { isPlainRecord } from '@sim/utils/object' +import { isPlainRecord, isRecordLike } from '@sim/utils/object' import { normalizeName } from '@/executor/constants' import type { DAG } from '@/executor/dag/builder' import type { SerializableExecutionState } from '@/executor/execution/types' @@ -6,6 +6,7 @@ import type { NormalizedBlockOutput } from '@/executor/types' import { buildLoopSentinelStartId, buildParallelSentinelStartId, + stripCloneSuffixes, } from '@/executor/utils/subflow-node-id-codec' import type { SerializedWorkflow } from '@/serializer/types' @@ -262,6 +263,28 @@ export function validateRunFromBlock( return { valid: true } } +/** + * Where a run-from-block rerun of a failure in `blockId` starts, in a workflow's stored `blocks`: + * the block itself at the top level, else the outermost loop or parallel holding it, since + * {@link validateRunFromBlock} refuses a start inside one. A parallel branch id (`block₍0₎`) is + * read as its block. Undefined when the block, or a container it sits in, is not in `blocks`. + */ +export function findRerunStartBlockId( + blockId: string, + blocks: Readonly> +): string | undefined { + const visited = new Set() + let current = stripCloneSuffixes(blockId) + while (!visited.has(current) && Object.hasOwn(blocks, current)) { + visited.add(current) + const block = blocks[current] + const parentId = isRecordLike(block) && isRecordLike(block.data) ? block.data.parentId : null + if (typeof parentId !== 'string' || !parentId) return current + current = parentId + } + return undefined +} + /** * The top-level loop or parallel a block sits in, however deeply nested. A nested container * is refused as a start too, so naming the immediate parent would point at another refusal. diff --git a/apps/sim/executor/variables/resolver.test.ts b/apps/sim/executor/variables/resolver.test.ts index b528f7852d0..5f08c6b1712 100644 --- a/apps/sim/executor/variables/resolver.test.ts +++ b/apps/sim/executor/variables/resolver.test.ts @@ -1403,6 +1403,24 @@ describe('VariableResolver JSON text inputs', () => { }) }) + it('serializes a bare string reference as a JSON string unless it already is JSON', async () => { + const { resolve } = createJsonResolver(BlockType.RESPONSE, { + dataMode: 'json', + data: '{"error": , "empty": , "token": {{QUOTED_SECRET}}, "nested": , "port": {{PORT}}}', + }) + const resolved = await resolve({ + env: { PORT: '8080' }, + output: { blank: '', jsonText: '{"country": "F\\"R"}' }, + }) + expect(JSON.parse(resolved.data)).toEqual({ + error: awkwardText, + empty: '', + token: 'p"ss\\word', + nested: { country: 'F"R' }, + port: 8080, + }) + }) + it('escapes environment variables inside JSON strings', async () => { await expect(resolveResponseBody('{"auth": "Bearer {{QUOTED_SECRET}}"}')).resolves.toEqual({ auth: 'Bearer p"ss\\word', diff --git a/apps/sim/executor/variables/resolver.ts b/apps/sim/executor/variables/resolver.ts index 0ffc0849ade..a73b3d20028 100644 --- a/apps/sim/executor/variables/resolver.ts +++ b/apps/sim/executor/variables/resolver.ts @@ -23,7 +23,7 @@ import { escapeInertStringContent, formatInertStringLiteral, } from '@/executor/utils/code-formatting' -import { isJSONString } from '@/executor/utils/json' +import { isJSONString, mayBeJsonText } from '@/executor/utils/json' import { createEnvVarPattern, createReferencePattern } from '@/executor/utils/reference-validation' import { BlockResolver } from '@/executor/variables/resolvers/block' import { EnvResolver } from '@/executor/variables/resolvers/env' @@ -146,21 +146,39 @@ function isJsonStringContent(value: string): boolean { } } +/** + * Whether string `value` already reads as one JSON value (`42`, `true`, `{"a": 1}`, `"quoted"`). + * A bare reference in JSON text has always spliced its string as written, and workflows rely on a + * string holding JSON (an agent's JSON answer, a numeric env var) landing as that value. + */ +function isJsonValueText(value: string): boolean { + const trimmed = value.trim() + if (!mayBeJsonText(trimmed)) return false + try { + JSON.parse(trimmed) + return true + } catch { + return false + } +} + /** * Splices placeholder values into `text`. When `text` is JSON, a value landing inside one of its * string literals that would break the literal becomes escaped string content, so it cannot close - * the string; a value that is already valid string content is spliced as written. Placeholders + * the string; a value that is already valid string content is spliced as written. A string value + * landing outside a string literal becomes a JSON string unless it already reads as one JSON + * value, so `{"error": }` stays JSON whatever the message holds. Placeholders * must arrive in ascending offset order: the lexer resumes where the previous one stopped, then * skips the placeholder itself, so characters inside its own text never toggle the state. */ function placeholderSplicer( text: string, jsonText: boolean | undefined -): (value: string, start: number, end: number) => string { +): (value: string, start: number, end: number, isString: boolean) => string { if (!jsonText) return (value) => value let position = 0 let inString = false - return (value, start, end) => { + return (value, start, end, isString) => { while (position < start) { const char = text[position] if (inString && char === '\\') { @@ -171,7 +189,10 @@ function placeholderSplicer( position++ } position = Math.max(position, end) - return inString && !isJsonStringContent(value) ? JSON.stringify(value).slice(1, -1) : value + if (inString) { + return isJsonStringContent(value) ? value : JSON.stringify(value).slice(1, -1) + } + return isString && !isJsonValueText(value) ? JSON.stringify(value) : value } } @@ -1872,7 +1893,12 @@ export class VariableResolver { } const raw = this.blockResolver.formatValueForBlock(resolved, blockType, language) - const formatted = spliceReference(raw, index, index + match.length) + const formatted = spliceReference( + raw, + index, + index + match.length, + typeof resolved === 'string' + ) projectedReferenceResult += containsResolvedSecret ? match : formatted return formatted } catch (error) { @@ -1891,7 +1917,7 @@ export class VariableResolver { result = await replaceEnvVarsAsync(result, async (match, index) => { const resolved = await this.resolveReference(match, resolutionContext) if (typeof resolved !== 'string') return match - return spliceEnvVar(resolved, index, index + match.length) + return spliceEnvVar(resolved, index, index + match.length, true) }) ctx.resolvedSecretTraceRegistry?.recordResolvedInputProjection( options.inputPath, diff --git a/apps/sim/hooks/queries/organization-payment-method.ts b/apps/sim/hooks/queries/organization-payment-method.ts new file mode 100644 index 00000000000..3f384606747 --- /dev/null +++ b/apps/sim/hooks/queries/organization-payment-method.ts @@ -0,0 +1,75 @@ +import { type QueryState, useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { requestJson } from '@/lib/api/client/request' +import { + getOrganizationPaymentMethodContract, + startOrganizationAutoPayContract, +} from '@/lib/api/contracts/organization' +import { organizationKeys } from '@/hooks/queries/utils/organization-keys' + +const ORGANIZATION_PAYMENT_METHOD_STALE_TIME = 60 * 1000 +/** How often, and how many times, to re-read while auto-pay waits on Stripe's webhook. */ +const AUTO_PAY_CONFIRM_INTERVAL_MS = 2_000 +const AUTO_PAY_CONFIRM_ATTEMPTS = 15 + +async function fetchOrganizationPaymentMethod(orgId: string, signal?: AbortSignal) { + const response = await requestJson(getOrganizationPaymentMethodContract, { + params: { id: orgId }, + signal, + }) + return response.data +} + +type PaymentMethodState = QueryState>> + +/** Whether the contract has not switched to auto-pay yet and tries remain, failed reads included. */ +function awaitsAutoPay(state: PaymentMethodState | undefined): boolean { + if (!state) return true + return ( + state.data?.collectionMethod !== 'charge_automatically' && + state.dataUpdateCount + state.errorUpdateCount < AUTO_PAY_CONFIRM_ATTEMPTS + ) +} + +/** + * How a self-serve Enterprise organization pays. `confirmingAutoPay` keeps re-reading after the + * customer returns from Stripe's setup page, until the webhook has switched the contract to + * automatic payment or the tries run out; `isConfirmingAutoPay` is true for that window. + */ +export function useOrganizationPaymentMethod( + orgId: string, + options: { enabled: boolean; confirmingAutoPay: boolean } +) { + const queryClient = useQueryClient() + const queryKey = organizationKeys.paymentMethod(orgId) + const query = useQuery({ + queryKey, + queryFn: ({ signal }) => fetchOrganizationPaymentMethod(orgId, signal), + enabled: !!orgId && options.enabled, + staleTime: ORGANIZATION_PAYMENT_METHOD_STALE_TIME, + refetchInterval: (current) => + options.confirmingAutoPay && awaitsAutoPay(current.state) + ? AUTO_PAY_CONFIRM_INTERVAL_MS + : false, + }) + return { + ...query, + isConfirmingAutoPay: + options.confirmingAutoPay && + awaitsAutoPay( + queryClient.getQueryState>>( + queryKey + ) + ), + } +} + +/** Opens Stripe's setup page that saves a payment method and turns on auto-pay. */ +export function useStartOrganizationAutoPay() { + return useMutation({ + mutationFn: ({ organizationId, returnUrl }: { organizationId: string; returnUrl: string }) => + requestJson(startOrganizationAutoPayContract, { + params: { id: organizationId }, + body: { returnUrl }, + }), + }) +} diff --git a/apps/sim/hooks/queries/organization.test.tsx b/apps/sim/hooks/queries/organization.test.tsx index de1f85d253b..c498f50ea1e 100644 --- a/apps/sim/hooks/queries/organization.test.tsx +++ b/apps/sim/hooks/queries/organization.test.tsx @@ -77,6 +77,7 @@ const BILLING_A: OrganizationPlanSeatsResponse = { usedSeats: 2, membersTotal: 2, hasEnterprisePlan: true, + seatCapKind: 'fixed', }, } diff --git a/apps/sim/hooks/queries/subscription.ts b/apps/sim/hooks/queries/subscription.ts index e5067c542fb..3c49be5f8ef 100644 --- a/apps/sim/hooks/queries/subscription.ts +++ b/apps/sim/hooks/queries/subscription.ts @@ -3,6 +3,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { requestJson } from '@/lib/api/client/request' import type { ContractBodyInput } from '@/lib/api/contracts' import { + billingEndTrialContract, createBillingPortalContract, getInvoicesContract, getUserUsageLimitContract, @@ -218,3 +219,19 @@ export function useOpenBillingPortal() { }, }) } + +/** + * Ends the viewer's own Pro free trial now. The card is charged by Stripe and the webhooks raise + * the trial allowance to the plan's, so every billing read is refetched once the call returns. + */ +export function useEndProTrial() { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: () => requestJson(billingEndTrialContract, { body: {} }), + onSettled: () => + Promise.all([ + queryClient.invalidateQueries({ queryKey: subscriptionKeys.all }), + invalidateWorkspaceUsage(queryClient), + ]), + }) +} diff --git a/apps/sim/hooks/queries/utils/organization-keys.ts b/apps/sim/hooks/queries/utils/organization-keys.ts index e58e8a72b03..8673da7da73 100644 --- a/apps/sim/hooks/queries/utils/organization-keys.ts +++ b/apps/sim/hooks/queries/utils/organization-keys.ts @@ -8,6 +8,7 @@ export const organizationKeys = { billing: (id: string) => [...organizationKeys.detail(id), 'billing'] as const, planSeats: (id: string) => [...organizationKeys.billing(id), 'plan-seats'] as const, billingSummary: (id: string) => [...organizationKeys.billing(id), 'summary'] as const, + paymentMethod: (id: string) => [...organizationKeys.billing(id), 'payment-method'] as const, members: (id: string) => [...organizationKeys.detail(id), 'members'] as const, memberUsage: (id: string) => [...organizationKeys.detail(id), 'member-usage'] as const, memberUsageLimit: (id: string, userId: string) => diff --git a/apps/sim/hooks/queries/workflow-source.test.ts b/apps/sim/hooks/queries/workflow-source.test.ts index c9b20117fc5..e5dd998070d 100644 --- a/apps/sim/hooks/queries/workflow-source.test.ts +++ b/apps/sim/hooks/queries/workflow-source.test.ts @@ -21,7 +21,13 @@ function sourceServer() { workspaceId: 'ws-1', files: { 'workflow.ts': state.text }, lock: { version: 1, blocks: {}, variables: {} }, - base: { workflowId: WORKFLOW_ID, workspaceId: 'ws-1', fingerprint: 'f', catalogHash: 'c' }, + base: { + version: 1, + workflowId: WORKFLOW_ID, + workspaceId: 'ws-1', + fingerprint: 'f', + catalogHash: 'c', + }, canonicalHash: 'h', sdkMajor: 1, blockTypes: [], diff --git a/apps/sim/hooks/use-permission-config.ts b/apps/sim/hooks/use-permission-config.ts index 06291749e6d..e68f8bf77d9 100644 --- a/apps/sim/hooks/use-permission-config.ts +++ b/apps/sim/hooks/use-permission-config.ts @@ -3,7 +3,7 @@ import { useMemo } from 'react' import { useParams } from 'next/navigation' import type { IntegrationAvailabilityResponse } from '@/lib/api/contracts/common' -import { getEnv, isTruthy } from '@/lib/core/config/env' +import { useDeploymentShape } from '@/lib/core/config/deployment-shape' import { resolveIntegrationAccess } from '@/lib/integrations/access' import { DEFAULT_PERMISSION_GROUP_CONFIG, @@ -54,6 +54,7 @@ export interface PermissionConfigResult { export function usePermissionConfig(): PermissionConfigResult { const params = useParams() + const deployment = useDeploymentShape() const workspaceId = typeof params?.workspaceId === 'string' ? params.workspaceId : undefined const { @@ -134,15 +135,8 @@ export function usePermissionConfig(): PermissionConfigResult { } }, [config.allowedModelProviders]) - const isInvitationsDisabled = useMemo(() => { - const featureFlagDisabled = isTruthy(getEnv('NEXT_PUBLIC_DISABLE_INVITATIONS')) - return featureFlagDisabled || config.disableInvitations - }, [config.disableInvitations]) - - const isPublicApiDisabled = useMemo(() => { - const featureFlagDisabled = isTruthy(getEnv('NEXT_PUBLIC_DISABLE_PUBLIC_API')) - return featureFlagDisabled || config.disablePublicApi - }, [config.disablePublicApi]) + const isInvitationsDisabled = Boolean(deployment.invitationsDisabled) || config.disableInvitations + const isPublicApiDisabled = Boolean(deployment.publicApiDisabled) || config.disablePublicApi const mergedConfig = useMemo( () => ({ ...config, allowedIntegrations: mergedAllowedIntegrations }), diff --git a/apps/sim/hooks/use-workspace-invite-policy.ts b/apps/sim/hooks/use-workspace-invite-policy.ts index b3ee90723b2..78da19faae7 100644 --- a/apps/sim/hooks/use-workspace-invite-policy.ts +++ b/apps/sim/hooks/use-workspace-invite-policy.ts @@ -21,7 +21,7 @@ export interface UseWorkspaceInvitePolicyReturn { * teammate-management action must read it. * * Two independent sources say no, and both have to be consulted: the deployment - * or permission-group switch (`NEXT_PUBLIC_DISABLE_INVITATIONS`, a permission + * or permission-group switch (`DISABLE_INVITATIONS`, a permission * group's `disableInvitations`), which is silent about why, and the workspace's * own plan policy, which supplies {@link UseWorkspaceInvitePolicyReturn.inviteDisabledReason}. * Reading only one of them is what lets an entry point offer an invite the server diff --git a/apps/sim/lib/admin/dashboard-organizations.test.ts b/apps/sim/lib/admin/dashboard-organizations.test.ts index e0780f801a9..fc840eea133 100644 --- a/apps/sim/lib/admin/dashboard-organizations.test.ts +++ b/apps/sim/lib/admin/dashboard-organizations.test.ts @@ -170,6 +170,7 @@ describe('toDashboardConfigurationUpdate', () => { desiredTerms: null, hasUnappliedIntent: true, effectiveSeatCapacity: 20, + seatsUncapped: false, configurationUpdate: { id: 'config-2', status: 'pending', @@ -190,6 +191,8 @@ describe('toDashboardConfigurationUpdate', () => { requestedReportingPeriodInterval: null, requestedReportingPeriodAnchorDate: null, requestedSeats: 20, + requestedSelfServe: null, + requestedSeatPriceUsd: null, requestedConcurrencyLimit: 50, requestedWorkflowExecutionTimeoutSeconds: null, providerAccepted: false, diff --git a/apps/sim/lib/admin/dashboard.ts b/apps/sim/lib/admin/dashboard.ts index 252bfd2ad9b..2e797053aa6 100644 --- a/apps/sim/lib/admin/dashboard.ts +++ b/apps/sim/lib/admin/dashboard.ts @@ -1,6 +1,7 @@ import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit' import { db } from '@sim/db' import { + enterpriseSeatTrueUp, member, organization, organizationMemberUsageLimit, @@ -27,6 +28,7 @@ import { } from '@/lib/admin/organization-economics' import { parseBillingConcurrencyLimit } from '@/lib/billing/concurrency-defaults' import { getBillingConcurrencyLimit } from '@/lib/billing/concurrency-limits' +import { INVOICE_DAYS_UNTIL_DUE } from '@/lib/billing/constants' import { getHighestPrioritySubscription } from '@/lib/billing/core/plan' import { type ResolvedUsagePeriod, @@ -34,6 +36,7 @@ import { resolveSubscriptionUsagePeriodOrDefault, } from '@/lib/billing/core/reporting-period' import { creditsToDollars, dollarsToCredits } from '@/lib/billing/credits/conversion' +import { configuredEnterpriseUsageCredits } from '@/lib/billing/enterprise-credit-limits' import { enterpriseMetadataSyncPayloadSchema, resolveEnterpriseMetadataIntent, @@ -56,12 +59,15 @@ import { transferOrganizationOwnership, } from '@/lib/billing/organizations/membership' import { reconcileOrganizationSeats } from '@/lib/billing/organizations/seats' +import { requireStripeClient } from '@/lib/billing/stripe-client' import { ENTITLED_SUBSCRIPTION_STATUSES, getPerUserMinimumLimit, hasPaidSubscriptionStatus, + isEnterpriseSelfServe, isOrgScopedSubscription, } from '@/lib/billing/subscriptions/utils' +import { parseEnterpriseSubscriptionMetadata } from '@/lib/billing/types' import { toDecimal } from '@/lib/billing/utils/decimal' import { countPendingSeatInvitations } from '@/lib/billing/validation/seat-management' import { env } from '@/lib/core/config/env' @@ -97,6 +103,17 @@ function metadataNumber(metadata: Record, key: string): number return Number.isFinite(numeric) ? numeric : null } +/** + * An Enterprise contract's included usage in credits. Never derived from the organization's + * enforced limit, which on a self-serve contract is the customer's own cap. + */ +function configuredEnterpriseUsageLimitCredits(metadata: Record): number { + return configuredEnterpriseUsageCredits( + metadata.usageLimitCredits, + parseEnterpriseSubscriptionMetadata(metadata)?.invoiceAmountUsd ?? 0 + ) +} + async function enqueueEnterpriseMetadataIntent( tx: DbOrTx, params: { @@ -199,7 +216,7 @@ function buildDashboardOrganizationSummary({ usagePeriod, }: DashboardOrganizationSummaryInput) { const metadata = metadataRecord(latestSubscription?.metadata) - const teamEconomics = getTeamOrganizationEconomics(latestSubscription?.plan, memberCount) + const teamEconomics = getTeamOrganizationEconomics(latestSubscription ?? undefined, memberCount) const invoiceAmountCents = metadataNumber(metadata, 'invoiceAmountCents') const monthlyPrice = metadataNumber(metadata, 'monthlyPrice') const usageLimitDollars = Math.max(0, Number(org.orgUsageLimit ?? 0)) @@ -273,9 +290,23 @@ function buildDashboardOrganizationSummary({ } } +/** + * Whether an intent changes one key. Every intent carries the full desired metadata, and Stripe + * holds strings, so compare as delivered strings with an absent key and null alike. + */ +function changesMetadata( + requested: Record, + applied: Record, + key: string +): boolean { + const asDelivered = (value: unknown) => (value == null || value === '' ? null : String(value)) + return asDelivered(requested[key]) !== asDelivered(applied[key]) +} + export function toDashboardConfigurationUpdate( intent: Awaited> | null, - prepaidBalanceDollars = 0 + prepaidBalanceDollars = 0, + appliedMetadata: Record = {} ) { const update = intent?.configurationUpdate if (!update) return null @@ -288,6 +319,9 @@ export function toDashboardConfigurationUpdate( metadata, 'workflowExecutionTimeoutSeconds' ) + const requestedSeatPriceCents = changesMetadata(metadata, appliedMetadata, 'seatPriceCents') + ? metadataNumber(metadata, 'seatPriceCents') + : null return { id: update.id, @@ -307,6 +341,10 @@ export function toDashboardConfigurationUpdate( ? metadata.reportingPeriodAnchorDate : null, requestedSeats: seats === null ? null : Math.round(seats), + requestedSelfServe: changesMetadata(metadata, appliedMetadata, 'selfServe') + ? metadata.selfServe === 'true' + : null, + requestedSeatPriceUsd: requestedSeatPriceCents === null ? null : requestedSeatPriceCents / 100, requestedConcurrencyLimit: concurrencyLimit === null ? null : Math.round(concurrencyLimit), requestedWorkflowExecutionTimeoutSeconds: workflowExecutionTimeoutSeconds === null ? null : Math.round(workflowExecutionTimeoutSeconds), @@ -605,6 +643,49 @@ export async function listDashboardOrganizations({ search, limit, offset }: Pagi } } +/** Seat true-up windows the admin view lists, newest first. */ +const ADMIN_SEAT_TRUE_UP_HISTORY = 8 + +/** + * An Enterprise contract's self-serve state for the admin view: whether it is on, its seat rate, + * the usage limit the customer chose, and its recent seat true-up windows. + */ +async function readDashboardEnterpriseSelfServe( + organizationId: string, + subscriptionRow: { id: string; plan: string; metadata: unknown } +) { + const [orgRows, trueUps] = await Promise.all([ + db + .select({ selfServeUsageLimit: organization.selfServeUsageLimit }) + .from(organization) + .where(eq(organization.id, organizationId)) + .limit(1), + db + .select() + .from(enterpriseSeatTrueUp) + .where(eq(enterpriseSeatTrueUp.subscriptionId, subscriptionRow.id)) + .orderBy(desc(enterpriseSeatTrueUp.windowStart)) + .limit(ADMIN_SEAT_TRUE_UP_HISTORY), + ]) + const seatPriceCents = parseEnterpriseSubscriptionMetadata( + subscriptionRow.metadata + )?.seatPriceCents + const customerUsageLimit = orgRows[0]?.selfServeUsageLimit + return { + enabled: isEnterpriseSelfServe(subscriptionRow), + seatPriceUsd: seatPriceCents === undefined ? null : seatPriceCents / 100, + customerUsageLimitDollars: customerUsageLimit == null ? null : Number(customerUsageLimit), + seatTrueUps: trueUps.map((row) => ({ + windowStart: row.windowStart.toISOString(), + windowEnd: row.windowEnd.toISOString(), + peakExtraSeats: row.peakExtraSeats, + seatPriceUsd: row.seatPriceCents / 100, + amountUsd: row.amountCents === null ? null : row.amountCents / 100, + billedAt: row.billedAt?.toISOString() ?? null, + })), + } +} + export async function getDashboardOrganization( organizationId: string, pagination: { @@ -719,9 +800,12 @@ export async function getDashboardOrganization( historicalActorSpend, } } - const [workflowRuns, page] = await Promise.all([ + const [workflowRuns, page, selfServe] = await Promise.all([ readDashboardOrganizationWorkflowRuns(organizationId, usagePeriod), readPage(), + subscriptionRow?.plan === 'enterprise' + ? readDashboardEnterpriseSelfServe(organizationId, subscriptionRow) + : Promise.resolve(null), ]) const limits = new Map(page.limitRows.map((row) => [row.userId, Number(row.limit)])) const usageByUser = page.spendByOrganization.get(organizationId) ?? new Map() @@ -734,8 +818,10 @@ export async function getDashboardOrganization( usage: { ...base.usage, workflowRuns: workflowRuns?.total ?? null }, configurationUpdate: toDashboardConfigurationUpdate( page.configurationIntent, - base.prepaidBalanceDollars + base.prepaidBalanceDollars, + metadataRecord(subscriptionRow?.metadata) ), + selfServe, historicalActorUsage: { usedDollars: historicalUsedDollars, usedCredits: dollarsToCredits(historicalUsedDollars), @@ -861,7 +947,8 @@ export async function updateDashboardEnterpriseSeats( .where(eq(member.organizationId, organizationId)) const pendingSeats = await countPendingSeatInvitations(organizationId, tx) const requiredSeats = (memberCountRow?.value ?? 0) + pendingSeats - if (seats < requiredSeats) { + // A self-serve contract's seats are its committed baseline; members past it are trued up. + if (seats < requiredSeats && !isEnterpriseSelfServe(subscriptionRow)) { throw new Error( `Seat capacity cannot be below ${requiredSeats} occupied or reserved seats (${memberCountRow?.value ?? 0} members and ${pendingSeats} pending invitations)` ) @@ -971,6 +1058,11 @@ export async function updateDashboardEnterpriseReportingPeriod( if (!subscriptionRow?.stripeSubscriptionId) { throw new Error('Active Stripe-backed Enterprise subscription not found') } + if (isEnterpriseSelfServe(subscriptionRow)) { + throw new Error( + 'Self-serve contracts measure usage on Stripe billing periods. Turn off self-serve to set a reporting period.' + ) + } await enqueueEnterpriseMetadataIntent(tx, { subscriptionId: subscriptionRow.id, appliedMetadata: subscriptionRow.metadata, @@ -1061,6 +1153,148 @@ export async function retryDashboardEnterpriseConfigurationUpdate( }) } +/** + * Turns an Enterprise contract's self-serve billing on or off. Enabling clears the reporting-period + * anchor (self-serve overage closes on Stripe billing periods), so a contract whose reporting + * interval differs must restate included usage for the billing interval. Disabling restores the + * hard caps and emailed invoices. + */ +export async function updateDashboardEnterpriseSelfServe( + organizationId: string, + values: { enabled: boolean; seatPriceUsd?: number; usageLimitDollars?: number }, + actor: AdminMutationActor +) { + await db.transaction(async (tx) => { + await acquireOrganizationMutationLock(tx, organizationId) + const [org] = await tx + .select({ creditBalance: organization.creditBalance }) + .from(organization) + .where(eq(organization.id, organizationId)) + .for('update') + .limit(1) + if (!org) throw new Error('Organization not found') + const [subscriptionRow] = await tx + .select() + .from(subscription) + .where( + and( + eq(subscription.referenceId, organizationId), + eq(subscription.plan, 'enterprise'), + inArray(subscription.status, ENTITLED_SUBSCRIPTION_STATUSES) + ) + ) + .for('update') + .limit(1) + if (!subscriptionRow) throw new Error('Active Enterprise subscription not found') + + if (!values.enabled) { + // Off restores the hard seat cap, which the contract webhook refuses below occupied seats. + const [memberCountRow] = await tx + .select({ value: count() }) + .from(member) + .where(eq(member.organizationId, organizationId)) + const requiredSeats = + (memberCountRow?.value ?? 0) + (await countPendingSeatInvitations(organizationId, tx)) + const contractSeats = metadataNumber(metadataRecord(subscriptionRow.metadata), 'seats') ?? 0 + if (contractSeats < requiredSeats) { + throw new Error( + `Raise contracted seats to at least ${requiredSeats} occupied or reserved seats before turning off self-serve` + ) + } + } + + const prepaidBalanceDollars = Number(org.creditBalance ?? 0) + if ( + values.usageLimitDollars !== undefined && + values.usageLimitDollars < prepaidBalanceDollars + ) { + throw new Error('Enterprise usage limit cannot be below its prepaid balance') + } + await enqueueEnterpriseMetadataIntent(tx, { + subscriptionId: subscriptionRow.id, + appliedMetadata: subscriptionRow.metadata, + buildDesiredMetadata: (current) => { + if (!values.enabled) return { ...current, selfServe: null } + if (values.seatPriceUsd === undefined) { + throw new Error('A seat price is required to enable self-serve') + } + const reportingInterval = current.reportingPeriodInterval + if ( + values.usageLimitDollars === undefined && + typeof current.reportingPeriodAnchorDate === 'string' && + reportingInterval !== undefined && + reportingInterval !== subscriptionRow.billingInterval + ) { + throw new Error( + `Usage is reported each ${String(reportingInterval)} but billed each ${String(subscriptionRow.billingInterval)}. Restate the included usage per billing period to enable self-serve.` + ) + } + const usageLimitCredits = + values.usageLimitDollars === undefined + ? configuredEnterpriseUsageLimitCredits(current) + : dollarsToCredits(values.usageLimitDollars - prepaidBalanceDollars) + return { + ...current, + selfServe: 'true', + seatPriceCents: Math.round(values.seatPriceUsd * 100), + usageLimitCredits, + reportingPeriodAnchorDate: null, + reportingPeriodInterval: null, + } + }, + }) + }) + recordAudit({ + actorId: actor.id, + actorName: actor.name, + actorEmail: actor.email, + action: AuditAction.ORGANIZATION_UPDATED, + resourceType: AuditResourceType.ORGANIZATION, + resourceId: organizationId, + description: values.enabled + ? 'Admin requested Enterprise self-serve billing' + : 'Admin requested Enterprise self-serve billing off', + metadata: values, + }) +} + +/** + * Returns a self-serve Enterprise contract from automatic payment to emailed invoices due in 30 + * days. Only invoices created afterwards change; the saved payment method stays on file. + */ +export async function revertDashboardEnterpriseToInvoicing( + organizationId: string, + actor: AdminMutationActor +) { + const [subscriptionRow] = await db + .select({ stripeSubscriptionId: subscription.stripeSubscriptionId }) + .from(subscription) + .where( + and( + eq(subscription.referenceId, organizationId), + eq(subscription.plan, 'enterprise'), + inArray(subscription.status, ENTITLED_SUBSCRIPTION_STATUSES) + ) + ) + .limit(1) + if (!subscriptionRow?.stripeSubscriptionId) { + throw new Error('Active Enterprise subscription not found') + } + await requireStripeClient().subscriptions.update(subscriptionRow.stripeSubscriptionId, { + collection_method: 'send_invoice', + days_until_due: INVOICE_DAYS_UNTIL_DUE, + }) + recordAudit({ + actorId: actor.id, + actorName: actor.name, + actorEmail: actor.email, + action: AuditAction.ORGANIZATION_UPDATED, + resourceType: AuditResourceType.ORGANIZATION, + resourceId: organizationId, + description: 'Admin returned Enterprise contract to invoice payment', + }) +} + export async function updateDashboardOrganizationLimits( organizationId: string, values: { @@ -1118,12 +1352,7 @@ export async function updateDashboardOrganizationLimits( buildDesiredMetadata: (current) => { const configuredUsageLimit = values.usageLimitDollars === undefined - ? Math.round( - metadataNumber(current, 'usageLimitCredits') ?? - dollarsToCredits( - Math.max(0, Number(org.orgUsageLimit ?? 0) - prepaidBalanceDollars) - ) - ) + ? configuredEnterpriseUsageLimitCredits(current) : dollarsToCredits(values.usageLimitDollars - prepaidBalanceDollars) return { ...current, @@ -1144,10 +1373,7 @@ export async function updateDashboardOrganizationLimits( .select({ value: count() }) .from(member) .where(eq(member.organizationId, organizationId)) - const teamEconomics = getTeamOrganizationEconomics( - subscriptionRow?.plan, - memberCountRow?.value ?? 0 - ) + const teamEconomics = getTeamOrganizationEconomics(subscriptionRow, memberCountRow?.value ?? 0) const planAllowance = teamEconomics?.planAllowanceDollars ?? 0 const prepaid = Number(org.creditBalance) const configuredUsageLimit = @@ -1214,7 +1440,14 @@ export async function grantDashboardOrganizationBalance( .limit(1) if (!org) throw new Error('Organization not found') const [subscriptionRow] = await tx - .select({ plan: subscription.plan, metadata: subscription.metadata }) + .select({ + plan: subscription.plan, + metadata: subscription.metadata, + billingInterval: subscription.billingInterval, + periodStart: subscription.periodStart, + allowancePeriodStart: subscription.allowancePeriodStart, + allowanceSeatMonths: subscription.allowanceSeatMonths, + }) .from(subscription) .where(eq(subscription.referenceId, organizationId)) .orderBy( @@ -1228,7 +1461,7 @@ export async function grantDashboardOrganizationBalance( .from(member) .where(eq(member.organizationId, organizationId)) const teamEconomics = getTeamOrganizationEconomics( - subscriptionRow?.plan, + subscriptionRow, memberCountRow?.value ?? 0 ) const planAllowanceDollars = teamEconomics?.planAllowanceDollars ?? 0 diff --git a/apps/sim/lib/admin/organization-economics.test.ts b/apps/sim/lib/admin/organization-economics.test.ts index 22c9413215e..2c01e564111 100644 --- a/apps/sim/lib/admin/organization-economics.test.ts +++ b/apps/sim/lib/admin/organization-economics.test.ts @@ -6,7 +6,7 @@ import { describe('getTeamOrganizationEconomics', () => { it('derives the pooled Pro allowance and invoice from internal seats', () => { - expect(getTeamOrganizationEconomics('team_6000', 3)).toEqual({ + expect(getTeamOrganizationEconomics({ plan: 'team_6000' }, 3)).toEqual({ seats: 3, planAllowanceDollars: 90, monthlyInvoiceAmountUsd: 75, @@ -14,7 +14,7 @@ describe('getTeamOrganizationEconomics', () => { }) it('derives the pooled Max allowance and invoice from internal seats', () => { - expect(getTeamOrganizationEconomics('team_25000', 2)).toEqual({ + expect(getTeamOrganizationEconomics({ plan: 'team_25000' }, 2)).toEqual({ seats: 2, planAllowanceDollars: 250, monthlyInvoiceAmountUsd: 200, @@ -22,7 +22,7 @@ describe('getTeamOrganizationEconomics', () => { }) it('does not invent pricing for non-Team plans', () => { - expect(getTeamOrganizationEconomics('enterprise', 5)).toBeNull() + expect(getTeamOrganizationEconomics({ plan: 'enterprise' }, 5)).toBeNull() }) }) diff --git a/apps/sim/lib/admin/organization-economics.ts b/apps/sim/lib/admin/organization-economics.ts index 6380686b317..aaea38ba164 100644 --- a/apps/sim/lib/admin/organization-economics.ts +++ b/apps/sim/lib/admin/organization-economics.ts @@ -1,5 +1,8 @@ -import { CREDIT_MULTIPLIER } from '@/lib/billing/credits/conversion' -import { getPlanTierCredits, getPlanTierDollars, isTeam } from '@/lib/billing/plan-helpers' +import { getPlanTierDollars, isTeam } from '@/lib/billing/plan-helpers' +import { + getOrgIncludedUsageDollars, + type OrgAllowanceInput, +} from '@/lib/billing/subscriptions/utils' import { Decimal, toDecimal } from '@/lib/billing/utils/decimal' export interface TeamOrganizationEconomics { @@ -8,16 +11,20 @@ export interface TeamOrganizationEconomics { monthlyInvoiceAmountUsd: number } -/** Canonical pooled Team allowance and invoice amount (`per-seat × members`). */ +/** + * Canonical pooled Team allowance for the billing period (`per-seat × members`, a year's worth on + * annual billing) and the monthly invoice amount. + */ export function getTeamOrganizationEconomics( - plan: string | null | undefined, + subscription: OrgAllowanceInput | undefined, internalMemberCount: number ): TeamOrganizationEconomics | null { - if (!plan || !isTeam(plan)) return null + const plan = subscription?.plan + if (!subscription || !plan || !isTeam(plan)) return null const seats = Math.max(0, Math.trunc(internalMemberCount)) return { seats, - planAllowanceDollars: (getPlanTierCredits(plan) * seats) / CREDIT_MULTIPLIER, + planAllowanceDollars: seats === 0 ? 0 : getOrgIncludedUsageDollars({ ...subscription, seats }), monthlyInvoiceAmountUsd: getPlanTierDollars(plan) * seats, } } diff --git a/apps/sim/lib/api/contracts/logs.ts b/apps/sim/lib/api/contracts/logs.ts index 0c85e989a31..6db317d1793 100644 --- a/apps/sim/lib/api/contracts/logs.ts +++ b/apps/sim/lib/api/contracts/logs.ts @@ -213,6 +213,7 @@ export type LogTraceSpan = { errorType?: string errorMessage?: string blockId?: string + childDeploymentVersionId?: string input?: unknown output?: unknown tokens?: number | { total?: number; input?: number; output?: number } @@ -244,6 +245,12 @@ export const traceSpanSchema: z.ZodType = z errorType: z.string().describe('Recorded error type.').optional(), errorMessage: z.string().describe('Recorded error message.').optional(), blockId: z.string().describe('Workflow block associated with the span.').optional(), + childDeploymentVersionId: z + .string() + .describe( + "Deployment version of the child workflow this call ran, on a workflow block span or a workflow Agent tool span. Match it to the child workflow's versions list. Absent for draft children, custom blocks, failed Agent tool calls, and runs recorded before this field existed." + ) + .optional(), input: z.unknown().describe('Input captured for the traced operation.').optional(), output: z.unknown().describe('Output captured for the traced operation.').optional(), tokens: z diff --git a/apps/sim/lib/api/contracts/organization.ts b/apps/sim/lib/api/contracts/organization.ts index 2ae74ed9898..e03d85d9e53 100644 --- a/apps/sim/lib/api/contracts/organization.ts +++ b/apps/sim/lib/api/contracts/organization.ts @@ -641,6 +641,7 @@ const organizationPlanSeatsResponseSchema = z.object({ usedSeats: z.number().int().nonnegative(), membersTotal: z.number().int().nonnegative(), hasEnterprisePlan: z.boolean(), + seatCapKind: z.enum(['fixed', 'baseline', 'on-demand']).nullable(), }), }) @@ -676,10 +677,60 @@ export const organizationBillingSummarySchema = z.object({ blockedByOrgOwner: z.boolean(), upgradeWorkspaceId: workspaceIdSchema.nullable(), userRole: z.enum(['admin', 'owner']), + enterpriseSelfServe: z + .object({ + contractSeats: z.number().int().min(0), + seatPriceCents: z.number().int().positive(), + includedUsage: z.number().min(0), + peakExtraSeats: z.number().int().min(0), + }) + .nullable(), }) export type OrganizationBillingSummary = z.output +/** + * Marks the billing page Stripe returns to after the customer saves a payment method, so the page + * keeps checking until the webhook has switched the contract to automatic payment. + */ +export const AUTO_PAY_RETURN_PARAM = 'autopay' + +const enterprisePaymentMethodSchema = z.object({ + collectionMethod: z.enum(['charge_automatically', 'send_invoice']), + paymentMethod: z + .object({ + type: z.enum(['card', 'us_bank_account', 'other']), + label: z.string(), + }) + .nullable(), +}) + +/** How a self-serve Enterprise contract pays; organization admins and owners only. */ +export const getOrganizationPaymentMethodContract = defineRouteContract({ + method: 'GET', + path: '/api/organizations/[id]/payment-method', + params: organizationParamsSchema, + response: { + mode: 'json', + schema: z.object({ + success: z.literal(true), + data: enterprisePaymentMethodSchema, + }), + }, +}) + +/** Opens Stripe's page that saves a payment method and turns on auto-pay for the contract. */ +export const startOrganizationAutoPayContract = defineRouteContract({ + method: 'POST', + path: '/api/organizations/[id]/payment-method', + params: organizationParamsSchema, + body: z.object({ returnUrl: z.string().url() }), + response: { + mode: 'json', + schema: z.object({ url: z.string().url() }), + }, +}) + export const getOrganizationBillingSummaryContract = defineRouteContract({ method: 'GET', path: '/api/organizations/[id]/billing-summary', diff --git a/apps/sim/lib/api/contracts/subscription.ts b/apps/sim/lib/api/contracts/subscription.ts index 8242b4ac1f3..5b189a47ccf 100644 --- a/apps/sim/lib/api/contracts/subscription.ts +++ b/apps/sim/lib/api/contracts/subscription.ts @@ -67,6 +67,8 @@ export const subscriptionBillingDataSchema = z isExceeded: z.boolean(), daysRemaining: z.number(), creditBalance: z.number(), + /** The plan's included usage for this billing period, in dollars: also the lowest limit the payer may set. */ + includedUsage: z.number(), billingInterval: z.enum(['month', 'year']), isPaid: z.boolean(), isPro: z.boolean(), @@ -85,6 +87,8 @@ export const subscriptionBillingDataSchema = z billingBlockedReason: z.enum(['payment_failed', 'dispute']).nullable(), blockedByOrgOwner: z.boolean(), upgradeWorkspaceId: workspaceIdSchema.nullable(), + /** The viewer may still start Pro's free trial at checkout. Personal context only. */ + proTrialEligible: z.boolean().optional(), organization: z .object({ id: z.string(), @@ -372,6 +376,17 @@ export const billingSwitchPlanContract = defineRouteContract({ }, }) +/** Ends the caller's own Pro free trial now, so the card is charged and the full plan starts. */ +export const billingEndTrialContract = defineRouteContract({ + method: 'POST', + path: '/api/billing/end-trial', + body: z.object({}), + response: { + mode: 'json', + schema: z.object({ success: z.literal(true) }), + }, +}) + export const billingUpdateCostContract = defineRouteContract({ method: 'POST', path: '/api/billing/update-cost', diff --git a/apps/sim/lib/api/contracts/tables.ts b/apps/sim/lib/api/contracts/tables.ts index 332177cfdbc..b86c491f6db 100644 --- a/apps/sim/lib/api/contracts/tables.ts +++ b/apps/sim/lib/api/contracts/tables.ts @@ -49,13 +49,21 @@ import { export const domainObjectSchema = () => z.custom(isRecordLike) +/** Column types the server accepts but the public documents leave out. */ +const UNDOCUMENTED_COLUMN_TYPES: readonly string[] = ['ttl'] + /** * Column types are a fixed enum derived from `COLUMN_TYPES` so callers cannot * send arbitrary strings the server would reject downstream. */ export const columnTypeSchema = z .enum(COLUMN_TYPES) - .meta({ omitEnumValuesFromOpenApi: ['ttl'] as const }) + .meta({ omitEnumValuesFromOpenApi: UNDOCUMENTED_COLUMN_TYPES }) + +/** The sentence naming the public column types, for the column inputs' help. */ +export const COLUMN_TYPES_HELP = `A column's type is one of ${COLUMN_TYPES.filter( + (type) => !UNDOCUMENTED_COLUMN_TYPES.includes(type) +).join(', ')}; a select column also takes options.` /** One choice in a `select` column. `id` is the stable cell key. */ export const selectOptionSchema = z.object({ @@ -901,6 +909,12 @@ export const updateRowsByFilterBodySchema = z.object({ .describe('Private encrypted secret provenance for trusted internal callers.'), }) +/** + * The keys of a row write that name no column, which a lax name-keyed write drops instead of + * refusing. Only the workflow Table tools' writes report it; the grid's routes never do. + */ +const ignoredColumnsSchema = z.array(z.string()).optional() + const successResponseSchema = (dataSchema: T) => z.object({ success: z.literal(true), @@ -1225,6 +1239,7 @@ export const insertTableRowsContract = defineRouteContract({ z.object({ row: tableRowSchema, message: z.string(), + ignoredColumns: ignoredColumnsSchema, }) ), successResponseSchema( @@ -1232,6 +1247,7 @@ export const insertTableRowsContract = defineRouteContract({ rows: z.array(tableRowSchema), insertedCount: z.number(), message: z.string(), + ignoredColumns: ignoredColumnsSchema, }) ), ]), @@ -1423,6 +1439,7 @@ export const upsertTableRowContract = defineRouteContract({ row: tableRowWireSchema, operation: z.enum(['insert', 'update']), message: z.string(), + ignoredColumns: ignoredColumnsSchema, }) ), }, @@ -1455,6 +1472,7 @@ export const updateTableRowContract = defineRouteContract({ z.object({ row: tableRowWireSchema, message: z.string(), + ignoredColumns: ignoredColumnsSchema, }) ), }, @@ -1489,6 +1507,7 @@ export const updateTableRowsByFilterContract = defineRouteContract({ message: z.string(), updatedCount: z.number(), updatedRowIds: z.array(z.string()).optional(), + ignoredColumns: ignoredColumnsSchema, }) ), }, diff --git a/apps/sim/lib/api/contracts/v1/admin/dashboard.ts b/apps/sim/lib/api/contracts/v1/admin/dashboard.ts index 55627b285fa..5b27a8e3e40 100644 --- a/apps/sim/lib/api/contracts/v1/admin/dashboard.ts +++ b/apps/sim/lib/api/contracts/v1/admin/dashboard.ts @@ -170,6 +170,8 @@ export const adminDashboardOrganizationDetailSchema = requestedReportingPeriodInterval: adminDashboardBillingIntervalSchema.nullable(), requestedReportingPeriodAnchorDate: adminDashboardDateOnlySchema.nullable(), requestedSeats: z.number().int().positive().nullable(), + requestedSelfServe: z.boolean().nullable(), + requestedSeatPriceUsd: z.number().positive().nullable(), requestedConcurrencyLimit: z .number() .int() @@ -187,6 +189,28 @@ export const adminDashboardOrganizationDetailSchema = error: z.string().nullable(), }) .nullable(), + /** Self-serve billing for an Enterprise contract; null for every other plan. */ + selfServe: z + .object({ + enabled: z.boolean(), + /** Rate for each seat past the contract, per seat per month. */ + seatPriceUsd: z.number().positive().nullable(), + /** The usage limit the customer chose, above the contract's included usage. */ + customerUsageLimitDollars: dollarAmountSchema.nullable(), + seatTrueUps: z.array( + z.object({ + windowStart: z.string(), + windowEnd: z.string(), + /** Most members past the contract seen while the window was open. */ + peakExtraSeats: z.number().int().min(0), + /** The seat rate the window opened with, per seat per month. */ + seatPriceUsd: z.number().positive(), + amountUsd: z.number().min(0).nullable(), + billedAt: z.string().nullable(), + }) + ), + }) + .nullable(), historicalActorUsage: z.object({ usedDollars: dollarAmountSchema, usedCredits: z.number().int().min(0), @@ -392,6 +416,18 @@ export const adminDashboardLimitsBodySchema = z { error: 'At least one limit must be provided' } ) +const adminDashboardSelfServeBodySchema = z + .object({ + enabled: z.boolean(), + /** Rate for each seat past the contract, per seat per month; required to enable. */ + seatPriceUsd: adminDashboardInvoiceAmountSchema.optional(), + /** Included usage per billing period, restated when the reporting interval differs. */ + usageLimitDollars: creditAlignedDollarAmountSchema.optional(), + }) + .refine((value) => !value.enabled || value.seatPriceUsd !== undefined, { + error: 'A seat price is required to enable self-serve', + }) + export const adminDashboardBalanceGrantBodySchema = z.object({ operationId: z.string().uuid(), amountDollars: positiveCreditAlignedDollarAmountSchema, @@ -921,6 +957,29 @@ export const adminDashboardUpdateLimitsContract = defineRouteContract({ }, }) +/** Turns an Enterprise contract's self-serve billing on (with its seat rate) or off. */ +export const adminDashboardUpdateSelfServeContract = defineRouteContract({ + method: 'PATCH', + path: '/api/v1/admin/dashboard/organizations/[id]/self-serve', + params: adminV1IdParamsSchema, + body: adminDashboardSelfServeBodySchema, + response: { + mode: 'json', + schema: adminV1SingleResponseSchema(adminDashboardMutationResultSchema), + }, +}) + +/** Returns a self-serve Enterprise contract from automatic payment to emailed invoices. */ +export const adminDashboardRevertToInvoicingContract = defineRouteContract({ + method: 'POST', + path: '/api/v1/admin/dashboard/organizations/[id]/invoice-payment', + params: adminV1IdParamsSchema, + response: { + mode: 'json', + schema: adminV1SingleResponseSchema(adminDashboardMutationResultSchema), + }, +}) + export const adminDashboardPreviewReportingPeriodContract = defineRouteContract({ method: 'POST', path: '/api/v1/admin/dashboard/organizations/[id]/reporting-period/preview', diff --git a/apps/sim/lib/api/contracts/v2/catalog.ts b/apps/sim/lib/api/contracts/v2/catalog.ts index 9d35456d248..7c8f2579743 100644 --- a/apps/sim/lib/api/contracts/v2/catalog.ts +++ b/apps/sim/lib/api/contracts/v2/catalog.ts @@ -303,11 +303,6 @@ export const v2BlockSummarySchema = z }) export type V2BlockSummary = z.output -const v2BlockOutputSchema = z.object({ - type: z.string().describe('Value type of the output.'), - description: z.string().optional().describe('What the output holds.'), -}) - /** Block-level input definition. */ const v2BlockInputDefinitionSchema = z.object({ type: z @@ -401,12 +396,27 @@ export const v2ToolOutputSchema = z }) export type V2ToolOutput = z.output +/** One declared output of a block, nesting the way a tool's output does. */ +const v2BlockOutputSchema = v2ToolOutputSchema.pick({ + type: true, + description: true, + properties: true, + items: true, +}) + const v2HostedApiKeySchema = z .enum(['always', 'conditional', 'none']) .describe( 'API-key hosting on this deployment: `always`, `conditional` for some parameter combinations, or `none` when Sim does not supply a key. Supply your own key only if the tool requires one. Self-hosted deployments report `none` for every tool.' ) +/** A tool's declared effect, shared by every catalog that names one. */ +export const v2ToolEffectSchema = z + .enum(['read', 'write']) + .describe( + "What running the tool does outside Sim. `read` changes nothing there: no create, update, delete, send, post, trigger, enqueue, consume, or mark-read; no asynchronous provider job or query execution started (one with its own id that can keep running, even briefly; a synchronous read-only query is fine); no run, conversation, history item, or other resource left in an account; no contact data revealed for credits; no external delivery. Usage billing for the call itself does not count. `write` is anything else, including an effect that depends on the input. Revealing a person's contact data (email, phone) for credits is `write`; company/firmographic lookups and verifications that only spend lookup credits are `read`." + ) + const v2ToolOAuthSchema = z.object({ required: z.boolean().describe('Whether the tool cannot run without an OAuth credential.'), provider: z.string().describe('OAuth service the credential must authenticate.'), @@ -420,6 +430,7 @@ export const v2ToolSummarySchema = z name: z.string().describe('Display name.'), description: z.string().describe('What the tool does.'), version: z.string().optional().describe('Tool version.'), + effect: v2ToolEffectSchema, hostedApiKey: v2HostedApiKeySchema, oauth: v2ToolOAuthSchema.optional().describe('OAuth requirement, when the tool has one.'), }) @@ -560,6 +571,7 @@ const v2OperationInputSchema = z const v2BlockOperationSchema = z.object({ toolId: z.string().optional().describe('Built-in tool that performs this operation.'), toolName: z.string().optional().describe('Display name of that tool.'), + effect: v2ToolEffectSchema.optional().describe("That tool's effect."), description: z.string().optional().describe('What the operation does.'), inputs: z .record(z.string(), v2OperationInputSchema) diff --git a/apps/sim/lib/api/contracts/v2/logs.ts b/apps/sim/lib/api/contracts/v2/logs.ts index e657a31519f..0ae94581507 100644 --- a/apps/sim/lib/api/contracts/v2/logs.ts +++ b/apps/sim/lib/api/contracts/v2/logs.ts @@ -248,6 +248,32 @@ export const v2LogDetailSchema = z .number() .nullable() .describe('Total execution duration in milliseconds, or null while unavailable.'), + /** + * Listed before `workflowState` and `traceSpans` on purpose: a reader scanning a long + * record for why the run failed finds it here instead of past the state dump. + */ + failure: z + .object({ + blockId: z.string().describe('Identifier of the block the run failed in.'), + blockName: z.string().describe('Name of the block the run failed in.'), + blockType: z.string().describe('Type of the block the run failed in.'), + error: z + .string() + .nullable() + .describe( + "The error the block recorded, or null when its span carries none (a withheld or compacted trace). A Function block's error leads with the line and code that threw." + ), + errorMessage: z + .string() + .nullable() + .describe( + "The failed block's declared `errorMessage` output (Function blocks today): the thrown message alone, which is the text to reply with. Null for any other block." + ), + }) + .nullable() + .describe( + 'Where the run failed, read from the trace: the innermost block whose error nothing handled. Null when the run did not fail, or the trace does not name one (not recorded, compacted, or withheld by a permission group).' + ), files: v2LogFilesSchema, /** * The identity the run acted as, captured by the run itself rather than read diff --git a/apps/sim/lib/api/contracts/v2/openapi/logs.ts b/apps/sim/lib/api/contracts/v2/openapi/logs.ts index eff693b0ad0..561f8a47ef8 100644 --- a/apps/sim/lib/api/contracts/v2/openapi/logs.ts +++ b/apps/sim/lib/api/contracts/v2/openapi/logs.ts @@ -64,6 +64,7 @@ const LOG_DETAIL_EXAMPLE = { startedAt: '2026-01-15T10:30:00.000Z', endedAt: '2026-01-15T10:30:01.250Z', totalDurationMs: 1250, + failure: null, files: LOG_LIST_EXAMPLE.data[0].files, /** * Deliberately a different address from `workflow.ownerEmail` below. This is diff --git a/apps/sim/lib/api/contracts/v2/openapi/resources.ts b/apps/sim/lib/api/contracts/v2/openapi/resources.ts index 703f8548d09..b1f2f399de9 100644 --- a/apps/sim/lib/api/contracts/v2/openapi/resources.ts +++ b/apps/sim/lib/api/contracts/v2/openapi/resources.ts @@ -162,6 +162,7 @@ const BLOCK_DETAIL_EXAMPLE = { send: { toolId: 'slack_message', toolName: 'Slack Send Message', + effect: 'write', description: 'Send a message to a Slack channel.', inputs: { text: { type: 'string', required: true, description: 'Message body.' } }, outputs: { ts: { type: 'string', description: 'Message timestamp.' } }, @@ -174,6 +175,7 @@ const BLOCK_DETAIL_EXAMPLE = { name: 'Slack Send Message', description: 'Send a message to a Slack channel.', version: '1.0.0', + effect: 'write', hostedApiKey: 'none', oauth: { required: true, provider: 'slack', requiredScopes: ['chat:write'] }, params: { text: { type: 'string', required: true, description: 'Message body.' } }, @@ -355,6 +357,7 @@ const TOOL_SUMMARY_EXAMPLE = { name: 'Slack Send Message', description: 'Send a message to a Slack channel.', version: '1.0.0', + effect: 'write', hostedApiKey: 'none', oauth: { required: true, provider: 'slack', requiredScopes: ['chat:write'] }, } as const diff --git a/apps/sim/lib/api/contracts/v2/openapi/source-resources.ts b/apps/sim/lib/api/contracts/v2/openapi/source-resources.ts index d7145cfba48..32e839a6206 100644 --- a/apps/sim/lib/api/contracts/v2/openapi/source-resources.ts +++ b/apps/sim/lib/api/contracts/v2/openapi/source-resources.ts @@ -36,7 +36,7 @@ const SOURCE_RESOURCES_EXAMPLE = { }, ], skills: [{ key: 'triage', id: 'skl_7e2a4c19', name: 'Triage' }], - customTools: [{ key: 'lookup-order', id: 'ctl_2b8d6f03', name: 'lookup_order' }], + customTools: [{ key: 'lookup-order', id: 'ctl_2b8d6f03', name: 'Lookup order' }], mcpServers: [ { key: 'github', id: 'mcp-1a2b3c4d', name: 'GitHub', tools: ['create_issue', 'list_issues'] }, ], diff --git a/apps/sim/lib/api/contracts/v2/openapi/workflows.ts b/apps/sim/lib/api/contracts/v2/openapi/workflows.ts index 2568f74eca0..32077cd08dc 100644 --- a/apps/sim/lib/api/contracts/v2/openapi/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/openapi/workflows.ts @@ -210,6 +210,7 @@ const RUN_RESULT_EXAMPLE = { startedAt: '2026-08-09T18:04:10.000Z', endedAt: '2026-08-09T18:04:11.000Z', durationMs: 1_000, + paused: null, }, } as const @@ -1590,7 +1591,7 @@ const declaredRoutes = [ operationId: 'resumeWorkflowRunV2', summary: 'Resume workflow run', description: - "Resume one human-in-the-loop pause with workspace write access, naming a `contextId` from the run's `paused.points`. The resumed attempt receives a new run ID and returns a synchronous result or queue receipt. A run that originally streamed resumes asynchronously through v2; this endpoint returns no SSE stream.", + "Resume one human-in-the-loop pause with workspace write access, naming a `contextId` from the run's `paused.points`. The resumed attempt receives a new run ID and returns a synchronous result or queue receipt; when it pauses again, `paused.runId` names the run to resume next. A run that originally streamed resumes asynchronously through v2; this endpoint returns no SSE stream.", errors: [...RESOURCE_ERRORS, 'UsageLimitExceeded', 'Conflict', 'PayloadTooLarge'], success: { byStatus: { diff --git a/apps/sim/lib/api/contracts/v2/source-catalog.ts b/apps/sim/lib/api/contracts/v2/source-catalog.ts index 78091e623d3..57a63b68c0f 100644 --- a/apps/sim/lib/api/contracts/v2/source-catalog.ts +++ b/apps/sim/lib/api/contracts/v2/source-catalog.ts @@ -1,6 +1,7 @@ import { z } from 'zod' import { workflowIdSchema, workspaceIdSchema } from '@/lib/api/contracts/primitives' import { defineRouteContract } from '@/lib/api/contracts/types' +import { v2ToolEffectSchema } from '@/lib/api/contracts/v2/catalog' import { v2DataResponse } from '@/lib/api/contracts/v2/shared' /** @@ -242,6 +243,10 @@ const catalogOutputSchema = z .optional() .describe('When the output is present: `{ field, value, not?, and? }`.'), hiddenFromDisplay: z.boolean().optional().describe('Hidden from the output picker.'), + mayBeText: z + .literal(true) + .optional() + .describe('A `json` or `any` output whose value can still be text at run time.'), properties: z .record(z.string(), z.unknown().describe('A nested output, of this same shape.')) .optional() @@ -339,6 +344,15 @@ const catalogBlockSchema = z ) .optional() .describe('Per operation id: the outputs its tool returns, where they differ.'), + effect: v2ToolEffectSchema + .optional() + .describe( + '`read` when every tool the block can run changes nothing outside Sim, else `write`. Absent for a block with no `tools.access`.' + ), + operationEffects: z + .record(z.string(), v2ToolEffectSchema) + .optional() + .describe("Per operation id: its tool's effect, where it differs from `effect`."), dynamicOutputs: z .object({ source: z @@ -348,6 +362,12 @@ const catalogBlockSchema = z }) .optional() .describe('Present when outputs derive from a param at run time.'), + errorOutputs: z + .array(z.string()) + .optional() + .describe( + 'Text outputs the block writes only when it fails into an error edge, beside `error`.' + ), graph: z .object({ canBeTarget: z.boolean().describe('Whether an edge may connect into the block.'), @@ -366,33 +386,6 @@ const catalogBlockSchema = z .describe('The field lifted into named branches.'), }) .describe('Edge rules for the block.'), - legacyIds: z - .array( - z - .object({ - from: z.string().describe('Legacy field id.'), - to: z.string().nullable().describe('Current field id, or null when removed.'), - whenOperation: z - .array(z.string()) - .optional() - .describe('Operations the rename applies to.'), - conditional: z.literal(true).optional().describe('Applies only to some values.'), - }) - .describe('One field id rename.') - ) - .optional() - .describe('Field id renames applied on load.'), - legacyCanonicalIds: z - .array( - z - .object({ - from: z.string().describe('Legacy pair id.'), - to: z.string().describe('Current pair id.'), - }) - .describe('One pair id rename.') - ) - .optional() - .describe('Basic/advanced pair id renames applied on load.'), paramAliases: z .object({ action: z.record(z.string(), z.string()).optional().describe('Action-surface aliases.'), diff --git a/apps/sim/lib/api/contracts/v2/tables.ts b/apps/sim/lib/api/contracts/v2/tables.ts index 00d945a085a..4362808bd9b 100644 --- a/apps/sim/lib/api/contracts/v2/tables.ts +++ b/apps/sim/lib/api/contracts/v2/tables.ts @@ -7,6 +7,7 @@ import { import { addWorkflowGroupBodySchema, archivedTableIdParamsSchema, + COLUMN_TYPES_HELP, cancelTableRunsBodyBaseSchema, columnNameSchema, columnTypeSchema, @@ -470,11 +471,25 @@ const v2TableColumnInputShape = { type: columnTypeSchema.describe('Column data type.'), required: z.boolean().optional().describe('Whether inserts must supply a value for this column.'), unique: z.boolean().optional().describe('Whether values in the column must be unique.'), - options: selectOptionsSchema.optional().describe('Select options for select-type columns.'), + options: selectOptionsSchema + .optional() + .describe('Select options for select-type columns, as [{"id":"open","name":"Open"}].'), multiple: z.boolean().optional().describe('Whether a select column accepts multiple values.'), currencyCode: currencyCodeSchema.optional().describe('ISO 4217 code for currency columns.'), } +/** + * Every field a column input accepts and what it means, read from the shape the server validates, + * so the help cannot name a field the server rejects or leave out one it takes. + */ +function describeColumnFields(shape: Record): string { + const fields = Object.entries(shape).map( + ([field, schema]) => + `${field}${schema.isOptional() ? '' : ' (required)'} - ${schema.description?.replace(/\.$/, '')}` + ) + return `Column fields: ${fields.join('; ')}.` +} + /** * Public column input. * @@ -517,7 +532,9 @@ export const v2CreateTableBodySchema = v1CreateTableBodySchema .describe('Initial table columns.'), }) .strict() - .describe('Initial table column definitions.'), + .describe( + `Initial table column definitions: {"columns":[{"name":"email","type":"string","required":true,"unique":true}]}. ${describeColumnFields(v2TableColumnInputShape)} ${COLUMN_TYPES_HELP}` + ), folderPath: v2FolderPathInputSchema.optional().describe('Folder in which to create the table.'), }) .strict() @@ -727,22 +744,26 @@ export const v2DeleteTableContract = defineRouteContract({ }, }) +const v2AddedColumnInputShape = { + ...v2TableColumnInputShape, + position: z + .number() + .int() + .min(0) + .optional() + .describe('Zero-based insertion position for the column.'), +} + export const v2CreateTableColumnBodySchema = z .object({ workspaceId: workspaceIdSchema.describe('Workspace that owns the table.'), column: z - .object({ - ...v2TableColumnInputShape, - position: z - .number() - .int() - .min(0) - .optional() - .describe('Zero-based insertion position for the column.'), - }) + .object(v2AddedColumnInputShape) .strict() .superRefine(refineColumnOptions) - .describe('Column definition to add.'), + .describe( + `Column definition to add: {"name":"status","type":"string"}. ${describeColumnFields(v2AddedColumnInputShape)} ${COLUMN_TYPES_HELP}` + ), }) .strict() diff --git a/apps/sim/lib/api/contracts/v2/workflows.ts b/apps/sim/lib/api/contracts/v2/workflows.ts index 48bd67376b9..29e3ded0daa 100644 --- a/apps/sim/lib/api/contracts/v2/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/workflows.ts @@ -86,6 +86,12 @@ export const v2WorkflowRunIdSchema = runIdSchema .describe('Unique workflow run identifier.') .meta({ examples: ['run_8f14e45f-ceea-467f-a'] }) +const v2PausedRunIdSchema = z + .string() + .describe( + 'Run to name in Resume workflow run: the run this pause is recorded under, which for a resumed run that paused again is the run it resumed.' + ) + /** * `X-Run-Id` reserves an execution ID without guaranteeing a retrievable run. * Claims can survive uncertain execution outcomes; a missing run does not make @@ -1597,6 +1603,17 @@ export const v2ExecutionErrorSchema = z .describe( 'Integration or block type that failed, when attributable. Present whenever `blockId` is.' ), + /** + * A run cannot start inside a loop or parallel, so a failure in one is rerun from the + * outermost container holding it. Execute reads containment from the graph the run + * executed; the run resource, which keeps no graph, from the saved draft a rerun runs. + */ + rerunFromBlockId: z + .string() + .optional() + .describe( + 'Block a rerun of this failure starts from (`run.entry` of type `block` naming it, with this run as `sourceRunId`): the failing block, or the outermost loop or parallel holding it, since a run cannot start inside one. Set by Execute workflow from the graph the run executed and by Get workflow run from the saved draft, whenever `blockId` is and that graph still has the block.' + ), }) .meta({ id: 'ExecutionError', @@ -1839,6 +1856,101 @@ const v2AppliedExecutionTimeoutSchema = z "Execution timeout applied to this run, in seconds: the plan's timeout, lowered by `executionTimeoutSeconds` when one was requested. Null when the run has no execution timeout." ) +const v2PauseInputFieldSchema = z + .object({ + name: z.string().describe('Key to supply this field under in the resume `input`.'), + label: z.string().describe('Display label for the field.'), + type: z.string().describe('Declared value type, such as `string`, `number`, or `boolean`.'), + description: z.string().optional().describe('Field help text, when configured.'), + placeholder: z.string().optional().describe('Placeholder text, when configured.'), + required: z.boolean().describe('Whether the field is marked required.'), + options: z + .array(z.unknown().describe('One selectable option.')) + .optional() + .describe('Selectable options, when the field offers a fixed set.'), + }) + .meta({ + id: 'WorkflowRunPauseInputField', + title: 'Pause input field', + description: 'One field a human pause asks the resumer to fill.', + }) + +const v2WorkflowRunPausePointSchema = z + .object({ + contextId: z + .string() + .describe('Pause context to name in `contextId` when resuming this point.'), + blockId: z.string().describe('Workflow block that paused.'), + blockName: z + .string() + .nullable() + .describe( + 'Name of the block as the run executed it. Null only for a point paused before names were recorded whose run was manual or whose deployment version no longer exists.' + ), + kind: z + .enum(['human', 'time']) + .describe('`human` waits for a resume request; `time` resumes automatically at `resumeAt`.'), + status: z + .enum(['paused', 'queued', 'resuming', 'resumed', 'failed']) + .describe( + 'Resume state of this point: waiting, queued behind another resume, resuming, resumed, or a failed resume attempt.' + ), + registeredAt: z + .string() + .nullable() + .describe( + 'ISO 8601 timestamp when the run paused at this point, or null for a point recorded without one.' + ) + .meta({ format: 'date-time' }), + resumeAt: z + .string() + .nullable() + .describe('ISO 8601 automatic-resume timestamp for a time pause, otherwise null.') + .meta({ format: 'date-time' }), + parallel: z + .object({ + parallelId: z.string().describe('Parallel block containing the pause.'), + branchIndex: z.number().int().describe('Zero-based branch that paused.'), + branchTotal: z + .number() + .int() + .nullable() + .describe('Number of branches, or null when unrecorded.'), + }) + .nullable() + .describe('Parallel branch of the pause, or null outside a parallel.'), + loop: z + .object({ + loopId: z.string().describe('Loop block containing the pause.'), + iteration: z.number().int().describe('Zero-based iteration that paused.'), + }) + .nullable() + .describe('Loop iteration of the pause, or null outside a loop.'), + inputFields: z + .array(v2PauseInputFieldSchema) + .nullable() + .describe( + 'Fields a human pause asks for, without default values. Labels and descriptions are resolved, so they are withheld when organization permission groups hide execution data. Null then, for a time pause, a pause with no declared form, fields over 64 KiB or not provably free of secrets, or one recorded before pause details were captured.' + ), + display: z + .unknown() + .describe('Reviewer content value.') + .nullable() + .describe( + "Content the pause presents to its reviewer, with the run's resolved secrets redacted. Null unless `includeOutput=true`, when hidden by organization permission groups, for a time pause, for content over 64 KiB or not provably free of secrets, or for a pause recorded before pause details were captured." + ), + queuePosition: z + .number() + .int() + .nullable() + .describe('Position among pending resume requests for this run, or null when none waits.'), + }) + .meta({ + id: 'WorkflowRunPausePoint', + title: 'Workflow run pause point', + description: 'One point at which a paused run waits.', + }) + /** * The run result resource. In-band run failures are `status: 'failed'` * with a structured `error` — never an HTTP error: **a `runId` means 200/202 + @@ -1874,6 +1986,17 @@ export const v2ExecuteWorkflowDataSchema = z .meta({ format: 'date-time' }), durationMs: z.number().nonnegative().optional().describe('Execution duration in milliseconds.'), executionTimeoutSeconds: v2AppliedExecutionTimeoutSchema, + paused: z + .object({ + runId: v2PausedRunIdSchema, + points: z + .array(v2WorkflowRunPausePointSchema.pick({ contextId: true, kind: true, status: true })) + .describe( + 'Every point the run is paused at. Resume one with Resume workflow run, naming `runId` and its `contextId`.' + ), + }) + .nullable() + .describe('Where the run waits when `status` is `paused`; null otherwise.'), }) .meta({ id: 'WorkflowRunResult', @@ -1968,6 +2091,12 @@ export type V2ResumeWorkflowQueued = z.output -const v2PauseInputFieldSchema = z - .object({ - name: z.string().describe('Key to supply this field under in the resume `input`.'), - label: z.string().describe('Display label for the field.'), - type: z.string().describe('Declared value type, such as `string`, `number`, or `boolean`.'), - description: z.string().optional().describe('Field help text, when configured.'), - placeholder: z.string().optional().describe('Placeholder text, when configured.'), - required: z.boolean().describe('Whether the field is marked required.'), - options: z - .array(z.unknown().describe('One selectable option.')) - .optional() - .describe('Selectable options, when the field offers a fixed set.'), - }) - .meta({ - id: 'WorkflowRunPauseInputField', - title: 'Pause input field', - description: 'One field a human pause asks the resumer to fill.', - }) - -const v2WorkflowRunPausePointSchema = z - .object({ - contextId: z - .string() - .describe('Pause context to name in `contextId` when resuming this point.'), - blockId: z.string().describe('Workflow block that paused.'), - blockName: z - .string() - .nullable() - .describe( - 'Name of the block as the run executed it. Null only for a point paused before names were recorded whose run was manual or whose deployment version no longer exists.' - ), - kind: z - .enum(['human', 'time']) - .describe('`human` waits for a resume request; `time` resumes automatically at `resumeAt`.'), - status: z - .enum(['paused', 'queued', 'resuming', 'resumed', 'failed']) - .describe( - 'Resume state of this point: waiting, queued behind another resume, resuming, resumed, or a failed resume attempt.' - ), - registeredAt: z - .string() - .nullable() - .describe( - 'ISO 8601 timestamp when the run paused at this point, or null for a point recorded without one.' - ) - .meta({ format: 'date-time' }), - resumeAt: z - .string() - .nullable() - .describe('ISO 8601 automatic-resume timestamp for a time pause, otherwise null.') - .meta({ format: 'date-time' }), - parallel: z - .object({ - parallelId: z.string().describe('Parallel block containing the pause.'), - branchIndex: z.number().int().describe('Zero-based branch that paused.'), - branchTotal: z - .number() - .int() - .nullable() - .describe('Number of branches, or null when unrecorded.'), - }) - .nullable() - .describe('Parallel branch of the pause, or null outside a parallel.'), - loop: z - .object({ - loopId: z.string().describe('Loop block containing the pause.'), - iteration: z.number().int().describe('Zero-based iteration that paused.'), - }) - .nullable() - .describe('Loop iteration of the pause, or null outside a loop.'), - inputFields: z - .array(v2PauseInputFieldSchema) - .nullable() - .describe( - 'Fields a human pause asks for, without default values. Labels and descriptions are resolved, so they are withheld when organization permission groups hide execution data. Null then, for a time pause, a pause with no declared form, fields over 64 KiB or not provably free of secrets, or one recorded before pause details were captured.' - ), - display: z - .unknown() - .describe('Reviewer content value.') - .nullable() - .describe( - "Content the pause presents to its reviewer, with the run's resolved secrets redacted. Null unless `includeOutput=true`, when hidden by organization permission groups, for a time pause, for content over 64 KiB or not provably free of secrets, or for a pause recorded before pause details were captured." - ), - queuePosition: z - .number() - .int() - .nullable() - .describe('Position among pending resume requests for this run, or null when none waits.'), - }) - .meta({ - id: 'WorkflowRunPausePoint', - title: 'Workflow run pause point', - description: 'One point at which a paused run waits.', - }) - /** * The polled run resource. `queued` is backfilled from the async job * queue before the worker writes the durable log row — v1's jobs endpoint 404 @@ -2314,6 +2348,7 @@ export const v2WorkflowRunStatusSchema = z paused: workflowExecutionPausedDetailSchema .omit({ pausedExecutionId: true }) .extend({ + runId: v2PausedRunIdSchema, points: z .array(v2WorkflowRunPausePointSchema) .describe( diff --git a/apps/sim/lib/api/contracts/v2/workspace-source.ts b/apps/sim/lib/api/contracts/v2/workspace-source.ts index a7785a09215..cbc1dbd005a 100644 --- a/apps/sim/lib/api/contracts/v2/workspace-source.ts +++ b/apps/sim/lib/api/contracts/v2/workspace-source.ts @@ -115,7 +115,7 @@ const baseResourceSchema = z z.string(), z.object({ id: z.string().describe('Stored id of the binary file.'), - rev: z.union([z.number().int(), z.string()]).describe('Content revision as last read.'), + rev: z.string().describe('Content revision as last read.'), sha256: sha256Schema, }) ) diff --git a/apps/sim/lib/api/contracts/workflow-source.ts b/apps/sim/lib/api/contracts/workflow-source.ts index c44227b4d8a..39f43eedae9 100644 --- a/apps/sim/lib/api/contracts/workflow-source.ts +++ b/apps/sim/lib/api/contracts/workflow-source.ts @@ -144,10 +144,7 @@ export function sourceFingerprintSchema(field: string) { } export const sourceBaseSchema = withExtensions({ - version: z - .literal(1) - .default(1) - .describe('Base format version; a base written before it existed reads as 1.'), + version: z.literal(1).describe('Base format version.'), workflowId: z .string() .min(1, 'base.workflowId cannot be empty') diff --git a/apps/sim/lib/api/contracts/workspaces.ts b/apps/sim/lib/api/contracts/workspaces.ts index abc9ab8a50e..36b4586ef60 100644 --- a/apps/sim/lib/api/contracts/workspaces.ts +++ b/apps/sim/lib/api/contracts/workspaces.ts @@ -273,6 +273,15 @@ export const deploymentShapeSchema = z.object({ * with app versions that predate projecting it; readers treat absent as `open`. */ registrationMode: z.enum(REGISTRATION_MODES).optional(), + /** + * Server-only switches the browser used to read from `NEXT_PUBLIC_*` twins. Optional + * for rolling compatibility with app versions that predate projecting them; readers + * treat absent as `false`. + */ + e2bEnabled: z.boolean().optional(), + slackExtendedScopes: z.boolean().optional(), + invitationsDisabled: z.boolean().optional(), + publicApiDisabled: z.boolean().optional(), }) export type DeploymentShape = z.output diff --git a/apps/sim/lib/api/mcp/generated/v2-operations.ts b/apps/sim/lib/api/mcp/generated/v2-operations.ts index 17226db8242..ee6a66d1b0f 100644 --- a/apps/sim/lib/api/mcp/generated/v2-operations.ts +++ b/apps/sim/lib/api/mcp/generated/v2-operations.ts @@ -2812,7 +2812,7 @@ export const V2_MCP_OPERATIONS = { contract: v2ResumeWorkflowContract, summary: 'Resume workflow run', description: - "Resume one human-in-the-loop pause with workspace write access, naming a `contextId` from the run's `paused.points`. The resumed attempt receives a new run ID and returns a synchronous result or queue receipt. A run that originally streamed resumes asynchronously through v2; this endpoint returns no SSE stream.\n\nOAuth scope: `api:write`.", + "Resume one human-in-the-loop pause with workspace write access, naming a `contextId` from the run's `paused.points`. The resumed attempt receives a new run ID and returns a synchronous result or queue receipt; when it pauses again, `paused.runId` names the run to resume next. A run that originally streamed resumes asynchronously through v2; this endpoint returns no SSE stream.\n\nOAuth scope: `api:write`.", handler: () => import('@/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route').then( (route) => route.POST diff --git a/apps/sim/lib/assistant-actions/application/context.ts b/apps/sim/lib/assistant-actions/application/context.ts index c25ec4b2958..4f50f3a6784 100644 --- a/apps/sim/lib/assistant-actions/application/context.ts +++ b/apps/sim/lib/assistant-actions/application/context.ts @@ -110,14 +110,14 @@ export async function resolveAssistantActionPolicy( scope, executor ) - const operation = tools.find((tool) => tool.toolId === input.toolId)?.config.assistant - if (!account.active || !operation || binding.credentialId !== scope.credentialId) + const tool = tools.find((entry) => entry.toolId === input.toolId)?.config + if (!account.active || !tool?.assistant || binding.credentialId !== scope.credentialId) throw new OrchestrationError( 'forbidden', 'This operation requires your active connected account.' ) const permissions = await loadAssistantToolPermissions(scope, executor) - const policy = resolveAssistantToolPolicy(permissions, input.toolId, operation) + const policy = resolveAssistantToolPolicy(permissions, input.toolId, tool.effect, tool.assistant) if (policy === 'block') throw new OrchestrationError('forbidden', 'This tool is blocked in your account permissions.') return { binding, policy: policy === 'allow' && !canAutoApprove ? ('ask' as const) : policy } diff --git a/apps/sim/lib/assistant-actions/application/tool-permissions.ts b/apps/sim/lib/assistant-actions/application/tool-permissions.ts index 7fa0b626d15..546295d6b39 100644 --- a/apps/sim/lib/assistant-actions/application/tool-permissions.ts +++ b/apps/sim/lib/assistant-actions/application/tool-permissions.ts @@ -53,9 +53,14 @@ export const readOrganizationToolPermissions = defineAuthorizedOrganizationUseCa toolId, name: config.name, description: config.description, - effect: config.assistant.effect, + effect: config.effect, version: config.assistant.version, - policy: resolveAssistantToolPolicy(permissions, toolId, config.assistant), + policy: resolveAssistantToolPolicy( + permissions, + toolId, + config.effect, + config.assistant + ), inherited: permissions.overrides[toolId] === undefined, }, ] @@ -113,11 +118,12 @@ export const updateOrganizationToolPermissions = defineAuthorizedOrganizationUse next[change.effect === 'read' ? 'readPolicy' : 'writePolicy'] = change.policy === 'allow' ? 'ask' : change.policy for (const toolId of Object.keys(next.overrides)) { - const operation = getToolMetadata(toolId)?.assistant - if (!operation || operation.effect === change.effect) delete next.overrides[toolId] + const metadata = getToolMetadata(toolId) + if (!metadata?.assistant || metadata.effect === change.effect) + delete next.overrides[toolId] } for (const tool of tools) { - if (tool.config.assistant?.effect !== change.effect) continue + if (!tool.config.assistant || tool.config.effect !== change.effect) continue if (change.policy === 'allow') next.overrides[tool.toolId] = { version: tool.config.assistant.version, diff --git a/apps/sim/lib/assistant-actions/tool-permissions.integration.ts b/apps/sim/lib/assistant-actions/tool-permissions.integration.ts index dd6c6a4b574..be98871d842 100644 --- a/apps/sim/lib/assistant-actions/tool-permissions.integration.ts +++ b/apps/sim/lib/assistant-actions/tool-permissions.integration.ts @@ -831,16 +831,19 @@ describe('organization Assistant tool permissions', () => { input: { ...input, revision: 0, change: { kind: 'group', effect: 'read', policy: 'allow' } }, }) const saved = await loadAssistantToolPermissions({ ...input, userId: ownerId }) - const operation = getToolMetadata('gmail_list_labels_v2')?.assistant - if (!operation) throw new Error('Fixture operation is unavailable') - expect(resolveAssistantToolPolicy(saved, 'gmail_list_labels_v2', operation)).toBe('allow') + const tool = getToolMetadata('gmail_list_labels_v2') + if (!tool?.assistant) throw new Error('Fixture operation is unavailable') expect( - resolveAssistantToolPolicy(saved, 'gmail_list_labels_v2', { - ...operation, - version: operation.version + 1, + resolveAssistantToolPolicy(saved, 'gmail_list_labels_v2', tool.effect, tool.assistant) + ).toBe('allow') + expect( + resolveAssistantToolPolicy(saved, 'gmail_list_labels_v2', tool.effect, { + version: tool.assistant.version + 1, }) ).toBe('ask') - expect(resolveAssistantToolPolicy(saved, 'future_operation', operation)).toBe('ask') + expect(resolveAssistantToolPolicy(saved, 'future_operation', tool.effect, tool.assistant)).toBe( + 'ask' + ) }) it.each(['ask', 'block'] as const)( diff --git a/apps/sim/lib/assistant-actions/tool-permissions.ts b/apps/sim/lib/assistant-actions/tool-permissions.ts index b78231065ee..f7048a3c780 100644 --- a/apps/sim/lib/assistant-actions/tool-permissions.ts +++ b/apps/sim/lib/assistant-actions/tool-permissions.ts @@ -15,7 +15,7 @@ import { sameResourceScopeCondition } from '@/lib/core/resource-scope.server' import { isManagedCredentialGroupBindingLive } from '@/lib/credential-groups/credentials' import { acquireAdvisoryXactLock, withLockTimeout } from '@/lib/db/advisory-locks' import type { DbOrTx, DbTransaction } from '@/lib/db/types' -import type { AssistantOperationMetadata } from '@/tools/types' +import type { AssistantOperationMetadata, ToolEffect } from '@/tools/types' /** One serialization point for settings changes and admission, including accounts with no saved preference. */ export async function lockAssistantToolPermissions( @@ -107,15 +107,16 @@ export async function loadAssistantToolPermissions( export function resolveAssistantToolPolicy( permissions: AssistantToolPermissions, toolId: string, - operation: AssistantOperationMetadata + effect: ToolEffect, + assistant: Pick ) { const override = permissions.overrides[toolId] if (override) { if (override.policy === 'block') return 'block' - if (override.version !== operation.version) return 'ask' + if (override.version !== assistant.version) return 'ask' return override.policy } - return operation.effect === 'read' ? permissions.readPolicy : permissions.writePolicy + return effect === 'read' ? permissions.readPolicy : permissions.writePolicy } /** Caller holds the account policy lock and has already checked the expected revision. */ diff --git a/apps/sim/lib/auth/auth.ts b/apps/sim/lib/auth/auth.ts index 53f6714c72a..159405ec3c6 100644 --- a/apps/sim/lib/auth/auth.ts +++ b/apps/sim/lib/auth/auth.ts @@ -108,14 +108,21 @@ import { getPlans, resolvePlanFromStripeSubscription, } from '@/lib/billing/plans' +import { + enforceOneTrialPerCard, + enforceOneTrialPerCardForCheckout, + getProTrialCheckoutParams, +} from '@/lib/billing/trial' import { syncSeatsFromStripeQuantity } from '@/lib/billing/validation/seat-management' import { handleAbandonedCheckout } from '@/lib/billing/webhooks/checkout' import { handleChargeDispute, handleDisputeClosed } from '@/lib/billing/webhooks/disputes' import { handleManualEnterpriseSubscription } from '@/lib/billing/webhooks/enterprise' +import { handleEnterpriseAutoPaySetup } from '@/lib/billing/webhooks/enterprise-auto-pay' import { handleInvoicePaymentFailed, handleInvoicePaymentSucceeded, } from '@/lib/billing/webhooks/invoices' +import { handleTrialWillEnd } from '@/lib/billing/webhooks/plan-notices' import { handleSubscriptionCreated, handleSubscriptionDeleted, @@ -1615,8 +1622,15 @@ export const auth = betterAuth({ requestedPlan ) }, - getCheckoutSessionParams: async () => ({ - params: { allow_promotion_codes: true }, + getCheckoutSessionParams: async ({ user, plan, subscription }) => ({ + params: { + allow_promotion_codes: true, + ...(await getProTrialCheckoutParams({ + userId: user.id, + referenceId: subscription.referenceId, + planName: plan.name, + })), + }, }), onSubscriptionComplete: async ({ event, @@ -1640,6 +1654,23 @@ export const auth = betterAuth({ status: subscription.status, }) + // The plugin swallows this hook's errors, so a failed check must not skip the rest of + // it; `onEvent` runs the check again on the retried checkout webhook. + const keptTrial = await enforceOneTrialPerCard( + stripeSubscription, + subscription + ).catch((error: unknown) => { + logger.error( + '[onSubscriptionComplete] Trial card check failed; retrying via onEvent', + { + subscriptionId: subscription.id, + error: toError(error).message, + } + ) + // Unconfirmed until the retry settles it, so the welcome email promises no trial. + return false + }) + if (!planFromStripe) { logUnresolvedStripePlan( 'onSubscriptionComplete', @@ -1704,11 +1735,18 @@ export const auth = betterAuth({ await handleSubscriptionCreated(resolvedSubscription, event.id) } - await syncSubscriptionUsageLimits(resolvedSubscription) + const billingInterval = isAnnual ? 'year' : 'month' + // The interval decides the included usage, so it is written before the limit sync. + await writeBillingInterval(resolvedSubscription.id, billingInterval) - await writeBillingInterval(resolvedSubscription.id, isAnnual ? 'year' : 'month') + await syncSubscriptionUsageLimits({ ...resolvedSubscription, billingInterval }) - await sendPlanWelcomeEmail(resolvedSubscription) + await sendPlanWelcomeEmail(resolvedSubscription, { + trialEnd: + keptTrial && stripeSubscription.trial_end + ? new Date(stripeSubscription.trial_end * 1000) + : null, + }) }, onSubscriptionUpdate: async ({ event, @@ -1881,10 +1919,19 @@ export const auth = betterAuth({ await handleSubscriptionUsageUpdate(event) break } + case 'checkout.session.completed': { + await enforceOneTrialPerCardForCheckout(event.data.object) + await handleEnterpriseAutoPaySetup(event.data.object) + break + } case 'checkout.session.expired': { await handleAbandonedCheckout(event) break } + case 'customer.subscription.trial_will_end': { + await handleTrialWillEnd(event.data.object) + break + } case 'charge.dispute.created': { await handleChargeDispute(event) break diff --git a/apps/sim/lib/billing/activity-rollup/enqueue.ts b/apps/sim/lib/billing/activity-rollup/enqueue.ts index 664c4c013b2..f06d8271b9d 100644 --- a/apps/sim/lib/billing/activity-rollup/enqueue.ts +++ b/apps/sim/lib/billing/activity-rollup/enqueue.ts @@ -1,5 +1,5 @@ import { type ScheduledPassResult, startScheduledPass } from '@/lib/core/async-jobs/scheduled-pass' -import { env } from '@/lib/core/config/env' +import { env, envNumber } from '@/lib/core/config/env' import { isFeatureEnabled } from '@/lib/core/config/feature-flags' import { isTriggerAvailable } from '@/lib/core/config/trigger-availability' import { createDetachedTouch } from '@/lib/core/utils/background' @@ -27,8 +27,11 @@ export async function runActivityRollupMaintenance(): Promise { const { runActivityRollupPass } = await import('@/lib/billing/activity-rollup/pass') await runActivityRollupPass({ budgetMs: ACTIVITY_ROLLUP_PASS_BUDGET_MS, - backfillRowsPerSecond: - env.ACTIVITY_ROLLUP_BACKFILL_ROWS_PER_SECOND ?? DEFAULT_BACKFILL_ROWS_PER_SECOND, + backfillRowsPerSecond: envNumber( + env.ACTIVITY_ROLLUP_BACKFILL_ROWS_PER_SECOND, + DEFAULT_BACKFILL_ROWS_PER_SECOND, + { min: 1, integer: true } + ), backfillMinGapMs: BACKFILL_MIN_GAP_MS, }) } diff --git a/apps/sim/lib/billing/application/member-usage-limits/use-cases.ts b/apps/sim/lib/billing/application/member-usage-limits/use-cases.ts index f24be27760b..b735cce0df4 100644 --- a/apps/sim/lib/billing/application/member-usage-limits/use-cases.ts +++ b/apps/sim/lib/billing/application/member-usage-limits/use-cases.ts @@ -3,7 +3,6 @@ import { db } from '@sim/db' import { createLogger } from '@sim/logger' import { memberUsageLimitOperations } from '@/lib/billing/application/member-usage-limits/operations' import { getOrganizationSubscription } from '@/lib/billing/core/billing' -import { resolveBillingInterval } from '@/lib/billing/core/subscription' import { creditsToDollars, dollarsToCredits } from '@/lib/billing/credits/conversion' import { getOrgMemberUsageForCurrentPeriod, @@ -12,6 +11,7 @@ import { setOrgMemberUsageLimit, } from '@/lib/billing/organizations/member-limits' import { acquireOrganizationUserMutationLocks } from '@/lib/billing/organizations/membership' +import { resolveBillingInterval } from '@/lib/billing/subscriptions/utils' import { defineAuthorizedOrganizationUseCase, type OrganizationUseCaseContext, diff --git a/apps/sim/lib/billing/application/organization-billing/enterprise-payment-method.ts b/apps/sim/lib/billing/application/organization-billing/enterprise-payment-method.ts new file mode 100644 index 00000000000..83f1047273e --- /dev/null +++ b/apps/sim/lib/billing/application/organization-billing/enterprise-payment-method.ts @@ -0,0 +1,132 @@ +import type Stripe from 'stripe' +import { AUTO_PAY_RETURN_PARAM } from '@/lib/api/contracts/organization' +import { defineAuthorizedOrganizationBillingUseCase } from '@/lib/billing/application/organization-billing/authorized-organization-billing-use-case' +import { organizationBillingOperations } from '@/lib/billing/application/organization-billing/operations' +import { getOrganizationSubscription } from '@/lib/billing/core/billing' +import { requireStripeClient } from '@/lib/billing/stripe-client' +import { isEnterpriseSelfServe } from '@/lib/billing/subscriptions/utils' +import { ENTERPRISE_AUTO_PAY_PURPOSE } from '@/lib/billing/webhooks/enterprise-auto-pay' +import { OrchestrationError } from '@/lib/core/orchestration/types' +import { getBaseUrl } from '@/lib/core/utils/urls' + +export interface EnterprisePaymentMethodInput { + organizationId: string +} + +export interface EnterprisePaymentMethodSummary { + /** `charge_automatically` once the customer has turned on auto-pay; else emailed invoices. */ + collectionMethod: 'charge_automatically' | 'send_invoice' + /** The method renewals, true-ups, and overage charge; null while the customer pays by invoice. */ + paymentMethod: { type: 'card' | 'us_bank_account' | 'other'; label: string } | null +} + +export interface StartEnterpriseAutoPayInput { + organizationId: string + /** Where Stripe returns the customer; must be on this deployment's origin. */ + returnUrl: string +} + +function withAutoPayReturnMarker(returnUrl: string): string { + const url = new URL(returnUrl) + url.searchParams.set(AUTO_PAY_RETURN_PARAM, 'true') + return url.toString() +} + +async function requireSelfServeEnterpriseSubscription(organizationId: string) { + const subscription = await getOrganizationSubscription(organizationId, { onError: 'throw' }) + if (!subscription || !isEnterpriseSelfServe(subscription)) { + throw new OrchestrationError( + 'forbidden', + 'Payment methods are managed by Sim for this organization. Contact your account team to make changes.' + ) + } + if (!subscription.stripeCustomerId || !subscription.stripeSubscriptionId) { + throw new OrchestrationError('conflict', 'This contract is not linked to Stripe yet') + } + return { + stripeCustomerId: subscription.stripeCustomerId, + stripeSubscriptionId: subscription.stripeSubscriptionId, + } +} + +/** Stripe's lowercase slugs (`american_express`, `link`) as a customer reads them. */ +function toDisplayName(slug: string): string { + return slug + .split('_') + .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) + .join(' ') +} + +function describePaymentMethod( + paymentMethod: string | Stripe.PaymentMethod | null +): EnterprisePaymentMethodSummary['paymentMethod'] { + if (!paymentMethod || typeof paymentMethod === 'string') return null + if (paymentMethod.type === 'card' && paymentMethod.card) { + const brand = toDisplayName(paymentMethod.card.display_brand ?? paymentMethod.card.brand) + return { type: 'card', label: `${brand} •••• ${paymentMethod.card.last4}` } + } + if (paymentMethod.type === 'us_bank_account' && paymentMethod.us_bank_account) { + const bank = paymentMethod.us_bank_account.bank_name ?? 'Bank account' + return { type: 'us_bank_account', label: `${bank} •••• ${paymentMethod.us_bank_account.last4}` } + } + return { type: 'other', label: toDisplayName(paymentMethod.type) } +} + +/** How a self-serve Enterprise contract pays: by emailed invoice, or automatically by a saved method. */ +export const getEnterprisePaymentMethod = defineAuthorizedOrganizationBillingUseCase({ + operation: organizationBillingOperations.read, + organizationId: (input: EnterprisePaymentMethodInput) => input.organizationId, + async execute({ context }): Promise { + const { stripeSubscriptionId } = await requireSelfServeEnterpriseSubscription( + context.organizationId + ) + const stripeSubscription = await requireStripeClient().subscriptions.retrieve( + stripeSubscriptionId, + { expand: ['default_payment_method'] } + ) + const autoPay = stripeSubscription.collection_method === 'charge_automatically' + return { + collectionMethod: autoPay ? 'charge_automatically' : 'send_invoice', + paymentMethod: autoPay + ? describePaymentMethod(stripeSubscription.default_payment_method) + : null, + } + }, +}) + +/** + * Opens Stripe's hosted page that saves a card or US bank account without charging it. The + * `checkout.session.completed` webhook then switches the contract to automatic payment. + */ +export const startEnterpriseAutoPaySetup = defineAuthorizedOrganizationBillingUseCase({ + operation: organizationBillingOperations.managePaymentMethod, + organizationId: (input: StartEnterpriseAutoPayInput) => input.organizationId, + async execute({ input, context }): Promise<{ url: string }> { + if (new URL(input.returnUrl).origin !== new URL(getBaseUrl()).origin) { + throw new OrchestrationError('validation', 'Return URL must be on this site') + } + const { stripeCustomerId, stripeSubscriptionId } = await requireSelfServeEnterpriseSubscription( + context.organizationId + ) + const metadata = { + purpose: ENTERPRISE_AUTO_PAY_PURPOSE, + organizationId: context.organizationId, + stripeSubscriptionId, + requestedByUserId: context.actorUserId, + } + const session = await requireStripeClient().checkout.sessions.create({ + mode: 'setup', + customer: stripeCustomerId, + currency: 'usd', + payment_method_types: ['card', 'us_bank_account'], + // Instant verification keeps the switch to auto-pay synchronous with the session. + payment_method_options: { us_bank_account: { verification_method: 'instant' } }, + success_url: withAutoPayReturnMarker(input.returnUrl), + cancel_url: input.returnUrl, + metadata, + setup_intent_data: { metadata }, + }) + if (!session.url) throw new OrchestrationError('internal', 'Stripe did not return a setup URL') + return { url: session.url } + }, +}) diff --git a/apps/sim/lib/billing/application/organization-billing/get-organization-billing-summary.ts b/apps/sim/lib/billing/application/organization-billing/get-organization-billing-summary.ts index e3c18d1e2b6..2a70b34f3d7 100644 --- a/apps/sim/lib/billing/application/organization-billing/get-organization-billing-summary.ts +++ b/apps/sim/lib/billing/application/organization-billing/get-organization-billing-summary.ts @@ -1,19 +1,30 @@ import { db, dbReplica } from '@sim/db' -import { organization, subscription as subscriptionTable } from '@sim/db/schema' -import { desc, eq } from 'drizzle-orm' +import { + enterpriseSeatTrueUp, + organization, + subscription as subscriptionTable, +} from '@sim/db/schema' +import { and, desc, eq, gt, isNull } from 'drizzle-orm' import { defineAuthorizedOrganizationBillingUseCase } from '@/lib/billing/application/organization-billing/authorized-organization-billing-use-case' import { organizationBillingOperations } from '@/lib/billing/application/organization-billing/operations' -import { getOrganizationSubscription, getPlanPricing } from '@/lib/billing/core/billing' +import { getOrganizationSubscription } from '@/lib/billing/core/billing' import { getOrganizationBillingBlockState, getUpgradeWorkspaceId, } from '@/lib/billing/core/payer-context' import { resolveSubscriptionUsagePeriodOrDefault } from '@/lib/billing/core/reporting-period' -import { resolveBillingInterval } from '@/lib/billing/core/subscription' import { getBillingPeriodUsageCost } from '@/lib/billing/core/usage-log' import { computeWeeklyRefreshConsumed } from '@/lib/billing/credits/weekly-refresh' -import { getPlanWeeklyRefreshDollars, isEnterprise, isPaid } from '@/lib/billing/plan-helpers' -import { getEffectiveSeats } from '@/lib/billing/subscriptions/utils' +import { isPaid } from '@/lib/billing/plan-helpers' +import { + type EnterpriseSelfServeTerms, + getEffectiveSeats, + getEnterpriseSelfServeTerms, + getOrgIncludedUsageDollars, + getSubscriptionWeeklyRefreshDollars, + isHardCappedEnterprise, + resolveBillingInterval, +} from '@/lib/billing/subscriptions/utils' import { toDecimal, toNumber } from '@/lib/billing/utils/decimal' import { OrchestrationError } from '@/lib/core/orchestration/types' @@ -39,6 +50,37 @@ export interface OrganizationBillingSummaryResult { blockedByOrgOwner: boolean upgradeWorkspaceId: string | null userRole: 'admin' | 'owner' + /** The contract terms when the organization's Enterprise contract is self-serve, else null. */ + enterpriseSelfServe: + | (EnterpriseSelfServeTerms & { + /** The most seats past the contract so far in the open true-up window. */ + peakExtraSeats: number + }) + | null +} + +/** + * The open true-up window's peak seats past the contract and the rate it bills them at, or null + * before its first sample. + */ +async function getOpenTrueUpWindow(subscriptionId: string) { + const [window] = await dbReplica + .select({ + peakExtraSeats: enterpriseSeatTrueUp.peakExtraSeats, + seatPriceCents: enterpriseSeatTrueUp.seatPriceCents, + }) + .from(enterpriseSeatTrueUp) + .where( + and( + eq(enterpriseSeatTrueUp.subscriptionId, subscriptionId), + isNull(enterpriseSeatTrueUp.billedAt), + // A closed window awaiting the hourly sweep is not the open one. + gt(enterpriseSeatTrueUp.windowEnd, new Date()) + ) + ) + .orderBy(desc(enterpriseSeatTrueUp.windowStart)) + .limit(1) + return window ?? null } function roundCurrency(value: number): number { @@ -105,7 +147,7 @@ export const getOrganizationBillingSummary = defineAuthorizedOrganizationBilling ? resolveSubscriptionUsagePeriodOrDefault(entitledSubscription) : null - const weeklyRefreshDollars = getPlanWeeklyRefreshDollars(entitledSubscription?.plan) + const weeklyRefreshDollars = getSubscriptionWeeklyRefreshDollars(entitledSubscription) const [ledgerUsage, weeklyRefreshConsumed] = billingPeriod ? await Promise.all([ getBillingPeriodUsageCost( @@ -130,19 +172,32 @@ export const getOrganizationBillingSummary = defineAuthorizedOrganizationBilling : [0, 0] const totalCurrentUsage = Math.max(0, ledgerUsage - weeklyRefreshConsumed) - const { basePrice: pricePerSeat } = getPlanPricing(entitledSubscription?.plan ?? 'free') - const licensedSeats = entitledSubscription?.seats || 1 const totalSeats = entitledSubscription ? getEffectiveSeats(entitledSubscription) : 0 const configuredLimit = entitledSubscription && organizationRecord.orgUsageLimit ? toNumber(toDecimal(organizationRecord.orgUsageLimit)) : null - const minimumBillingAmount = - entitledSubscription && isEnterprise(entitledSubscription.plan) + const selfServeTerms = entitledSubscription + ? getEnterpriseSelfServeTerms(entitledSubscription) + : null + const openWindow = + entitledSubscription && selfServeTerms + ? await getOpenTrueUpWindow(entitledSubscription.id) + : null + // The open window bills at the rate it opened with, which a mid-window change does not move. + const enterpriseSelfServe = selfServeTerms + ? { + ...selfServeTerms, + seatPriceCents: openWindow?.seatPriceCents ?? selfServeTerms.seatPriceCents, + peakExtraSeats: openWindow?.peakExtraSeats ?? 0, + } + : null + // A hard-capped Enterprise contract includes exactly its configured limit. + const minimumBillingAmount = !entitledSubscription + ? 0 + : isHardCappedEnterprise(entitledSubscription) ? (configuredLimit ?? 0) - : entitledSubscription - ? licensedSeats * pricePerSeat - : 0 + : getOrgIncludedUsageDollars(entitledSubscription) const totalUsageLimit = configuredLimit === null ? minimumBillingAmount @@ -164,6 +219,7 @@ export const getOrganizationBillingSummary = defineAuthorizedOrganizationBilling ...billingStatus, upgradeWorkspaceId, userRole, + enterpriseSelfServe, } }, }) diff --git a/apps/sim/lib/billing/application/organization-billing/get-organization-plan-seats.ts b/apps/sim/lib/billing/application/organization-billing/get-organization-plan-seats.ts index b694470be52..0bf7c57c22b 100644 --- a/apps/sim/lib/billing/application/organization-billing/get-organization-plan-seats.ts +++ b/apps/sim/lib/billing/application/organization-billing/get-organization-plan-seats.ts @@ -7,7 +7,8 @@ import { getOrganizationSubscription } from '@/lib/billing/core/billing' import { isOrganizationOnEnterprisePlan } from '@/lib/billing/core/subscription' import { countPendingSeatInvitations, - resolveSeatCapacity, + resolveSeatCap, + type SeatCapKind, } from '@/lib/billing/validation/seat-management' import { OrchestrationError } from '@/lib/core/orchestration/types' @@ -23,6 +24,8 @@ interface OrganizationPlanSeatsResult { usedSeats: number membersTotal: number hasEnterprisePlan: boolean + /** How `totalSeats` bounds membership; only `fixed` refuses members past it. */ + seatCapKind: SeatCapKind | null } /** Primary-backed plan, feature access, and seat reservations, independent of usage analytics. */ @@ -45,14 +48,16 @@ export const getOrganizationPlanSeats = defineAuthorizedOrganizationBillingUseCa ]) if (!organizations[0]) throw new OrchestrationError('not_found', 'Organization not found') const membersTotal = memberCounts[0]?.total ?? 0 + const seatCap = subscription ? await resolveSeatCap(subscription, db) : null return { organizationId, subscriptionPlan: subscription?.plan ?? null, subscriptionStatus: subscription?.status ?? null, - totalSeats: subscription ? await resolveSeatCapacity(subscription, db) : 0, + totalSeats: seatCap?.seats ?? 0, usedSeats: membersTotal + pendingSeats, membersTotal, hasEnterprisePlan, + seatCapKind: seatCap?.kind ?? null, } }, }) diff --git a/apps/sim/lib/billing/application/organization-billing/operations.ts b/apps/sim/lib/billing/application/organization-billing/operations.ts index 8bf46e97c15..4327808521d 100644 --- a/apps/sim/lib/billing/application/organization-billing/operations.ts +++ b/apps/sim/lib/billing/application/organization-billing/operations.ts @@ -35,6 +35,14 @@ export const organizationBillingOperations = { principalKinds: ['session', 'organization_delegated'], capability: 'none', }), + // permission-group-exempt: saving the organization's payment method requires current organization administrator authority. + managePaymentMethod: defineOrganizationBillingOperation({ + id: 'organization_billing.payment_method.manage', + organizationRoles: ['admin', 'owner'], + workspaceApiKey: 'deny', + principalKinds: ['session', 'organization_delegated'], + capability: 'none', + }), // permission-group-exempt: an organization-admin surface — admins and owners sit above every group, and no group key names organization billing read: defineOrganizationBillingOperation({ id: 'organization_billing.summary.read', diff --git a/apps/sim/lib/billing/application/organization-usage/get-organization-usage-breakdown.test.ts b/apps/sim/lib/billing/application/organization-usage/get-organization-usage-breakdown.test.ts new file mode 100644 index 00000000000..55e681ad2ae --- /dev/null +++ b/apps/sim/lib/billing/application/organization-usage/get-organization-usage-breakdown.test.ts @@ -0,0 +1,60 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { mockReadUsageGroups, mockReadUsageEntities } = vi.hoisted(() => ({ + mockReadUsageGroups: vi.fn(), + mockReadUsageEntities: vi.fn(), +})) + +vi.mock('@/lib/billing/core/usage-analytics-queries', () => ({ + readUsageGroups: mockReadUsageGroups, + readUsageEntities: mockReadUsageEntities, +})) + +import { buildUsageBreakdown } from '@/lib/billing/application/organization-usage/get-organization-usage-breakdown' +import type { UsageBreakdownDimension } from '@/lib/billing/core/usage-analytics' + +function breakdown(dimension: UsageBreakdownDimension) { + return buildUsageBreakdown({ + entity: { type: 'organization', id: 'org-1' }, + window: { kind: 'range', from: new Date('2026-01-01'), to: new Date('2026-01-08') }, + timezone: 'UTC', + dimension, + limit: 10, + }) +} + +describe('buildUsageBreakdown model attribution', () => { + beforeEach(() => { + mockReadUsageEntities.mockResolvedValue(new Map()) + }) + + it('marks a sim-auto model row as Auto, never as an Ollama model', async () => { + mockReadUsageGroups.mockResolvedValue([ + { key: 'sim-auto', cost: 2, events: 2 }, + { key: 'claude-sonnet-5-5', cost: 1, events: 1 }, + { key: 'llama3.1:8b', cost: 0.5, events: 1 }, + ]) + + const { rows } = await breakdown('model') + + expect(rows.map(({ id, label, providerId }) => ({ id, label, providerId }))).toEqual([ + { id: 'sim-auto', label: 'Auto', providerId: 'sim-auto' }, + { id: 'claude-sonnet-5-5', label: 'claude-sonnet-5-5', providerId: 'anthropic' }, + { id: 'llama3.1:8b', label: 'llama3.1:8b', providerId: 'ollama' }, + ]) + }) + + it('keeps BYOK sim-auto usage as its own Auto row rather than merging it into Ollama', async () => { + mockReadUsageGroups.mockResolvedValue([ + { key: 'sim-auto', cost: 0, events: 1, inputTokens: 100, outputTokens: 50 }, + { key: 'ollama/llama3', cost: 0, events: 1, inputTokens: 10, outputTokens: 5 }, + ]) + + const { rows } = await breakdown('byok') + + expect(rows.map(({ id, label, tokens }) => ({ id, label, tokens }))).toEqual([ + { id: 'sim-auto', label: 'Auto', tokens: 150 }, + { id: 'ollama', label: 'Ollama', tokens: 15 }, + ]) + }) +}) diff --git a/apps/sim/lib/billing/application/organization-usage/get-organization-usage-breakdown.ts b/apps/sim/lib/billing/application/organization-usage/get-organization-usage-breakdown.ts index a1fe99c2a12..34118d7a233 100644 --- a/apps/sim/lib/billing/application/organization-usage/get-organization-usage-breakdown.ts +++ b/apps/sim/lib/billing/application/organization-usage/get-organization-usage-breakdown.ts @@ -27,7 +27,12 @@ import { type InternalUsageLogSource, toBillingUsageLogSource, } from '@/lib/billing/usage-sources' -import { getProviderFromModel, PROVIDER_DEFINITIONS } from '@/providers/models' +import { + getProviderFromModel, + isAutoModel, + PROVIDER_DEFINITIONS, + SIM_AUTO_MODEL_ID, +} from '@/providers/models' export interface OrganizationUsageBreakdownInput { organizationId: string @@ -66,7 +71,9 @@ export interface OrganizationUsageBreakdownResult { /** Entity-backed dimensions need a second lookup to turn ids into names. */ const NAMED_DIMENSIONS = new Set(['member', 'workspace', 'workflow']) -/** Provider ids that read better with their conventional casing. */ +/** How the usage panel names sim-auto, in the model and BYOK dimensions alike. */ +const SIM_AUTO_LABEL = 'Auto' + /** * The registry's own display name, not a second hand-written table. * @@ -75,9 +82,19 @@ const NAMED_DIMENSIONS = new Set(['member', 'workspace' * module, so reading the registry costs nothing a client bundle would pay for. */ function providerLabel(providerId: string): string { + if (providerId === SIM_AUTO_MODEL_ID) return SIM_AUTO_LABEL return PROVIDER_DEFINITIONS[providerId]?.name ?? providerId } +/** + * The provider a model's usage is attributed to, for its mark in the model dimension and its + * row in the BYOK dimension. sim-auto has no provider of its own, so it keeps its own key + * instead of the registry's Ollama default. + */ +function usageProviderId(model: string): string { + return isAutoModel(model) ? SIM_AUTO_MODEL_ID : getProviderFromModel(model) +} + interface BuildUsageBreakdownArgs { entity: BillingEntity window: UsageAnalyticsWindow @@ -130,7 +147,7 @@ export async function buildUsageBreakdown({ key ? toBillingUsageLogSource(key as InternalUsageLogSource) : null ) : dimension === 'byok' - ? mergeRowsByKey(raw, (key) => (key ? getProviderFromModel(key) : null)) + ? mergeRowsByKey(raw, (key) => (key ? usageProviderId(key) : null)) : raw const totalCost = rows.reduce((sum, row) => sum + row.cost, 0) @@ -159,7 +176,7 @@ export async function buildUsageBreakdown({ return BILLING_USAGE_LOG_SOURCE_LABELS[key as keyof typeof BILLING_USAGE_LOG_SOURCE_LABELS] } if (dimension === 'byok') return providerLabel(key) - if (dimension === 'model') return key + if (dimension === 'model') return isAutoModel(key) ? SIM_AUTO_LABEL : key // Retain the id if its name is unavailable, including stale cached attribution. return entities.get(key)?.name ?? key } @@ -202,7 +219,7 @@ export async function buildUsageBreakdown({ share: row.share, ...(isModelDimension && tokens > 0 ? { tokens } : {}), ...(dimension === 'byok' ? { providerId: row.id } : {}), - ...(dimension === 'model' && row.id ? { providerId: getProviderFromModel(row.id) } : {}), + ...(dimension === 'model' && row.id ? { providerId: usageProviderId(row.id) } : {}), ...(image ? { image } : {}), } }), diff --git a/apps/sim/lib/billing/application/organization-usage/get-organization-usage-overview.ts b/apps/sim/lib/billing/application/organization-usage/get-organization-usage-overview.ts index 1bf27d61765..381ed28699d 100644 --- a/apps/sim/lib/billing/application/organization-usage/get-organization-usage-overview.ts +++ b/apps/sim/lib/billing/application/organization-usage/get-organization-usage-overview.ts @@ -95,12 +95,7 @@ export const getOrganizationUsageOverview = defineAuthorizedOrganizationUsageUse limit: ORGANIZATION_USAGE_OVERVIEW_ROW_LIMIT, }), subscription - ? getOrgUsageLimit( - input.organizationId, - subscription.plan, - subscription.seats ?? null, - dbReplica - ) + ? getOrgUsageLimit(input.organizationId, subscription, dbReplica) : Promise.resolve(null), ]) diff --git a/apps/sim/lib/billing/application/pro-trial.ts b/apps/sim/lib/billing/application/pro-trial.ts new file mode 100644 index 00000000000..b00a030b23d --- /dev/null +++ b/apps/sim/lib/billing/application/pro-trial.ts @@ -0,0 +1,54 @@ +import { getHighestPriorityPersonalSubscription } from '@/lib/billing/core/plan' +import { requireStripeClient } from '@/lib/billing/stripe-client' +import { isTrialingSubscription } from '@/lib/billing/subscriptions/utils' +import { assertOperationCapability, type OperationUseCase } from '@/lib/core/application' +import { OrchestrationError } from '@/lib/core/orchestration/types' +import type { UserAccountOperation } from '@/lib/users/application/operations' +import { authorizeAccountPreferences } from '@/lib/users/application/preferences-authorization' + +/** Session-only: ending a trial charges the account's own card, so no delegation may do it. */ +function defineProTrialOperation(id: Id) { + const operation = { + id, + capability: 'none', + principalKinds: Object.freeze(['session'] as const), + } satisfies UserAccountOperation + assertOperationCapability(operation) + return Object.freeze(operation) +} + +export const proTrialOperations = { + // permission-group-exempt: ending your own personal trial is an account act, not a workspace act. + end: defineProTrialOperation('billing.trial.end'), +} as const + +/** + * Ends the caller's own Pro free trial now. Stripe charges the card for the first paid period, + * and the subscription webhooks replace the trial allowance with the plan's. Only the account's + * own trialing personal subscription qualifies; nobody else's trial can be ended this way. + */ +export const endProTrial: OperationUseCase< + typeof proTrialOperations.end, + Record, + { success: true } +> = { + operation: proTrialOperations.end, + async execute({ principal }) { + const userId = await authorizeAccountPreferences(principal, proTrialOperations.end) + const subscription = await getHighestPriorityPersonalSubscription(userId, { onError: 'throw' }) + if ( + !subscription || + subscription.referenceId !== userId || + !isTrialingSubscription(subscription) || + !subscription.stripeSubscriptionId + ) { + throw new OrchestrationError('conflict', 'There is no free trial to end on this account') + } + await requireStripeClient().subscriptions.update( + subscription.stripeSubscriptionId, + { trial_end: 'now' }, + { idempotencyKey: `end-trial-early:${subscription.stripeSubscriptionId}` } + ) + return { success: true } + }, +} diff --git a/apps/sim/lib/billing/calculations/usage-monitor.ts b/apps/sim/lib/billing/calculations/usage-monitor.ts index b27f6226456..5da2a94cd76 100644 --- a/apps/sim/lib/billing/calculations/usage-monitor.ts +++ b/apps/sim/lib/billing/calculations/usage-monitor.ts @@ -22,8 +22,11 @@ import { getOrgMemberUsageForBillingPeriod, getOrgMemberUsageLimit, } from '@/lib/billing/organizations/member-limits' -import { getPlanWeeklyRefreshDollars, isPaid } from '@/lib/billing/plan-helpers' -import { isOrgScopedSubscription } from '@/lib/billing/subscriptions/utils' +import { isPaid } from '@/lib/billing/plan-helpers' +import { + getSubscriptionWeeklyRefreshDollars, + isOrgScopedSubscription, +} from '@/lib/billing/subscriptions/utils' import { isBillingEnabled, isHosted } from '@/lib/core/config/env-flags' const logger = createLogger('UsageMonitor') @@ -73,7 +76,7 @@ async function computePooledOrgUsage( return readSoftGateUsageCost({ type: 'organization', id: organizationId }, billingPeriod) } - const weeklyRefreshDollars = getPlanWeeklyRefreshDollars(sub.plan) + const weeklyRefreshDollars = getSubscriptionWeeklyRefreshDollars(sub) if (weeklyRefreshDollars <= 0) { return readSoftGateUsageCost({ type: 'organization', id: organizationId }, billingPeriod) } @@ -148,7 +151,7 @@ export async function checkUsageStatus( let refreshConsumed = 0 let appliedWeeklyRefresh = false if (sub && isPaid(sub.plan) && sub.periodStart) { - const weeklyRefreshDollars = getPlanWeeklyRefreshDollars(sub.plan) + const weeklyRefreshDollars = getSubscriptionWeeklyRefreshDollars(sub) if (weeklyRefreshDollars > 0) { const usage = await computeBillingPeriodUsageWithWeeklyRefresh({ billingEntity: { type: 'user', id: userId }, diff --git a/apps/sim/lib/billing/chat-plan.ts b/apps/sim/lib/billing/chat-plan.ts index 2b87add362f..3c960688fc4 100644 --- a/apps/sim/lib/billing/chat-plan.ts +++ b/apps/sim/lib/billing/chat-plan.ts @@ -1,3 +1,5 @@ +import { PRO_TRIAL_DAYS } from '@/lib/billing/constants' + /** The upgrade card's `reason` for a payer whose plan does not include Chat. */ export const CHAT_PLAN_REQUIRED_REASON = 'plan_required' as const @@ -10,5 +12,5 @@ export const CHAT_PLAN_REQUIRED_REASON = 'plan_required' as const export const CHAT_PLAN_REQUIRED_UPGRADE = { reason: CHAT_PLAN_REQUIRED_REASON, action: 'upgrade_plan', - message: 'Chat is included on paid plans. Upgrade your plan to talk to Sim.', + message: `Chat is included on paid plans, and Pro starts with a ${PRO_TRIAL_DAYS}-day free trial for new subscribers. Upgrade your plan to talk to Sim.`, } as const diff --git a/apps/sim/lib/billing/constants.ts b/apps/sim/lib/billing/constants.ts index a3db9fe9acf..497cea3f57f 100644 --- a/apps/sim/lib/billing/constants.ts +++ b/apps/sim/lib/billing/constants.ts @@ -17,6 +17,19 @@ export const DEFAULT_PRO_TIER_COST_LIMIT = 20 export const DEFAULT_TEAM_TIER_COST_LIMIT = 40 export const DEFAULT_ENTERPRISE_TIER_COST_LIMIT = 200 +/** + * Length of the Pro free trial a new subscriber gets at checkout. Stripe collects a card up front + * and charges it when the trial ends unless the subscriber cancels first. + */ +export const PRO_TRIAL_DAYS = 14 + +/** + * Usage a Pro trial may spend, in dollars (2,000 credits). A trial holds this fixed cap instead of + * the plan's included credits, with no weekly refresh and no on-demand usage, so a trial costs at + * most this much before the subscriber pays. + */ +export const PRO_TRIAL_USAGE_LIMIT_DOLLARS = 10 + /** * Base charge applied to every workflow execution * This charge is applied regardless of whether the workflow uses AI models @@ -93,7 +106,8 @@ export const CREDITS_PER_DOLLAR = 200 /** * Annual subscribers pay 15% less than the equivalent monthly plan - * but receive the same included credits. The Stripe annual price is + * but receive the same included credits: twelve months of them for the yearly + * billing period (see `getPlanPricing`). The Stripe annual price is * `monthlyDollars * 12 * (1 - ANNUAL_DISCOUNT_RATE)`. */ export const ANNUAL_DISCOUNT_RATE = 0.15 @@ -107,3 +121,9 @@ export const ON_DEMAND_UNLIMITED = 999999 /** Shown when usage could not be read, instead of a limit the read never measured. */ export const USAGE_UNAVAILABLE_MESSAGE = 'Usage could not be verified right now. Please try again in a moment.' + +/** + * Payment terms, in days, for every invoice emailed to a customer who pays by invoice: Enterprise + * contracts, and the overage, true-up, and final invoices billed on top of them. + */ +export const INVOICE_DAYS_UNTIL_DUE = 30 diff --git a/apps/sim/lib/billing/core/attribution.ts b/apps/sim/lib/billing/core/attribution.ts index e25dbcbb0f8..5f98d68a00b 100644 --- a/apps/sim/lib/billing/core/attribution.ts +++ b/apps/sim/lib/billing/core/attribution.ts @@ -106,6 +106,12 @@ export interface AccountBillingDecision { * verdict judges the payer's current one, so the limit can only be under-enforced. */ readonly payerSubscriptionId?: string + /** + * Whether the payer's spend past its limit is billed as overage at admission + * (`billsOverage`): false for the free plan and a trial, whose limit is a hard cap. + * Absent in decisions minted before it existed, which judge by `payerSubscriptionId` alone. + */ + readonly payerBillsOverage?: boolean } export interface ResolveBillingAttributionParams { @@ -574,6 +580,10 @@ function assertAccountBillingDecision(value: unknown): AccountBillingDecision { if (payerSubscriptionId !== undefined && !isNonEmptyString(payerSubscriptionId)) { throw new Error('Account billing decision must contain a valid payer subscription ID') } + const payerBillsOverage = value.payerBillsOverage + if (payerBillsOverage !== undefined && typeof payerBillsOverage !== 'boolean') { + throw new Error('Account billing decision must contain a valid overage flag') + } return Object.freeze({ userId: value.userId, @@ -587,6 +597,7 @@ function assertAccountBillingDecision(value: unknown): AccountBillingDecision { ...(source !== undefined ? { source } : {}), }), ...(payerSubscriptionId !== undefined ? { payerSubscriptionId } : {}), + ...(payerBillsOverage !== undefined ? { payerBillsOverage } : {}), }) } diff --git a/apps/sim/lib/billing/core/billing.test.ts b/apps/sim/lib/billing/core/billing.test.ts index 87c985ec292..f8fb5c24730 100644 --- a/apps/sim/lib/billing/core/billing.test.ts +++ b/apps/sim/lib/billing/core/billing.test.ts @@ -30,16 +30,12 @@ import { calculateSubscriptionOverage, getPersonalBillingSummary } from '@/lib/b const { mockEnsureUserStatsExists } = billingUsageMockFns const { mockGetBillingPeriodUsageCost, mockGetBillingPeriodUsageCostWithSourceSubset } = billingUsageLogMockFns -const { - mockGetHighestPriorityPersonalSubscription, - mockGetHighestPrioritySubscription, - mockResolveBillingInterval, -} = billingSubscriptionMockFns +const { mockGetHighestPriorityPersonalSubscription, mockGetHighestPrioritySubscription } = + billingSubscriptionMockFns describe('getPersonalBillingSummary', () => { beforeEach(() => { mockEnsureUserStatsExists.mockResolvedValue(undefined) - mockResolveBillingInterval.mockReturnValue('year') mockComputeWeeklyRefreshConsumed.mockResolvedValue(1) mockGetBillingPeriodUsageCostWithSourceSubset.mockResolvedValue({ total: 4, subset: 1 }) mockGetHighestPriorityPersonalSubscription.mockResolvedValue({ @@ -146,4 +142,24 @@ describe('calculateSubscriptionOverage', () => { }) expect(overage).toBe(80) }) + + it.each([ + { label: 'owes nothing when a trial is cancelled before it converts', trialDays: 14, owed: 0 }, + { label: 'bills a period that runs past the trial', trialDays: 3, owed: 70 }, + ])('$label', async ({ trialDays, owed }) => { + queueTableRows(schemaMock.organization, []) // isSubscriptionOrgScoped: personal + mockGetBillingPeriodUsageCost.mockResolvedValue(100) + const periodStart = new Date('2026-07-01T00:00:00.000Z') + + const overage = await calculateSubscriptionOverage({ + id: 'sub-1', + plan: 'pro_6000', + referenceId: 'user-1', + periodStart, + periodEnd: new Date('2026-07-15T00:00:00.000Z'), + trialEnd: new Date(periodStart.getTime() + trialDays * 86_400_000), + }) + + expect(overage).toBe(owed) + }) }) diff --git a/apps/sim/lib/billing/core/billing.ts b/apps/sim/lib/billing/core/billing.ts index 756434bb62f..4f8612fce1f 100644 --- a/apps/sim/lib/billing/core/billing.ts +++ b/apps/sim/lib/billing/core/billing.ts @@ -1,11 +1,9 @@ import { db } from '@sim/db' import { organization, subscription, userStats } from '@sim/db/schema' +import { createLogger } from '@sim/logger' import { and, desc, eq, inArray } from 'drizzle-orm' import { defaultBillingPeriod } from '@/lib/billing/core/billing-period' -import { - getHighestPriorityPersonalSubscription, - resolveBillingInterval, -} from '@/lib/billing/core/subscription' +import { getHighestPriorityPersonalSubscription } from '@/lib/billing/core/subscription' import { ensureUserStatsExists } from '@/lib/billing/core/usage' import { COPILOT_USAGE_SOURCES, @@ -24,16 +22,18 @@ import { ENTITLED_SUBSCRIPTION_STATUSES, getFreeTierAllowance, getFreeTierLimit, + getOrgIncludedUsageDollars, + getPerUserMinimumLimit, getPlanPricing, + getSubscriptionWeeklyRefreshDollars, hasPaidSubscriptionStatus, + isHardCappedEnterprise, + type OrgAllowanceInput, + resolveBillingInterval, } from '@/lib/billing/subscriptions/utils' import { Decimal, toDecimal, toNumber } from '@/lib/billing/utils/decimal' import type { DbClient, DbOrTx } from '@/lib/db/types' -export { getPlanPricing } - -import { createLogger } from '@sim/logger' - const logger = createLogger('Billing') interface GetOrganizationSubscriptionOptions { @@ -124,12 +124,13 @@ export async function isSubscriptionOrgScoped(sub: { referenceId: string }): Pro * All callers route through this to keep the overage math in one place. */ export async function computeOrgOverageAmount(params: { - plan: string | null - seats: number | null + subscription: OrgAllowanceInput & { plan: string | null; seats: number | null } periodStart: Date | null periodEnd: Date | null organizationId: string pooledLedgerUsage: number + /** The period's included usage when it differs from the subscription's current one. */ + includedUsage?: number }): Promise<{ effectiveUsage: number baseSubscriptionAmount: number @@ -139,20 +140,21 @@ export async function computeOrgOverageAmount(params: { const totalUsage = params.pooledLedgerUsage let weeklyRefreshDeduction = 0 - const weeklyRefreshDollars = getPlanWeeklyRefreshDollars(params.plan) + const { plan, seats } = params.subscription + const weeklyRefreshDollars = getPlanWeeklyRefreshDollars(plan) if (weeklyRefreshDollars > 0 && params.periodStart) { weeklyRefreshDeduction = await computeWeeklyRefreshConsumed({ billingEntity: { type: 'organization', id: params.organizationId }, periodStart: params.periodStart, periodEnd: params.periodEnd ?? null, weeklyRefreshDollars, - seats: params.seats || 1, + seats: seats || 1, }) } const effectiveUsage = Math.max(0, totalUsage - weeklyRefreshDeduction) - const { basePrice } = getPlanPricing(params.plan ?? '') - const baseSubscriptionAmount = (params.seats || 1) * basePrice + const baseSubscriptionAmount = + params.includedUsage ?? getOrgIncludedUsageDollars(params.subscription) const totalOverage = Math.max(0, effectiveUsage - baseSubscriptionAmount) return { effectiveUsage, baseSubscriptionAmount, weeklyRefreshDeduction, totalOverage } @@ -167,11 +169,15 @@ export async function calculateSubscriptionOverage(sub: { plan: string | null referenceId: string seats?: number | null + metadata?: unknown + billingInterval?: string | null periodStart?: Date | null periodEnd?: Date | null + trialEnd?: Date | null + allowancePeriodStart?: Date | null + allowanceSeatMonths?: number | string | null }): Promise { - // Enterprise plans have no overages - if (isEnterprise(sub.plan)) { + if (isHardCappedEnterprise(sub)) { logger.info('Enterprise plan has no overages', { subscriptionId: sub.id, plan: sub.plan, @@ -179,6 +185,9 @@ export async function calculateSubscriptionOverage(sub: { return 0 } + // A trial period owes nothing: its usage is capped at the trial allowance. + if (sub.trialEnd && sub.periodEnd && sub.periodEnd.getTime() <= sub.trialEnd.getTime()) return 0 + let totalOverageDecimal = new Decimal(0) const isOrgScoped = await isSubscriptionOrgScoped(sub) @@ -193,8 +202,7 @@ export async function calculateSubscriptionOverage(sub: { : 0 const { totalOverage, effectiveUsage, baseSubscriptionAmount } = await computeOrgOverageAmount({ - plan: sub.plan, - seats: sub.seats ?? null, + subscription: { ...sub, seats: sub.seats ?? null }, periodStart: sub.periodStart ?? null, periodEnd: sub.periodEnd ?? null, organizationId: sub.referenceId, @@ -239,7 +247,7 @@ export async function calculateSubscriptionOverage(sub: { } } - const { basePrice } = getPlanPricing(sub.plan || 'free') + const { basePrice } = getPlanPricing(sub) totalOverageDecimal = Decimal.max( 0, toDecimal(ledgerUsage).minus(toDecimal(weeklyRefreshDeduction)).minus(basePrice) @@ -311,7 +319,7 @@ export async function getPersonalBillingSummary(userId: string, executor: DbClie hasPaidSubscriptionStatus(personalSubscription.status) && personalSubscription.periodStart ) { - const weeklyRefreshDollars = getPlanWeeklyRefreshDollars(plan) + const weeklyRefreshDollars = getSubscriptionWeeklyRefreshDollars(personalSubscription) if (weeklyRefreshDollars > 0) { refreshDeduction = await computeWeeklyRefreshConsumed( { @@ -351,6 +359,7 @@ export async function getPersonalBillingSummary(userId: string, executor: DbClie isExceeded, daysRemaining, creditBalance: toNumber(toDecimal(stats.creditBalance)), + includedUsage: getPerUserMinimumLimit(personalSubscription, stats.freeTierEligible), billingInterval: resolveBillingInterval(personalSubscription), isPaid: hasPaidEntitlement && isPaid(plan), isPro: hasPaidEntitlement && isPro(plan), @@ -408,6 +417,7 @@ function getDefaultBillingSummary(type: 'individual' | 'organization') { isExceeded: false, daysRemaining: 0, creditBalance: 0, + includedUsage: 0, billingInterval: 'month' as const, // Subscription details isPaid: false, diff --git a/apps/sim/lib/billing/core/chat-access.integration.ts b/apps/sim/lib/billing/core/chat-access.integration.ts index 804597d16d2..1484a7202e6 100644 --- a/apps/sim/lib/billing/core/chat-access.integration.ts +++ b/apps/sim/lib/billing/core/chat-access.integration.ts @@ -72,7 +72,7 @@ describe('payerHasChatAccess', () => { const userId = await createUser() const payer = { billingEntity: { type: 'user' as const, id: userId }, - payerSubscription: { plan: 'free' }, + payerSubscription: { plan: 'free', status: null }, } expect(await payerHasChatAccess(payer)).toBe(false) @@ -88,7 +88,7 @@ describe('payerHasChatAccess', () => { expect( await payerHasChatAccess({ billingEntity: { type: 'user', id: userId }, - payerSubscription: { plan: 'pro_6000' }, + payerSubscription: { plan: 'pro_6000', status: 'active' }, }) ).toBe(true) }) diff --git a/apps/sim/lib/billing/core/chat-access.ts b/apps/sim/lib/billing/core/chat-access.ts index f5623df2839..4cb205c6ae9 100644 --- a/apps/sim/lib/billing/core/chat-access.ts +++ b/apps/sim/lib/billing/core/chat-access.ts @@ -22,8 +22,9 @@ interface PaidAccessOptions { * free plan, unless that payer holds prepaid credits, which an admin grants to customers billed * outside a subscription. * - * The plan is the payer's entitled subscription (active or past due), so a canceled - * plan reads as free; a blocked payer is refused by the usage check every caller runs next. + * The plan is the payer's entitled subscription (active, trialing, or past due), so a + * canceled plan reads as free and a trial reads as its plan; a blocked payer is refused by the + * usage check every caller runs next. */ export async function payerHasPaidAccess( payer: UsageUpgradePayer, diff --git a/apps/sim/lib/billing/core/hosted-key-access.ts b/apps/sim/lib/billing/core/hosted-key-access.ts index ce82cde328b..8ed028e9927 100644 --- a/apps/sim/lib/billing/core/hosted-key-access.ts +++ b/apps/sim/lib/billing/core/hosted-key-access.ts @@ -1,9 +1,21 @@ +import { PRO_TRIAL_DAYS } from '@/lib/billing/constants' import { resolveWorkspaceBillingPayer } from '@/lib/billing/core/attribution' import { payerHasPaidAccess } from '@/lib/billing/core/chat-access' import type { UsageUpgradePayer } from '@/lib/billing/usage-upgrade' import { isBillingEnabled, isHosted } from '@/lib/core/config/env-flags' import { HttpError } from '@/lib/core/utils/http-error' +/** The fixed part of {@link HostedKeyRequiresPaidPlanError}'s message, which outlives its class. */ +const HOSTED_KEY_PAID_PLAN_PHRASE = "with Sim's hosted key is available on paid plans" + +/** + * Whether a run failed because a free payer reached for Sim's hosted key. A workflow's failure + * reaches its caller as text, so this reads the message rather than the error's class. + */ +export function isHostedKeyPaidPlanFailure(message: string | null | undefined): boolean { + return Boolean(message?.includes(HOSTED_KEY_PAID_PLAN_PHRASE)) +} + /** * Sim's hosted key was withheld because the run's payer is on the free plan. Carries a 402 so the * run fails as the caller's plan, not as a Sim fault. @@ -14,7 +26,7 @@ export class HostedKeyRequiresPaidPlanError extends HttpError { /** @param subject - what asked for the key: a tool's name or a model id */ constructor(subject: string) { super( - `${subject} with Sim's hosted key is available on paid plans. Upgrade your plan, or add your own API key under Settings > BYOK.` + `${subject} ${HOSTED_KEY_PAID_PLAN_PHRASE}. Upgrade your plan (Pro starts with a ${PRO_TRIAL_DAYS}-day free trial for new subscribers), or add your own API key under Settings > BYOK.` ) this.name = 'HostedKeyRequiresPaidPlanError' } diff --git a/apps/sim/lib/billing/core/mid-run-usage.test.ts b/apps/sim/lib/billing/core/mid-run-usage.test.ts new file mode 100644 index 00000000000..cce62bf6ed5 --- /dev/null +++ b/apps/sim/lib/billing/core/mid-run-usage.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from 'vitest' +import type { + AccountBillingDecision, + BillingAttributionSnapshot, +} from '@/lib/billing/core/attribution' +import { isCappedRunPayer } from '@/lib/billing/core/mid-run-usage' + +const decision: AccountBillingDecision = { + userId: 'user-1', + billingEntity: { type: 'user', id: 'user-1' }, + billingPeriod: { start: '2026-07-01T00:00:00.000Z', end: '2026-08-01T00:00:00.000Z' }, +} + +function attributed(plan: string | null, status = 'active'): BillingAttributionSnapshot { + return { + payerSubscription: plan + ? { + id: 'sub-1', + referenceId: 'user-1', + plan, + status, + seats: null, + periodStart: null, + periodEnd: null, + } + : null, + } as BillingAttributionSnapshot +} + +describe('isCappedRunPayer', () => { + it.each([ + { label: 'a free payer', payer: attributed(null), capped: true }, + { label: 'a trial', payer: attributed('pro_6000', 'trialing'), capped: true }, + { label: 'a paid plan', payer: attributed('pro_6000'), capped: false }, + ])('judges $label on an attributed run', ({ payer, capped }) => { + expect(isCappedRunPayer(payer)).toBe(capped) + }) + + it.each([ + { + label: 'a trial recorded at admission, despite its subscription', + payer: { ...decision, payerSubscriptionId: 'sub-1', payerBillsOverage: false }, + capped: true, + }, + { + label: 'a paid plan recorded at admission', + payer: { ...decision, payerSubscriptionId: 'sub-1', payerBillsOverage: true }, + capped: false, + }, + { + label: 'an older decision with a subscription', + payer: { ...decision, payerSubscriptionId: 'sub-1' }, + capped: false, + }, + { label: 'an older decision without one', payer: decision, capped: true }, + ])('judges $label on a direct-v1 run', ({ payer, capped }) => { + expect(isCappedRunPayer(payer)).toBe(capped) + }) +}) diff --git a/apps/sim/lib/billing/core/mid-run-usage.ts b/apps/sim/lib/billing/core/mid-run-usage.ts index c89748f3267..dcfcb6aaaa9 100644 --- a/apps/sim/lib/billing/core/mid-run-usage.ts +++ b/apps/sim/lib/billing/core/mid-run-usage.ts @@ -20,7 +20,7 @@ import { USAGE_GATE_TTL_MS, usageAdmissionTtlMs, } from '@/lib/billing/core/usage-gate-cache' -import { isFree } from '@/lib/billing/plan-helpers' +import { billsOverage } from '@/lib/billing/subscriptions/utils' import type { UsageUpgradePayer } from '@/lib/billing/usage-upgrade' import { coalesceLocally } from '@/lib/concurrency/singleflight' import { isBillingEnabled, isHosted } from '@/lib/core/config/env-flags' @@ -36,7 +36,7 @@ const logger = createLogger('MidRunUsage') * - `blocked`: the account is blocked (payment failed, dispute); the run is refused as a blocked * account, never with the upgrade card. * - `unknown`: usage, or the payer's current period, could not be read. Admission fails closed - * on an unreadable ledger. Callers stop a free payer's run on it (see {@link isFreeRunPayer}), + * on an unreadable ledger. Callers stop a capped payer's run on it (see {@link isCappedRunPayer}), * whose spend past the limit is never billed, and let a paid payer's run continue: a database * blip must not end a paying user's long run, and the next step or re-check reads again. */ @@ -52,24 +52,26 @@ export type MidRunUsageVerdict = interface MidRunUsageReadOptions { /** - * Reads a free payer's standing from the ledger rather than a cached admission, for a caller - * that has just recorded a charge: a free payer is always near its limit, and a cached + * Reads a capped payer's standing from the ledger rather than a cached admission, for a caller + * that has just recorded a charge: a capped payer is always near its limit, and a cached * admission would let that charge run past it unseen. Paid payers keep the cached admission. */ - uncachedForFreePayer?: boolean + uncachedForCappedPayer?: boolean } /** - * Whether a run's payer is on the free plan, as admitted. An attributed run reads its payer - * subscription (an organization payer without one is free). A direct-v1 decision records a - * subscription only for a payer with an entitled one, and a free payer has none. + * Whether a run's payer has a hard usage cap, as admitted: the free plan or a paid plan's trial, + * whose spend past the limit is never billed ({@link billsOverage}). An attributed run reads its + * payer subscription (an organization payer without one is free); a direct-v1 decision records the + * verdict, or, when minted before it did, only whether the payer had a subscription. */ -export function isFreeRunPayer( +export function isCappedRunPayer( payer: BillingAttributionSnapshot | AccountBillingDecision ): boolean { - return 'payerSubscription' in payer - ? isFree(payer.payerSubscription?.plan) - : !payer.payerSubscriptionId + if ('payerSubscription' in payer) return !billsOverage(payer.payerSubscription) + return payer.payerBillsOverage === undefined + ? !payer.payerSubscriptionId + : !payer.payerBillsOverage } /** @@ -144,7 +146,7 @@ async function readGateVerdict( let usage: AttributedUsageLimitsResult try { usage = - options.uncachedForFreePayer && isFreeRunPayer(attribution) + options.uncachedForCappedPayer && isCappedRunPayer(attribution) ? await withinDeadline( () => checkAttributedUsageLimits(attribution), Date.now() + USAGE_GATE_SETTLE_TIMEOUT_MS @@ -221,8 +223,8 @@ const accountVerdictCache = new LRUCache({ * payer, in the gate's order: a blocked actor or payer first, then the payer's spend. The payer * is the one saved in the decision at admission, never re-selected from the actor's current * memberships, and the period judged is the one its charges land in, as for attributed runs. - * Whether {@link MidRunUsageReadOptions.uncachedForFreePayer} applies is judged by the plan the - * run was admitted with, as {@link isFreeRunPayer} judges it. + * Whether {@link MidRunUsageReadOptions.uncachedForCappedPayer} applies is judged by the plan the + * run was admitted with, as {@link isCappedRunPayer} judges it. */ export async function readMidRunAccountUsageVerdict( decision: AccountBillingDecision, @@ -257,7 +259,7 @@ export async function readMidRunAccountUsageVerdict( subscription?.status ?? '', subscription?.seats ?? '', ].join(':') - const uncached = options.uncachedForFreePayer === true && isFreeRunPayer(decision) + const uncached = options.uncachedForCappedPayer === true && isCappedRunPayer(decision) const cached = uncached ? undefined : accountVerdictCache.get(key) if (cached) return cached const block = await checkAccountBillingBlocks(decision) diff --git a/apps/sim/lib/billing/core/organization-activity-rollup.integration.ts b/apps/sim/lib/billing/core/organization-activity-rollup.integration.ts index 31365a977fb..bda54c99bb8 100644 --- a/apps/sim/lib/billing/core/organization-activity-rollup.integration.ts +++ b/apps/sim/lib/billing/core/organization-activity-rollup.integration.ts @@ -27,7 +27,11 @@ vi.mock('@sim/db', () => { runOutsideTransactionContext: (work: () => T) => work(), } }) -vi.mock('@/lib/core/config/redis', () => ({ getRedisClient: () => null })) +vi.mock('@/lib/core/config/redis', () => ({ + getRedisClient: () => { + throw new Error('Redis is not used by this suite; the usage cache reads the ledger') + }, +})) /** * The legacy oracle is the uncached SQL (a cached settled day would hide the changes the * failure-mode cases make), so every segment misses and the window is read in one range, exactly diff --git a/apps/sim/lib/billing/core/organization-activity.integration.ts b/apps/sim/lib/billing/core/organization-activity.integration.ts index 5104e9e2604..6cf512780dd 100644 --- a/apps/sim/lib/billing/core/organization-activity.integration.ts +++ b/apps/sim/lib/billing/core/organization-activity.integration.ts @@ -8,7 +8,11 @@ const { execute, select } = vi.hoisted(() => ({ execute: vi.fn(), select: vi.fn( const databaseUrl = readTestDatabaseUrl() vi.mock('@sim/db', () => ({ dbReplica: { execute, select } })) -vi.mock('@/lib/core/config/redis', () => ({ getRedisClient: () => null })) +vi.mock('@/lib/core/config/redis', () => ({ + getRedisClient: () => { + throw new Error('Redis is not used by this suite; the usage cache reads the ledger') + }, +})) import type { ActivityScope } from '@/lib/billing/core/organization-activity' import { diff --git a/apps/sim/lib/billing/core/organization.ts b/apps/sim/lib/billing/core/organization.ts index 0998f1b640d..79fbdce5a7f 100644 --- a/apps/sim/lib/billing/core/organization.ts +++ b/apps/sim/lib/billing/core/organization.ts @@ -3,7 +3,7 @@ import { member, organization, usageLog, user, userStats } from '@sim/db/schema' import { createLogger } from '@sim/logger' import { and, count, eq, gte, lt, sql } from 'drizzle-orm' import { isOrganizationBillingBlocked } from '@/lib/billing/core/access' -import { getOrganizationSubscription, getPlanPricing } from '@/lib/billing/core/billing' +import { getOrganizationSubscription } from '@/lib/billing/core/billing' import { readLedgerBounded } from '@/lib/billing/core/ledger-read' import { resolveSubscriptionUsagePeriodOrDefault } from '@/lib/billing/core/reporting-period' import { @@ -11,12 +11,18 @@ import { getBillingPeriodUsageCostByUser, type UsageQueryPeriod, } from '@/lib/billing/core/usage-log' +import { formatCredits } from '@/lib/billing/credits/conversion' import { computeWeeklyRefreshConsumed } from '@/lib/billing/credits/weekly-refresh' -import { getPlanWeeklyRefreshDollars, isEnterprise, isPaid } from '@/lib/billing/plan-helpers' +import { acquireOrganizationMutationLock } from '@/lib/billing/organizations/membership' +import { isEnterprise, isPaid } from '@/lib/billing/plan-helpers' import { getEffectiveSeats, getFreeTierLimit, + getOrgIncludedUsageDollars, + getSubscriptionWeeklyRefreshDollars, hasUsableSubscriptionStatus, + isEnterpriseSelfServe, + isHardCappedEnterprise, } from '@/lib/billing/subscriptions/utils' import { toDecimal, toNumber } from '@/lib/billing/utils/decimal' import { countPendingSeatInvitations } from '@/lib/billing/validation/seat-management' @@ -298,7 +304,7 @@ export async function getOrganizationBillingData( : 0 if (isPaid(subscription.plan) && subscription.periodStart) { - const weeklyRefreshDollars = getPlanWeeklyRefreshDollars(subscription.plan) + const weeklyRefreshDollars = getSubscriptionWeeklyRefreshDollars(subscription) if (weeklyRefreshDollars > 0) { const refreshConsumed = await computeWeeklyRefreshConsumed( { @@ -314,8 +320,6 @@ export async function getOrganizationBillingData( } } - const { basePrice: pricePerSeat } = getPlanPricing(subscription.plan) - // Stripe subscription quantity; `||` not `??` because 0 seats is // never valid for a paid sub — fall through to 1. const licensedSeats = subscription.seats || 1 @@ -328,10 +332,12 @@ export async function getOrganizationBillingData( if (isEnterprise(subscription.plan)) { const configuredLimit = toNumber(toDecimal(organizationData.orgUsageLimit)) - minimumBillingAmount = configuredLimit + minimumBillingAmount = isHardCappedEnterprise(subscription) + ? configuredLimit + : getOrgIncludedUsageDollars(subscription) totalUsageLimit = configuredLimit } else { - minimumBillingAmount = licensedSeats * pricePerSeat + minimumBillingAmount = getOrgIncludedUsageDollars(subscription) const configuredLimit = organizationData.orgUsageLimit ? toNumber(toDecimal(organizationData.orgUsageLimit)) @@ -391,6 +397,56 @@ export async function getOrganizationBillingData( } } +/** + * Sets a self-serve Enterprise customer's own usage limit. It may not fall below what the + * contract already covers (its allowance plus prepaid credit); usage past the allowance is billed + * as overage. The choice is stored apart from the enforced limit so the contract webhook keeps it. + */ +async function updateSelfServeEnterpriseUsageLimit( + organizationId: string, + newLimit: number +): Promise<{ success: boolean; error?: string }> { + return db.transaction(async (tx) => { + await acquireOrganizationMutationLock(tx, organizationId) + // The contract webhook takes the same lock, so these terms are the ones it last applied. + const subscription = await getOrganizationSubscription(organizationId, { + executor: tx, + onError: 'throw', + }) + if (!subscription || !isEnterpriseSelfServe(subscription)) { + return { + success: false, + error: 'Enterprise plans have fixed usage limits that cannot be changed', + } + } + const includedUsage = getOrgIncludedUsageDollars(subscription) + const [row] = await tx + .select({ creditBalance: organization.creditBalance }) + .from(organization) + .where(eq(organization.id, organizationId)) + .for('update') + .limit(1) + const minimumLimit = toNumber(toDecimal(includedUsage).plus(toDecimal(row?.creditBalance))) + if (newLimit < minimumLimit) { + return { + success: false, + error: `Usage limit cannot be less than ${formatCredits(minimumLimit)} credits, your contract's included usage plus prepaid credit`, + } + } + const limit = roundCurrency(newLimit).toFixed(2) + await tx + .update(organization) + .set({ orgUsageLimit: limit, selfServeUsageLimit: limit, updatedAt: new Date() }) + .where(eq(organization.id, organizationId)) + logger.info('Self-serve Enterprise usage limit updated', { + organizationId, + newLimit, + minimumLimit, + }) + return { success: true } + }) +} + /** * Update organization usage limit (cap) */ @@ -424,10 +480,13 @@ export async function updateOrganizationUsageLimit( } if (isEnterprise(subscription.plan)) { - return { - success: false, - error: 'Enterprise plans have fixed usage limits that cannot be changed', + if (isHardCappedEnterprise(subscription)) { + return { + success: false, + error: 'Enterprise plans have fixed usage limits that cannot be changed', + } } + return await updateSelfServeEnterpriseUsageLimit(organizationId, newLimit) } if (!isPaid(subscription.plan)) { @@ -437,14 +496,12 @@ export async function updateOrganizationUsageLimit( } } - const { basePrice } = getPlanPricing(subscription.plan) - const seatCount = subscription.seats || 1 - const minimumLimit = seatCount * basePrice + const minimumLimit = getOrgIncludedUsageDollars(subscription) if (newLimit < minimumLimit) { return { success: false, - error: `Usage limit cannot be less than minimum billing amount of $${roundCurrency(minimumLimit).toFixed(2)}`, + error: `Usage limit cannot be less than your plan's ${formatCredits(minimumLimit)} included credits`, } } diff --git a/apps/sim/lib/billing/core/plan-switch.ts b/apps/sim/lib/billing/core/plan-switch.ts new file mode 100644 index 00000000000..324cf9df325 --- /dev/null +++ b/apps/sim/lib/billing/core/plan-switch.ts @@ -0,0 +1,129 @@ +import { db } from '@sim/db' +import { organization, subscription as subscriptionTable, userStats } from '@sim/db/schema' +import { createLogger } from '@sim/logger' +import { type AnyColumn, eq, sql } from 'drizzle-orm' +import { ON_DEMAND_UNLIMITED } from '@/lib/billing/constants' +import { writeBillingInterval } from '@/lib/billing/core/subscription' +import { + getOrgIncludedUsageDollars, + getPlanPricing, + isTrialingSubscription, + type OrgAllowanceInput, + resolveBillingInterval, +} from '@/lib/billing/subscriptions/utils' +import { toDecimal } from '@/lib/billing/utils/decimal' +import type { DbOrTx } from '@/lib/db/types' + +const logger = createLogger('PlanSwitch') + +interface SwitchedSubscription extends OrgAllowanceInput { + id: string + plan: string + referenceId: string + status: string | null + trialEnd?: Date | null +} + +/** + * Moves a usage pool's limit from one included-usage amount to another. The on-demand headroom + * the payer chose above the old amount (with prepaid credit) carries over, scaled by + * `headroomScale` (an interval change turns a year's headroom into a month's twelfth), so an + * untouched limit lands on the new amount and never reads as on-demand usage nobody turned on. A + * limit already at the new amount is untouched too: the Stripe webhook's floor sync can raise it + * there first. An unlimited limit stays unlimited. + */ +export async function rebaseUsageLimit( + params: { + pool: { type: 'user' | 'organization'; id: string } + previousIncluded: number + nextIncluded: number + headroomScale?: number + }, + executor: DbOrTx = db +): Promise { + const { pool, previousIncluded, nextIncluded, headroomScale = 1 } = params + const rebased = (limit: AnyColumn, creditBalance: AnyColumn) => { + const previousCovered = sql`(${toDecimal(previousIncluded).toString()}::numeric + ${creditBalance})` + const nextCovered = sql`(${toDecimal(nextIncluded).toString()}::numeric + ${creditBalance})` + const headroom = sql`case when ${limit} = ${nextCovered} then 0 else greatest(0, coalesce(${limit}, ${previousCovered}) - ${previousCovered}) end` + return sql`case when ${limit} >= ${ON_DEMAND_UNLIMITED} then ${limit} else ${nextCovered} + ${headroom} * ${headroomScale}::numeric end` + } + + if (pool.type === 'organization') { + await executor + .update(organization) + .set({ + orgUsageLimit: rebased(organization.orgUsageLimit, organization.creditBalance), + updatedAt: new Date(), + }) + .where(eq(organization.id, pool.id)) + } else { + await executor + .update(userStats) + .set({ + currentUsageLimit: rebased(userStats.currentUsageLimit, userStats.creditBalance), + usageLimitUpdatedAt: new Date(), + }) + .where(eq(userStats.userId, pool.id)) + } +} + +/** + * Records a tier or billing-interval change Stripe has already applied: the plan, the interval, + * and the payer's usage limit. + * + * The limit moves with the plan's included usage ({@link rebaseUsageLimit}): an untouched limit + * left at a pricier allowance would read as on-demand usage nobody turned on. A personal trial + * keeps its fixed allowance. + */ +export async function recordPlanSwitch(params: { + subscription: SwitchedSubscription + targetPlanName: string + targetInterval: 'month' | 'year' + orgScoped: boolean +}): Promise { + const { subscription, targetPlanName, targetInterval, orgScoped } = params + + const trialing = !orgScoped && isTrialingSubscription(subscription) + const previousInterval = resolveBillingInterval(subscription) + const target = { ...subscription, plan: targetPlanName, billingInterval: targetInterval } + const previousBase = orgScoped + ? getOrgIncludedUsageDollars(subscription) + : getPlanPricing(subscription).basePrice + const nextBase = orgScoped ? getOrgIncludedUsageDollars(target) : getPlanPricing(target).basePrice + const headroomScale = + previousInterval === targetInterval ? 1 : targetInterval === 'year' ? 12 : 1 / 12 + + // One transaction: a retry of a half-recorded switch finds the plan already matching and would + // never rebase the limit. + await db.transaction(async (tx) => { + if (subscription.plan !== targetPlanName) { + await tx + .update(subscriptionTable) + .set({ plan: targetPlanName }) + .where(eq(subscriptionTable.id, subscription.id)) + } + await writeBillingInterval(subscription.id, targetInterval, tx) + if (trialing) return + await rebaseUsageLimit( + { + pool: orgScoped + ? { type: 'organization', id: subscription.referenceId } + : { type: 'user', id: subscription.referenceId }, + previousIncluded: previousBase, + nextIncluded: nextBase, + headroomScale, + }, + tx + ) + }) + + logger.info('Recorded plan switch', { + subscriptionId: subscription.id, + fromPlan: subscription.plan, + toPlan: targetPlanName, + interval: targetInterval, + previousBase, + nextBase, + }) +} diff --git a/apps/sim/lib/billing/core/subscription.ts b/apps/sim/lib/billing/core/subscription.ts index f3af4916440..c57a017741b 100644 --- a/apps/sim/lib/billing/core/subscription.ts +++ b/apps/sim/lib/billing/core/subscription.ts @@ -3,11 +3,13 @@ import { db } from '@sim/db' import { member, organization, subscription, user } from '@sim/db/schema' import { createLogger } from '@sim/logger' import { and, eq, inArray, sql } from 'drizzle-orm' +import { PRO_TRIAL_USAGE_LIMIT_DOLLARS } from '@/lib/billing/constants' import { getEffectiveBillingStatus, isOrganizationBillingBlocked } from '@/lib/billing/core/access' import { getHighestPriorityPersonalSubscription, getHighestPrioritySubscription, } from '@/lib/billing/core/plan' +import { formatCredits } from '@/lib/billing/credits/conversion' import { isMaxTier, isOrgPlan, @@ -22,6 +24,7 @@ import { checkProPlan, checkTeamPlan, ENTITLED_SUBSCRIPTION_STATUSES, + formatTrialEndDate, hasUsableSubscriptionAccess, USABLE_SUBSCRIPTION_STATUSES, } from '@/lib/billing/subscriptions/utils' @@ -41,50 +44,24 @@ const logger = createLogger('SubscriptionCore') export { getHighestPriorityPersonalSubscription, getHighestPrioritySubscription } -export interface SubscriptionMetadata { - billingInterval?: 'month' | 'year' - [key: string]: unknown -} - export interface HasPaidSubscriptionOptions { onError?: 'assume-active' | 'throw' } /** - * Extract the billing interval from subscription metadata, defaulting to 'month'. - */ -export function getBillingInterval( - metadata: SubscriptionMetadata | null | undefined -): 'month' | 'year' { - return metadata?.billingInterval === 'year' ? 'year' : 'month' -} - -/** - * Resolves a subscription's effective billing interval. Prefers the Stripe-synced - * `billingInterval` column — the only source populated on enterprise/manual - * subscriptions, which skip the checkout flow that writes the metadata value — and - * falls back to `metadata.billingInterval` (the column is often null on - * checkout-created subs), defaulting to monthly. Where both are set they agree. - */ -export function resolveBillingInterval( - sub: { billingInterval?: string | null; metadata?: unknown } | null | undefined -): 'month' | 'year' { - const column = sub?.billingInterval - if (column === 'year' || column === 'month') return column - return getBillingInterval((sub?.metadata ?? null) as SubscriptionMetadata | null) -} - -/** - * Merge a `billingInterval` value into a subscription's metadata JSON column. + * Write a subscription's billing interval to both places `resolveBillingInterval` reads: the column + * it prefers and the metadata fallback, so neither can contradict the other after a switch. */ export async function writeBillingInterval( subscriptionId: string, - interval: 'month' | 'year' + interval: 'month' | 'year', + executor: DbOrTx = db ): Promise { const patch = JSON.stringify({ billingInterval: interval }) - await db + await executor .update(subscription) .set({ + billingInterval: interval, metadata: sql`(COALESCE(metadata::jsonb, '{}'::jsonb) || ${patch}::jsonb)::json`, }) .where(eq(subscription.id, subscriptionId)) @@ -904,9 +881,13 @@ export async function hasWorkspaceSandboxRetentionAccess( } /** - * Send welcome email for Pro and Team plan subscriptions + * Send welcome email for Pro and Team plan subscriptions. `trialEnd` is passed when the plan + * starts with a free trial, so the email states when the card is first charged. */ -export async function sendPlanWelcomeEmail(subscription: any): Promise { +export async function sendPlanWelcomeEmail( + subscription: any, + options: { trialEnd?: Date | null } = {} +): Promise { try { const subPlan = subscription.plan if (isPlanPro(subPlan) || isPlanTeam(subPlan)) { @@ -927,15 +908,23 @@ export async function sendPlanWelcomeEmail(subscription: any): Promise { const { getDisplayPlanName } = await import('@/lib/billing/plan-helpers') const displayName = getDisplayPlanName(subPlan) + const trial = options.trialEnd + ? { + endsOn: formatTrialEndDate(options.trialEnd), + credits: formatCredits(PRO_TRIAL_USAGE_LIMIT_DOLLARS), + } + : undefined + const html = await renderPlanWelcomeEmail({ planName: displayName, userName: users[0].name || undefined, loginLink: `${baseUrl}/login`, + trial, }) await sendEmail({ to: users[0].email, - subject: getPlanWelcomeSubject(displayName), + subject: getPlanWelcomeSubject(displayName, Boolean(trial)), html, emailType: 'updates', }) diff --git a/apps/sim/lib/billing/core/usage-log.integration.ts b/apps/sim/lib/billing/core/usage-log.integration.ts index b3bf624f002..fa0b681534a 100644 --- a/apps/sim/lib/billing/core/usage-log.integration.ts +++ b/apps/sim/lib/billing/core/usage-log.integration.ts @@ -143,7 +143,7 @@ describe('Cumulative billing with PostgreSQL', () => { CREATE TABLE driver_probe (id text PRIMARY KEY); CREATE TABLE subscription ( id text PRIMARY KEY, period_start timestamp, period_end timestamp, - last_closed_period_start timestamp + last_closed_period_start timestamp, allowance_period_start timestamp, allowance_seats integer, allowance_seat_months numeric, metadata json ) `) transaction.mockImplementation(async (callback: (tx: Transaction) => Promise) => { diff --git a/apps/sim/lib/billing/core/usage.test.ts b/apps/sim/lib/billing/core/usage.test.ts index 897b2cb1c46..f4ea8d77527 100644 --- a/apps/sim/lib/billing/core/usage.test.ts +++ b/apps/sim/lib/billing/core/usage.test.ts @@ -94,6 +94,9 @@ const { } = emailTemplatesMockFns const { mockSendEmail } = emailMailerMockFns billingSubscriptionUtilsMockFns.mockGetPlanPricing.mockReturnValue({ basePrice: 20 } as never) +billingSubscriptionUtilsMockFns.mockGetOrgIncludedUsageDollars.mockImplementation( + (subscription: { seats?: number | null }) => (subscription.seats || 1) * 20 +) mockGetEmailSubject.mockReturnValue('Subject') mockGetLimitEmailSubject.mockReturnValue('Limit subject') mockRenderCreditsExhausted.mockResolvedValue('free') diff --git a/apps/sim/lib/billing/core/usage.ts b/apps/sim/lib/billing/core/usage.ts index c18df4cd308..49502071be7 100644 --- a/apps/sim/lib/billing/core/usage.ts +++ b/apps/sim/lib/billing/core/usage.ts @@ -1,5 +1,5 @@ import { db } from '@sim/db' -import { member, organization, userStats } from '@sim/db/schema' +import { member, organization, subscription as subscriptionTable, userStats } from '@sim/db/schema' import { createLogger } from '@sim/logger' import { generateId } from '@sim/utils/id' import { and, eq, isNull, sql } from 'drizzle-orm' @@ -22,22 +22,23 @@ import { } from '@/lib/billing/core/reporting-period' import { readSoftGateUsageCost } from '@/lib/billing/core/reporting-usage-cache' import { type BillingEntity, getBillingPeriodUsageCost } from '@/lib/billing/core/usage-log' +import { formatCredits } from '@/lib/billing/credits/conversion' import { computeWeeklyRefreshConsumed } from '@/lib/billing/credits/weekly-refresh' -import { - getPlanWeeklyRefreshDollars, - isEnterprise, - isFree, - isPaid, -} from '@/lib/billing/plan-helpers' +import { isEnterprise, isFree, isPaid, isTeam } from '@/lib/billing/plan-helpers' +import type { OrgAllowanceInput } from '@/lib/billing/subscriptions/utils' import { canEditUsageLimit, + formatTrialEndDate, getFreeTierAllowance, getFreeTierLimit, + getOrgIncludedUsageDollars, getPerUserMinimumLimit, - getPlanPricing, + getSubscriptionWeeklyRefreshDollars, hasPaidSubscriptionStatus, hasUsableSubscriptionAccess, isOrgScopedSubscription, + isTrialingSubscription, + resolveBillingInterval, } from '@/lib/billing/subscriptions/utils' import type { UsageData, UsageLimitInfo } from '@/lib/billing/types' import { buildUpgradeHref } from '@/lib/billing/upgrade-reasons' @@ -116,20 +117,24 @@ export async function getOrgLastPeriodCost( */ export async function getOrgUsageLimit( organizationId: string, - plan: string, - seats: number | null, + subscription: OrgLimitSubscription, executor: DbClient = db ): Promise { return ( - (await findOrgUsageLimit(organizationId, plan, seats, executor)) ?? - calculateOrgUsageLimit(organizationId, plan, seats, null) + (await findOrgUsageLimit(organizationId, subscription, executor)) ?? + calculateOrgUsageLimit(organizationId, subscription, null) ) } +/** + * The subscription fields that decide an organization's usage-limit floor. A caller holding only a + * snapshot passes `id`, and an annual Team's recorded seat-months are read from the row. + */ +type OrgLimitSubscription = OrgAllowanceInput & { plan: string; id?: string } + async function findOrgUsageLimit( organizationId: string, - plan: string, - seats: number | null, + subscription: OrgLimitSubscription, executor: DbClient = db ): Promise { const [orgData] = await executor @@ -140,20 +145,36 @@ async function findOrgUsageLimit( if (!orgData) return null + const needsRecordedAllowance = + subscription.id !== undefined && + subscription.allowanceSeatMonths === undefined && + isTeam(subscription.plan) && + resolveBillingInterval(subscription) === 'year' + const [recordedAllowance] = needsRecordedAllowance + ? await executor + .select({ + periodStart: subscriptionTable.periodStart, + allowancePeriodStart: subscriptionTable.allowancePeriodStart, + allowanceSeatMonths: subscriptionTable.allowanceSeatMonths, + }) + .from(subscriptionTable) + .where(eq(subscriptionTable.id, subscription.id ?? '')) + .limit(1) + : [] + return calculateOrgUsageLimit( organizationId, - plan, - seats, + { ...subscription, ...recordedAllowance }, orgData.orgUsageLimit ? toNumber(toDecimal(orgData.orgUsageLimit)) : null ) } function calculateOrgUsageLimit( organizationId: string, - plan: string, - seats: number | null, + subscription: OrgLimitSubscription, configured: number | null ): OrgUsageLimitResult { + const { plan, seats } = subscription if (isEnterprise(plan)) { // Enterprise: Use configured limit directly (no per-seat minimum) if (configured !== null) { @@ -163,10 +184,9 @@ function calculateOrgUsageLimit( return { limit: 0, minimum: 0 } } - const { basePrice } = getPlanPricing(plan) // `||` not `??` — 0 is never a valid seat count for a paid sub. const seatCount = seats || 1 - const minimum = seatCount * basePrice + const minimum = getOrgIncludedUsageDollars(subscription) if (configured !== null) { return { limit: Math.max(configured, minimum), minimum } @@ -387,12 +407,7 @@ async function getResolvedUserUsageData( let limit: number if (orgScoped && subscription) { - const orgLimit = await getOrgUsageLimit( - subscription.referenceId, - subscription.plan, - subscription.seats, - executor - ) + const orgLimit = await getOrgUsageLimit(subscription.referenceId, subscription, executor) limit = orgLimit.limit lastPeriodCost = await getOrgLastPeriodCost(subscription.referenceId, executor) @@ -413,7 +428,7 @@ async function getResolvedUserUsageData( let weeklyRefreshConsumed = 0 if (subscription && isPaid(subscription.plan) && billingPeriodStart) { - const weeklyRefreshDollars = getPlanWeeklyRefreshDollars(subscription.plan) + const weeklyRefreshDollars = getSubscriptionWeeklyRefreshDollars(subscription) if (weeklyRefreshDollars > 0) { weeklyRefreshConsumed = await computeWeeklyRefreshConsumed( { @@ -485,11 +500,7 @@ export async function getUserUsageLimitInfo(userId: string): Promise { try { if (!isBillingEnabled) return @@ -877,6 +902,7 @@ export async function maybeSendUsageThresholdEmail(params: { const baseUrl = getBaseUrl() const isFreeUser = params.planName === 'Free' + const trialEndsOn = params.trialEnd ? formatTrialEndDate(params.trialEnd) : undefined const upgradeCreditsLink = params.workspaceId ? `${baseUrl}${buildUpgradeHref(params.workspaceId, 'credits')}` @@ -903,11 +929,12 @@ export async function maybeSendUsageThresholdEmail(params: { currentUsage, limit: params.limit, ctaLink, + trialEndsOn, }) await sendEmail({ to: email, - subject: getEmailSubject('usage-threshold'), + subject: getEmailSubject(trialEndsOn ? 'trial-usage-threshold' : 'usage-threshold'), html, emailType: 'notifications', }) @@ -966,13 +993,16 @@ export async function maybeSendUsageThresholdEmail(params: { currentUsage, limit: params.limit, ctaLink: billingSettingsLink, + trialEndsOn, }) await sendEmail({ to: email, subject: useFreeCopy ? getEmailSubject('free-tier-exhausted') - : getLimitEmailSubject('credits', 'reached'), + : trialEndsOn + ? getEmailSubject('trial-credits-exhausted') + : getLimitEmailSubject('credits', 'reached'), html, emailType: 'notifications', }) diff --git a/apps/sim/lib/billing/core/workspace-access.ts b/apps/sim/lib/billing/core/workspace-access.ts index 206d011a91a..98fced77f09 100644 --- a/apps/sim/lib/billing/core/workspace-access.ts +++ b/apps/sim/lib/billing/core/workspace-access.ts @@ -1,8 +1,10 @@ import { getBillingEntityBlockStatus } from '@/lib/billing/core/access' import { resolveWorkspaceBillingPayer } from '@/lib/billing/core/attribution' -import { resolveBillingInterval } from '@/lib/billing/core/subscription' import { isEnterprise, isPaid, isPro, isTeam } from '@/lib/billing/plan-helpers' -import { hasPaidSubscriptionStatus } from '@/lib/billing/subscriptions/utils' +import { + hasPaidSubscriptionStatus, + resolveBillingInterval, +} from '@/lib/billing/subscriptions/utils' /** * The subscription access fields of a workspace's billed account, as a workspace- diff --git a/apps/sim/lib/billing/credits/purchase.ts b/apps/sim/lib/billing/credits/purchase.ts index 90c4a84f0ae..81c7444a86c 100644 --- a/apps/sim/lib/billing/credits/purchase.ts +++ b/apps/sim/lib/billing/credits/purchase.ts @@ -2,28 +2,36 @@ import { db } from '@sim/db' import { organization, userStats } from '@sim/db/schema' import { createLogger } from '@sim/logger' import { eq } from 'drizzle-orm' -import { getPlanPricing } from '@/lib/billing/core/billing' +import { PRO_TRIAL_USAGE_LIMIT_DOLLARS } from '@/lib/billing/constants' +import { + getOrgIncludedUsageDollars, + getPlanPricing, + isTrialingSubscription, + type OrgAllowanceInput, +} from '@/lib/billing/subscriptions/utils' import { toDecimal, toNumber } from '@/lib/billing/utils/decimal' const logger = createLogger('CreditPurchase') /** * Sets usage limit to planBase + creditBalance. - * This ensures users can use their plan's included amount plus any prepaid credits. + * This ensures users can use their plan's included amount plus any prepaid credits. A personal + * trial's base is its fixed allowance, not the plan's. */ export async function setUsageLimitForCredits( entityType: 'user' | 'organization', entityId: string, - plan: string, + subscription: OrgAllowanceInput & { plan: string; status: string | null }, seats: number | null, creditBalance: number ): Promise { try { - const { basePrice } = getPlanPricing(plan) - - const seatCount = seats || 1 const planBase = - entityType === 'organization' ? Number(basePrice) * seatCount : Number(basePrice) + entityType === 'organization' + ? getOrgIncludedUsageDollars({ ...subscription, seats }) + : isTrialingSubscription(subscription) + ? PRO_TRIAL_USAGE_LIMIT_DOLLARS + : getPlanPricing(subscription).basePrice const creditBalanceNum = Number(creditBalance) const newLimit = planBase + creditBalanceNum @@ -44,7 +52,7 @@ export async function setUsageLimitForCredits( logger.info('Set org usage limit to planBase + credits', { organizationId: entityId, - plan, + plan: subscription.plan, seats, planBase, creditBalance, @@ -70,7 +78,7 @@ export async function setUsageLimitForCredits( logger.info('Set user usage limit to planBase + credits', { userId: entityId, - plan, + plan: subscription.plan, planBase, creditBalance, previousLimit: currentLimit, diff --git a/apps/sim/lib/billing/cycle-close.test.ts b/apps/sim/lib/billing/cycle-close.test.ts index 88be66239be..1a7eec26558 100644 --- a/apps/sim/lib/billing/cycle-close.test.ts +++ b/apps/sim/lib/billing/cycle-close.test.ts @@ -168,14 +168,15 @@ describe('closeElapsedBillingPeriod', () => { expect(result.status).toBe('closed') expect(result.overageBilled).toBe(70) - expect(mockComputeOrgOverageAmount).toHaveBeenCalledWith({ - plan: 'team', - seats: null, - periodStart: PREV_PERIOD_START, - periodEnd: PERIOD_START, - organizationId: 'org-1', - pooledLedgerUsage: 150, - }) + expect(mockComputeOrgOverageAmount).toHaveBeenCalledWith( + expect.objectContaining({ + subscription: expect.objectContaining({ plan: 'team', seats: null, metadata: null }), + periodStart: PREV_PERIOD_START, + periodEnd: PERIOD_START, + organizationId: 'org-1', + pooledLedgerUsage: 150, + }) + ) expect(mockEnqueueOutboxEvent).toHaveBeenCalledTimes(1) const [, eventType, payload] = mockEnqueueOutboxEvent.mock.calls[0] @@ -279,14 +280,15 @@ describe('closeElapsedBillingPeriod', () => { await closeElapsedBillingPeriod(subRow()) - expect(mockComputeOrgOverageAmount).toHaveBeenCalledWith({ - plan: 'team', - seats: null, - periodStart: PREV_PERIOD_START, - periodEnd: PERIOD_START, - organizationId: 'org-1', - pooledLedgerUsage: 150, - }) + expect(mockComputeOrgOverageAmount).toHaveBeenCalledWith( + expect.objectContaining({ + subscription: expect.objectContaining({ plan: 'team', seats: null, metadata: null }), + periodStart: PREV_PERIOD_START, + periodEnd: PERIOD_START, + organizationId: 'org-1', + pooledLedgerUsage: 150, + }) + ) }) it('subtracts the current period tracker from the final overage', async () => { diff --git a/apps/sim/lib/billing/cycle-close.ts b/apps/sim/lib/billing/cycle-close.ts index d1870de52de..ec893c41090 100644 --- a/apps/sim/lib/billing/cycle-close.ts +++ b/apps/sim/lib/billing/cycle-close.ts @@ -19,8 +19,14 @@ import { getStampedPeriodRangeUsageCostByUser, } from '@/lib/billing/core/usage-log' import { computeWeeklyRefreshConsumed } from '@/lib/billing/credits/weekly-refresh' -import { getPlanWeeklyRefreshDollars, isEnterprise, isFree } from '@/lib/billing/plan-helpers' -import { ENTITLED_SUBSCRIPTION_STATUSES, getPlanPricing } from '@/lib/billing/subscriptions/utils' +import { isEnterprise, isFree } from '@/lib/billing/plan-helpers' +import { + getOrgIncludedUsageDollars, + getPlanPricing, + getSubscriptionWeeklyRefreshDollars, + isHardCappedEnterprise, + SETTLED_SUBSCRIPTION_STATUSES, +} from '@/lib/billing/subscriptions/utils' import { toDecimal, toNumber } from '@/lib/billing/utils/decimal' import { OUTBOX_EVENT_TYPES } from '@/lib/billing/webhooks/outbox-events' import { enqueueOutboxEvent } from '@/lib/core/outbox/service' @@ -29,6 +35,32 @@ import { captureServerEvent } from '@/lib/posthog/server' const logger = createLogger('BillingCycleClose') +const AVERAGE_MONTH_MS = 30.44 * 24 * 60 * 60 * 1000 + +/** + * The usage a closed period included, from the period itself rather than the subscription's + * current terms: an interval switch moves the subscription onto the new interval before the old + * period closes, and that period must not be priced at the new allowance. A full year counts its + * seat-months (kept for the year until it closes); a shorter period counts its own months. + */ +function closedPeriodIncludedUsage( + sub: SubscriptionRow, + closedRange: { from: Date; to: Date }, + orgScoped: boolean +): number { + if (isEnterprise(sub.plan)) return getOrgIncludedUsageDollars(sub) + const months = Math.max( + 1, + Math.round((closedRange.to.getTime() - closedRange.from.getTime()) / AVERAGE_MONTH_MS) + ) + if (months >= 12) { + const year = { ...sub, periodStart: closedRange.from, billingInterval: 'year' } + return orgScoped ? getOrgIncludedUsageDollars(year) : getPlanPricing(year).basePrice + } + const monthly = getPlanPricing({ ...sub, billingInterval: 'month' }).basePrice + return monthly * months * (orgScoped ? sub.seats || 1 : 1) +} + /** * Minimum residual overage worth invoicing at cycle close, in dollars. * Anything below this is forgiven rather than billed as a sub-cent invoice. @@ -149,7 +181,7 @@ export async function isSubscriptionCycleCloseCurrent( * Close any elapsed-but-unclosed billing period for a subscription that is * being deleted, ahead of its terminal settlement. A deleted subscription * leaves the sweep's candidate set (its status leaves - * `ENTITLED_SUBSCRIPTION_STATUSES`), so this is the last chance to settle a + * `SETTLED_SUBSCRIPTION_STATUSES`), so this is the last chance to settle a * period the sweep has not caught up to — without it, `claimTerminalPeriod` * would advance the marker past the elapsed period and silently forgive its * final overage, while the elapsed period's threshold collections would @@ -224,6 +256,8 @@ export async function claimTerminalPeriod( periodStart: Date | null periodEnd: Date | null markerWasCurrent: boolean + /** The row's contract metadata, which decides whether a self-serve Enterprise bills overage. */ + metadata: unknown }> { return db.transaction(async (tx) => { const [row] = await tx @@ -231,6 +265,7 @@ export async function claimTerminalPeriod( periodStart: subscriptionTable.periodStart, periodEnd: subscriptionTable.periodEnd, lastClosedPeriodStart: subscriptionTable.lastClosedPeriodStart, + metadata: subscriptionTable.metadata, }) .from(subscriptionTable) .where(eq(subscriptionTable.id, subscriptionId)) @@ -240,14 +275,18 @@ export async function claimTerminalPeriod( if (!row?.periodStart) { // Mirrors the threshold gate: a null `periodStart` cannot race a // rollover, so any tracked collections are legitimately current. - return { periodStart: null, periodEnd: null, markerWasCurrent: true } + return { periodStart: null, periodEnd: null, markerWasCurrent: true, metadata: row?.metadata } } const markerWasCurrent = !!row.lastClosedPeriodStart && row.lastClosedPeriodStart.getTime() >= row.periodStart.getTime() - if (!markerWasCurrent && !options.sealLagging) { - return { periodStart: row.periodStart, periodEnd: row.periodEnd, markerWasCurrent } + const claim = { + periodStart: row.periodStart, + periodEnd: row.periodEnd, + markerWasCurrent, + metadata: row.metadata, } + if (!markerWasCurrent && !options.sealLagging) return claim if (!markerWasCurrent) { logger.error( 'Sealing an unclosed elapsed period at terminal claim; residual overage forgiven', @@ -259,7 +298,7 @@ export async function claimTerminalPeriod( ) } await claimCloseMarker(tx, subscriptionId, row.periodEnd ?? row.periodStart) - return { periodStart: row.periodStart, periodEnd: row.periodEnd, markerWasCurrent } + return claim }) } @@ -298,7 +337,8 @@ async function claimCloseMarker( * * 1. Sums the closed period's ledger usage per member from write-time period * stamps (`getStampedPeriodRangeUsageCostByUser`) — never `created_at`. - * 2. Collects final sub-threshold overage for non-enterprise plans: computed + * 2. Collects final sub-threshold overage for every plan but a hard-capped + * Enterprise contract: computed * overage minus what threshold billing already collected * (`billedOverageThisPeriod`), credits applied first, remainder invoiced * through the transaction-enlisted Stripe outbox with deterministic @@ -309,8 +349,8 @@ async function claimCloseMarker( * and marker commit atomically — a crash retries the whole close, and the * outbox's Stripe idempotency keys collapse invoice replays. * - * Enterprise subscriptions never collect money here (billing is contractual, - * outside Stripe); they get bookkeeping + marker only, and orgs on reporting + * Enterprise contracts outside self-serve never collect money here (billing is + * contractual); they get bookkeeping + marker only, and orgs on reporting * anchors skip bookkeeping too because their windows derive live from the * anchor. A null marker initializes to the current `periodStart` without * billing, so historical periods are never retroactively closed. @@ -429,24 +469,25 @@ export async function closeElapsedBillingPeriod( ? (memberRows.find((row) => row.role === 'owner')?.userId ?? null) : sub.referenceId - // Final overage for the closed period (enterprise never bills overage). + // Final overage for the closed period. // Refresh reads are scoped by the same entity/period stamps as the ledger // sums, so a departed member's org-attributed rows offset the overage // exactly like a current member's. let totalOverage = 0 - if (!enterprise) { + const billsClosedOverage = !isHardCappedEnterprise(sub) + if (billsClosedOverage) { if (orgScoped) { const { totalOverage: computed } = await computeOrgOverageAmount({ - plan: sub.plan, - seats: sub.seats ?? null, + subscription: { ...sub, seats: sub.seats ?? null }, periodStart: closeFrom, periodEnd: periodStart, organizationId: sub.referenceId, pooledLedgerUsage: closedLedgerUsage, + includedUsage: closedPeriodIncludedUsage(sub, closedRange, true), }) totalOverage = computed } else { - const weeklyRefreshDollars = getPlanWeeklyRefreshDollars(sub.plan) + const weeklyRefreshDollars = getSubscriptionWeeklyRefreshDollars(sub) let refreshConsumed = 0 if (weeklyRefreshDollars > 0) { refreshConsumed = await computeWeeklyRefreshConsumed({ @@ -456,15 +497,15 @@ export async function closeElapsedBillingPeriod( weeklyRefreshDollars, }) } - const { basePrice } = getPlanPricing(sub.plan) - totalOverage = Math.max(0, closedLedgerUsage - refreshConsumed - basePrice) + const includedUsage = closedPeriodIncludedUsage(sub, closedRange, false) + totalOverage = Math.max(0, closedLedgerUsage - refreshConsumed - includedUsage) } } // Labels use the closed period's END month, matching threshold billing's // period-end labeling for overage invoices. const billingPeriodLabel = periodStart.toISOString().slice(0, 7) - const collectMoney = !enterprise && totalOverage > 0 + const collectMoney = billsClosedOverage && totalOverage > 0 if (collectMoney && (!sub.stripeCustomerId || !sub.stripeSubscriptionId)) { // Claiming the marker here would silently forgive the overage. Defer the // whole close — the sweep retries every run until the Stripe linkage is @@ -824,19 +865,19 @@ const SWEEP_PAGE_SIZE = 250 const SWEEP_CLOSE_CONCURRENCY = 10 /** - * Entitled statuses inlined as SQL literals rather than bind parameters: the + * Settled statuses inlined as SQL literals rather than bind parameters: the * candidate scan targets the partial index on exactly this predicate, and the * planner can only prove a query implies a partial index's predicate from * literals — a parameterized generic plan would fall back to scanning the * whole table. */ -const ENTITLED_STATUS_LITERALS = sql.raw( - ENTITLED_SUBSCRIPTION_STATUSES.map((status) => `'${status}'`).join(', ') +const SETTLED_STATUS_LITERALS = sql.raw( + SETTLED_SUBSCRIPTION_STATUSES.map((status) => `'${status}'`).join(', ') ) /** * Daily catch-all that closes every elapsed billing period. Candidates are - * entitled subscriptions whose close marker lags their current `periodStart` + * settled subscriptions whose close marker lags their current `periodStart` * — i.e. the period advanced (via Stripe sync) since the last close. * * Iterates candidates in keyset pages (matching the partial index on exactly @@ -862,7 +903,7 @@ export async function sweepBillingCycleCloses(): Promise .from(subscriptionTable) .where( and( - sql`${subscriptionTable.status} in (${ENTITLED_STATUS_LITERALS})`, + sql`${subscriptionTable.status} in (${SETTLED_STATUS_LITERALS})`, sql`${subscriptionTable.periodStart} IS NOT NULL`, or( isNull(subscriptionTable.lastClosedPeriodStart), diff --git a/apps/sim/lib/billing/enterprise-credit-limits.ts b/apps/sim/lib/billing/enterprise-credit-limits.ts index 3f18dd715f9..2e78dfb84dd 100644 --- a/apps/sim/lib/billing/enterprise-credit-limits.ts +++ b/apps/sim/lib/billing/enterprise-credit-limits.ts @@ -7,15 +7,29 @@ interface DeriveEnterpriseCreditLimitsInput { prepaidBalanceDollars: string | number } +/** + * The credits an Enterprise contract includes each period, before prepaid credit or self-serve + * overage: its configured limit, or the invoice amount a contract without one defaults to. + */ +export function configuredEnterpriseUsageCredits( + usageLimitCredits: unknown, + invoiceAmountUsd: number +): number { + const parsedUsageLimitCredits = Number(usageLimitCredits) + return Number.isFinite(parsedUsageLimitCredits) + ? Math.max(0, Math.round(parsedUsageLimitCredits)) + : dollarsToCredits(invoiceAmountUsd) +} + export function deriveEnterpriseCreditLimits({ metadata, invoiceAmountUsd, prepaidBalanceDollars, }: DeriveEnterpriseCreditLimitsInput) { - const parsedUsageLimitCredits = Number(metadata.usageLimitCredits) - const configuredUsageLimitCredits = Number.isFinite(parsedUsageLimitCredits) - ? Math.max(0, Math.round(parsedUsageLimitCredits)) - : dollarsToCredits(invoiceAmountUsd) + const configuredUsageLimitCredits = configuredEnterpriseUsageCredits( + metadata.usageLimitCredits, + invoiceAmountUsd + ) const prepaidBalance = toDecimal(prepaidBalanceDollars) const prepaidCredits = dollarsToCredits(prepaidBalance.toNumber()) const effectiveUsageLimitDollars = toDecimal(configuredUsageLimitCredits) diff --git a/apps/sim/lib/billing/enterprise-outbox.ts b/apps/sim/lib/billing/enterprise-outbox.ts index 19087e30d8e..5eeadce7ad2 100644 --- a/apps/sim/lib/billing/enterprise-outbox.ts +++ b/apps/sim/lib/billing/enterprise-outbox.ts @@ -4,11 +4,13 @@ import { and, desc, eq, sql } from 'drizzle-orm' import type Stripe from 'stripe' import { z } from 'zod' import { MAX_BILLING_CONCURRENCY_LIMIT } from '@/lib/billing/concurrency-defaults' +import { INVOICE_DAYS_UNTIL_DUE } from '@/lib/billing/constants' import { ENTERPRISE_METADATA_SYNC_EVENT_TYPE, ENTERPRISE_PROVISION_EVENT_TYPE, } from '@/lib/billing/enterprise-outbox-events' import { MAX_WORKFLOW_EXECUTION_TIMEOUT_SECONDS } from '@/lib/billing/execution-timeout-defaults' +import { isSelfServeEnterpriseMetadata } from '@/lib/billing/subscriptions/utils' import type { DbOrTx } from '@/lib/db/types' import { MAX_INVITE_EMAILS } from '@/lib/invitations/limits' @@ -159,7 +161,7 @@ export function enterpriseMetadataIntentMatchesStripeSubscription( return ( !stripeSubscription.schedule && stripeSubscription.collection_method === 'send_invoice' && - stripeSubscription.days_until_due === 30 && + stripeSubscription.days_until_due === INVOICE_DAYS_UNTIL_DUE && items.length === 1 && (items[0]?.quantity ?? 1) === 1 && price?.currency === 'usd' && @@ -273,7 +275,7 @@ export function enterpriseOperationMatchesStripeSubscription( items.length === 1 && (item?.quantity ?? 1) === 1 && stripeSubscription.collection_method === 'send_invoice' && - stripeSubscription.days_until_due === 30 && + stripeSubscription.days_until_due === INVOICE_DAYS_UNTIL_DUE && price?.currency === 'usd' && price.unit_amount === request.invoiceAmountCents && price.recurring?.interval === request.billingInterval && @@ -360,12 +362,25 @@ function positiveInteger(value: unknown): number | null { return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null } +/** The metadata Stripe holds once an intent is delivered: a null value clears its key. */ +export function deliveredEnterpriseMetadata( + metadata: Record +): Record { + return Object.fromEntries(Object.entries(metadata).filter(([, value]) => value != null)) +} + export interface EnterpriseMetadataIntentState { latestRevision: number desiredMetadata: Record desiredTerms: EnterpriseMetadataSyncPayload['terms'] | null hasUnappliedIntent: boolean effectiveSeatCapacity: number | null + /** + * Whether the contract's seats are a baseline members may outgrow (self-serve, trued up) rather + * than a cap. Holds only when both the applied terms and any pending change are self-serve, so a + * change turning self-serve off caps seats from the moment it is requested. + */ + seatsUncapped: boolean configurationUpdate: { id: string status: 'pending' | 'processing' | 'failed' @@ -412,6 +427,7 @@ export async function resolveEnterpriseMetadataIntent( ) .limit(1) + const appliedSelfServe = isSelfServeEnterpriseMetadata(appliedMetadata) if (!latest) { return { latestRevision: appliedRevision, @@ -419,6 +435,7 @@ export async function resolveEnterpriseMetadataIntent( desiredTerms: null, hasUnappliedIntent: false, effectiveSeatCapacity: appliedSeats, + seatsUncapped: appliedSelfServe, configurationUpdate: null, } } @@ -455,6 +472,10 @@ export async function resolveEnterpriseMetadataIntent( desiredTerms: hasUnappliedIntent ? (parsed.data.terms ?? null) : null, hasUnappliedIntent, effectiveSeatCapacity, + seatsUncapped: + appliedSelfServe && + (!hasUnappliedIntent || + isSelfServeEnterpriseMetadata(deliveredEnterpriseMetadata(parsed.data.metadata))), configurationUpdate: operationApplied ? null : { diff --git a/apps/sim/lib/billing/enterprise-provisioning.ts b/apps/sim/lib/billing/enterprise-provisioning.ts index 439a2890de8..9ef7b05726e 100644 --- a/apps/sim/lib/billing/enterprise-provisioning.ts +++ b/apps/sim/lib/billing/enterprise-provisioning.ts @@ -34,6 +34,7 @@ import { parseAdminInvitationOperationPayload } from '@/lib/admin/invitation-ope import { ADMIN_INVITATION_OPERATION_EVENT_TYPE } from '@/lib/admin/invitation-operation-event' import { parseBillingConcurrencyLimit } from '@/lib/billing/concurrency-defaults' import { getBillingConcurrencyLimit } from '@/lib/billing/concurrency-limits' +import { INVOICE_DAYS_UNTIL_DUE } from '@/lib/billing/constants' import { resolveEnterpriseReportingPeriod } from '@/lib/billing/core/reporting-period' import { getBillingPeriodUsageCost, @@ -41,6 +42,7 @@ import { } from '@/lib/billing/core/usage-log' import { creditsToDollars, dollarsToCredits } from '@/lib/billing/credits/conversion' import { + deliveredEnterpriseMetadata, deriveEnterpriseOperationStatus, type EnterpriseInvitePeoplePayload, type EnterpriseMetadataSyncPayload, @@ -73,7 +75,10 @@ import { reapplyPaidOrgJoinBillingForExistingMemberTx, } from '@/lib/billing/organizations/membership' import { requireStripeClient } from '@/lib/billing/stripe-client' -import { TERMINAL_SUBSCRIPTION_STATUSES } from '@/lib/billing/subscriptions/utils' +import { + isSelfServeEnterpriseMetadata, + TERMINAL_SUBSCRIPTION_STATUSES, +} from '@/lib/billing/subscriptions/utils' import { countPendingSeatInvitations } from '@/lib/billing/validation/seat-management' import { withEnterpriseReconciliationLease } from '@/lib/billing/webhooks/enterprise-reconciliation-lease' import { OUTBOX_EVENT_TYPES } from '@/lib/billing/webhooks/outbox-events' @@ -2522,7 +2527,7 @@ export const provisionEnterpriseInStripe: OutboxHandler = async (rawPay customer: customerId, items: [{ price: priceId, quantity: 1 }], collection_method: 'send_invoice', - days_until_due: 30, + days_until_due: INVOICE_DAYS_UNTIL_DUE, metadata, }, { idempotencyKey: `enterprise:${context.eventId}:subscription` } @@ -2671,7 +2676,8 @@ export const syncEnterpriseMetadataInStripe: OutboxHandler = async ( }) if ( !Number.isSafeInteger(desiredSeats) || - desiredSeats < currentSeatRequirement.requiredSeats + (desiredSeats < currentSeatRequirement.requiredSeats && + !isSelfServeEnterpriseMetadata(deliveredEnterpriseMetadata(latestPayload.data.metadata))) ) { throw new Error('Enterprise seat intent is below current occupied or reserved seats') } @@ -2682,10 +2688,18 @@ export const syncEnterpriseMetadataInStripe: OutboxHandler = async ( } await context.checkpointPayload({ deliveryState }) + // Leaving self-serve also returns the contract to emailed invoices, in the same update: its + // customer loses the surface that manages the payment method automatic payment would charge. + const leavesSelfServe = + isSelfServeEnterpriseMetadata(stripeSubscription.metadata) && + !isSelfServeEnterpriseMetadata(deliveredEnterpriseMetadata(latestPayload.data.metadata)) const updatedSubscription = await stripe.subscriptions.update( stripeSubscriptionId, { metadata, + ...(leavesSelfServe + ? { collection_method: 'send_invoice', days_until_due: INVOICE_DAYS_UNTIL_DUE } + : {}), }, { idempotencyKey: `enterprise-config:${payload.subscriptionId}:${context.eventId}:delivery:${latestPayload.data.deliveryRevision}:attempt:${context.attempts}`, diff --git a/apps/sim/lib/billing/enterprise-seat-true-up.ts b/apps/sim/lib/billing/enterprise-seat-true-up.ts new file mode 100644 index 00000000000..23ebf1c3664 --- /dev/null +++ b/apps/sim/lib/billing/enterprise-seat-true-up.ts @@ -0,0 +1,222 @@ +import { db } from '@sim/db' +import { enterpriseSeatTrueUp, member, subscription } from '@sim/db/schema' +import { createLogger } from '@sim/logger' +import { generateId } from '@sim/utils/id' +import { and, count, eq, inArray, isNull, lte, sql } from 'drizzle-orm' +import { + isEnterpriseSelfServe, + SETTLED_SUBSCRIPTION_STATUSES, +} from '@/lib/billing/subscriptions/utils' +import { parseEnterpriseSubscriptionMetadata } from '@/lib/billing/types' +import { OUTBOX_EVENT_TYPES } from '@/lib/billing/webhooks/outbox-events' +import { enqueueOutboxEvent } from '@/lib/core/outbox/service' + +const logger = createLogger('EnterpriseSeatTrueUp') + +/** Annual contracts true up each quarter; a monthly contract trues up each term. */ +const ANNUAL_TRUE_UP_WINDOW_MONTHS = 3 + +export interface SeatTrueUpWindow { + start: Date + end: Date +} + +function addUtcMonths(date: Date, months: number): Date { + const result = new Date(date.getTime()) + const day = result.getUTCDate() + result.setUTCDate(1) + result.setUTCMonth(result.getUTCMonth() + months) + const lastDay = new Date( + Date.UTC(result.getUTCFullYear(), result.getUTCMonth() + 1, 0) + ).getUTCDate() + result.setUTCDate(Math.min(day, lastDay)) + return result +} + +/** + * The true-up window containing `now` within a subscription's current billing period: one of the + * four quarters of an annual term, or the whole monthly term. Null without a current period. + */ +export function resolveSeatTrueUpWindow( + sub: { periodStart: Date | null; periodEnd: Date | null; billingInterval: string | null }, + now: Date = new Date() +): SeatTrueUpWindow | null { + if (!sub.periodStart || !sub.periodEnd) return null + if (now < sub.periodStart || now >= sub.periodEnd) return null + if (sub.billingInterval !== 'year') { + return { start: sub.periodStart, end: sub.periodEnd } + } + let offset = 0 + while ( + offset + ANNUAL_TRUE_UP_WINDOW_MONTHS < 12 && + addUtcMonths(sub.periodStart, offset + ANNUAL_TRUE_UP_WINDOW_MONTHS) <= now + ) { + offset += ANNUAL_TRUE_UP_WINDOW_MONTHS + } + const start = addUtcMonths(sub.periodStart, offset) + const end = + offset + ANNUAL_TRUE_UP_WINDOW_MONTHS >= 12 + ? sub.periodEnd + : addUtcMonths(sub.periodStart, offset + ANNUAL_TRUE_UP_WINDOW_MONTHS) + return { start, end } +} + +/** + * Raises the open window's peak to the members past the contract right now, for one self-serve + * Enterprise contract. Pending invitations are not seats until accepted. A window keeps the seat + * rate it opened with, so a rate change applies from the next window. + */ +async function sampleSeatPeak(sub: typeof subscription.$inferSelect, now: Date): Promise { + const window = resolveSeatTrueUpWindow(sub, now) + const terms = parseEnterpriseSubscriptionMetadata(sub.metadata) + if (!window || !terms?.seatPriceCents) return false + const [memberCount] = await db + .select({ value: count() }) + .from(member) + .where(eq(member.organizationId, sub.referenceId)) + const extraSeats = Math.max(0, (memberCount?.value ?? 0) - terms.seats) + await db + .insert(enterpriseSeatTrueUp) + .values({ + id: generateId(), + subscriptionId: sub.id, + organizationId: sub.referenceId, + windowStart: window.start, + windowEnd: window.end, + peakExtraSeats: extraSeats, + seatPriceCents: terms.seatPriceCents, + }) + .onConflictDoUpdate({ + target: [enterpriseSeatTrueUp.subscriptionId, enterpriseSeatTrueUp.windowStart], + set: { + peakExtraSeats: sql`GREATEST(${enterpriseSeatTrueUp.peakExtraSeats}, ${extraSeats})`, + updatedAt: now, + }, + setWhere: isNull(enterpriseSeatTrueUp.billedAt), + }) + return true +} + +/** Whole months a window spans: what each seat past the contract is billed for. */ +function windowMonths(row: { windowStart: Date; windowEnd: Date }): number { + let months = 0 + while (months < 12 && addUtcMonths(row.windowStart, months + 1) <= row.windowEnd) months++ + return Math.max(1, months) +} + +/** + * Invoices one closed window: its peak seats past the contract, at the seat rate it opened with, + * for the months it spans. Stamping `billedAt` and enqueuing the invoice commit together under the + * row lock, so a window is invoiced at most once. + */ +async function billClosedWindow(windowId: string): Promise { + return db.transaction(async (tx) => { + const [row] = await tx + .select({ + window: enterpriseSeatTrueUp, + stripeCustomerId: subscription.stripeCustomerId, + stripeSubscriptionId: subscription.stripeSubscriptionId, + }) + .from(enterpriseSeatTrueUp) + .innerJoin(subscription, eq(subscription.id, enterpriseSeatTrueUp.subscriptionId)) + .where(and(eq(enterpriseSeatTrueUp.id, windowId), isNull(enterpriseSeatTrueUp.billedAt))) + .for('update', { of: enterpriseSeatTrueUp }) + .limit(1) + if (!row) return 0 + + const { peakExtraSeats, seatPriceCents } = row.window + const months = windowMonths(row.window) + const amountCents = peakExtraSeats * seatPriceCents * months + const { stripeCustomerId, stripeSubscriptionId } = row + if (amountCents > 0 && (!stripeCustomerId || !stripeSubscriptionId)) { + logger.error('Deferring seat true-up: Stripe identifiers are missing', { + windowId, + subscriptionId: row.window.subscriptionId, + }) + return 0 + } + + await tx + .update(enterpriseSeatTrueUp) + .set({ amountCents, billedAt: new Date(), updatedAt: new Date() }) + .where(eq(enterpriseSeatTrueUp.id, windowId)) + + if (amountCents > 0 && stripeCustomerId && stripeSubscriptionId) { + const from = row.window.windowStart.toISOString().slice(0, 10) + const to = row.window.windowEnd.toISOString().slice(0, 10) + await enqueueOutboxEvent(tx, OUTBOX_EVENT_TYPES.STRIPE_THRESHOLD_OVERAGE_INVOICE, { + customerId: stripeCustomerId, + stripeSubscriptionId, + amountCents, + description: `Seat true-up – ${from} to ${to}`, + itemDescription: `${peakExtraSeats} additional seat${peakExtraSeats === 1 ? '' : 's'} × ${months} month${months === 1 ? '' : 's'} at $${(seatPriceCents / 100).toFixed(2)} per seat per month`, + billingPeriod: row.window.windowEnd.toISOString().slice(0, 7), + invoiceIdemKeyStem: `seat-true-up-invoice:${windowId}`, + itemIdemKeyStem: `seat-true-up-item:${windowId}`, + metadata: { + type: 'enterprise_seat_true_up', + organizationId: row.window.organizationId, + subscriptionId: stripeSubscriptionId, + windowStart: row.window.windowStart.toISOString(), + windowEnd: row.window.windowEnd.toISOString(), + extraSeats: String(peakExtraSeats), + }, + }) + } + + logger.info('Closed Enterprise seat true-up window', { + windowId, + organizationId: row.window.organizationId, + peakExtraSeats, + amountCents, + }) + return amountCents + }) +} + +/** + * The seat true-up sweep for self-serve Enterprise contracts: records each open window's peak + * seats past the contract, then invoices every closed, unbilled window. Seats are billed in + * arrears, so a customer who removes members pays less from the next window on. + */ +export async function runEnterpriseSeatTrueUps(now: Date = new Date()) { + const candidates = await db + .select() + .from(subscription) + .where( + and( + eq(subscription.plan, 'enterprise'), + inArray(subscription.status, SETTLED_SUBSCRIPTION_STATUSES), + sql`${subscription.metadata} ->> 'selfServe' = 'true'` + ) + ) + let sampled = 0 + let failed = 0 + for (const sub of candidates) { + if (!isEnterpriseSelfServe(sub)) continue + try { + if (await sampleSeatPeak(sub, now)) sampled++ + } catch (error) { + failed++ + logger.error('Failed to sample Enterprise seat true-up peak', { + subscriptionId: sub.id, + error, + }) + } + } + + const closed = await db + .select({ id: enterpriseSeatTrueUp.id }) + .from(enterpriseSeatTrueUp) + .where(and(isNull(enterpriseSeatTrueUp.billedAt), lte(enterpriseSeatTrueUp.windowEnd, now))) + let billedCents = 0 + for (const window of closed) { + try { + billedCents += await billClosedWindow(window.id) + } catch (error) { + failed++ + logger.error('Failed to bill Enterprise seat true-up window', { windowId: window.id, error }) + } + } + return { sampled, closed: closed.length, failed, billedCents } +} diff --git a/apps/sim/lib/billing/enterprise-self-serve.integration.ts b/apps/sim/lib/billing/enterprise-self-serve.integration.ts new file mode 100644 index 00000000000..54fb5ac8689 --- /dev/null +++ b/apps/sim/lib/billing/enterprise-self-serve.integration.ts @@ -0,0 +1,558 @@ +/** + * Self-serve Enterprise billing against real PostgreSQL, with Stripe stubbed at its client. + * + * Failure modes covered: + * - a contract outside self-serve (or one still carrying a reporting anchor) lets its customer + * raise the usage limit, or bills overage on usage the flat contract already covers; + * - a self-serve customer sets a limit below what the contract covers; + * - a self-serve contract's seats still cap who can join, or a hard-capped contract's do not; + * - a contract missing its seat rate runs as self-serve; + * - auto-pay switches a contract from a session that is not its own, or one that no longer + * belongs to a self-serve contract; + * - the seat true-up misses the window's peak, bills an open window, bills a window twice, or + * bills a contract that is not self-serve. + */ +import { db } from '@sim/db' +import { + enterpriseSeatTrueUp, + member, + organization, + outboxEvent, + subscription, + usageLog, + user, +} from '@sim/db/schema' +import { generateId } from '@sim/utils/id' +import { and, eq, inArray, sql } from 'drizzle-orm' +import type Stripe from 'stripe' +import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { calculateSubscriptionOverage } from '@/lib/billing/core/billing' +import { updateOrganizationUsageLimit } from '@/lib/billing/core/organization' +import { + resolveSeatTrueUpWindow, + runEnterpriseSeatTrueUps, +} from '@/lib/billing/enterprise-seat-true-up' +import { ensureUserInOrganization } from '@/lib/billing/organizations/membership' +import { + ENTERPRISE_AUTO_PAY_PURPOSE, + handleEnterpriseAutoPaySetup, +} from '@/lib/billing/webhooks/enterprise-auto-pay' +import { OUTBOX_EVENT_TYPES } from '@/lib/billing/webhooks/outbox-events' + +const { stripeStub } = vi.hoisted(() => ({ + stripeStub: { + setupIntents: { retrieve: vi.fn() }, + customers: { update: vi.fn() }, + subscriptions: { retrieve: vi.fn(), update: vi.fn() }, + }, +})) + +vi.mock('@/lib/billing/stripe-client', () => ({ + requireStripeClient: () => stripeStub, + getStripeClient: () => stripeStub, +})) +// Seat caps are enforced only where billing runs. +vi.mock('@/lib/core/config/env-flags', async (importOriginal) => ({ + ...(await importOriginal()), + isBillingEnabled: true, +})) + +const DAY_MS = 86_400_000 +/** $1,000 of included usage. */ +const INCLUDED_CREDITS = 200_000 +const SEAT_PRICE_CENTS = 1_000 + +const userIds: string[] = [] +const organizationIds: string[] = [] +const subscriptionIds: string[] = [] + +async function createUser(): Promise { + const id = `ent-self-serve-${generateId()}` + const now = new Date() + await db.insert(user).values({ + id, + name: 'Self Serve Test', + email: `${id}@self-serve.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + userIds.push(id) + return id +} + +async function createOrganization(memberCount: number, creditBalance = '0') { + const id = `ent-self-serve-org-${generateId()}` + await db.insert(organization).values({ + id, + name: 'Self Serve Org', + slug: id, + creditBalance, + createdAt: new Date(), + updatedAt: new Date(), + }) + organizationIds.push(id) + const members: string[] = [] + for (let index = 0; index < memberCount; index++) { + const userId = await createUser() + await db.insert(member).values({ + id: generateId(), + userId, + organizationId: id, + role: index === 0 ? 'owner' : 'member', + createdAt: new Date(), + }) + members.push(userId) + } + return { id, members } +} + +async function addEnterpriseSubscription( + organizationId: string, + options: { + selfServe: boolean + seatPriceCents?: number | null + seats: number + periodStart: Date + billingInterval?: 'month' | 'year' + reportingPeriodAnchorDate?: string + } +) { + const id = generateId() + const billingInterval = options.billingInterval ?? 'year' + const periodEnd = new Date(options.periodStart) + if (billingInterval === 'year') periodEnd.setUTCFullYear(periodEnd.getUTCFullYear() + 1) + else periodEnd.setUTCMonth(periodEnd.getUTCMonth() + 1) + await db.insert(subscription).values({ + id, + plan: 'enterprise', + referenceId: organizationId, + stripeCustomerId: `cus_${generateId()}`, + stripeSubscriptionId: `sub_${generateId()}`, + status: 'active', + periodStart: options.periodStart, + periodEnd, + seats: 1, + billingInterval, + metadata: { + plan: 'enterprise', + referenceId: organizationId, + invoiceAmountCents: '1000000', + usageLimitCredits: String(INCLUDED_CREDITS), + seats: String(options.seats), + ...(options.seatPriceCents === null + ? {} + : { seatPriceCents: String(options.seatPriceCents ?? SEAT_PRICE_CENTS) }), + ...(options.selfServe ? { selfServe: 'true' } : {}), + ...(options.reportingPeriodAnchorDate + ? { + reportingPeriodAnchorDate: options.reportingPeriodAnchorDate, + reportingPeriodInterval: billingInterval, + } + : {}), + }, + }) + subscriptionIds.push(id) + const [row] = await db.select().from(subscription).where(eq(subscription.id, id)) + return row +} + +async function recordOrganizationUsage( + organizationId: string, + userId: string, + period: { start: Date; end: Date }, + cost: number +) { + await db.insert(usageLog).values({ + id: generateId(), + userId, + category: 'model', + source: 'workflow', + description: 'self-serve overage test', + cost: String(cost), + billingEntityType: 'organization', + billingEntityId: organizationId, + billingPeriodStart: period.start, + billingPeriodEnd: period.end, + createdAt: new Date(period.start.getTime() + DAY_MS), + }) +} + +async function trueUpInvoices(stripeSubscriptionId: string | null) { + return db + .select({ payload: outboxEvent.payload }) + .from(outboxEvent) + .where( + and( + eq(outboxEvent.eventType, OUTBOX_EVENT_TYPES.STRIPE_THRESHOLD_OVERAGE_INVOICE), + sql`${outboxEvent.payload} ->> 'stripeSubscriptionId' = ${stripeSubscriptionId}` + ) + ) +} + +function monthsAgo(months: number): Date { + const date = new Date() + date.setUTCMonth(date.getUTCMonth() - months) + return date +} + +afterAll(async () => { + if (subscriptionIds.length > 0) { + const rows = await db + .select({ stripeSubscriptionId: subscription.stripeSubscriptionId }) + .from(subscription) + .where(inArray(subscription.id, subscriptionIds)) + for (const row of rows) { + await db + .delete(outboxEvent) + .where(sql`${outboxEvent.payload} ->> 'stripeSubscriptionId' = ${row.stripeSubscriptionId}`) + } + await db.delete(subscription).where(inArray(subscription.id, subscriptionIds)) + } + if (userIds.length > 0) { + await db.delete(usageLog).where(inArray(usageLog.userId, userIds)) + await db.delete(user).where(inArray(user.id, userIds)) + } + if (organizationIds.length > 0) { + await db.delete(organization).where(inArray(organization.id, organizationIds)) + } +}) + +describe('the customer usage limit', () => { + it('stays fixed on a contract outside self-serve', async () => { + const org = await createOrganization(1) + await addEnterpriseSubscription(org.id, { + selfServe: false, + seats: 5, + periodStart: monthsAgo(1), + }) + + const result = await updateOrganizationUsageLimit(org.id, 5_000) + + expect(result.success).toBe(false) + }) + + it('stays fixed while a self-serve contract still carries a reporting anchor', async () => { + const org = await createOrganization(1) + await addEnterpriseSubscription(org.id, { + selfServe: true, + seats: 5, + periodStart: monthsAgo(1), + reportingPeriodAnchorDate: monthsAgo(1).toISOString().slice(0, 10), + }) + + const result = await updateOrganizationUsageLimit(org.id, 5_000) + + expect(result.success).toBe(false) + }) + + it('cannot fall below the included usage plus prepaid credit', async () => { + const org = await createOrganization(1, '50') + await addEnterpriseSubscription(org.id, { + selfServe: true, + seats: 5, + periodStart: monthsAgo(1), + }) + + const result = await updateOrganizationUsageLimit(org.id, 1_000) + + expect(result).toMatchObject({ success: false }) + expect(result.error).toContain('210,000 credits') + }) + + it('is stored apart from the enforced limit once a self-serve customer raises it', async () => { + const org = await createOrganization(1, '50') + await addEnterpriseSubscription(org.id, { + selfServe: true, + seats: 5, + periodStart: monthsAgo(1), + }) + + const result = await updateOrganizationUsageLimit(org.id, 2_500) + + expect(result).toEqual({ success: true }) + const [row] = await db + .select({ + orgUsageLimit: organization.orgUsageLimit, + selfServeUsageLimit: organization.selfServeUsageLimit, + }) + .from(organization) + .where(eq(organization.id, org.id)) + expect(Number(row?.orgUsageLimit)).toBe(2_500) + expect(Number(row?.selfServeUsageLimit)).toBe(2_500) + }) +}) + +describe('overage', () => { + it('bills usage past the included allowance on a self-serve contract', async () => { + const org = await createOrganization(1) + const sub = await addEnterpriseSubscription(org.id, { + selfServe: true, + seats: 5, + periodStart: monthsAgo(1), + billingInterval: 'month', + }) + if (!sub?.periodStart || !sub.periodEnd) throw new Error('subscription period missing') + await recordOrganizationUsage( + org.id, + org.members[0], + { start: sub.periodStart, end: sub.periodEnd }, + 1_500 + ) + + expect(await calculateSubscriptionOverage(sub)).toBeCloseTo(500, 6) + }) + + it('never bills usage on a contract outside self-serve', async () => { + const org = await createOrganization(1) + const sub = await addEnterpriseSubscription(org.id, { + selfServe: false, + seats: 5, + periodStart: monthsAgo(1), + billingInterval: 'month', + }) + if (!sub?.periodStart || !sub.periodEnd) throw new Error('subscription period missing') + await recordOrganizationUsage( + org.id, + org.members[0], + { start: sub.periodStart, end: sub.periodEnd }, + 1_500 + ) + + expect(await calculateSubscriptionOverage(sub)).toBe(0) + }) +}) + +describe('the seat cap', () => { + it('admits members past a self-serve contract and refuses them past a hard-capped one', async () => { + const selfServeOrg = await createOrganization(2) + await addEnterpriseSubscription(selfServeOrg.id, { + selfServe: true, + seats: 2, + periodStart: monthsAgo(1), + }) + const fixedOrg = await createOrganization(2) + await addEnterpriseSubscription(fixedOrg.id, { + selfServe: false, + seats: 2, + periodStart: monthsAgo(1), + }) + + const joinedSelfServe = await ensureUserInOrganization({ + userId: await createUser(), + organizationId: selfServeOrg.id, + role: 'member', + }) + const joinedFixed = await ensureUserInOrganization({ + userId: await createUser(), + organizationId: fixedOrg.id, + role: 'member', + }) + + expect(joinedSelfServe.success).toBe(true) + expect(joinedFixed).toMatchObject({ success: false, failureCode: 'no-seats-available' }) + }) + + it('stays capped when a self-serve contract has no seat rate', async () => { + const org = await createOrganization(2) + await addEnterpriseSubscription(org.id, { + selfServe: true, + seatPriceCents: null, + seats: 2, + periodStart: monthsAgo(1), + }) + + const joined = await ensureUserInOrganization({ + userId: await createUser(), + organizationId: org.id, + role: 'member', + }) + + expect(joined).toMatchObject({ success: false, failureCode: 'no-seats-available' }) + }) +}) + +describe('auto-pay', () => { + beforeEach(() => { + stripeStub.setupIntents.retrieve.mockReset() + stripeStub.customers.update.mockReset() + stripeStub.subscriptions.update.mockReset() + stripeStub.subscriptions.retrieve.mockReset() + stripeStub.setupIntents.retrieve.mockResolvedValue({ + status: 'succeeded', + payment_method: 'pm_saved', + payment_method_types: ['card'], + }) + }) + + function setupSession( + sub: { + referenceId: string + stripeCustomerId: string | null + stripeSubscriptionId: string | null + }, + overrides: Partial = {} + ): Stripe.Checkout.Session { + return { + id: `cs_${generateId()}`, + mode: 'setup', + customer: sub.stripeCustomerId, + setup_intent: 'seti_1', + metadata: { + purpose: ENTERPRISE_AUTO_PAY_PURPOSE, + organizationId: sub.referenceId, + stripeSubscriptionId: sub.stripeSubscriptionId ?? '', + }, + ...overrides, + } as Stripe.Checkout.Session + } + + it('switches a self-serve contract to its saved payment method', async () => { + const org = await createOrganization(1) + const sub = await addEnterpriseSubscription(org.id, { + selfServe: true, + seats: 2, + periodStart: monthsAgo(1), + }) + if (!sub) throw new Error('subscription missing') + stripeStub.subscriptions.retrieve.mockResolvedValue({ metadata: sub.metadata }) + + await handleEnterpriseAutoPaySetup(setupSession(sub)) + + expect(stripeStub.subscriptions.update).toHaveBeenCalledWith( + sub.stripeSubscriptionId, + { collection_method: 'charge_automatically', default_payment_method: 'pm_saved' }, + expect.anything() + ) + }) + + it('does not switch a contract that left self-serve after the session was checked', async () => { + const org = await createOrganization(1) + const sub = await addEnterpriseSubscription(org.id, { + selfServe: true, + seats: 2, + periodStart: monthsAgo(1), + }) + if (!sub) throw new Error('subscription missing') + stripeStub.subscriptions.retrieve.mockResolvedValue({ + metadata: { ...(sub.metadata as Record), selfServe: '' }, + }) + + await handleEnterpriseAutoPaySetup(setupSession(sub)) + + expect(stripeStub.subscriptions.update).not.toHaveBeenCalled() + }) + + it("ignores another customer's session and a contract outside self-serve", async () => { + const org = await createOrganization(1) + const sub = await addEnterpriseSubscription(org.id, { + selfServe: true, + seats: 2, + periodStart: monthsAgo(1), + }) + const fixedOrg = await createOrganization(1) + const fixedSub = await addEnterpriseSubscription(fixedOrg.id, { + selfServe: false, + seats: 2, + periodStart: monthsAgo(1), + }) + if (!sub || !fixedSub) throw new Error('subscriptions missing') + + await handleEnterpriseAutoPaySetup(setupSession(sub, { customer: 'cus_someone_else' })) + await handleEnterpriseAutoPaySetup(setupSession(fixedSub)) + + expect(stripeStub.customers.update).not.toHaveBeenCalled() + expect(stripeStub.subscriptions.update).not.toHaveBeenCalled() + }) +}) + +describe('the seat true-up', () => { + it('records the peak, bills a closed window once, and skips contracts outside self-serve', async () => { + const selfServeOrg = await createOrganization(3) + const selfServeSub = await addEnterpriseSubscription(selfServeOrg.id, { + selfServe: true, + seats: 2, + periodStart: monthsAgo(4), + }) + // Asks for self-serve but keeps a reporting anchor, so only the self-serve check excludes it. + const fixedOrg = await createOrganization(3) + const fixedSub = await addEnterpriseSubscription(fixedOrg.id, { + selfServe: true, + seats: 2, + periodStart: monthsAgo(4), + reportingPeriodAnchorDate: monthsAgo(4).toISOString().slice(0, 10), + }) + if (!selfServeSub || !fixedSub) throw new Error('subscriptions missing') + + const now = new Date() + const window = resolveSeatTrueUpWindow(selfServeSub, now) + if (!window) throw new Error('no open true-up window') + await runEnterpriseSeatTrueUps(now) + + // A member leaving after the sample does not lower the window's peak. + await db.delete(member).where(eq(member.userId, selfServeOrg.members[2])) + await runEnterpriseSeatTrueUps(now) + + const [open] = await db + .select() + .from(enterpriseSeatTrueUp) + .where( + and( + eq(enterpriseSeatTrueUp.subscriptionId, selfServeSub.id), + eq(enterpriseSeatTrueUp.windowStart, window.start) + ) + ) + expect(open).toMatchObject({ + peakExtraSeats: 1, + seatPriceCents: SEAT_PRICE_CENTS, + billedAt: null, + }) + expect(await trueUpInvoices(selfServeSub.stripeSubscriptionId)).toHaveLength(0) + + const afterClose = new Date(window.end.getTime() + 60_000) + await runEnterpriseSeatTrueUps(afterClose) + await runEnterpriseSeatTrueUps(afterClose) + + const [closed] = await db + .select() + .from(enterpriseSeatTrueUp) + .where(eq(enterpriseSeatTrueUp.id, open?.id ?? '')) + expect(closed).toMatchObject({ amountCents: SEAT_PRICE_CENTS * 3 }) + expect(closed?.billedAt).not.toBeNull() + const invoices = await trueUpInvoices(selfServeSub.stripeSubscriptionId) + expect(invoices).toHaveLength(1) + expect(invoices[0]?.payload).toMatchObject({ amountCents: SEAT_PRICE_CENTS * 3 }) + + const fixedWindows = await db + .select() + .from(enterpriseSeatTrueUp) + .where(eq(enterpriseSeatTrueUp.subscriptionId, fixedSub.id)) + expect(fixedWindows).toHaveLength(0) + }) + + it('splits an annual term into quarters and a monthly term into one window', () => { + const periodStart = new Date('2026-01-31T12:00:00.000Z') + const annual = { + periodStart, + periodEnd: new Date('2027-01-31T12:00:00.000Z'), + billingInterval: 'year', + } + expect(resolveSeatTrueUpWindow(annual, new Date('2026-05-15T00:00:00.000Z'))).toEqual({ + start: new Date('2026-04-30T12:00:00.000Z'), + end: new Date('2026-07-31T12:00:00.000Z'), + }) + expect(resolveSeatTrueUpWindow(annual, new Date('2026-12-01T00:00:00.000Z'))).toEqual({ + start: new Date('2026-10-31T12:00:00.000Z'), + end: annual.periodEnd, + }) + const monthly = { + ...annual, + periodEnd: new Date('2026-02-28T12:00:00.000Z'), + billingInterval: 'month', + } + expect(resolveSeatTrueUpWindow(monthly, new Date('2026-02-10T00:00:00.000Z'))).toEqual({ + start: periodStart, + end: monthly.periodEnd, + }) + }) +}) diff --git a/apps/sim/lib/billing/free-plan.integration.ts b/apps/sim/lib/billing/free-plan.integration.ts new file mode 100644 index 00000000000..3b1e45d6816 --- /dev/null +++ b/apps/sim/lib/billing/free-plan.integration.ts @@ -0,0 +1,316 @@ +/** + * What the Free plan and the trial edges do against real PostgreSQL: web search is held to paid + * payers like every hosted tool, a schedule a free payer's run cannot serve turns off at once, the + * trial-ending reminder goes out once per trial, and only an account's own trial can be ended + * early (Stripe and mail stubbed at their clients). + */ +import { db } from '@sim/db' +import { subscription, user, userStats, workflowSchedule, workspace } from '@sim/db/schema' +import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' +import { generateId } from '@sim/utils/id' +import { eq, inArray } from 'drizzle-orm' +import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { endProTrial } from '@/lib/billing/application/pro-trial' +import { HostedKeyRequiresPaidPlanError } from '@/lib/billing/core/hosted-key-access' +import { + handleTrialWillEnd, + type TrialEndingSubscription, +} from '@/lib/billing/webhooks/plan-notices' +import { executeSearchTool } from '@/lib/internal/search/execute-tool' +import { applyScheduleRunFailureUpdate } from '@/background/schedule-execution' + +const { stripeStub, mockSendEmail, mockNotifyScheduleAutoDisabled } = vi.hoisted(() => ({ + stripeStub: { subscriptions: { update: vi.fn() }, invoices: { createPreview: vi.fn() } }, + mockSendEmail: vi.fn(), + mockNotifyScheduleAutoDisabled: vi.fn(), +})) + +vi.mock('@/lib/core/config/env-flags', async (importOriginal) => ({ + ...(await importOriginal()), + isHosted: true, + isBillingEnabled: true, +})) + +vi.mock('@/lib/billing/stripe-client', () => ({ + requireStripeClient: () => stripeStub, + getStripeClient: () => stripeStub, +})) + +vi.mock('@/lib/messaging/email/mailer', () => ({ sendEmail: mockSendEmail })) + +vi.mock('@/lib/workflows/schedules/disable-notifications', () => ({ + notifyScheduleAutoDisabled: mockNotifyScheduleAutoDisabled, +})) + +const PRO_PLAN = 'pro_6000' +const DAY_MS = 86_400_000 + +const userIds: string[] = [] +const workspaceIds: string[] = [] +const scheduleIds: string[] = [] + +async function createUser(): Promise { + const id = `free-plan-user-${generateId()}` + const now = new Date() + await db.insert(user).values({ + id, + name: 'Free Plan Test', + email: `${id}@free-plan.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + await db.insert(userStats).values({ id: generateId(), userId: id }) + userIds.push(id) + return id +} + +async function createWorkspace(ownerId: string): Promise { + const id = generateId() + await insertWorkspaceFixture(db, { + id, + ownerId, + billedAccountUserId: ownerId, + name: 'Free plan workspace', + }) + workspaceIds.push(id) + return id +} + +async function addSubscription(referenceId: string, status: string) { + const stripeSubscriptionId = `sub_${generateId()}` + const now = Date.now() + await db.insert(subscription).values({ + id: generateId(), + plan: PRO_PLAN, + referenceId, + status, + stripeSubscriptionId, + periodStart: new Date(now - DAY_MS), + periodEnd: new Date(now + 13 * DAY_MS), + trialStart: status === 'trialing' ? new Date(now - DAY_MS) : null, + trialEnd: status === 'trialing' ? new Date(now + 13 * DAY_MS) : null, + }) + return stripeSubscriptionId +} + +function search(userId: string, workspaceId: string) { + return executeSearchTool({ + toolId: 'search_tool', + input: { query: 'sim workflows' }, + headers: new Headers(), + context: { workflowId: 'workflow-under-test', workspaceId, userId }, + requestId: generateId(), + }) +} + +function trialWillEnd(stripeSubscriptionId: string, status = 'trialing'): TrialEndingSubscription { + return { + id: stripeSubscriptionId, + status, + trial_end: Math.floor((Date.now() + 3 * DAY_MS) / 1000), + items: { + data: [{ quantity: 1, price: { unit_amount: 2500, recurring: { interval: 'month' } } }], + }, + } +} + +async function addClaimedSchedule() { + const id = generateId() + const claimedAt = new Date() + await db.insert(workflowSchedule).values({ + id, + triggerType: 'schedule', + cronExpression: '*/5 * * * *', + status: 'active', + failedCount: 0, + lastQueuedAt: claimedAt, + nextRunAt: claimedAt, + }) + scheduleIds.push(id) + return { id, claimedAt } +} + +async function readSchedule(id: string) { + const [row] = await db + .select({ status: workflowSchedule.status, failedCount: workflowSchedule.failedCount }) + .from(workflowSchedule) + .where(eq(workflowSchedule.id, id)) + return row +} + +beforeEach(() => { + stripeStub.subscriptions.update.mockReset() + stripeStub.subscriptions.update.mockResolvedValue({}) + mockSendEmail.mockReset() + mockSendEmail.mockResolvedValue({ success: true }) + stripeStub.invoices.createPreview.mockReset() + stripeStub.invoices.createPreview.mockResolvedValue({ amount_due: 2500 }) + mockNotifyScheduleAutoDisabled.mockReset() +}) + +afterAll(async () => { + if (scheduleIds.length > 0) { + await db.delete(workflowSchedule).where(inArray(workflowSchedule.id, scheduleIds)) + } + if (workspaceIds.length > 0) { + await deleteWorkspaceFixture(db, inArray(workspace.id, workspaceIds)) + } + if (userIds.length > 0) { + await db.delete(subscription).where(inArray(subscription.referenceId, userIds)) + await db.delete(user).where(inArray(user.id, userIds)) + } +}) + +describe('web search', () => { + it('refuses a free payer with the paid-plan 402', async () => { + const userId = await createUser() + const workspaceId = await createWorkspace(userId) + + const response = await search(userId, workspaceId) + + expect(response.status).toBe(402) + expect((await response.json()).error).toBe( + new HostedKeyRequiresPaidPlanError('Web Search').message + ) + }) + + it('lets a paid payer through to the search provider', async () => { + const userId = await createUser() + const workspaceId = await createWorkspace(userId) + await addSubscription(userId, 'active') + + const response = await search(userId, workspaceId) + + // Past the plan gate, the request reaches the provider step, which has no key under test. + expect(response.status).toBe(503) + expect((await response.json()).error).toBe('Search service not configured') + }) +}) + +describe('applyScheduleRunFailureUpdate', () => { + it("disables a schedule at once when the run was refused Sim's hosted key", async () => { + const schedule = await addClaimedSchedule() + + const result = await applyScheduleRunFailureUpdate({ + scheduleId: schedule.id, + now: new Date(), + nextRunAt: new Date(Date.now() + 300_000), + expectedLastQueuedAt: schedule.claimedAt, + requestId: generateId(), + context: 'test', + failureMessage: `Agent 1: ${new HostedKeyRequiresPaidPlanError('claude-sonnet-5-5').message}`, + }) + + expect(result.disabled).toBe(true) + expect((await readSchedule(schedule.id))?.status).toBe('disabled') + expect(mockNotifyScheduleAutoDisabled).toHaveBeenCalledWith( + expect.objectContaining({ scheduleId: schedule.id, reason: 'paid_plan_required' }) + ) + }) + + it('keeps counting any other failure toward the consecutive-failure limit', async () => { + const schedule = await addClaimedSchedule() + + const result = await applyScheduleRunFailureUpdate({ + scheduleId: schedule.id, + now: new Date(), + nextRunAt: new Date(Date.now() + 300_000), + expectedLastQueuedAt: schedule.claimedAt, + requestId: generateId(), + context: 'test', + failureMessage: 'Request timed out', + }) + + expect(result.disabled).toBe(false) + expect(await readSchedule(schedule.id)).toEqual({ status: 'active', failedCount: 1 }) + expect(mockNotifyScheduleAutoDisabled).not.toHaveBeenCalled() + }) +}) + +describe('handleTrialWillEnd', () => { + it('emails the trial reminder once however often Stripe redelivers it', async () => { + const userId = await createUser() + const stripeSubscriptionId = await addSubscription(userId, 'trialing') + const redelivered = trialWillEnd(stripeSubscriptionId) + + await handleTrialWillEnd(redelivered) + await handleTrialWillEnd(redelivered) + + expect(mockSendEmail).toHaveBeenCalledTimes(1) + expect(mockSendEmail).toHaveBeenCalledWith( + expect.objectContaining({ to: `${userId}@free-plan.test` }) + ) + }) + + it('quotes the discounted charge from the invoice preview', async () => { + const userId = await createUser() + const stripeSubscriptionId = await addSubscription(userId, 'trialing') + stripeStub.invoices.createPreview.mockResolvedValue({ amount_due: 1250 }) + + await handleTrialWillEnd(trialWillEnd(stripeSubscriptionId)) + + expect(mockSendEmail.mock.calls[0]?.[0].html).toContain('$12.50/month') + }) + + it('retries a reminder whose email failed to send', async () => { + const userId = await createUser() + const stripeSubscriptionId = await addSubscription(userId, 'trialing') + const event = trialWillEnd(stripeSubscriptionId) + mockSendEmail.mockResolvedValueOnce({ success: false, message: 'Failed to send email' }) + + await expect(handleTrialWillEnd(event)).rejects.toThrow() + await handleTrialWillEnd(event) + + expect(mockSendEmail).toHaveBeenCalledTimes(2) + }) + + it('sends nothing for a subscription that is no longer trialing', async () => { + const userId = await createUser() + const stripeSubscriptionId = await addSubscription(userId, 'active') + + await handleTrialWillEnd(trialWillEnd(stripeSubscriptionId, 'active')) + + expect(mockSendEmail).not.toHaveBeenCalled() + }) +}) + +describe('endProTrial', () => { + function asSession(userId: string) { + return { kind: 'session', userId, sessionId: generateId() } as const + } + + it("ends the caller's own trial now", async () => { + const userId = await createUser() + const stripeSubscriptionId = await addSubscription(userId, 'trialing') + + await endProTrial.execute({ principal: asSession(userId), input: {} }) + + expect(stripeStub.subscriptions.update).toHaveBeenCalledWith( + stripeSubscriptionId, + { trial_end: 'now' }, + expect.anything() + ) + }) + + it('refuses an account whose plan is already paid', async () => { + const userId = await createUser() + await addSubscription(userId, 'active') + + await expect(endProTrial.execute({ principal: asSession(userId), input: {} })).rejects.toThrow( + 'There is no free trial to end' + ) + expect(stripeStub.subscriptions.update).not.toHaveBeenCalled() + }) + + it("never ends another account's trial", async () => { + const trialing = await createUser() + await addSubscription(trialing, 'trialing') + const caller = await createUser() + + await expect(endProTrial.execute({ principal: asSession(caller), input: {} })).rejects.toThrow( + 'There is no free trial to end' + ) + expect(stripeStub.subscriptions.update).not.toHaveBeenCalled() + }) +}) diff --git a/apps/sim/lib/billing/organization.test.ts b/apps/sim/lib/billing/organization.test.ts index f23ce7f0321..c4793737abe 100644 --- a/apps/sim/lib/billing/organization.test.ts +++ b/apps/sim/lib/billing/organization.test.ts @@ -211,7 +211,6 @@ describe('syncSubscriptionUsageLimits', () => { it('keeps prepaid headroom additive when a Team seat increase raises the base', async () => { mockGetOrganizationIdForSubscriptionReference.mockResolvedValue('org-1') - mockGetPlanPricing.mockReturnValue({ basePrice: 25 }) await syncSubscriptionUsageLimits({ id: 'sub-1', @@ -225,7 +224,7 @@ describe('syncSubscriptionUsageLimits', () => { const expression = JSON.stringify(update?.orgUsageLimit) expect(expression).toContain('greatest') expect(expression).toContain('creditBalance') - expect(expression).toContain('50') + expect(expression).toContain('60') expect(expression).not.toContain('0.001') }) }) diff --git a/apps/sim/lib/billing/organization.ts b/apps/sim/lib/billing/organization.ts index 7683cbcb35b..b01623756ef 100644 --- a/apps/sim/lib/billing/organization.ts +++ b/apps/sim/lib/billing/organization.ts @@ -4,7 +4,8 @@ import { createLogger } from '@sim/logger' import { isOrgAdminRole } from '@sim/platform-authz/workspace' import { generateId } from '@sim/utils/id' import { and, eq, inArray, ne, sql } from 'drizzle-orm' -import { getPlanPricing, isSubscriptionOrgScoped } from '@/lib/billing/core/billing' +import { isSubscriptionOrgScoped } from '@/lib/billing/core/billing' +import { rebaseUsageLimit } from '@/lib/billing/core/plan-switch' import { getOrganizationIdForSubscriptionReference } from '@/lib/billing/core/subscription' import { syncUsageLimitsFromSubscription } from '@/lib/billing/core/usage' import { assertNoCompetingEnterpriseIssuance } from '@/lib/billing/enterprise-outbox' @@ -13,7 +14,12 @@ import { acquireUserBillingIdentityLock } from '@/lib/billing/organizations/iden import { acquireOrganizationMutationLock } from '@/lib/billing/organizations/membership' import { isEnterprise, isOrgPlan, isPaid } from '@/lib/billing/plan-helpers' import { SubscriptionReferenceNotFoundError } from '@/lib/billing/subscriptions/errors' -import { ENTITLED_SUBSCRIPTION_STATUSES } from '@/lib/billing/subscriptions/utils' +import { + ENTITLED_SUBSCRIPTION_STATUSES, + getOrgIncludedUsageDollars, + resolveBillingInterval, + SETTLED_SUBSCRIPTION_STATUSES, +} from '@/lib/billing/subscriptions/utils' import { toDecimal } from '@/lib/billing/utils/decimal' import type { DbTransaction } from '@/lib/db/types' import { @@ -29,6 +35,11 @@ type SubscriptionData = { referenceId: string status: string | null seats?: number | null + billingInterval?: string | null + metadata?: unknown + periodStart?: Date | null + allowancePeriodStart?: Date | null + allowanceSeatMonths?: number | string | null /** Correlation copied from Stripe metadata by the generic webhook callback. */ enterpriseOperationId?: string | null } @@ -530,9 +541,10 @@ export async function syncSubscriptionUsageLimits(subscription: SubscriptionData } else { /** Enterprise has custom pricing; other paid pools retain prepaid headroom when seats increase. */ if (isPaid(subscription.plan) && !isEnterprise(subscription.plan)) { - const { basePrice } = getPlanPricing(subscription.plan) - const seats = subscription.seats || 1 - const planBase = toDecimal(basePrice).times(seats).toString() + const current = await reconcileAnnualSeatMonths(subscription.id, organizationId) + const priced = current ?? subscription + const seats = priced.seats || 1 + const planBase = toDecimal(getOrgIncludedUsageDollars(priced)).toString() const liveMinimum = sql`${planBase}::numeric + ${organization.creditBalance}` await db @@ -552,7 +564,7 @@ export async function syncSubscriptionUsageLimits(subscription: SubscriptionData organizationId, plan: subscription.plan, seats, - basePrice, + planBase, }) } } @@ -565,3 +577,156 @@ export async function syncSubscriptionUsageLimits(subscription: SubscriptionData throw error } } + +/** Annual subscriptions read per page of the hourly sweep. */ +const ANNUAL_SWEEP_PAGE_SIZE = 200 + +const AVERAGE_MONTH_MS = 30.44 * 24 * 60 * 60 * 1000 + +/** Months left in a period at `now`, as a fraction: what Stripe prorates a seat change against. */ +function monthsRemaining(periodEnd: Date | null, now: Date): number { + if (!periodEnd) return 12 + return Math.min(12, Math.max(0, (periodEnd.getTime() - now.getTime()) / AVERAGE_MONTH_MS)) +} + +/** + * The hourly upkeep of annual Pro and Team plans: an annual period includes twelve months of + * credits, and the stored usage limit must reflect it. + * + * For a Team plan it first keeps the period's seat-months in step with the seat count: a new + * period starts at `seats × 12`, and a seat added or removed since the last run adds or removes + * only the months left, as Stripe prorates the charge. It then re-applies the limit floor, which + * only ever raises a limit. Pages through every settled annual subscription. Returns how many it + * synced. + */ +export async function syncAnnualPlanUsageLimits(): Promise { + let synced = 0 + let cursor = '' + for (;;) { + const page = await db + .select() + .from(subscriptionTable) + .where( + and( + inArray(subscriptionTable.status, SETTLED_SUBSCRIPTION_STATUSES), + ne(subscriptionTable.plan, 'enterprise'), + ne(subscriptionTable.plan, 'free'), + sql`coalesce(${subscriptionTable.billingInterval}, ${subscriptionTable.metadata}::jsonb->>'billingInterval') = 'year'`, + sql`${subscriptionTable.id} > ${cursor}` + ) + ) + .orderBy(subscriptionTable.id) + .limit(ANNUAL_SWEEP_PAGE_SIZE) + if (page.length === 0) return synced + cursor = page[page.length - 1].id + + for (const listed of page) { + try { + // Re-read the row: a plan switch since the page was read must not be raised back. + const [annual] = await db + .select() + .from(subscriptionTable) + .where(eq(subscriptionTable.id, listed.id)) + .limit(1) + if ( + !annual || + resolveBillingInterval(annual) !== 'year' || + !isPaid(annual.plan) || + !(SETTLED_SUBSCRIPTION_STATUSES as readonly string[]).includes(annual.status ?? '') + ) { + continue + } + if (annual.billingInterval !== 'year') { + // Older checkouts kept the interval only in metadata; readers of the column alone (the + // billing attribution snapshot) then priced the plan as monthly. + await db + .update(subscriptionTable) + .set({ billingInterval: 'year' }) + .where(eq(subscriptionTable.id, annual.id)) + } + await syncSubscriptionUsageLimits({ ...annual, billingInterval: 'year' }) + synced++ + } catch (error) { + logger.error('Failed to sync an annual plan usage limit', { + subscriptionId: listed.id, + error, + }) + } + } + } +} + +/** + * Brings an annual Team subscription's seat-months up to date with its seat count, and moves the + * organization's limit with the allowance. A new period starts at `seats × 12`; a seat added or + * removed since the last count adds or removes only the months left, as Stripe prorates the charge. + * The closing year's count is kept until its cycle close has priced it. Returns the current row, or + * null when the subscription is not an annual Team plan. + */ +async function reconcileAnnualSeatMonths( + subscriptionId: string, + organizationId: string, + now: Date = new Date() +): Promise { + const [annual] = await db + .select() + .from(subscriptionTable) + .where(eq(subscriptionTable.id, subscriptionId)) + .limit(1) + if ( + !annual?.periodStart || + !isOrgPlan(annual.plan) || + isEnterprise(annual.plan) || + resolveBillingInterval(annual) !== 'year' + ) { + return annual ?? null + } + + const seats = annual.seats || 1 + const samePeriod = annual.allowancePeriodStart?.getTime() === annual.periodStart.getTime() + if (samePeriod && annual.allowanceSeats === seats && annual.allowanceSeatMonths !== null) { + return annual + } + const previousYearOpen = + !samePeriod && + annual.allowancePeriodStart !== null && + (annual.lastClosedPeriodStart === null || + annual.lastClosedPeriodStart.getTime() < annual.periodStart.getTime()) + if (previousYearOpen) return annual + + const allowanceSeatMonths = + samePeriod && annual.allowanceSeats !== null && annual.allowanceSeatMonths !== null + ? Math.max( + 0, + Number(annual.allowanceSeatMonths) + + (seats - annual.allowanceSeats) * monthsRemaining(annual.periodEnd, now) + ) + : seats * 12 + const next = { + ...annual, + allowancePeriodStart: annual.periodStart, + allowanceSeats: seats, + allowanceSeatMonths: allowanceSeatMonths.toFixed(4), + } + const previousIncluded = getOrgIncludedUsageDollars(annual) + const nextIncluded = getOrgIncludedUsageDollars(next) + + // One transaction: a limit left unrebased after the count advanced would never be retried. + await db.transaction(async (tx) => { + await tx + .update(subscriptionTable) + .set({ + allowancePeriodStart: next.allowancePeriodStart, + allowanceSeats: next.allowanceSeats, + allowanceSeatMonths: next.allowanceSeatMonths, + }) + .where(eq(subscriptionTable.id, annual.id)) + if (previousIncluded !== nextIncluded) { + await rebaseUsageLimit( + { pool: { type: 'organization', id: organizationId }, previousIncluded, nextIncluded }, + tx + ) + } + }) + return next +} diff --git a/apps/sim/lib/billing/organizations/membership.ts b/apps/sim/lib/billing/organizations/membership.ts index 7b1ae93aa44..dbe46fbf4b7 100644 --- a/apps/sim/lib/billing/organizations/membership.ts +++ b/apps/sim/lib/billing/organizations/membership.ts @@ -31,22 +31,16 @@ import { } from '@/lib/auth/security-policy' import { applySessionPolicyToNewMember } from '@/lib/auth/session-policy' import { createUserStatsIfMissing, syncUsageLimitsFromSubscription } from '@/lib/billing/core/usage' -import { - assertNoUnresolvedEnterpriseIssuance, - resolveEnterpriseMetadataIntent, -} from '@/lib/billing/enterprise-outbox' +import { assertNoUnresolvedEnterpriseIssuance } from '@/lib/billing/enterprise-outbox' import { acquireUserBillingIdentityLock } from '@/lib/billing/organizations/identity-lock' import { setOrgMemberUsageLimit } from '@/lib/billing/organizations/member-limits' import { MEMBER_BILLING_RECONCILIATION_EVENT_TYPE } from '@/lib/billing/organizations/membership-reconciliation-event' import { reassignOrganizationSharedResourcesTx } from '@/lib/billing/organizations/resource-handoff' import { isPaid, sqlIsPro } from '@/lib/billing/plan-helpers' import { changeOrganizationWorkspaceBilledAccountsInTx } from '@/lib/billing/storage/payer-transfer' -import { - ENTITLED_SUBSCRIPTION_STATUSES, - getEffectiveSeats, -} from '@/lib/billing/subscriptions/utils' +import { ENTITLED_SUBSCRIPTION_STATUSES } from '@/lib/billing/subscriptions/utils' import { toDecimal, toNumber } from '@/lib/billing/utils/decimal' -import { validateSeatAvailability } from '@/lib/billing/validation/seat-management' +import { resolveSeatCap, validateSeatAvailability } from '@/lib/billing/validation/seat-management' import { OUTBOX_EVENT_TYPES } from '@/lib/billing/webhooks/outbox-events' import { enqueueCancelAtPeriodEndSync, @@ -768,17 +762,8 @@ export async function ensureUserInOrganizationTx( .select({ value: count() }) .from(member) .where(eq(member.organizationId, organizationId)) - const canonicalSeats = getEffectiveSeats(organizationSubscription) - const metadataIntent = - organizationSubscription.plan === 'enterprise' - ? await resolveEnterpriseMetadataIntent( - tx, - organizationSubscription.id, - organizationSubscription.metadata - ) - : null - const effectiveSeats = metadataIntent?.effectiveSeatCapacity ?? canonicalSeats - if ((memberCountRow?.value ?? 0) >= effectiveSeats) { + const seatCap = await resolveSeatCap(organizationSubscription, tx) + if (seatCap.kind !== 'baseline' && (memberCountRow?.value ?? 0) >= seatCap.seats) { return { success: false, alreadyMember: false, diff --git a/apps/sim/lib/billing/organizations/provision-seat.ts b/apps/sim/lib/billing/organizations/provision-seat.ts index 4594e257e30..114a26e3e5c 100644 --- a/apps/sim/lib/billing/organizations/provision-seat.ts +++ b/apps/sim/lib/billing/organizations/provision-seat.ts @@ -15,7 +15,10 @@ import { isTeam, } from '@/lib/billing/plan-helpers' import { getPlanByName } from '@/lib/billing/plans' -import { hasUsableSubscriptionStatus } from '@/lib/billing/subscriptions/utils' +import { + hasUsableSubscriptionStatus, + isTrialingSubscription, +} from '@/lib/billing/subscriptions/utils' import { enqueueCancelAtPeriodEndSync, enqueueSubscriptionSeatsSync, @@ -164,7 +167,13 @@ async function convertPersonalSubscriptionToTeam( onError: 'throw', executor, }) - if (!personalSub || !hasUsableSubscriptionStatus(personalSub.status)) { + // A trial cannot become a seat-billed team: the team would inherit Pro's trial without its + // capped allowance, and nothing has been paid yet. + if ( + !personalSub || + !hasUsableSubscriptionStatus(personalSub.status) || + isTrialingSubscription(personalSub) + ) { return { success: false, failureCode: 'upgrade-required' } } diff --git a/apps/sim/lib/billing/organizations/seats.ts b/apps/sim/lib/billing/organizations/seats.ts index 7e7b804cae2..4d76cd4a317 100644 --- a/apps/sim/lib/billing/organizations/seats.ts +++ b/apps/sim/lib/billing/organizations/seats.ts @@ -74,7 +74,16 @@ export async function reconcileOrganizationSeats({ previousSeats: number seats: number outboxEventId: string - sync: { id: string; plan: string; status: string | null } + sync: { + id: string + plan: string + status: string | null + billingInterval: string | null + metadata: unknown + periodStart: Date | null + allowancePeriodStart: Date | null + allowanceSeatMonths: string | null + } } const outcome = await db.transaction(async (tx) => { @@ -138,6 +147,11 @@ export async function reconcileOrganizationSeats({ id: orgSubscription.id, plan: orgSubscription.plan, status: orgSubscription.status, + billingInterval: orgSubscription.billingInterval, + metadata: orgSubscription.metadata, + periodStart: orgSubscription.periodStart, + allowancePeriodStart: orgSubscription.allowancePeriodStart, + allowanceSeatMonths: orgSubscription.allowanceSeatMonths, }, } }) @@ -156,6 +170,11 @@ export async function reconcileOrganizationSeats({ referenceId: organizationId, status: outcome.sync.status, seats: outcome.seats, + billingInterval: outcome.sync.billingInterval, + metadata: outcome.sync.metadata, + periodStart: outcome.sync.periodStart, + allowancePeriodStart: outcome.sync.allowancePeriodStart, + allowanceSeatMonths: outcome.sync.allowanceSeatMonths, }) } catch (error) { // Seats already committed in the transaction above; a failure here must not diff --git a/apps/sim/lib/billing/plan-allowance.integration.ts b/apps/sim/lib/billing/plan-allowance.integration.ts new file mode 100644 index 00000000000..2bf0bd202ba --- /dev/null +++ b/apps/sim/lib/billing/plan-allowance.integration.ts @@ -0,0 +1,423 @@ +/** + * A paid plan's included usage against real PostgreSQL: an annual plan carries twelve months of + * credits for its yearly billing period (limit floor, overage, the hourly re-sync), and a plan + * switch moves an untouched usage limit to the new plan's allowance while the closed period keeps + * its own. + */ +import { db } from '@sim/db' +import { organization, subscription, usageLog, user, userStats } from '@sim/db/schema' +import { generateId } from '@sim/utils/id' +import { eq, inArray } from 'drizzle-orm' +import { afterAll, describe, expect, it, vi } from 'vitest' +import { ON_DEMAND_UNLIMITED } from '@/lib/billing/constants' +import { calculateSubscriptionOverage } from '@/lib/billing/core/billing' +import { recordPlanSwitch } from '@/lib/billing/core/plan-switch' +import { getOrgUsageLimit, syncUsageLimitsFromSubscription } from '@/lib/billing/core/usage' +import { closeElapsedBillingPeriod } from '@/lib/billing/cycle-close' +import { syncAnnualPlanUsageLimits } from '@/lib/billing/organization' + +vi.mock('@/lib/core/config/env-flags', async (importOriginal) => ({ + ...(await importOriginal()), + isBillingEnabled: true, +})) + +const DAY_MS = 86_400_000 +const PRO_MONTHLY_DOLLARS = 30 +const MAX_MONTHLY_DOLLARS = 125 + +const userIds: string[] = [] +const organizationIds: string[] = [] + +async function createUser(usageLimit: number | null = null, creditBalance = 0): Promise { + const id = `allowance-user-${generateId()}` + const now = new Date() + await db.insert(user).values({ + id, + name: 'Allowance Test', + email: `${id}@allowance.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + await db.insert(userStats).values({ + id: generateId(), + userId: id, + currentUsageLimit: usageLimit === null ? null : String(usageLimit), + creditBalance: String(creditBalance), + }) + userIds.push(id) + return id +} + +async function addSubscription( + referenceId: string, + fields: { + plan: string + billingInterval: 'month' | 'year' | null + status?: string + seats?: number + metadata?: Record + } +) { + const now = Date.now() + const days = fields.billingInterval === 'year' ? 365 : 30 + const row = { + id: generateId(), + plan: fields.plan, + referenceId, + status: fields.status ?? 'active', + seats: fields.seats ?? 1, + billingInterval: fields.billingInterval, + metadata: fields.metadata ?? null, + stripeSubscriptionId: `sub_${generateId()}`, + periodStart: new Date(now - DAY_MS), + periodEnd: new Date(now + (days - 1) * DAY_MS), + } + await db.insert(subscription).values(row) + return row +} + +async function createOrganization(): Promise { + const id = `allowance-org-${generateId()}` + await db.insert(organization).values({ + id, + name: 'Allowance Org', + slug: id, + createdAt: new Date(), + updatedAt: new Date(), + }) + organizationIds.push(id) + return id +} + +async function readLimit(userId: string): Promise { + const [stats] = await db + .select({ currentUsageLimit: userStats.currentUsageLimit }) + .from(userStats) + .where(eq(userStats.userId, userId)) + return Number(stats?.currentUsageLimit) +} + +afterAll(async () => { + if (userIds.length > 0) { + await db.delete(subscription).where(inArray(subscription.referenceId, userIds)) + await db.delete(usageLog).where(inArray(usageLog.userId, userIds)) + await db.delete(user).where(inArray(user.id, userIds)) + } + if (organizationIds.length > 0) { + await db.delete(subscription).where(inArray(subscription.referenceId, organizationIds)) + await db.delete(organization).where(inArray(organization.id, organizationIds)) + } +}) + +describe('annual plan allowance', () => { + it('floors an annual Pro usage limit at twelve months of included usage', async () => { + const userId = await createUser(PRO_MONTHLY_DOLLARS) + await addSubscription(userId, { plan: 'pro_6000', billingInterval: 'year' }) + + await syncUsageLimitsFromSubscription(userId) + + expect(await readLimit(userId)).toBe(PRO_MONTHLY_DOLLARS * 12) + }) + + it('reads the annual interval from metadata when the column is empty', async () => { + const userId = await createUser(PRO_MONTHLY_DOLLARS) + await addSubscription(userId, { + plan: 'pro_6000', + billingInterval: null, + metadata: { billingInterval: 'year' }, + }) + + await syncUsageLimitsFromSubscription(userId) + + expect(await readLimit(userId)).toBe(PRO_MONTHLY_DOLLARS * 12) + }) + + it('owes no overage on an annual plan until usage passes the yearly allowance', async () => { + const userId = await createUser(PRO_MONTHLY_DOLLARS * 12) + const sub = await addSubscription(userId, { plan: 'pro_6000', billingInterval: 'year' }) + await db.insert(usageLog).values({ + id: generateId(), + userId, + category: 'model', + source: 'workflow', + description: 'annual allowance test', + cost: '100', + billingEntityType: 'user', + billingEntityId: userId, + billingPeriodStart: sub.periodStart, + billingPeriodEnd: sub.periodEnd, + createdAt: new Date(sub.periodStart.getTime() + 60_000), + }) + + expect(await calculateSubscriptionOverage(sub)).toBe(0) + }) + + it('floors an annual Team organization at twelve months per seat', async () => { + const organizationId = await createOrganization() + + const { minimum } = await getOrgUsageLimit(organizationId, { + plan: 'team_6000', + seats: 3, + billingInterval: 'year', + }) + + expect(minimum).toBe(PRO_MONTHLY_DOLLARS * 12 * 3) + }) + + it('includes only the months left for a Team seat added partway through the year', async () => { + const organizationId = await createOrganization() + const sub = await addSubscription(organizationId, { + plan: 'team_6000', + billingInterval: 'year', + seats: 3, + }) + + await syncAnnualPlanUsageLimits() + // Two seats join with two months left in the year. + await db + .update(subscription) + .set({ seats: 5, periodEnd: new Date(Date.now() + 60 * DAY_MS) }) + .where(eq(subscription.id, sub.id)) + await syncAnnualPlanUsageLimits() + + const [row] = await db.select().from(subscription).where(eq(subscription.id, sub.id)) + const recorded = Number(row?.allowanceSeatMonths) + expect(recorded).toBeCloseTo(3 * 12 + 2 * (60 / 30.44), 3) + const { minimum } = await getOrgUsageLimit(organizationId, row as NonNullable) + expect(minimum).toBe(Math.round(recorded * PRO_MONTHLY_DOLLARS * 100) / 100) + }) + + it('credits a seat added in the last days of the year for the days left', async () => { + const organizationId = await createOrganization() + const sub = await addSubscription(organizationId, { + plan: 'team_6000', + billingInterval: 'year', + seats: 1, + }) + await syncAnnualPlanUsageLimits() + await db + .update(subscription) + .set({ seats: 2, periodEnd: new Date(Date.now() + 10 * DAY_MS) }) + .where(eq(subscription.id, sub.id)) + + await syncAnnualPlanUsageLimits() + + const [row] = await db.select().from(subscription).where(eq(subscription.id, sub.id)) + expect(Number(row?.allowanceSeatMonths)).toBeCloseTo(12 + 10 / 30.44, 3) + }) + + it('lowers an untouched Team limit when a seat leaves partway through the year', async () => { + const organizationId = await createOrganization() + const sub = await addSubscription(organizationId, { + plan: 'team_6000', + billingInterval: 'year', + seats: 2, + }) + await syncAnnualPlanUsageLimits() + await db + .update(subscription) + .set({ seats: 1, periodEnd: new Date(Date.now() + 182 * DAY_MS) }) + .where(eq(subscription.id, sub.id)) + + await syncAnnualPlanUsageLimits() + + const [org] = await db + .select({ orgUsageLimit: organization.orgUsageLimit }) + .from(organization) + .where(eq(organization.id, organizationId)) + expect(Number(org?.orgUsageLimit)).toBeCloseTo((2 * 12 - 182 / 30.44) * PRO_MONTHLY_DOLLARS, 1) + }) + + it('raises annual subscriptions still capped at one month and leaves monthly ones alone', async () => { + const annualUser = await createUser(PRO_MONTHLY_DOLLARS) + await addSubscription(annualUser, { plan: 'pro_6000', billingInterval: 'year' }) + const monthlyUser = await createUser(PRO_MONTHLY_DOLLARS) + await addSubscription(monthlyUser, { plan: 'pro_6000', billingInterval: 'month' }) + + await syncAnnualPlanUsageLimits() + + expect(await readLimit(annualUser)).toBe(PRO_MONTHLY_DOLLARS * 12) + expect(await readLimit(monthlyUser)).toBe(PRO_MONTHLY_DOLLARS) + }) +}) + +describe('closing a period after an interval switch', () => { + it('bills the closed monthly period against one month, not the new annual allowance', async () => { + const userId = await createUser(PRO_MONTHLY_DOLLARS * 12) + const periodStart = new Date(Date.now() - 2 * DAY_MS) + const closedStart = new Date(periodStart.getTime() - 30 * DAY_MS) + const row = { + id: generateId(), + plan: 'pro_6000', + referenceId: userId, + status: 'active', + seats: 1, + billingInterval: 'year', + stripeCustomerId: `cus_${generateId()}`, + stripeSubscriptionId: `sub_${generateId()}`, + periodStart, + periodEnd: new Date(periodStart.getTime() + 365 * DAY_MS), + lastClosedPeriodStart: closedStart, + } + await db.insert(subscription).values(row) + await db.insert(usageLog).values({ + id: generateId(), + userId, + category: 'model', + source: 'workflow', + description: 'closed monthly period', + cost: '100', + billingEntityType: 'user', + billingEntityId: userId, + billingPeriodStart: closedStart, + billingPeriodEnd: periodStart, + createdAt: new Date(closedStart.getTime() + DAY_MS), + }) + const [sub] = await db.select().from(subscription).where(eq(subscription.id, row.id)) + + const result = await closeElapsedBillingPeriod(sub as NonNullable, { + bypassSettlementGrace: true, + }) + + // $100 used, less one week's $10 refresh and one month's $30 allowance. + expect(result.overageBilled).toBe(60) + }) +}) + +describe('recordPlanSwitch', () => { + it('lowers an untouched limit to the cheaper plan on a Max to Pro downgrade', async () => { + const userId = await createUser(MAX_MONTHLY_DOLLARS) + const sub = await addSubscription(userId, { plan: 'pro_25000', billingInterval: 'month' }) + + await recordPlanSwitch({ + subscription: sub, + targetPlanName: 'pro_6000', + targetInterval: 'month', + orgScoped: false, + }) + + expect(await readLimit(userId)).toBe(PRO_MONTHLY_DOLLARS) + const [row] = await db.select().from(subscription).where(eq(subscription.id, sub.id)) + expect(row?.plan).toBe('pro_6000') + }) + + it('keeps chosen headroom on an upgrade to a pricier tier', async () => { + const userId = await createUser(100) + const sub = await addSubscription(userId, { plan: 'pro_6000', billingInterval: 'month' }) + + await recordPlanSwitch({ + subscription: sub, + targetPlanName: 'pro_25000', + targetInterval: 'month', + orgScoped: false, + }) + + expect(await readLimit(userId)).toBe(MAX_MONTHLY_DOLLARS + (100 - PRO_MONTHLY_DOLLARS)) + }) + + it('keeps the on-demand headroom a payer raised above the old plan', async () => { + const userId = await createUser(500) + const sub = await addSubscription(userId, { plan: 'pro_25000', billingInterval: 'month' }) + + await recordPlanSwitch({ + subscription: sub, + targetPlanName: 'pro_6000', + targetInterval: 'month', + orgScoped: false, + }) + + expect(await readLimit(userId)).toBe(PRO_MONTHLY_DOLLARS + (500 - MAX_MONTHLY_DOLLARS)) + }) + + it("rescales a year's on-demand headroom to a month on a switch to monthly billing", async () => { + const userId = await createUser(PRO_MONTHLY_DOLLARS * 12 + 120) + const sub = await addSubscription(userId, { plan: 'pro_6000', billingInterval: 'year' }) + + await recordPlanSwitch({ + subscription: sub, + targetPlanName: 'pro_6000', + targetInterval: 'month', + orgScoped: false, + }) + + expect(await readLimit(userId)).toBe(PRO_MONTHLY_DOLLARS + 10) + const [row] = await db.select().from(subscription).where(eq(subscription.id, sub.id)) + expect(row?.billingInterval).toBe('month') + }) + + it('counts prepaid credit once when rebasing an untouched limit', async () => { + const userId = await createUser(MAX_MONTHLY_DOLLARS + 50, 50) + const sub = await addSubscription(userId, { plan: 'pro_25000', billingInterval: 'month' }) + + await recordPlanSwitch({ + subscription: sub, + targetPlanName: 'pro_6000', + targetInterval: 'month', + orgScoped: false, + }) + + expect(await readLimit(userId)).toBe(PRO_MONTHLY_DOLLARS + 50) + }) + + it('does not read a limit the webhook already raised as chosen headroom', async () => { + // The checkout webhook raised the monthly limit to the annual floor before the switch recorded. + const userId = await createUser(PRO_MONTHLY_DOLLARS * 12) + const sub = await addSubscription(userId, { plan: 'pro_6000', billingInterval: 'month' }) + + await recordPlanSwitch({ + subscription: sub, + targetPlanName: 'pro_6000', + targetInterval: 'year', + orgScoped: false, + }) + + expect(await readLimit(userId)).toBe(PRO_MONTHLY_DOLLARS * 12) + }) + + it('keeps an unlimited limit unlimited', async () => { + const userId = await createUser(ON_DEMAND_UNLIMITED) + const sub = await addSubscription(userId, { plan: 'pro_25000', billingInterval: 'month' }) + + await recordPlanSwitch({ + subscription: sub, + targetPlanName: 'pro_6000', + targetInterval: 'month', + orgScoped: false, + }) + + expect(await readLimit(userId)).toBe(ON_DEMAND_UNLIMITED) + }) + + it('moves an annual limit back to one month on a switch to monthly billing', async () => { + const userId = await createUser(PRO_MONTHLY_DOLLARS * 12) + const sub = await addSubscription(userId, { plan: 'pro_6000', billingInterval: 'year' }) + + await recordPlanSwitch({ + subscription: sub, + targetPlanName: 'pro_6000', + targetInterval: 'month', + orgScoped: false, + }) + + expect(await readLimit(userId)).toBe(PRO_MONTHLY_DOLLARS) + }) + + it('leaves a trial at its fixed allowance', async () => { + const userId = await createUser(10) + const sub = await addSubscription(userId, { + plan: 'pro_6000', + billingInterval: 'month', + status: 'trialing', + }) + + await recordPlanSwitch({ + subscription: sub, + targetPlanName: 'pro_25000', + targetInterval: 'month', + orgScoped: false, + }) + + expect(await readLimit(userId)).toBe(10) + }) +}) diff --git a/apps/sim/lib/billing/plan-helpers.ts b/apps/sim/lib/billing/plan-helpers.ts index fa399067c7b..6fe070be351 100644 --- a/apps/sim/lib/billing/plan-helpers.ts +++ b/apps/sim/lib/billing/plan-helpers.ts @@ -13,6 +13,7 @@ import type { AnyColumn } from 'drizzle-orm' import { eq, like, or, type SQL } from 'drizzle-orm' import { + ANNUAL_DISCOUNT_RATE, CREDIT_TIERS, CREDITS_PER_DOLLAR, DEFAULT_PRO_TIER_COST_LIMIT, @@ -107,6 +108,15 @@ export function getPlanTierDollars(plan: string | null | undefined): number { return 0 } +/** + * A plan's per-seat monthly price as shown to customers: the list price on monthly billing, or the + * annual price spread over twelve months, to the cent ($21.25, not $21). + */ +export function formatMonthlyPlanPrice(monthlyDollars: number, isAnnual: boolean): string { + const price = isAnnual ? monthlyDollars * (1 - ANNUAL_DISCOUNT_RATE) : monthlyDollars + return `$${Number.isInteger(price) ? price : price.toFixed(2)}` +} + /** * Weekly refresh allowance for a plan, in dollars per seat per week. * diff --git a/apps/sim/lib/billing/storage/project-accounting.integration.ts b/apps/sim/lib/billing/storage/project-accounting.integration.ts index d495a3aa598..b01fdcf12c7 100644 --- a/apps/sim/lib/billing/storage/project-accounting.integration.ts +++ b/apps/sim/lib/billing/storage/project-accounting.integration.ts @@ -94,7 +94,7 @@ describe('Project storage admission, transfer, and reconciliation in PostgreSQL' stripe_customer_id text, stripe_subscription_id text, status text, period_start timestamp, period_end timestamp, cancel_at_period_end boolean, cancel_at timestamp, canceled_at timestamp, ended_at timestamp, seats integer, trial_start timestamp, trial_end timestamp, - billing_interval text, stripe_schedule_id text, metadata json, last_closed_period_start timestamp); + billing_interval text, stripe_schedule_id text, metadata json, last_closed_period_start timestamp, allowance_period_start timestamp, allowance_seats integer, allowance_seat_months numeric); CREATE TABLE project (id text PRIMARY KEY, owner_id text NOT NULL, organization_id text, organization_scope_key text GENERATED ALWAYS AS (CASE WHEN organization_id IS NULL THEN 'personal' ELSE 'organization:' || organization_id END) STORED, name text NOT NULL DEFAULT 'Project', created_at timestamp NOT NULL DEFAULT now(), diff --git a/apps/sim/lib/billing/stripe-payment-method.ts b/apps/sim/lib/billing/stripe-payment-method.ts index 1c0e9dc7988..0de5da5dfaa 100644 --- a/apps/sim/lib/billing/stripe-payment-method.ts +++ b/apps/sim/lib/billing/stripe-payment-method.ts @@ -9,7 +9,7 @@ const logger = createLogger('StripePaymentMethod') * for a `default_payment_method` field (id string, full object, null, * or undefined). */ -function getPaymentMethodId( +export function getPaymentMethodId( pm: string | Stripe.PaymentMethod | null | undefined ): string | undefined { return typeof pm === 'string' ? pm : pm?.id diff --git a/apps/sim/lib/billing/subscriptions/utils.test.ts b/apps/sim/lib/billing/subscriptions/utils.test.ts index e01131c9c30..61f7cced481 100644 --- a/apps/sim/lib/billing/subscriptions/utils.test.ts +++ b/apps/sim/lib/billing/subscriptions/utils.test.ts @@ -6,6 +6,7 @@ import { checkProPlan, checkTeamPlan, getEffectiveSeats, + getSubscriptionWeeklyRefreshDollars, hasPaidSubscriptionStatus, hasUsableSubscriptionAccess, hasUsableSubscriptionStatus, @@ -60,4 +61,11 @@ describe('billing subscription status helpers', () => { expect(getEffectiveSeats({ plan: 'team_8000', status: 'past_due', seats: undefined })).toBe(1) expect(getEffectiveSeats({ plan: 'team_8000', status: 'canceled', seats: null })).toBe(0) }) + + it('earns no weekly refresh during a trial', () => { + expect(getSubscriptionWeeklyRefreshDollars({ plan: 'pro_6000', status: 'trialing' })).toBe(0) + expect( + getSubscriptionWeeklyRefreshDollars({ plan: 'pro_6000', status: 'active' }) + ).toBeGreaterThan(0) + }) }) diff --git a/apps/sim/lib/billing/subscriptions/utils.ts b/apps/sim/lib/billing/subscriptions/utils.ts index ad763635693..e5ecb2a99c2 100644 --- a/apps/sim/lib/billing/subscriptions/utils.ts +++ b/apps/sim/lib/billing/subscriptions/utils.ts @@ -1,24 +1,40 @@ +import { toRecord } from '@sim/utils/object' import { DEFAULT_ENTERPRISE_TIER_COST_LIMIT, DEFAULT_FREE_CREDITS, DEFAULT_PRO_TIER_COST_LIMIT, DEFAULT_TEAM_TIER_COST_LIMIT, + PRO_TRIAL_USAGE_LIMIT_DOLLARS, } from '@/lib/billing/constants' import { CREDIT_MULTIPLIER } from '@/lib/billing/credits/conversion' +import { configuredEnterpriseUsageCredits } from '@/lib/billing/enterprise-credit-limits' import { getPlanTierCredits, + getPlanWeeklyRefreshDollars, isEnterprise, isFree, isOrgPlan, + isPaid, isPro, isTeam, } from '@/lib/billing/plan-helpers' import { parseEnterpriseSubscriptionMetadata } from '@/lib/billing/types' import { env, envNumber } from '@/lib/core/config/env' -export const ENTITLED_SUBSCRIPTION_STATUSES = ['active', 'past_due'] as const +/** + * Statuses that hold a paid plan's entitlement. `trialing` is a free trial of a paid plan: it gets + * the plan's features under a capped allowance (see {@link isTrialingSubscription}). + */ +export const ENTITLED_SUBSCRIPTION_STATUSES = ['active', 'trialing', 'past_due'] as const + +export const USABLE_SUBSCRIPTION_STATUSES = ['active', 'trialing'] as const -export const USABLE_SUBSCRIPTION_STATUSES = ['active'] as const +/** + * Statuses whose billing periods Sim settles (cycle close, overage). A `trialing` period is left + * out: Stripe charges nothing for it and its usage is capped, so it never owes overage, and its + * close marker initializes on the first paid period instead. + */ +export const SETTLED_SUBSCRIPTION_STATUSES = ['active', 'past_due'] as const /** * Statuses where the subscription is finished and can no longer bill anyone. @@ -27,8 +43,8 @@ export const USABLE_SUBSCRIPTION_STATUSES = ['active'] as const * `incomplete` — is still attached to a live Stripe subscription that can * convert or retry, even where it grants no entitlement today. Use this, not * {@link ENTITLED_SUBSCRIPTION_STATUSES}, when the question is "would removing - * the thing this row points at strand live billing?" — a `trialing` - * subscription is unentitled but very much alive. + * the thing this row points at strand live billing?" — an `incomplete` or + * `unpaid` subscription is unentitled but very much alive. * * Deliberately expressed as the terminal set rather than the live one, so a * status Stripe adds later is treated as live by default. For a destructive @@ -36,6 +52,162 @@ export const USABLE_SUBSCRIPTION_STATUSES = ['active'] as const */ export const TERMINAL_SUBSCRIPTION_STATUSES = ['canceled', 'incomplete_expired'] as const +/** + * Whether the subscription is in its free trial. A trial has the plan's features but spends a + * fixed allowance ({@link PRO_TRIAL_USAGE_LIMIT_DOLLARS}) with no weekly refresh, no on-demand + * usage, and no overage billing. + */ +export function isTrialingSubscription( + subscription: { status?: string | null } | null | undefined +): boolean { + return subscription?.status === 'trialing' +} + +/** A trial's end date as billing emails state it, in UTC so every recipient reads the same day. */ +export function formatTrialEndDate(trialEnd: Date): string { + return trialEnd.toLocaleDateString('en-US', { + month: 'long', + day: 'numeric', + year: 'numeric', + timeZone: 'UTC', + }) +} + +/** + * Whether a payer's limit admits spend past it: a paid plan outside its trial. Every other payer's + * limit is a hard cap. Whether that spend is then invoiced is {@link invoicesOverage}. + */ +export function billsOverage( + subscription: { plan?: string | null; status?: string | null } | null | undefined +): boolean { + return isPaid(subscription?.plan) && !isTrialingSubscription(subscription) +} + +/** + * Whether Enterprise subscription metadata opts the contract into self-serve billing. Self-serve + * overage closes on Stripe billing periods and seats past the contract are billed at its seat + * rate, so metadata that still carries a reporting-period anchor, or has no seat rate, fails + * closed to the hard-capped contract until an admin fixes it. + */ +export function isSelfServeEnterpriseMetadata(metadata: unknown): boolean { + const terms = parseEnterpriseSubscriptionMetadata(metadata) + return ( + terms?.selfServe === true && + terms.seatPriceCents !== undefined && + terms.reportingPeriodAnchorDate === undefined + ) +} + +/** Whether a subscription is an Enterprise contract opted into self-serve billing. */ +export function isEnterpriseSelfServe( + subscription: { plan?: string | null; metadata?: unknown } | null | undefined +): boolean { + return isEnterprise(subscription?.plan) && isSelfServeEnterpriseMetadata(subscription?.metadata) +} + +/** + * Whether a subscription is an Enterprise contract outside self-serve: its seats and usage limit + * are hard caps the flat contract price covers, and it never bills overage. + */ +export function isHardCappedEnterprise( + subscription: { plan?: string | null; metadata?: unknown } | null | undefined +): boolean { + return isEnterprise(subscription?.plan) && !isSelfServeEnterpriseMetadata(subscription?.metadata) +} + +/** Whether spend past the plan's included usage is invoiced as overage. */ +export function invoicesOverage( + subscription: + | { plan?: string | null; status?: string | null; metadata?: unknown } + | null + | undefined +): boolean { + return billsOverage(subscription) && !isHardCappedEnterprise(subscription) +} + +/** The subscription fields that decide an organization's included usage. */ +export interface OrgAllowanceInput extends PlanPricingInput { + seats?: number | null + periodStart?: Date | null + allowancePeriodStart?: Date | null + allowanceSeatMonths?: number | string | null +} + +/** + * Seat-months an annual Team period includes: the prorated count the hourly reconcile keeps for + * this period, or every seat for all twelve months until it has recorded one. + */ +function getAnnualSeatMonths(subscription: OrgAllowanceInput): number { + const recordedForThisPeriod = + subscription.allowanceSeatMonths != null && + subscription.allowancePeriodStart != null && + subscription.periodStart != null && + subscription.allowancePeriodStart.getTime() === subscription.periodStart.getTime() + return recordedForThisPeriod + ? Number(subscription.allowanceSeatMonths) + : (subscription.seats || 1) * 12 +} + +/** + * The usage an organization subscription includes each period, in dollars, before overage: the + * Enterprise contract allowance, or the plan's base price per seat. An annual Team period counts + * seat-months ({@link getAnnualSeatMonths}), so a seat added late includes only the months left. + */ +export function getOrgIncludedUsageDollars(subscription: OrgAllowanceInput): number { + if (isEnterprise(subscription.plan)) { + const metadata = parseEnterpriseSubscriptionMetadata(subscription.metadata) + if (!metadata) return 0 + return ( + configuredEnterpriseUsageCredits( + toRecord(subscription.metadata).usageLimitCredits, + metadata.invoiceAmountUsd + ) / CREDIT_MULTIPLIER + ) + } + if (resolveBillingInterval(subscription) === 'year') { + const monthly = getPlanPricing({ ...subscription, billingInterval: 'month', metadata: null }) + // Fractional seat-months price to the cent, the precision every limit is stored and edited in. + return Math.round(getAnnualSeatMonths(subscription) * monthly.basePrice * 100) / 100 + } + return (subscription.seats || 1) * getPlanPricing(subscription).basePrice +} + +/** What a self-serve Enterprise contract commits to, for the surfaces that explain its billing. */ +export interface EnterpriseSelfServeTerms { + /** Seats the contract price covers; members past it are trued up. */ + contractSeats: number + /** The rate for each seat past the contract, in cents per seat per month. */ + seatPriceCents: number + /** Usage the contract includes each billing period, in dollars, before overage. */ + includedUsage: number +} + +/** A subscription's self-serve Enterprise terms, or null when it is not a self-serve contract. */ +export function getEnterpriseSelfServeTerms(subscription: { + plan?: string | null + seats?: number | null + metadata?: unknown +}): EnterpriseSelfServeTerms | null { + if (!isEnterpriseSelfServe(subscription)) return null + const metadata = parseEnterpriseSubscriptionMetadata(subscription.metadata) + return { + contractSeats: metadata?.seats ?? 0, + seatPriceCents: metadata?.seatPriceCents ?? 0, + includedUsage: getOrgIncludedUsageDollars(subscription), + } +} + +/** + * The weekly refresh allowance a subscription earns, in dollars per seat per week: the plan's + * allowance, or nothing during a trial. + */ +export function getSubscriptionWeeklyRefreshDollars( + subscription: { plan?: string | null; status?: string | null } | null | undefined +): number { + if (isTrialingSubscription(subscription)) return 0 + return getPlanWeeklyRefreshDollars(subscription?.plan) +} + /** * Returns true when a subscription should still count as a paid plan entitlement. */ @@ -183,11 +355,9 @@ export function getPerUserMinimumLimit(subscription: any, freeTierEligible: bool return getFreeTierAllowance(freeTierEligible) } - if (isPro(subscription.plan)) { - const tierCredits = getPlanTierCredits(subscription.plan) - if (tierCredits > 0) return tierCredits / CREDIT_MULTIPLIER - return getProTierLimit() - } + if (isTrialingSubscription(subscription)) return PRO_TRIAL_USAGE_LIMIT_DOLLARS + + if (isPro(subscription.plan)) return getPlanPricing(subscription).basePrice if (isOrgPlan(subscription.plan)) { return 0 @@ -197,34 +367,64 @@ export function getPerUserMinimumLimit(subscription: any, freeTierEligible: bool } /** - * Check if a user can edit their usage limits based on their subscription - * Free and Enterprise plans cannot edit limits - * Pro and Team plans can increase their limits - * @param subscription The subscription object - * @returns Whether the user can edit their usage limits + * Whether a subscription's usage limit is customer-editable: Pro, Team, or self-serve Enterprise, + * active and outside a trial. */ export function canEditUsageLimit(subscription: any): boolean { if (!subscription || !hasUsableSubscriptionStatus(subscription.status)) { return false // Free plan users cannot edit limits } - // Only Pro and Team plans can edit limits - // Enterprise has a fixed, administrator-controlled contract-period limit. - return isPro(subscription.plan) || isTeam(subscription.plan) + if (isTrialingSubscription(subscription)) return false + + return ( + isPro(subscription.plan) || isTeam(subscription.plan) || isEnterpriseSelfServe(subscription) + ) +} + +/** + * Resolves a subscription's effective billing interval. Prefers the Stripe-synced + * `billingInterval` column — the only source populated on enterprise/manual + * subscriptions, which skip the checkout flow that writes the metadata value — and + * falls back to `metadata.billingInterval` (the column is often null on + * checkout-created subs), defaulting to monthly. Where both are set they agree. + */ +export function resolveBillingInterval( + sub: { billingInterval?: string | null; metadata?: unknown } | null | undefined +): 'month' | 'year' { + const column = sub?.billingInterval + if (column === 'year' || column === 'month') return column + return toRecord(sub?.metadata).billingInterval === 'year' ? 'year' : 'month' +} + +/** The billing fields that decide a plan's included usage per period. */ +export interface PlanPricingInput { + plan?: string | null + billingInterval?: string | null + metadata?: unknown } /** - * Get pricing info for a plan. Supports both legacy names (`'pro'`, `'team'`) - * and new credit-tier names (`'pro_4000'`, `'team_8000'`). + * A plan's included usage per seat for one billing period, in dollars. Supports both legacy names + * (`'pro'`, `'team'`) and credit-tier names (`'pro_6000'`, `'team_25000'`). + * + * An annual Pro or Team plan includes twelve months of credits, pooled across its yearly billing + * period, since its usage window is that whole year. Enterprise contracts set their own allowance. */ -export function getPlanPricing(plan: string): { basePrice: number } { +export function getPlanPricing(subscription: PlanPricingInput): { basePrice: number } { + const plan = subscription.plan ?? '' if (isFree(plan)) return { basePrice: 0 } if (isEnterprise(plan)) return { basePrice: getEnterpriseTierLimitPerSeat() } if (isPro(plan) || isTeam(plan)) { const tierCredits = getPlanTierCredits(plan) - if (tierCredits > 0) return { basePrice: tierCredits / CREDIT_MULTIPLIER } - return { basePrice: isPro(plan) ? getProTierLimit() : getTeamTierLimitPerSeat() } + const monthly = + tierCredits > 0 + ? tierCredits / CREDIT_MULTIPLIER + : isPro(plan) + ? getProTierLimit() + : getTeamTierLimitPerSeat() + return { basePrice: resolveBillingInterval(subscription) === 'year' ? monthly * 12 : monthly } } return { basePrice: 0 } diff --git a/apps/sim/lib/billing/threshold-billing.test.ts b/apps/sim/lib/billing/threshold-billing.test.ts index c4ba3ad66af..39add7dc1e4 100644 --- a/apps/sim/lib/billing/threshold-billing.test.ts +++ b/apps/sim/lib/billing/threshold-billing.test.ts @@ -309,7 +309,8 @@ describe('checkAndBillOverageThreshold', () => { }, { name: 'plan ineligible', - prepare: () => mockIsFree.mockReturnValue(true), + prepare: () => + mockGetHighestPrioritySubscription.mockResolvedValue({ ...userSubscription, plan: 'free' }), }, { name: 'below threshold', @@ -331,6 +332,23 @@ describe('checkAndBillOverageThreshold', () => { ).resolves.toBeUndefined() }) + it('never bills a trial, which is capped at its allowance', async () => { + queuePersonalReads() + mockGetHighestPrioritySubscription.mockResolvedValue({ + ...userSubscription, + status: 'trialing', + }) + mockCalculateSubscriptionOverage.mockResolvedValue(250) + + await expect( + checkAndBillOverageThreshold('user-1', undefined, { + onError: 'throw', + expectedBillingPeriod, + }) + ).resolves.toEqual({ status: 'no-op', reason: 'plan-ineligible' }) + expect(mockEnqueueOutboxEvent).not.toHaveBeenCalled() + }) + it('returns a distinct modern no-op when overage is below threshold', async () => { queuePersonalReads() mockCalculateSubscriptionOverage.mockResolvedValue(99) @@ -343,8 +361,17 @@ describe('checkAndBillOverageThreshold', () => { ).resolves.toEqual({ status: 'no-op', reason: 'below-threshold' }) }) - it('does not compare an Enterprise reporting window to Stripe before the ineligible no-op', async () => { - mockIsEnterprise.mockReturnValue(true) + it('does not compare a hard-capped Enterprise reporting window to Stripe before the ineligible no-op', async () => { + mockGetHighestPrioritySubscription.mockResolvedValue({ + ...userSubscription, + plan: 'enterprise', + metadata: { + plan: 'enterprise', + referenceId: 'org-1', + seats: '5', + invoiceAmountCents: '100000', + }, + }) await expect( checkAndBillOverageThreshold('user-1', undefined, { @@ -498,8 +525,7 @@ describe('checkAndBillOverageThreshold', () => { await checkAndBillOverageThreshold('user-1') expect(mockComputeOrgOverageAmount).toHaveBeenCalledWith({ - plan: 'team', - seats: 2, + subscription: expect.objectContaining({ plan: 'team', seats: 2, metadata: undefined }), periodStart: new Date('2026-05-01T00:00:00.000Z'), periodEnd: new Date('2026-06-01T00:00:00.000Z'), organizationId: userSubscription.referenceId, diff --git a/apps/sim/lib/billing/threshold-billing.ts b/apps/sim/lib/billing/threshold-billing.ts index afb72fb6a36..cf7c9af19a2 100644 --- a/apps/sim/lib/billing/threshold-billing.ts +++ b/apps/sim/lib/billing/threshold-billing.ts @@ -15,9 +15,9 @@ import { } from '@/lib/billing/core/subscription' import { type BillingEntity, getBillingPeriodUsageCost } from '@/lib/billing/core/usage-log' import { isSubscriptionCycleCloseCurrent } from '@/lib/billing/cycle-close' -import { isEnterprise, isFree } from '@/lib/billing/plan-helpers' import { hasUsableSubscriptionAccess, + invoicesOverage, isOrgScopedSubscription, } from '@/lib/billing/subscriptions/utils' import { toDecimal, toNumber } from '@/lib/billing/utils/decimal' @@ -260,7 +260,7 @@ export async function checkAndBillOverageThreshold( return noOp(options, 'no-subscription') } - if (isFree(userSubscription.plan) || isEnterprise(userSubscription.plan)) { + if (!invoicesOverage(userSubscription)) { return noOp(options, 'plan-ineligible') } @@ -300,6 +300,8 @@ export async function checkAndBillOverageThreshold( plan: userSubscription.plan, referenceId: userSubscription.referenceId, seats: userSubscription.seats, + metadata: userSubscription.metadata, + billingInterval: userSubscription.billingInterval, periodStart: userSubscription.periodStart, periodEnd: userSubscription.periodEnd, }) @@ -546,7 +548,7 @@ async function checkAndBillOrganizationOverageThreshold( return noOp(options, 'no-subscription') } - if (isEnterprise(orgSubscription.plan) || isFree(orgSubscription.plan)) { + if (!invoicesOverage(orgSubscription)) { logger.debug('Organization plan not eligible for overage billing, skipping', { organizationId, plan: orgSubscription.plan, @@ -633,8 +635,15 @@ async function checkAndBillOrganizationOverageThreshold( baseSubscriptionAmount: basePrice, effectiveUsage: effectiveTeamUsage, } = await computeOrgOverageAmount({ - plan: orgSubscription.plan, - seats: orgSubscription.seats ?? null, + subscription: { + plan: orgSubscription.plan, + seats: orgSubscription.seats ?? null, + metadata: orgSubscription.metadata, + billingInterval: orgSubscription.billingInterval, + periodStart: orgSubscription.periodStart, + allowancePeriodStart: orgSubscription.allowancePeriodStart, + allowanceSeatMonths: orgSubscription.allowanceSeatMonths, + }, periodStart: orgSubscription.periodStart ?? null, periodEnd: orgSubscription.periodEnd ?? null, organizationId, @@ -852,8 +861,8 @@ async function checkAndBillOrganizationOverageThreshold( customerId, stripeSubscriptionId, amountCents, - description: `Team threshold overage billing – ${billingPeriod}`, - itemDescription: `Team usage overage ($${amountToBill.toFixed(2)})`, + description: `Organization threshold overage billing – ${billingPeriod}`, + itemDescription: `Organization usage overage ($${amountToBill.toFixed(2)})`, billingPeriod, invoiceIdemKeyStem: `threshold-overage-org-invoice:${customerId}:${stripeSubscriptionId}:${billingPeriod}:${totalOverageCents}:${amountCents}`, itemIdemKeyStem: `threshold-overage-org-item:${customerId}:${stripeSubscriptionId}:${billingPeriod}:${totalOverageCents}:${amountCents}`, diff --git a/apps/sim/lib/billing/trial.integration.ts b/apps/sim/lib/billing/trial.integration.ts new file mode 100644 index 00000000000..6d76ec74c8b --- /dev/null +++ b/apps/sim/lib/billing/trial.integration.ts @@ -0,0 +1,566 @@ +/** + * The Pro free trial against real PostgreSQL: which checkouts start a trial, how each card and + * account is held to one trial (with Stripe stubbed at its client), and the trial's usage limit + * from start through conversion. + */ +import { db } from '@sim/db' +import { organization, subscription, trialCard, user, userStats } from '@sim/db/schema' +import { generateId } from '@sim/utils/id' +import { eq, inArray } from 'drizzle-orm' +import type Stripe from 'stripe' +import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { PRO_TRIAL_DAYS, PRO_TRIAL_USAGE_LIMIT_DOLLARS } from '@/lib/billing/constants' +import { syncUsageLimitsFromSubscription, updateUserUsageLimit } from '@/lib/billing/core/usage' +import { setUsageLimitForCredits } from '@/lib/billing/credits/purchase' +import { + enforceOneTrialPerCard, + enforceOneTrialPerCardForCheckout, + getProTrialCheckoutParams, +} from '@/lib/billing/trial' +import { resolveUsageUpgradePayload } from '@/lib/billing/usage-upgrade' + +const { stripeStub } = vi.hoisted(() => ({ + stripeStub: { + paymentMethods: { retrieve: vi.fn() }, + subscriptions: { retrieve: vi.fn(), update: vi.fn() }, + }, +})) + +vi.mock('@/lib/billing/stripe-client', () => ({ + requireStripeClient: () => stripeStub, + getStripeClient: () => stripeStub, +})) + +const PRO_PLAN = 'pro_6000' +const PRO_BASE_DOLLARS = 30 + +const userIds: string[] = [] +const organizationIds: string[] = [] +const fingerprints: string[] = [] + +async function createUser(options: { freeTierEligible?: boolean } = {}): Promise { + const id = `trial-user-${generateId()}` + const now = new Date() + await db.insert(user).values({ + id, + name: 'Trial Test', + email: `${id}@trial.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + await db.insert(userStats).values({ + id: generateId(), + userId: id, + freeTierEligible: options.freeTierEligible ?? true, + }) + userIds.push(id) + return id +} + +async function addSubscription( + referenceId: string, + fields: { status: string; plan?: string; trialStart?: Date | null; stripeSubscriptionId?: string } +): Promise { + const id = generateId() + const now = Date.now() + await db.insert(subscription).values({ + id, + plan: fields.plan ?? PRO_PLAN, + referenceId, + status: fields.status, + stripeSubscriptionId: fields.stripeSubscriptionId ?? `sub_${generateId()}`, + periodStart: new Date(now), + periodEnd: new Date(now + PRO_TRIAL_DAYS * 86_400_000), + trialStart: fields.trialStart ?? null, + trialEnd: fields.trialStart ? new Date(now + PRO_TRIAL_DAYS * 86_400_000) : null, + }) + return id +} + +function trialingStripeSubscription( + id: string, + defaultPaymentMethod: string | null +): Stripe.Subscription { + return { + id, + status: 'trialing', + default_payment_method: defaultPaymentMethod, + } as Stripe.Subscription +} + +function payer(userId: string): { plan: string; referenceId: string } { + return { plan: PRO_PLAN, referenceId: userId } +} + +function useCard(fingerprint: string | null): void { + if (fingerprint) fingerprints.push(fingerprint) + stripeStub.paymentMethods.retrieve.mockResolvedValue({ + id: `pm_${generateId()}`, + card: fingerprint ? { fingerprint } : undefined, + }) +} + +async function readLimit(userId: string): Promise { + const [stats] = await db + .select({ currentUsageLimit: userStats.currentUsageLimit }) + .from(userStats) + .where(eq(userStats.userId, userId)) + return Number(stats?.currentUsageLimit) +} + +beforeEach(() => { + stripeStub.paymentMethods.retrieve.mockReset() + stripeStub.subscriptions.retrieve.mockReset() + stripeStub.subscriptions.update.mockReset() + stripeStub.subscriptions.update.mockResolvedValue({}) +}) + +afterAll(async () => { + if (fingerprints.length > 0) { + await db.delete(trialCard).where(inArray(trialCard.fingerprint, fingerprints)) + } + if (userIds.length > 0) { + await db.delete(subscription).where(inArray(subscription.referenceId, userIds)) + await db.delete(user).where(inArray(user.id, userIds)) + } + if (organizationIds.length > 0) { + await db.delete(organization).where(inArray(organization.id, organizationIds)) + } +}) + +describe('getProTrialCheckoutParams', () => { + it("starts a card-required trial for a new account's personal Pro checkout", async () => { + const userId = await createUser() + // The incomplete row the Stripe plugin writes before building the checkout. + await addSubscription(userId, { status: 'incomplete' }) + + const params = await getProTrialCheckoutParams({ + userId, + referenceId: userId, + planName: PRO_PLAN, + }) + + expect(params).toEqual({ + payment_method_types: ['card'], + payment_method_collection: 'always', + subscription_data: { + trial_period_days: PRO_TRIAL_DAYS, + trial_settings: { end_behavior: { missing_payment_method: 'cancel' } }, + }, + }) + }) + + it('still offers the trial after an abandoned checkout', async () => { + const userId = await createUser() + await addSubscription(userId, { status: 'incomplete_expired' }) + + expect( + await getProTrialCheckoutParams({ userId, referenceId: userId, planName: PRO_PLAN }) + ).not.toBeNull() + }) + + it.each([ + { label: 'Max', planName: 'pro_25000', organization: false }, + { label: 'a team plan', planName: 'team_6000', organization: false }, + { label: 'an organization checkout', planName: PRO_PLAN, organization: true }, + ])('offers no trial for $label', async ({ planName, organization }) => { + const userId = await createUser() + + expect( + await getProTrialCheckoutParams({ + userId, + referenceId: organization ? `org-${generateId()}` : userId, + planName, + }) + ).toBeNull() + }) + + it('offers no trial to an account that already trialed', async () => { + const userId = await createUser() + await addSubscription(userId, { status: 'canceled', trialStart: new Date() }) + + expect( + await getProTrialCheckoutParams({ userId, referenceId: userId, planName: PRO_PLAN }) + ).toBeNull() + }) + + it('offers no trial to an account that already paid for a plan', async () => { + const userId = await createUser() + await addSubscription(userId, { status: 'canceled' }) + + expect( + await getProTrialCheckoutParams({ userId, referenceId: userId, planName: PRO_PLAN }) + ).toBeNull() + }) + + it("offers no trial to an account reusing a deleted account's identity", async () => { + const userId = await createUser({ freeTierEligible: false }) + + expect( + await getProTrialCheckoutParams({ userId, referenceId: userId, planName: PRO_PLAN }) + ).toBeNull() + }) +}) + +describe('enforceOneTrialPerCard', () => { + it("keeps a card's first trial and records the card", async () => { + const userId = await createUser() + const stripeSubscriptionId = `sub_${generateId()}` + await addSubscription(userId, { + status: 'trialing', + trialStart: new Date(), + stripeSubscriptionId, + }) + const fingerprint = `fp_${generateId()}` + useCard(fingerprint) + + expect( + await enforceOneTrialPerCard( + trialingStripeSubscription(stripeSubscriptionId, 'pm_1'), + payer(userId) + ) + ).toBe(true) + + expect(stripeStub.subscriptions.update).not.toHaveBeenCalled() + const [claim] = await db.select().from(trialCard).where(eq(trialCard.fingerprint, fingerprint)) + expect(claim).toMatchObject({ userId, stripeSubscriptionId }) + }) + + it('keeps the trial when the same checkout webhook is delivered again', async () => { + const userId = await createUser() + const stripeSubscriptionId = `sub_${generateId()}` + await addSubscription(userId, { + status: 'trialing', + trialStart: new Date(), + stripeSubscriptionId, + }) + useCard(`fp_${generateId()}`) + const trial = trialingStripeSubscription(stripeSubscriptionId, 'pm_1') + + expect(await enforceOneTrialPerCard(trial, payer(userId))).toBe(true) + expect(await enforceOneTrialPerCard(trial, payer(userId))).toBe(true) + expect(stripeStub.subscriptions.update).not.toHaveBeenCalled() + }) + + it("ends a second account's trial on a card that already trialed, even after the first account is deleted", async () => { + const fingerprint = `fp_${generateId()}` + useCard(fingerprint) + const firstUserId = await createUser() + const firstSubscriptionId = `sub_${generateId()}` + await addSubscription(firstUserId, { + status: 'trialing', + trialStart: new Date(), + stripeSubscriptionId: firstSubscriptionId, + }) + expect( + await enforceOneTrialPerCard( + trialingStripeSubscription(firstSubscriptionId, 'pm_1'), + payer(firstUserId) + ) + ).toBe(true) + await db.delete(subscription).where(eq(subscription.referenceId, firstUserId)) + await db.delete(user).where(eq(user.id, firstUserId)) + + const secondUserId = await createUser() + const secondSubscriptionId = `sub_${generateId()}` + await addSubscription(secondUserId, { + status: 'trialing', + trialStart: new Date(), + stripeSubscriptionId: secondSubscriptionId, + }) + + expect( + await enforceOneTrialPerCard( + trialingStripeSubscription(secondSubscriptionId, 'pm_2'), + payer(secondUserId) + ) + ).toBe(false) + expect(stripeStub.subscriptions.update).toHaveBeenCalledExactlyOnceWith( + secondSubscriptionId, + { trial_end: 'now' }, + { idempotencyKey: `end-ineligible-trial:${secondSubscriptionId}` } + ) + const [claim] = await db.select().from(trialCard).where(eq(trialCard.fingerprint, fingerprint)) + expect(claim).toMatchObject({ userId: null, stripeSubscriptionId: firstSubscriptionId }) + }) + + it('ends a trial whose card cannot be identified', async () => { + const userId = await createUser() + const stripeSubscriptionId = `sub_${generateId()}` + await addSubscription(userId, { + status: 'trialing', + trialStart: new Date(), + stripeSubscriptionId, + }) + + expect( + await enforceOneTrialPerCard( + trialingStripeSubscription(stripeSubscriptionId, null), + payer(userId) + ) + ).toBe(false) + expect(stripeStub.subscriptions.update).toHaveBeenCalledOnce() + }) + + it("ends an account's racing second trial and keeps the first through a redelivery", async () => { + const userId = await createUser() + const firstSubscriptionId = `sub_${generateId()}` + const racingSubscriptionId = `sub_${generateId()}` + for (const stripeSubscriptionId of [firstSubscriptionId, racingSubscriptionId]) { + await addSubscription(userId, { + status: 'trialing', + trialStart: new Date(), + stripeSubscriptionId, + }) + } + const firstCard = `fp_${generateId()}` + + useCard(firstCard) + expect( + await enforceOneTrialPerCard( + trialingStripeSubscription(firstSubscriptionId, 'pm_1'), + payer(userId) + ) + ).toBe(true) + + useCard(`fp_${generateId()}`) + expect( + await enforceOneTrialPerCard( + trialingStripeSubscription(racingSubscriptionId, 'pm_2'), + payer(userId) + ) + ).toBe(false) + expect(stripeStub.subscriptions.update).toHaveBeenCalledExactlyOnceWith( + racingSubscriptionId, + { trial_end: 'now' }, + { idempotencyKey: `end-ineligible-trial:${racingSubscriptionId}` } + ) + + useCard(firstCard) + expect( + await enforceOneTrialPerCard( + trialingStripeSubscription(firstSubscriptionId, 'pm_1'), + payer(userId) + ) + ).toBe(true) + expect(stripeStub.subscriptions.update).toHaveBeenCalledOnce() + }) + + it('keeps exactly one of two checkouts racing on one account', async () => { + const userId = await createUser() + const racing = [`sub_${generateId()}`, `sub_${generateId()}`] + for (const stripeSubscriptionId of racing) { + await addSubscription(userId, { + status: 'trialing', + trialStart: new Date(), + stripeSubscriptionId, + }) + } + const cards = racing.map(() => `fp_${generateId()}`) + fingerprints.push(...cards) + stripeStub.paymentMethods.retrieve.mockImplementation(async (id: string) => ({ + id, + card: { fingerprint: cards[Number(id.slice(3))] }, + })) + + const kept = await Promise.all( + racing.map((stripeSubscriptionId, index) => + enforceOneTrialPerCard( + trialingStripeSubscription(stripeSubscriptionId, `pm_${index}`), + payer(userId) + ) + ) + ) + + expect(kept.filter(Boolean)).toHaveLength(1) + expect(stripeStub.subscriptions.update).toHaveBeenCalledOnce() + }) + + it('leaves a trial on any plan other than Pro alone', async () => { + const userId = await createUser() + + expect( + await enforceOneTrialPerCard(trialingStripeSubscription(`sub_${generateId()}`, 'pm_1'), { + plan: 'team_6000', + referenceId: userId, + }) + ).toBe(false) + expect(stripeStub.paymentMethods.retrieve).not.toHaveBeenCalled() + expect(stripeStub.subscriptions.update).not.toHaveBeenCalled() + }) + + it('leaves a checkout that did not start a trial alone', async () => { + const userId = await createUser() + + expect( + await enforceOneTrialPerCard( + { id: `sub_${generateId()}`, status: 'active' } as Stripe.Subscription, + payer(userId) + ) + ).toBe(false) + expect(stripeStub.paymentMethods.retrieve).not.toHaveBeenCalled() + expect(stripeStub.subscriptions.update).not.toHaveBeenCalled() + }) +}) + +describe('enforceOneTrialPerCardForCheckout', () => { + it("judges a completed checkout's trial by the subscription Sim recorded for it", async () => { + const fingerprint = `fp_${generateId()}` + useCard(fingerprint) + const firstUserId = await createUser() + const firstSubscriptionId = `sub_${generateId()}` + await addSubscription(firstUserId, { + status: 'trialing', + trialStart: new Date(), + stripeSubscriptionId: firstSubscriptionId, + }) + await enforceOneTrialPerCard( + trialingStripeSubscription(firstSubscriptionId, 'pm_1'), + payer(firstUserId) + ) + + const userId = await createUser() + const stripeSubscriptionId = `sub_${generateId()}` + await addSubscription(userId, { + status: 'trialing', + trialStart: new Date(), + stripeSubscriptionId, + }) + stripeStub.subscriptions.retrieve.mockResolvedValue( + trialingStripeSubscription(stripeSubscriptionId, 'pm_2') + ) + + await enforceOneTrialPerCardForCheckout({ + mode: 'subscription', + subscription: stripeSubscriptionId, + } as Stripe.Checkout.Session) + + expect(stripeStub.subscriptions.update).toHaveBeenCalledExactlyOnceWith( + stripeSubscriptionId, + { trial_end: 'now' }, + { idempotencyKey: `end-ineligible-trial:${stripeSubscriptionId}` } + ) + }) + + it('fails, so the webhook retries, for a trial Sim has not recorded yet', async () => { + const stripeSubscriptionId = `sub_${generateId()}` + stripeStub.subscriptions.retrieve.mockResolvedValue( + trialingStripeSubscription(stripeSubscriptionId, 'pm_1') + ) + + await expect( + enforceOneTrialPerCardForCheckout({ + mode: 'subscription', + subscription: stripeSubscriptionId, + } as Stripe.Checkout.Session) + ).rejects.toThrow('is not recorded yet') + expect(stripeStub.subscriptions.update).not.toHaveBeenCalled() + }) +}) + +describe('the trial usage limit', () => { + it("holds a trial to its allowance, lowering a limit an earlier plan left higher, until it converts to the plan's base", async () => { + const userId = await createUser() + await db + .update(userStats) + .set({ currentUsageLimit: '500', creditBalance: '2' }) + .where(eq(userStats.userId, userId)) + const subscriptionId = await addSubscription(userId, { + status: 'trialing', + trialStart: new Date(), + }) + + await syncUsageLimitsFromSubscription(userId) + expect(await readLimit(userId)).toBe(PRO_TRIAL_USAGE_LIMIT_DOLLARS + 2) + + await db + .update(subscription) + .set({ status: 'active' }) + .where(eq(subscription.id, subscriptionId)) + await syncUsageLimitsFromSubscription(userId) + expect(await readLimit(userId)).toBe(PRO_BASE_DOLLARS + 2) + }) + + it('raises a trial limit by granted credits from the trial allowance, not the plan base', async () => { + const userId = await createUser() + await addSubscription(userId, { status: 'trialing', trialStart: new Date() }) + await syncUsageLimitsFromSubscription(userId) + + await setUsageLimitForCredits('user', userId, { plan: PRO_PLAN, status: 'trialing' }, null, 1) + + expect(await readLimit(userId)).toBe(PRO_TRIAL_USAGE_LIMIT_DOLLARS + 1) + }) + + it("raises an organization's limit for credits from its seat-priced plan base, even while Stripe reports it trialing", async () => { + const organizationId = `trial-org-${generateId()}` + await db.insert(organization).values({ + id: organizationId, + name: 'Trial Org', + slug: organizationId, + orgUsageLimit: '0', + }) + organizationIds.push(organizationId) + + await setUsageLimitForCredits( + 'organization', + organizationId, + { plan: PRO_PLAN, status: 'trialing' }, + 3, + 1 + ) + + const [org] = await db + .select({ orgUsageLimit: organization.orgUsageLimit }) + .from(organization) + .where(eq(organization.id, organizationId)) + expect(Number(org?.orgUsageLimit)).toBe(PRO_BASE_DOLLARS * 3 + 1) + }) + + it('refuses to raise the limit during a trial', async () => { + const userId = await createUser() + await addSubscription(userId, { status: 'trialing', trialStart: new Date() }) + await syncUsageLimitsFromSubscription(userId) + + expect(await updateUserUsageLimit(userId, 999_999)).toEqual({ + success: false, + error: 'Usage limits can be changed once your trial ends', + }) + expect(await readLimit(userId)).toBe(PRO_TRIAL_USAGE_LIMIT_DOLLARS) + }) +}) + +describe('the usage limit card', () => { + it('tells a trialing payer usage resumes when the trial ends instead of offering a limit increase', async () => { + const userId = `trial-payer-${generateId()}` + + const card = await resolveUsageUpgradePayload(userId, { + billingEntity: { type: 'user', id: userId }, + payerSubscription: { plan: PRO_PLAN, status: 'trialing' }, + }) + + expect(card.action).toBe('upgrade_plan') + expect(card.message).toContain('free trial') + }) + + it("reads the trial from the account's subscription when the payer is not known", async () => { + const userId = await createUser() + await addSubscription(userId, { status: 'trialing', trialStart: new Date() }) + + const card = await resolveUsageUpgradePayload(userId) + + expect(card.action).toBe('upgrade_plan') + expect(card.message).toContain('free trial') + }) + + it('still offers a converted Pro payer a limit increase', async () => { + const userId = `trial-payer-${generateId()}` + + const card = await resolveUsageUpgradePayload(userId, { + billingEntity: { type: 'user', id: userId }, + payerSubscription: { plan: PRO_PLAN, status: 'active' }, + }) + + expect(card.action).toBe('increase_limit') + }) +}) diff --git a/apps/sim/lib/billing/trial.ts b/apps/sim/lib/billing/trial.ts new file mode 100644 index 00000000000..d1ecb6e1602 --- /dev/null +++ b/apps/sim/lib/billing/trial.ts @@ -0,0 +1,200 @@ +import { db } from '@sim/db' +import { subscription, trialCard, userStats } from '@sim/db/schema' +import { createLogger } from '@sim/logger' +import { and, asc, eq, isNotNull, notInArray, or, sql } from 'drizzle-orm' +import type Stripe from 'stripe' +import { PRO_CREDIT_TIER, PRO_TRIAL_DAYS } from '@/lib/billing/constants' +import { buildPlanName } from '@/lib/billing/plan-helpers' +import { requireStripeClient } from '@/lib/billing/stripe-client' +import { acquireAdvisoryXactLock } from '@/lib/db/advisory-locks' +import type { DbClient } from '@/lib/db/types' + +const logger = createLogger('ProTrial') + +/** Statuses a checkout leaves behind without ever trialing or paying: abandoned or failed. */ +const NEVER_STARTED_STATUSES = ['incomplete', 'incomplete_expired'] + +/** The only plan a checkout trial is offered on: personal Pro. */ +const TRIAL_PLAN = buildPlanName('pro', PRO_CREDIT_TIER.credits) + +type TrialCheckoutParams = Pick< + Stripe.Checkout.SessionCreateParams, + 'payment_method_types' | 'payment_method_collection' | 'subscription_data' +> + +/** + * Whether an account may start a Pro free trial: it has never trialed or held a subscription and + * still holds its free allowance (an account reusing a deleted one's identity does not). Abandoned + * checkouts do not count. The card check runs later, at checkout ({@link enforceOneTrialPerCard}). + */ +export async function isProTrialEligible( + userId: string, + executor: DbClient = db +): Promise { + const [[stats], [earlierSubscription]] = await Promise.all([ + executor + .select({ freeTierEligible: userStats.freeTierEligible }) + .from(userStats) + .where(eq(userStats.userId, userId)) + .limit(1), + executor + .select({ id: subscription.id }) + .from(subscription) + .where( + and( + eq(subscription.referenceId, userId), + or( + isNotNull(subscription.trialStart), + notInArray(subscription.status, NEVER_STARTED_STATUSES) + ) + ) + ) + .limit(1), + ]) + return Boolean(stats?.freeTierEligible) && !earlierSubscription +} + +/** + * The Checkout parameters that start a new subscriber's Pro free trial, or none when the checkout + * does not qualify. Only a personal checkout of the Pro tier qualifies, for an account + * {@link isProTrialEligible} admits. The card is collected up front and must be a card, so its + * fingerprint can hold it to one trial ({@link enforceOneTrialPerCard}); a trial left without a + * payment method cancels instead of invoicing. + */ +export async function getProTrialCheckoutParams(params: { + userId: string + referenceId: string + planName: string +}): Promise { + if (params.referenceId !== params.userId) return null + if (params.planName !== TRIAL_PLAN) return null + if (!(await isProTrialEligible(params.userId))) return null + + return { + payment_method_types: ['card'], + payment_method_collection: 'always', + subscription_data: { + trial_period_days: PRO_TRIAL_DAYS, + trial_settings: { end_behavior: { missing_payment_method: 'cancel' } }, + }, + } +} + +/** + * Holds each card, and each account, to one Pro trial. Runs when a checkout completes: a trial + * whose card already started another trial, whose account already has an earlier trial (two + * checkouts racing), or whose card cannot be identified ends at once, so Stripe charges the card + * for the first period as for any paid checkout. Only a Pro checkout trial is judged; any other + * trialing subscription is left alone. + * + * Every trial records a claim on its card, and the first claim wins: a card's winner is whichever + * subscription claimed it, and an account's winner is its earliest claim. Claims for one account + * are made one at a time under a lock and stamped with the clock at that moment, so racing + * checkouts agree on the order. The verdict reads only the claims, so a redelivered webhook + * reaches the same verdict, and a check that failed partway is safe to run again. + * + * @param subscription - the plan and payer (`referenceId`, the user for a personal plan) Sim + * recorded for this checkout + * @returns whether the subscription is still in its trial + */ +export async function enforceOneTrialPerCard( + stripeSubscription: Stripe.Subscription, + subscription: { plan: string; referenceId: string } +): Promise { + if (stripeSubscription.status !== 'trialing' || subscription.plan !== TRIAL_PLAN) return false + + const stripe = requireStripeClient() + const userId = subscription.referenceId + const reason = await findTrialIneligibility(stripe, stripeSubscription, userId) + if (!reason) return true + + await stripe.subscriptions.update( + stripeSubscription.id, + { trial_end: 'now' }, + { idempotencyKey: `end-ineligible-trial:${stripeSubscription.id}` } + ) + logger.info('Ended an ineligible trial; the card is charged now', { + userId, + stripeSubscriptionId: stripeSubscription.id, + reason, + }) + return false +} + +/** + * Enforces {@link enforceOneTrialPerCard} for a completed checkout, from the webhook path that + * Stripe retries on failure, so a check that failed in the plugin's completion hook still runs. + * A trial whose subscription Sim has not recorded yet fails, so the retried webhook records it + * first. + */ +export async function enforceOneTrialPerCardForCheckout( + session: Stripe.Checkout.Session +): Promise { + if (session.mode !== 'subscription' || !session.subscription) return + const stripeSubscriptionId = + typeof session.subscription === 'string' ? session.subscription : session.subscription.id + const stripeSubscription = + await requireStripeClient().subscriptions.retrieve(stripeSubscriptionId) + if (stripeSubscription.status !== 'trialing') return + + const [recorded] = await db + .select({ plan: subscription.plan, referenceId: subscription.referenceId }) + .from(subscription) + .where(eq(subscription.stripeSubscriptionId, stripeSubscriptionId)) + .limit(1) + if (!recorded) { + throw new Error(`Trialing subscription ${stripeSubscriptionId} is not recorded yet`) + } + await enforceOneTrialPerCard(stripeSubscription, recorded) +} + +async function findTrialIneligibility( + stripe: Stripe, + stripeSubscription: Stripe.Subscription, + userId: string +): Promise<'card-unidentified' | 'card-already-trialed' | 'account-already-trialed' | null> { + const fingerprint = await getCardFingerprint(stripe, stripeSubscription.default_payment_method) + if (!fingerprint) return 'card-unidentified' + + const claims = await db.transaction(async (tx) => { + await acquireAdvisoryXactLock(tx, 'trial_card_claim', `trial-card:${userId}`) + await tx + .insert(trialCard) + .values({ + fingerprint, + userId, + stripeSubscriptionId: stripeSubscription.id, + createdAt: sql`clock_timestamp()`, + }) + .onConflictDoNothing({ target: trialCard.fingerprint }) + return tx + .select({ + fingerprint: trialCard.fingerprint, + userId: trialCard.userId, + stripeSubscriptionId: trialCard.stripeSubscriptionId, + }) + .from(trialCard) + .where(or(eq(trialCard.fingerprint, fingerprint), eq(trialCard.userId, userId))) + .orderBy(asc(trialCard.createdAt), asc(trialCard.stripeSubscriptionId)) + }) + + const cardWinner = claims.find((claim) => claim.fingerprint === fingerprint) + if (cardWinner?.stripeSubscriptionId !== stripeSubscription.id) return 'card-already-trialed' + const accountWinner = claims.find((claim) => claim.userId === userId) + if (accountWinner?.stripeSubscriptionId !== stripeSubscription.id) { + return 'account-already-trialed' + } + return null +} + +async function getCardFingerprint( + stripe: Stripe, + paymentMethod: string | Stripe.PaymentMethod | null +): Promise { + if (!paymentMethod) return null + const resolved = + typeof paymentMethod === 'string' + ? await stripe.paymentMethods.retrieve(paymentMethod) + : paymentMethod + return resolved.card?.fingerprint ?? null +} diff --git a/apps/sim/lib/billing/types/index.test.ts b/apps/sim/lib/billing/types/index.test.ts index f1ce52770dc..fc1fcb420c7 100644 --- a/apps/sim/lib/billing/types/index.test.ts +++ b/apps/sim/lib/billing/types/index.test.ts @@ -53,9 +53,21 @@ describe('Enterprise subscription metadata', () => { monthlyPrice: 500, invoiceAmountUsd: 500, seats: 25, + selfServe: false, }) }) + it('enables self-serve only for the exact string true', () => { + for (const selfServe of ['false', 'TRUE', '1', '']) { + expect( + parseEnterpriseSubscriptionMetadata({ ...REQUIRED_METADATA, selfServe }) + ).toMatchObject({ selfServe: false }) + } + expect( + parseEnterpriseSubscriptionMetadata({ ...REQUIRED_METADATA, selfServe: 'true' }) + ).toMatchObject({ selfServe: true }) + }) + it('prefers the neutral invoice amount for annual Enterprise metadata', () => { expect( parseEnterpriseSubscriptionMetadata({ diff --git a/apps/sim/lib/billing/types/index.ts b/apps/sim/lib/billing/types/index.ts index 11370eafe51..54e75c8fdc8 100644 --- a/apps/sim/lib/billing/types/index.ts +++ b/apps/sim/lib/billing/types/index.ts @@ -43,6 +43,13 @@ export const enterpriseSubscriptionMetadataSchema = z (value) => parseWorkflowExecutionTimeoutSeconds(value) ?? undefined, z.number().int().positive().max(MAX_WORKFLOW_EXECUTION_TIMEOUT_SECONDS).optional() ), + /** Opts the contract into self-serve billing. Stripe metadata holds strings, so only `'true'` enables it. */ + selfServe: z + .string() + .optional() + .transform((value) => value === 'true'), + /** The contract rate for each seat past `seats`, in cents per seat per month. */ + seatPriceCents: z.coerce.number().int().positive().optional(), }) .refine( (metadata) => metadata.invoiceAmountCents !== undefined || metadata.monthlyPrice !== undefined, diff --git a/apps/sim/lib/billing/usage-upgrade.ts b/apps/sim/lib/billing/usage-upgrade.ts index 73548119081..111b61895d5 100644 --- a/apps/sim/lib/billing/usage-upgrade.ts +++ b/apps/sim/lib/billing/usage-upgrade.ts @@ -6,28 +6,33 @@ import type { AttributedUsageLimitsResult } from '@/lib/billing/core/attribution import { getHighestPrioritySubscription } from '@/lib/billing/core/plan' import type { BillingEntity } from '@/lib/billing/core/usage-log' import { isEnterprise, isPaid } from '@/lib/billing/plan-helpers' -import { isOrgScopedSubscription } from '@/lib/billing/subscriptions/utils' +import { isOrgScopedSubscription, isTrialingSubscription } from '@/lib/billing/subscriptions/utils' const logger = createLogger('UsageUpgrade') const UPGRADE_PLAN_MESSAGE = "You've reached your usage limit. Please upgrade your plan to continue." +const TRIAL_ALLOWANCE_MESSAGE = + "You've used the credits included in your free trial. Usage resumes when your trial ends and your plan's full allowance starts, or start your paid plan now under Settings > Subscription." + const MEMBER_CAP_MESSAGE = "You've reached the usage limit your organization set for you this billing period. Only an organization owner or admin can raise it — please ask them to continue." /** * The payer a run is billed to, as the upgrade card needs it: its billing entity and its - * subscription's plan. An attribution snapshot is one; a direct-v1 run's mid-run verdict carries one. + * subscription's plan and status. An attribution snapshot is one; a direct-v1 run's mid-run + * verdict carries one. */ export interface UsageUpgradePayer { readonly billingEntity: Readonly - readonly payerSubscription: { readonly plan: string } | null + readonly payerSubscription: { readonly plan: string; readonly status: string | null } | null } /** * The upgrade card for a payer over its usage limit: a plan upgrade for a free payer, a limit - * increase for a paid one, with copy naming who can raise an organization's limit. A member + * increase for a paid one, with copy naming who can raise an organization's limit. A personal + * trial's allowance cannot be raised, so its card says usage resumes when the trial ends. A member * over the cap their organization set gets copy naming who can raise that cap. A known payer * decides the card without a query; otherwise the actor's current subscription decides, and a * lookup that fails falls back to the plan-upgrade card. @@ -40,16 +45,16 @@ export async function resolveUsageUpgradePayload( if (scope === 'member') { return { reason: 'usage_limit', action: 'increase_limit', message: MEMBER_CAP_MESSAGE } } - let plan: string | undefined + let subscription: UsageUpgradePayer['payerSubscription'] = null let orgScoped = false try { if (payer) { - plan = payer.payerSubscription?.plan + subscription = payer.payerSubscription orgScoped = payer.billingEntity.type === 'organization' } else { - const subscription = await getHighestPrioritySubscription(userId) - plan = subscription?.plan - orgScoped = isOrgScopedSubscription(subscription, userId) + const current = await getHighestPrioritySubscription(userId) + subscription = current + orgScoped = isOrgScopedSubscription(current, userId) } } catch (error) { logger.warn('Failed to determine subscription plan, defaulting to upgrade_plan', { @@ -57,9 +62,13 @@ export async function resolveUsageUpgradePayload( }) } + const plan = subscription?.plan if (!plan || !isPaid(plan)) { return { reason: 'usage_limit', action: 'upgrade_plan', message: UPGRADE_PLAN_MESSAGE } } + if (!orgScoped && isTrialingSubscription(subscription)) { + return { reason: 'usage_limit', action: 'upgrade_plan', message: TRIAL_ALLOWANCE_MESSAGE } + } // Paid plans get `increase_limit`; the copy says who can raise it when the user cannot. const message = !orgScoped ? "You've reached your usage limit for this billing period. Please increase your usage limit from billing settings to continue." diff --git a/apps/sim/lib/billing/validation/seat-management.ts b/apps/sim/lib/billing/validation/seat-management.ts index 7c1a42abccc..4dbc3aad311 100644 --- a/apps/sim/lib/billing/validation/seat-management.ts +++ b/apps/sim/lib/billing/validation/seat-management.ts @@ -77,36 +77,39 @@ export async function countPendingSeatInvitations( } /** - * Resolves the organization's seat capacity, honouring an Enterprise seat - * change that is still in flight to Stripe. + * How an organization's seats bound membership: + * - `fixed`: an Enterprise contract outside self-serve, a cap that can actually be exhausted; + * - `baseline`: a self-serve Enterprise contract, whose members outgrow its seats and true up; + * - `on-demand`: Team, billed per member, so `subscription.seats` tracks the member count rather + * than a ceiling. */ -export async function resolveSeatCapacity( +export type SeatCapKind = 'fixed' | 'baseline' | 'on-demand' + +/** + * The organization's seats and how they bound membership, honouring an Enterprise change still + * in flight to Stripe. Every surface that admits members or gates remaining capacity branches on + * `kind`. + */ +export async function resolveSeatCap( organizationSubscription: { id: string; plan: string; metadata?: unknown } & Record< string, unknown >, executor: DbOrTx = db -): Promise { +): Promise<{ seats: number; kind: SeatCapKind }> { const canonicalSeats = getEffectiveSeats(organizationSubscription) - if (!isEnterprise(organizationSubscription.plan)) return canonicalSeats + if (!isEnterprise(organizationSubscription.plan)) { + return { seats: canonicalSeats, kind: 'on-demand' } + } const intent = await resolveEnterpriseMetadataIntent( executor, organizationSubscription.id, organizationSubscription.metadata ) - return intent?.effectiveSeatCapacity ?? canonicalSeats -} - -/** - * Whether the plan has a seat cap that can actually be exhausted. - * - * Only Enterprise does. Team seats are billed per member and grown on demand, - * so its `subscription.seats` tracks the current member count rather than a - * ceiling — comparing usage against it would always read as "full". Surfaces - * that gate or visualise remaining capacity must branch on this. - */ -export function planHasFixedSeatCap(plan: string | undefined | null): boolean { - return isEnterprise(plan) + return { + seats: intent.effectiveSeatCapacity ?? canonicalSeats, + kind: intent.seatsUncapped ? 'baseline' : 'fixed', + } } /** @@ -192,14 +195,15 @@ export async function validateSeatAvailability( } } - const [memberCount, pendingSeats, maxSeats] = await Promise.all([ + const [memberCount, pendingSeats, seatCap] = await Promise.all([ executor .select({ count: count() }) .from(member) .where(eq(member.organizationId, organizationId)), countPendingSeatInvitations(organizationId, executor, options.excludePendingInvitationId), - resolveSeatCapacity(subscription, executor), + resolveSeatCap(subscription, executor), ]) + const maxSeats = seatCap.seats const { usedSeats: currentSeats, @@ -209,7 +213,7 @@ export async function validateSeatAvailability( memberSeats: memberCount[0]?.count ?? 0, pendingSeats, totalSeats: maxSeats, - hasFixedSeatCap: planHasFixedSeatCap(subscription.plan), + hasFixedSeatCap: seatCap.kind === 'fixed', }) /** * Only a fixed cap can refuse an invite. Team seats are provisioned when the @@ -298,12 +302,13 @@ export async function getOrganizationSeatInfo( return null } - const maxSeats = await resolveSeatCapacity(subscription) + const seatCap = await resolveSeatCap(subscription) + const maxSeats = seatCap.seats const { availableSeats } = computeSeatUsage({ memberSeats, pendingSeats, totalSeats: maxSeats, - hasFixedSeatCap: planHasFixedSeatCap(subscription.plan), + hasFixedSeatCap: seatCap.kind === 'fixed', }) return { @@ -313,7 +318,7 @@ export async function getOrganizationSeatInfo( maxSeats, availableSeats, subscriptionPlan: subscription.plan, - canAddSeats: !isEnterprise(subscription.plan), + canAddSeats: seatCap.kind !== 'fixed', } } catch (error) { logger.error('Failed to get organization seat info', { organizationId, error }) diff --git a/apps/sim/lib/billing/webhooks/enterprise-auto-pay.ts b/apps/sim/lib/billing/webhooks/enterprise-auto-pay.ts new file mode 100644 index 00000000000..4462a6bfbd2 --- /dev/null +++ b/apps/sim/lib/billing/webhooks/enterprise-auto-pay.ts @@ -0,0 +1,108 @@ +import { db } from '@sim/db' +import { subscription } from '@sim/db/schema' +import { createLogger } from '@sim/logger' +import { eq } from 'drizzle-orm' +import type Stripe from 'stripe' +import { requireStripeClient } from '@/lib/billing/stripe-client' +import { getCustomerId, getPaymentMethodId } from '@/lib/billing/stripe-payment-method' +import { + hasPaidSubscriptionStatus, + isEnterpriseSelfServe, + isSelfServeEnterpriseMetadata, +} from '@/lib/billing/subscriptions/utils' +import { withEnterpriseReconciliationLease } from '@/lib/billing/webhooks/enterprise-reconciliation-lease' + +const logger = createLogger('EnterpriseAutoPay') + +/** Marks the setup Checkout session a self-serve Enterprise customer opens to turn on auto-pay. */ +export const ENTERPRISE_AUTO_PAY_PURPOSE = 'enterprise_auto_pay' + +/** + * Switches an Enterprise contract to automatic payment once its customer saves a payment method + * on Stripe's setup page: the method becomes the default for the subscription and for the + * customer's ad-hoc invoices (true-ups, overage), and renewals stop being emailed for payment. + * Changing the collection method only affects invoices created afterwards. Ignores every other + * Checkout session. + */ +export async function handleEnterpriseAutoPaySetup(session: Stripe.Checkout.Session) { + if (session.mode !== 'setup' || session.metadata?.purpose !== ENTERPRISE_AUTO_PAY_PURPOSE) return + + const { organizationId, stripeSubscriptionId } = session.metadata + const setupIntentId = + typeof session.setup_intent === 'string' ? session.setup_intent : session.setup_intent?.id + if (!organizationId || !stripeSubscriptionId || !setupIntentId) { + logger.error('Enterprise auto-pay session is missing its references', { + sessionId: session.id, + }) + return + } + + // A session lives a day: the contract may have left self-serve or ended since it was opened. + // A past-due contract still qualifies, since a new payment method is how it recovers. + const [contract] = await db + .select() + .from(subscription) + .where(eq(subscription.stripeSubscriptionId, stripeSubscriptionId)) + .limit(1) + if ( + !contract?.stripeCustomerId || + contract.referenceId !== organizationId || + contract.stripeCustomerId !== getCustomerId(session.customer) || + !isEnterpriseSelfServe(contract) || + !hasPaidSubscriptionStatus(contract.status) + ) { + logger.warn('Enterprise auto-pay session no longer matches a self-serve contract', { + sessionId: session.id, + organizationId, + }) + return + } + + const stripe = requireStripeClient() + const setupIntent = await stripe.setupIntents.retrieve(setupIntentId) + const paymentMethodId = getPaymentMethodId(setupIntent.payment_method) + if (setupIntent.status !== 'succeeded' || !paymentMethodId) { + logger.warn('Enterprise auto-pay setup did not save a payment method', { + sessionId: session.id, + setupIntentStatus: setupIntent.status, + }) + return + } + + const customerId = contract.stripeCustomerId + // Admin changes to the contract hold this lease while they write Stripe, so re-reading Stripe's + // terms under it sees a self-serve shutdown that landed after the local check above. + const switched = await withEnterpriseReconciliationLease(stripeSubscriptionId, async () => { + const current = await stripe.subscriptions.retrieve(stripeSubscriptionId) + if ( + current.metadata?.referenceId !== organizationId || + !isSelfServeEnterpriseMetadata(current.metadata) + ) { + return false + } + await stripe.customers.update( + customerId, + { invoice_settings: { default_payment_method: paymentMethodId } }, + { idempotencyKey: `enterprise-auto-pay:${session.id}:customer` } + ) + await stripe.subscriptions.update( + stripeSubscriptionId, + { collection_method: 'charge_automatically', default_payment_method: paymentMethodId }, + { idempotencyKey: `enterprise-auto-pay:${session.id}:subscription` } + ) + return true + }) + if (!switched) { + logger.warn('Enterprise contract left self-serve before auto-pay could switch', { + sessionId: session.id, + organizationId, + }) + return + } + + logger.info('Enterprise contract switched to automatic payment', { + organizationId, + stripeSubscriptionId, + paymentMethodId, + }) +} diff --git a/apps/sim/lib/billing/webhooks/enterprise.ts b/apps/sim/lib/billing/webhooks/enterprise.ts index f0f037f9352..abf692bb32b 100644 --- a/apps/sim/lib/billing/webhooks/enterprise.ts +++ b/apps/sim/lib/billing/webhooks/enterprise.ts @@ -34,7 +34,9 @@ import { requireStripeClient } from '@/lib/billing/stripe-client' import { ENTITLED_SUBSCRIPTION_STATUSES, hasPaidSubscriptionStatus, + isSelfServeEnterpriseMetadata, } from '@/lib/billing/subscriptions/utils' +import { Decimal, toDecimal } from '@/lib/billing/utils/decimal' import { assertEnterpriseReconciliationLeaseHeld, type EnterpriseReconciliationLease, @@ -80,6 +82,23 @@ async function processManualEnterpriseSubscription(event: Stripe.Event) { ) } +/** + * The usage limit a self-serve customer keeps across a contract reconcile. It starts at the + * contract's limit when self-serve turns on, so prepaid credit spent on overage mid-period never + * shrinks it. Leaving self-serve drops it; metadata that still asks for self-serve but cannot run + * it (a hand-added reporting anchor) keeps it for when the contract is repaired. + */ +function resolveSelfServeUsageLimit(params: { + selfServe: boolean + requestsSelfServe: boolean + chosen: string | null + contractLimit: string +}): string | null { + if (params.selfServe) return params.chosen ?? params.contractLimit + if (params.requestsSelfServe) return params.chosen + return null +} + async function reconcileManualEnterpriseSubscription( eventSubscription: Stripe.Subscription, reconciliationLease: EnterpriseReconciliationLease, @@ -139,6 +158,7 @@ async function reconcileManualEnterpriseSubscription( } const { seats, invoiceAmountUsd } = enterpriseMetadata + const selfServe = isSelfServeEnterpriseMetadata(metadata) // Get the first subscription item which contains the period information const referenceItem = stripeSubscription.items?.data?.[0] if ( @@ -196,7 +216,10 @@ async function reconcileManualEnterpriseSubscription( // whose lease was reclaimed cannot apply an older snapshot. await assertEnterpriseReconciliationLeaseHeld(tx, reconciliationLease) const [organizationRow] = await tx - .select({ creditBalance: organization.creditBalance }) + .select({ + creditBalance: organization.creditBalance, + selfServeUsageLimit: organization.selfServeUsageLimit, + }) .from(organization) .where(eq(organization.id, referenceId)) .for('update') @@ -288,7 +311,8 @@ async function reconcileManualEnterpriseSubscription( ? correlatedOperation.request.invitations.map((invite) => invite.email) : [], }) - if (isEntitled && seats < seatRequirement.requiredSeats) { + // A self-serve contract's seats are its committed baseline; members past it are trued up. + if (isEntitled && !selfServe && seats < seatRequirement.requiredSeats) { throw new Error( `Enterprise seat capacity ${seats} is below ${seatRequirement.requiredSeats} occupied or reserved seats` ) @@ -398,10 +422,22 @@ async function reconcileManualEnterpriseSubscription( invoiceAmountUsd, prepaidBalanceDollars: organizationRow.creditBalance, }) + const selfServeUsageLimit = resolveSelfServeUsageLimit({ + selfServe, + requestsSelfServe: metadata.selfServe === 'true', + chosen: organizationRow.selfServeUsageLimit, + contractLimit: creditLimits.effectiveUsageLimitDollars, + }) await tx .update(organization) .set({ - orgUsageLimit: creditLimits.effectiveUsageLimitDollars, + orgUsageLimit: selfServe + ? Decimal.max( + toDecimal(selfServeUsageLimit), + toDecimal(creditLimits.effectiveUsageLimitDollars) + ).toString() + : creditLimits.effectiveUsageLimitDollars, + selfServeUsageLimit, updatedAt: new Date(), }) .where(eq(organization.id, referenceId)) diff --git a/apps/sim/lib/billing/webhooks/invoices.ts b/apps/sim/lib/billing/webhooks/invoices.ts index ae8dbab8ebf..7f291a4a4c7 100644 --- a/apps/sim/lib/billing/webhooks/invoices.ts +++ b/apps/sim/lib/billing/webhooks/invoices.ts @@ -15,6 +15,7 @@ import { addCredits, getCreditBalanceForEntity } from '@/lib/billing/credits/bal import { setUsageLimitForCredits } from '@/lib/billing/credits/purchase' import { blockOrgMembers, unblockOrgMembers } from '@/lib/billing/organizations/membership' import { requireStripeClient } from '@/lib/billing/stripe-client' +import { getCustomerId } from '@/lib/billing/stripe-payment-method' import { ENTITLED_SUBSCRIPTION_STATUSES } from '@/lib/billing/subscriptions/utils' import { toDecimal, toNumber } from '@/lib/billing/utils/decimal' import { stripeWebhookIdempotency } from '@/lib/billing/webhooks/idempotency' @@ -67,6 +68,7 @@ const METADATA_SUBSCRIPTION_INVOICE_TYPES = new Set([ 'overage_billing', 'overage_threshold_billing', 'overage_threshold_billing_org', + 'enterprise_seat_true_up', ]) type InvoiceSubscriptionResolutionSource = @@ -477,7 +479,7 @@ async function handleCreditPurchaseSuccess(invoice: Stripe.Invoice): Promise 0) { const sub = subscription[0] const newCreditBalance = await getCreditBalanceForEntity(entityType, entityId) - await setUsageLimitForCredits(entityType, entityId, sub.plan, sub.seats, newCreditBalance) + await setUsageLimitForCredits(entityType, entityId, sub, sub.seats, newCreditBalance) } } catch (limitError) { // Limit bump is best-effort. Customer already got credits; if the @@ -591,6 +593,34 @@ async function handleCreditPurchaseSuccess(invoice: Stripe.Invoice): Promise { + const customerId = getCustomerId(invoice.customer) + if (!customerId) return false + for await (const open of requireStripeClient().invoices.list({ + customer: customerId, + status: 'open', + limit: 100, + })) { + if ( + open.id !== invoice.id && + open.collection_method === 'charge_automatically' && + (open.attempt_count ?? 0) > 0 && + resolveInvoiceSubscriptionContext(open).stripeSubscriptionId === stripeSubscriptionId + ) { + return true + } + } + return false +} + export async function handleInvoicePaymentSucceeded(event: Stripe.Event) { try { const invoice = event.data.object as Stripe.Invoice @@ -616,7 +646,12 @@ export async function handleInvoicePaymentSucceeded(event: Stripe.Event) { const subIsOrgScoped = await isSubscriptionOrgScoped(sub) const isProrationInvoice = invoice.billing_reason === 'subscription_update' - const shouldUnblock = !isProrationInvoice || (invoice.amount_paid ?? 0) > 0 + // A paid invoice restores access only when no other charge is still failing: overage and + // seat true-up invoices are separate from renewals, so one can stay unpaid while another + // succeeds. + const shouldUnblock = + (!isProrationInvoice || (invoice.amount_paid ?? 0) > 0) && + !(await hasOtherFailedInvoice(invoice, resolvedInvoice.stripeSubscriptionId)) if (shouldUnblock) { if (subIsOrgScoped) { diff --git a/apps/sim/lib/billing/webhooks/outbox-handlers.ts b/apps/sim/lib/billing/webhooks/outbox-handlers.ts index 6c71a48589a..37284070d1c 100644 --- a/apps/sim/lib/billing/webhooks/outbox-handlers.ts +++ b/apps/sim/lib/billing/webhooks/outbox-handlers.ts @@ -5,6 +5,7 @@ import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' import { generateShortId } from '@sim/utils/id' import { and, eq } from 'drizzle-orm' +import { INVOICE_DAYS_UNTIL_DUE } from '@/lib/billing/constants' import { isTeam } from '@/lib/billing/plan-helpers' import { getPlanByName } from '@/lib/billing/plans' import { requireStripeClient } from '@/lib/billing/stripe-client' @@ -87,6 +88,11 @@ interface StripeThresholdOverageInvoicePayload { invoiceIdemKeyStem: string itemIdemKeyStem: string metadata?: Record + /** How the invoice is collected, fixed on the first attempt (see the handler). */ + collection?: { + method: 'charge_automatically' | 'send_invoice' + paymentMethodId?: string + } } async function getSubscriptionSeatSyncState(subscriptionId: string) { @@ -342,11 +348,30 @@ const stripeThresholdOverageInvoice: OutboxHandler + } +} + +function formatDollars(cents: number): string { + const dollars = cents / 100 + return Number.isInteger(dollars) ? `$${dollars}` : `$${dollars.toFixed(2)}` +} + +/** + * What the card is charged when a trial converts. Stripe's invoice preview includes any discount a + * promotion code applied; the subscription's list price is the fallback if the preview fails. + */ +async function readRenewalCharge( + stripeSubscription: TrialEndingSubscription +): Promise { + const item = stripeSubscription.items?.data?.[0] + const interval = item?.price.recurring?.interval + if (!interval) return null + try { + const preview = await requireStripeClient().invoices.createPreview({ + subscription: stripeSubscription.id, + }) + return `${formatDollars(preview.amount_due)}/${interval}` + } catch (error) { + logger.warn('Invoice preview failed for the trial reminder; quoting the list price', { + stripeSubscriptionId: stripeSubscription.id, + error: getErrorMessage(error), + }) + } + if (!item?.price.unit_amount) return null + return `${formatDollars(item.price.unit_amount * (item.quantity ?? 1))}/${interval}` +} + +/** + * Handles Stripe's `customer.subscription.trial_will_end`, which arrives three days before a trial + * converts: emails the trialing account the date, the charge, and how to cancel. Sent once per + * subscription and trial end, however often Stripe redelivers the event. + */ +export async function handleTrialWillEnd( + stripeSubscription: TrialEndingSubscription +): Promise { + const trialEnd = stripeSubscription.trial_end + if (stripeSubscription.status !== 'trialing' || !trialEnd) return + + const [recorded] = await db + .select({ plan: subscription.plan, referenceId: subscription.referenceId }) + .from(subscription) + .where(eq(subscription.stripeSubscriptionId, stripeSubscription.id)) + .limit(1) + if (!recorded) { + logger.warn('Trial ending for a subscription Sim has not recorded', { + stripeSubscriptionId: stripeSubscription.id, + }) + return + } + + await stripeWebhookIdempotency.executeWithIdempotency( + 'trial-ending-reminder', + `${stripeSubscription.id}:${trialEnd}`, + async () => { + const recipient = await readRecipient(recorded.referenceId) + const price = await readRenewalCharge(stripeSubscription) + if (!recipient || !price) return { sent: false } + + const { getTrialEndingSubject, renderTrialEndingEmail } = await import('@/components/emails') + const { sendEmail } = await import('@/lib/messaging/email/mailer') + const planName = getDisplayPlanName(recorded.plan) + const endsOn = formatTrialEndDate(new Date(trialEnd * 1000)) + const html = await renderTrialEndingEmail({ + planName, + userName: recipient.name || undefined, + endsOn, + price, + billingLink: `${getBaseUrl()}/account/settings/billing`, + }) + const result = await sendEmail({ + to: recipient.email, + subject: getTrialEndingSubject(planName, endsOn), + html, + emailType: 'transactional', + }) + // Throwing leaves the reminder unrecorded, so Stripe's redelivery retries it. + if (!result.success) throw new Error('Trial reminder email failed to send') + return { sent: true } + } + ) +} + +/** The account a plan's emails go to: the user on a personal plan, the owner on an organization's. */ +async function resolvePlanOwnerId(referenceId: string): Promise { + const [owner] = await db + .select({ userId: member.userId }) + .from(member) + .where(and(eq(member.organizationId, referenceId), eq(member.role, 'owner'))) + .limit(1) + return owner?.userId ?? referenceId +} + +/** + * Tells a payer whose paid plan just ended that Sim-hosted models, tools, and Chat stopped, and + * how to keep workflows running. Skipped when the owner is still covered by another paid plan, such + * as an organization's or a restored personal Pro. Never throws: a missed notice must not fail + * the deletion webhook that settles the final invoice. + */ +export async function sendPlanEndedEmail(ended: { + id: string + plan: string | null + referenceId: string +}) { + try { + if (!isPaid(ended.plan)) return + const ownerId = await resolvePlanOwnerId(ended.referenceId) + const current = await getHighestPrioritySubscription(ownerId, { onError: 'throw' }) + const stillPaid = + current && + current.id !== ended.id && + isPaid(current.plan) && + hasPaidSubscriptionStatus(current.status) + if (stillPaid) return + + const recipient = await readRecipient(ownerId) + if (!recipient) return + + const { getPlanEndedSubject, renderPlanEndedEmail } = await import('@/components/emails') + const { sendEmail } = await import('@/lib/messaging/email/mailer') + const planName = getDisplayPlanName(ended.plan) + const html = await renderPlanEndedEmail({ + planName, + userName: recipient.name || undefined, + upgradeLink: `${getBaseUrl()}/account/settings/billing`, + }) + const result = await sendEmail({ + to: recipient.email, + subject: getPlanEndedSubject(planName), + html, + emailType: 'transactional', + }) + // A notice must not fail the deletion it follows; the error log is the alert. + if (!result.success) { + logger.error('Plan ended email failed to send', { referenceId: ended.referenceId }) + } + } catch (error) { + logger.error('Failed to send plan ended email', { referenceId: ended.referenceId, error }) + } +} diff --git a/apps/sim/lib/billing/webhooks/subscription-usage.ts b/apps/sim/lib/billing/webhooks/subscription-usage.ts index c5ef82cccb2..86d9c233061 100644 --- a/apps/sim/lib/billing/webhooks/subscription-usage.ts +++ b/apps/sim/lib/billing/webhooks/subscription-usage.ts @@ -25,6 +25,11 @@ export async function handleSubscriptionUsageUpdate(event: Stripe.Event): Promis plan: subscription.plan, status: subscription.status, seats: subscription.seats, + billingInterval: subscription.billingInterval, + metadata: subscription.metadata, + periodStart: subscription.periodStart, + allowancePeriodStart: subscription.allowancePeriodStart, + allowanceSeatMonths: subscription.allowanceSeatMonths, }) .from(subscription) .where(eq(subscription.stripeSubscriptionId, event.data.object.id)) diff --git a/apps/sim/lib/billing/webhooks/subscription.ts b/apps/sim/lib/billing/webhooks/subscription.ts index 6f6badb33c9..521d8205700 100644 --- a/apps/sim/lib/billing/webhooks/subscription.ts +++ b/apps/sim/lib/billing/webhooks/subscription.ts @@ -1,8 +1,9 @@ import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit' import { db } from '@sim/db' -import { member, subscription } from '@sim/db/schema' +import { member, organization, subscription, userStats } from '@sim/db/schema' import { createLogger } from '@sim/logger' -import { and, eq, inArray, ne } from 'drizzle-orm' +import { and, eq, inArray, ne, sql } from 'drizzle-orm' +import { INVOICE_DAYS_UNTIL_DUE } from '@/lib/billing/constants' import { calculateSubscriptionOverage, isSubscriptionOrgScoped } from '@/lib/billing/core/billing' import { syncUsageLimitsFromSubscription } from '@/lib/billing/core/usage' import { @@ -13,9 +14,12 @@ import { import { restoreUserProSubscription } from '@/lib/billing/organizations/membership' import { isEnterprise, isPaid, isPro, isTeam } from '@/lib/billing/plan-helpers' import { requireStripeClient } from '@/lib/billing/stripe-client' +import { getPaymentMethodId } from '@/lib/billing/stripe-payment-method' import { ENTITLED_SUBSCRIPTION_STATUSES } from '@/lib/billing/subscriptions/utils' +import { toDecimal, toNumber } from '@/lib/billing/utils/decimal' import { stripeWebhookIdempotency } from '@/lib/billing/webhooks/idempotency' import { getBilledOverageForSubscription } from '@/lib/billing/webhooks/invoices' +import { sendPlanEndedEmail } from '@/lib/billing/webhooks/plan-notices' import { captureServerEvent } from '@/lib/posthog/server' import { detachOrganizationWorkspaces } from '@/lib/workspaces/organization-workspaces' @@ -245,6 +249,179 @@ export async function handleSubscriptionCreated( } } +/** + * Spends an organization's prepaid credit on its final-period overage and returns the overage now + * covered: what threshold billing already collected this period plus the credit spent. The tracker + * ends holding exactly that sum, under the same row locks threshold billing takes, so a replayed + * deletion finds the credit already counted and spends nothing twice. When the tracker belongs to + * an elapsed, forgiven period (`trackerIsCurrent` false) its collections count for nothing here and + * are replaced, but the credit still covers the final period. + */ +async function spendFinalPrepaidCredit( + organizationId: string, + totalOverage: number, + trackerIsCurrent: boolean +): Promise { + return db.transaction(async (tx) => { + const [owner] = await tx + .select({ userId: member.userId }) + .from(member) + .where(and(eq(member.organizationId, organizationId), eq(member.role, 'owner'))) + .limit(1) + if (!owner) { + logger.warn('Organization has no owner when settling final overage', { organizationId }) + return 0 + } + const [tracker] = await tx + .select({ billedOverageThisPeriod: userStats.billedOverageThisPeriod }) + .from(userStats) + .where(eq(userStats.userId, owner.userId)) + .for('update') + .limit(1) + const [org] = await tx + .select({ creditBalance: organization.creditBalance }) + .from(organization) + .where(eq(organization.id, organizationId)) + .for('update') + .limit(1) + const collected = trackerIsCurrent ? toNumber(toDecimal(tracker?.billedOverageThisPeriod)) : 0 + const credit = Math.min( + Math.max(0, totalOverage - collected), + toNumber(toDecimal(org?.creditBalance)) + ) + if (credit <= 0 || !tracker) return collected + await tx + .update(organization) + .set({ creditBalance: sql`GREATEST(0, ${organization.creditBalance} - ${credit})` }) + .where(eq(organization.id, organizationId)) + await tx + .update(userStats) + .set({ billedOverageThisPeriod: String(collected + credit) }) + .where(eq(userStats.userId, owner.userId)) + logger.info('Spent prepaid credit on final overage', { organizationId, credit }) + return collected + credit + }) +} + +/** + * Invoices a cancelled subscription's final-period overage, net of what threshold billing already + * collected, and returns the amount invoiced. The invoice is collected the way the subscription + * was: charged to the method on file, or emailed when the customer pays by invoice. + */ +async function invoiceFinalOverage(params: { + subscription: { id: string; plan: string | null; referenceId: string } + stripeSubscriptionId: string + totalOverage: number + /** + * The tracker only ever holds collections for the period that began at the close marker — the + * threshold gate blocks settlement while the marker lags. If the marker was still lagging at + * claim time (the elapsed close deferred), the tracked amount belongs to that forgiven elapsed + * period, not the terminal window: subtracting it would under-bill the final invoice. + */ + markerWasCurrent: boolean +}): Promise { + const { subscription, stripeSubscriptionId, totalOverage } = params + if (totalOverage <= 0) return 0 + + // An Enterprise contract's prepaid credit is part of what it already paid for, so it covers the + // final period's usage before anything is invoiced. + const billedOverage = isEnterprise(subscription.plan) + ? await spendFinalPrepaidCredit(subscription.referenceId, totalOverage, params.markerWasCurrent) + : params.markerWasCurrent + ? await getBilledOverageForSubscription(subscription) + : 0 + const remainingOverage = Math.max(0, totalOverage - billedOverage) + + logger.info('Subscription deleted overage calculation', { + subscriptionId: subscription.id, + totalOverage, + billedOverage, + remainingOverage, + }) + + if (remainingOverage <= 0 || !stripeSubscriptionId) return 0 + + const stripe = requireStripeClient() + const stripeSubscription = await stripe.subscriptions.retrieve(stripeSubscriptionId) + const customerId = stripeSubscription.customer as string + const cents = Math.round(remainingOverage * 100) + const endedAt = stripeSubscription.ended_at || Math.floor(Date.now() / 1000) + const billingPeriod = new Date(endedAt * 1000).toISOString().slice(0, 7) + const sendInvoice = stripeSubscription.collection_method === 'send_invoice' + const subscriptionPaymentMethod = getPaymentMethodId(stripeSubscription.default_payment_method) + + const itemIdemKey = `final-overage-item:${customerId}:${stripeSubscriptionId}:${billingPeriod}` + const invoiceIdemKey = `final-overage-invoice:${customerId}:${stripeSubscriptionId}:${billingPeriod}` + const finalizeIdemKey = `final-overage-finalize:${customerId}:${stripeSubscriptionId}:${billingPeriod}` + const sendIdemKey = `final-overage-send:${customerId}:${stripeSubscriptionId}:${billingPeriod}` + + const overageInvoice = await stripe.invoices.create( + { + customer: customerId, + ...(sendInvoice + ? { collection_method: 'send_invoice', days_until_due: INVOICE_DAYS_UNTIL_DUE } + : { + collection_method: 'charge_automatically', + // An unlinked invoice otherwise falls back to the customer's default method only. + ...(subscriptionPaymentMethod + ? { default_payment_method: subscriptionPaymentMethod } + : {}), + }), + auto_advance: true, + description: `Final overage charges for ${subscription.plan} subscription (${billingPeriod})`, + metadata: { + type: 'final_overage_billing', + billingPeriod, + subscriptionId: stripeSubscriptionId, + cancelledAt: stripeSubscription.canceled_at?.toString() || '', + }, + }, + { idempotencyKey: invoiceIdemKey } + ) + + await stripe.invoiceItems.create( + { + customer: customerId, + invoice: overageInvoice.id, + amount: cents, + currency: 'usd', + description: `Usage overage for ${subscription.plan} plan (Final billing period)`, + metadata: { + type: 'final_usage_overage', + usage: remainingOverage.toFixed(2), + totalOverage: totalOverage.toFixed(2), + billedOverage: billedOverage.toFixed(2), + billingPeriod, + }, + }, + { idempotencyKey: itemIdemKey } + ) + + if (overageInvoice.id) { + const finalized = await stripe.invoices.finalizeInvoice( + overageInvoice.id, + {}, + { idempotencyKey: finalizeIdemKey } + ) + if (sendInvoice && finalized.status === 'open') { + await stripe.invoices.sendInvoice(overageInvoice.id, {}, { idempotencyKey: sendIdemKey }) + } + } + + logger.info('Created final overage invoice for cancelled subscription', { + subscriptionId: subscription.id, + stripeSubscriptionId, + invoiceId: overageInvoice.id, + totalOverage, + billedOverage, + remainingOverage, + cents, + billingPeriod, + collectionMethod: stripeSubscription.collection_method, + }) + return remainingOverage +} + /** * Handles a subscription deletion (cancel) event. Bills any final-period * overages, resets usage, and transitions the organization to a dormant @@ -263,6 +440,7 @@ export async function handleSubscriptionDeleted( billingInterval?: string | null periodStart?: Date | null periodEnd?: Date | null + trialEnd?: Date | null metadata?: unknown }, stripeEventId?: string @@ -311,12 +489,21 @@ export async function handleSubscriptionDeleted( periodStart: terminal.periodStart ?? subscription.periodStart ?? null, periodEnd: terminal.periodEnd ?? subscription.periodEnd ?? null, } + // Better Auth hands over only its own subscription fields; the contract terms that decide + // whether a self-serve Enterprise bills overage live in the row's metadata. + const metadata = terminal.metadata ?? subscription.metadata const totalOverage = await calculateSubscriptionOverage({ ...subscription, ...settlementPeriod, + metadata, + }) + const remainingOverage = await invoiceFinalOverage({ + subscription, + stripeSubscriptionId, + totalOverage, + markerWasCurrent: terminal.markerWasCurrent, }) - const stripe = requireStripeClient() if (isEnterprise(subscription.plan)) { await writeFinalPeriodBookkeeping({ @@ -325,7 +512,7 @@ export async function handleSubscriptionDeleted( referenceId: subscription.referenceId, billingInterval: subscription.billingInterval ?? null, ...settlementPeriod, - metadata: subscription.metadata, + metadata, }) const dormantResult = await transitionOrganizationToDormantState( @@ -358,95 +545,7 @@ export async function handleSubscriptionDeleted( reference_id: subscription.referenceId, }) - return { totalOverage: 0, kind: 'enterprise' as const } - } - - // The tracker only ever holds collections for the period that began - // at the close marker — the threshold gate blocks settlement while - // the marker lags. If the marker was still lagging at claim time - // (the elapsed close above deferred), the tracked amount belongs to - // that forgiven elapsed period, not the terminal window: subtracting - // it would under-bill the final invoice, so count nothing. - const billedOverage = terminal.markerWasCurrent - ? await getBilledOverageForSubscription(subscription) - : 0 - const remainingOverage = Math.max(0, totalOverage - billedOverage) - - logger.info('Subscription deleted overage calculation', { - subscriptionId: subscription.id, - totalOverage, - billedOverage, - remainingOverage, - }) - - if (remainingOverage > 0 && stripeSubscriptionId) { - const stripeSubscription = await stripe.subscriptions.retrieve(stripeSubscriptionId) - const customerId = stripeSubscription.customer as string - const cents = Math.round(remainingOverage * 100) - const endedAt = stripeSubscription.ended_at || Math.floor(Date.now() / 1000) - const billingPeriod = new Date(endedAt * 1000).toISOString().slice(0, 7) - - const itemIdemKey = `final-overage-item:${customerId}:${stripeSubscriptionId}:${billingPeriod}` - const invoiceIdemKey = `final-overage-invoice:${customerId}:${stripeSubscriptionId}:${billingPeriod}` - const finalizeIdemKey = `final-overage-finalize:${customerId}:${stripeSubscriptionId}:${billingPeriod}` - - const overageInvoice = await stripe.invoices.create( - { - customer: customerId, - collection_method: 'charge_automatically', - auto_advance: true, - description: `Final overage charges for ${subscription.plan} subscription (${billingPeriod})`, - metadata: { - type: 'final_overage_billing', - billingPeriod, - subscriptionId: stripeSubscriptionId, - cancelledAt: stripeSubscription.canceled_at?.toString() || '', - }, - }, - { idempotencyKey: invoiceIdemKey } - ) - - await stripe.invoiceItems.create( - { - customer: customerId, - invoice: overageInvoice.id, - amount: cents, - currency: 'usd', - description: `Usage overage for ${subscription.plan} plan (Final billing period)`, - metadata: { - type: 'final_usage_overage', - usage: remainingOverage.toFixed(2), - totalOverage: totalOverage.toFixed(2), - billedOverage: billedOverage.toFixed(2), - billingPeriod, - }, - }, - { idempotencyKey: itemIdemKey } - ) - - if (overageInvoice.id) { - await stripe.invoices.finalizeInvoice( - overageInvoice.id, - {}, - { idempotencyKey: finalizeIdemKey } - ) - } - - logger.info('Created final overage invoice for cancelled subscription', { - subscriptionId: subscription.id, - stripeSubscriptionId, - invoiceId: overageInvoice.id, - totalOverage, - billedOverage, - remainingOverage, - cents, - billingPeriod, - }) - } else { - logger.info('No overage to bill for cancelled subscription', { - subscriptionId: subscription.id, - plan: subscription.plan, - }) + return { totalOverage, remainingOverage, kind: 'enterprise' as const } } await writeFinalPeriodBookkeeping({ @@ -455,7 +554,7 @@ export async function handleSubscriptionDeleted( referenceId: subscription.referenceId, billingInterval: subscription.billingInterval ?? null, ...settlementPeriod, - metadata: subscription.metadata, + metadata, }) let restoredProCount = 0 @@ -504,6 +603,7 @@ export async function handleSubscriptionDeleted( plan: subscription.plan ?? 'unknown', reference_id: subscription.referenceId, }) + await sendPlanEndedEmail(subscription) return { totalOverage, remainingOverage, restoredProCount, workspacesDetached } } diff --git a/apps/sim/lib/catalog/projection/block-detail.ts b/apps/sim/lib/catalog/projection/block-detail.ts index 92e4eb520f7..e0720362dd4 100644 --- a/apps/sim/lib/catalog/projection/block-detail.ts +++ b/apps/sim/lib/catalog/projection/block-detail.ts @@ -22,7 +22,12 @@ import { projectToolDetail, } from '@/lib/catalog/projection/tool' import { isCustomBlockType } from '@/blocks/custom/build-config' -import { type BlockConfig, isHiddenFromDisplay, type SubBlockConfig } from '@/blocks/types' +import { + type BlockConfig, + isHiddenFromDisplay, + type OutputFieldDefinition, + type SubBlockConfig, +} from '@/blocks/types' import { getTrigger, isTriggerValid } from '@/triggers' const logger = createLogger('CatalogBlockProjection') @@ -46,16 +51,17 @@ export interface CatalogInputDefinition { schema?: unknown } -/** A declared output of a block. */ -export interface CatalogBlockOutput { - type: string - description?: string -} +/** A declared output of a block, nesting the way a tool's output does. */ +export type CatalogBlockOutput = Pick< + CatalogToolOutput, + 'type' | 'description' | 'properties' | 'items' +> /** One operation a block exposes, resolved to the tool that performs it. */ export interface CatalogBlockOperation { toolId?: string toolName?: string + effect?: CatalogToolDetail['effect'] description?: string /** Tool params plus operation-scoped block inputs, minus anything the block supplies itself. */ inputs: Record @@ -328,25 +334,28 @@ export function resolveToolIdForOperation( /** Projects a block's declared outputs, dropping the ones hidden from display. */ export function projectBlockOutputs( - outputs: BlockConfig['outputs'] | undefined + outputs: Record | undefined ): Record { const projected: Record = {} for (const [key, definition] of Object.entries(outputs ?? {})) { if (isHiddenFromDisplay(definition)) continue - if (typeof definition === 'string') { - projected[key] = { type: definition } - continue - } - if (!definition || typeof definition !== 'object') continue - const entry: CatalogBlockOutput = { type: String(definition.type ?? 'any') } - if ('description' in definition && typeof definition.description === 'string') { - entry.description = definition.description - } - projected[key] = entry + projected[key] = projectBlockOutput(definition) } return projected } +function projectBlockOutput(definition: OutputFieldDefinition): CatalogBlockOutput { + if (typeof definition === 'string') return { type: definition } + const entry: CatalogBlockOutput = { type: definition.type } + if (definition.description !== undefined) entry.description = definition.description + if (definition.properties) entry.properties = projectBlockOutputs(definition.properties) + if (definition.items) { + const { items: _nested, ...element } = projectBlockOutput(definition.items) + entry.items = element + } + return entry +} + /** * Projects the triggers a block supports, with each trigger's configurable * fields. @@ -483,6 +492,8 @@ export function projectBlockDetail( id: toolId, name: toolId, description: '', + // An id with no registered tool declares no effect, which counts as a write. + effect: 'write', hostedApiKey: 'none', params: {}, outputs: {}, @@ -507,7 +518,7 @@ export function projectBlockDetail( inputs, outputs: tool?.outputs ?? {}, inputSchema: operationFields[operationId] ?? [], - ...(toolId !== undefined ? { toolId } : {}), + ...(toolId !== undefined ? { toolId, effect: tool?.effect ?? 'write' } : {}), ...(tool ? { toolName: tool.name, description: describeTool(tool) } : {}), } } diff --git a/apps/sim/lib/catalog/projection/invariants.test.ts b/apps/sim/lib/catalog/projection/invariants.test.ts index 858cf330325..cb9361868e5 100644 --- a/apps/sim/lib/catalog/projection/invariants.test.ts +++ b/apps/sim/lib/catalog/projection/invariants.test.ts @@ -159,3 +159,36 @@ describe('a field publishes the value type its block declares, never a guessed o expect(field(detail.operationInputSchema.read ?? [], 'rowLimit')?.valueType).toBe('number') }) }) + +describe('a block output publishes its nested shape', () => { + it("keeps a json output's members and an array output's element shape", () => { + const row = { id: { type: 'string' }, data: { type: 'json', description: 'Cells' } } as const + const declared = { ...row, internal: { type: 'string', hiddenFromDisplay: true } } as const + const config = block({ + type: 'rows', + outputs: { + row: { + type: 'json', + description: 'One row', + condition: { field: 'operation', value: 'get_row' }, + properties: declared, + }, + rows: { type: 'array', items: { type: 'json', properties: declared } }, + }, + }) + expect(projectBlockDetail(config, { deployment: { hostedKeys: false } }).outputs).toEqual({ + row: { + type: 'json', + description: 'One row', + properties: row, + }, + rows: { + type: 'array', + items: { + type: 'json', + properties: row, + }, + }, + }) + }) +}) diff --git a/apps/sim/lib/catalog/projection/tool.ts b/apps/sim/lib/catalog/projection/tool.ts index f12091976f7..9587cdbb101 100644 --- a/apps/sim/lib/catalog/projection/tool.ts +++ b/apps/sim/lib/catalog/projection/tool.ts @@ -3,7 +3,7 @@ import type { HostedApiKeySupport } from '@/tools/hosted-api-key' import { getToolMetadata, type ToolMetadata } from '@/tools/metadata' import { getToolOutputsMetadata } from '@/tools/metadata-outputs' import { resolveToolId } from '@/tools/tool-ids' -import type { OutputProperty, ToolConfig } from '@/tools/types' +import type { OutputProperty, ToolConfig, ToolEffect } from '@/tools/types' /** * Surface-neutral projection of a built-in tool. @@ -69,6 +69,7 @@ export interface CatalogToolSummary { name: string description: string version?: string + effect: ToolEffect hostedApiKey: HostedApiKeySupport oauth?: CatalogToolOAuth } @@ -108,6 +109,7 @@ export function projectToolSummary( id: toolId, name: metadata.name ?? toolId, description: metadata.description ?? '', + effect: metadata.effect, hostedApiKey: deployment.hostedKeys ? (metadata.hostedApiKey ?? 'none') : 'none', } if (metadata.version !== undefined) summary.version = metadata.version diff --git a/apps/sim/lib/core/config/deployment-projection.dom.test.ts b/apps/sim/lib/core/config/deployment-projection.dom.test.ts index a9cfb1af17a..ea6a61fe2f8 100644 --- a/apps/sim/lib/core/config/deployment-projection.dom.test.ts +++ b/apps/sim/lib/core/config/deployment-projection.dom.test.ts @@ -11,8 +11,11 @@ import { describe, expect, it, vi } from 'vitest' vi.hoisted(() => { vi.stubEnv('NEXT_PUBLIC_APP_URL', '') - vi.stubEnv('NEXT_PUBLIC_BILLING_ENABLED', '') vi.stubEnv('SSO_ENABLED', 'false') + vi.stubEnv('E2B_ENABLED', 'false') + vi.stubEnv('SLACK_EXTENDED_SCOPES', 'false') + vi.stubEnv('DISABLE_INVITATIONS', 'false') + vi.stubEnv('DISABLE_PUBLIC_API', 'true') vi.stubEnv('INBOX_ENABLED', 'true') vi.stubEnv('REGISTRATION_MODE', 'open') document.documentElement.setAttribute( @@ -24,6 +27,9 @@ vi.hoisted(() => { azureConfigured: false, cohereConfigured: false, registrationMode: 'closed-no-email', + e2bEnabled: true, + slackExtendedScopes: true, + invitationsDisabled: true, features: { sso: true, accessControl: true, @@ -42,13 +48,17 @@ import { getRegistrationMode, isAccessControlEnabled, isAuditLogsEnabled, + isE2bEnabled, isEmailPasswordAuthEnabled, isEmailSignupAllowed, isInboxEnabled, + isInvitationsDisabled, isOrganizationsEnabled, + isPublicApiDisabled, isSandboxesEnabled, isSelfServeRegistrationClosed, isSessionPoliciesEnabled, + isSlackExtendedScopesEnabled, isSsoEnabled, } from '@/lib/core/config/env-flags' @@ -75,3 +85,15 @@ describe('browser registration flags', () => { expect(isEmailPasswordAuthEnabled).toBe(false) }) }) + +describe('browser deployment switches', () => { + it('take the projected server answer over the browser environment', () => { + expect(isE2bEnabled).toBe(true) + expect(isSlackExtendedScopesEnabled).toBe(true) + expect(isInvitationsDisabled).toBe(true) + }) + + it('read a switch the projection omits as off', () => { + expect(isPublicApiDisabled).toBe(false) + }) +}) diff --git a/apps/sim/lib/core/config/deployment-projection.ts b/apps/sim/lib/core/config/deployment-projection.ts index 04c920e4ba1..059f541017b 100644 --- a/apps/sim/lib/core/config/deployment-projection.ts +++ b/apps/sim/lib/core/config/deployment-projection.ts @@ -68,6 +68,15 @@ export function readProjectedEnterpriseFeatures( return state } +/** + * A top-level boolean of the projected shape, or `null` when there is no projection + * or it does not carry that field as a boolean. + */ +export function readProjectedBoolean(key: string): boolean | null { + const value = readDeploymentProjection()?.[key] + return typeof value === 'boolean' ? value : null +} + /** * The projected registration mode, or `null` when there is no projection or it * does not carry a recognized mode. diff --git a/apps/sim/lib/core/config/deployment-shape.dom.test.tsx b/apps/sim/lib/core/config/deployment-shape.dom.test.tsx index 396187ab242..99e0892aedc 100644 --- a/apps/sim/lib/core/config/deployment-shape.dom.test.tsx +++ b/apps/sim/lib/core/config/deployment-shape.dom.test.tsx @@ -16,7 +16,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' vi.hoisted(() => { vi.stubEnv('NEXT_PUBLIC_APP_URL', '') - vi.stubEnv('NEXT_PUBLIC_BILLING_ENABLED', '') vi.stubEnv('NEXT_PUBLIC_FORCE_HOSTED', '') document.documentElement.id = '__next_error__' }) diff --git a/apps/sim/lib/core/config/deployment-shape.ts b/apps/sim/lib/core/config/deployment-shape.ts index 347e36d2862..213034da8bd 100644 --- a/apps/sim/lib/core/config/deployment-shape.ts +++ b/apps/sim/lib/core/config/deployment-shape.ts @@ -19,13 +19,17 @@ import { isCustomBlocksEnabled, isDataDrainsEnabled, isDataRetentionEnabled, + isE2bEnabled, isForkingEnabled, isHosted, isInboxEnabled, + isInvitationsDisabled, isOrganizationsEnabled, + isPublicApiDisabled, isSandboxesEnabled, isScimEnabled, isSessionPoliciesEnabled, + isSlackExtendedScopesEnabled, isSsoEnabled, isUsageMonitoringEnabled, } from '@/lib/core/config/env-flags' @@ -108,6 +112,10 @@ export function resolveDeploymentShape(): DeploymentShape { azureConfigured: isAzureConfigured, cohereConfigured: isCohereConfigured, registrationMode: getRegistrationMode(), + e2bEnabled: isE2bEnabled, + slackExtendedScopes: isSlackExtendedScopesEnabled, + invitationsDisabled: isInvitationsDisabled, + publicApiDisabled: isPublicApiDisabled, features: { accessControl: isAccessControlEnabled, auditLogs: isAuditLogsEnabled, @@ -135,7 +143,11 @@ function isSameDeploymentShape(seeded: DeploymentShape | null, next: DeploymentS seeded.chatEnabled !== next.chatEnabled || seeded.azureConfigured !== next.azureConfigured || seeded.cohereConfigured !== next.cohereConfigured || - seeded.registrationMode !== next.registrationMode + seeded.registrationMode !== next.registrationMode || + seeded.e2bEnabled !== next.e2bEnabled || + seeded.slackExtendedScopes !== next.slackExtendedScopes || + seeded.invitationsDisabled !== next.invitationsDisabled || + seeded.publicApiDisabled !== next.publicApiDisabled ) { return false } diff --git a/apps/sim/lib/core/config/env-flags.ts b/apps/sim/lib/core/config/env-flags.ts index 88c55e10478..af913c6d1eb 100644 --- a/apps/sim/lib/core/config/env-flags.ts +++ b/apps/sim/lib/core/config/env-flags.ts @@ -25,6 +25,7 @@ import { } from '@sim/utils/sandbox-references' import { resolveCostMultiplier } from './cost-multiplier' import { + readProjectedBoolean, readProjectedEnterpriseFeatures, readProjectedRegistrationMode, } from './deployment-projection' @@ -122,16 +123,14 @@ export const isMothershipBenchmarkEnabled = isTruthy(env.MOTHERSHIP_BENCHMARK_EN /** * Is billing enforcement enabled. * - * Server code reads `BILLING_ENABLED`. Server-only vars never reach browser - * bundles, so client evaluation reads the `NEXT_PUBLIC_BILLING_ENABLED` twin - * (via `window.__ENV`, populated by ``) — reading - * `env.BILLING_ENABLED` in client code is always `undefined`. Deployments must - * set both vars together. + * Server code reads `BILLING_ENABLED`. The browser never sees that variable and + * takes the server's answer from the deployment-shape projection on `` + * (`./deployment-projection`); a document without one reads it as off. */ export const isBillingEnabled = typeof window === 'undefined' ? isTruthy(env.BILLING_ENABLED) - : isTruthy(getEnv('NEXT_PUBLIC_BILLING_ENABLED')) + : (readProjectedBoolean('billingEnabled') ?? false) /** * Is email verification enabled @@ -297,16 +296,15 @@ export const isAppConfigEnabled = * off there until review lands; a self-hosted deployment pointing at its own * (unlisted) Slack app can opt in. * - * Server code reads `SLACK_EXTENDED_SCOPES`. Server-only vars never reach browser - * bundles, so client evaluation reads the `NEXT_PUBLIC_SLACK_EXTENDED_SCOPES` - * twin (see {@link isBillingEnabled}) — deployments must set both together. The - * server value decides the grant; the client value only decides what the credential + * Server code reads `SLACK_EXTENDED_SCOPES`; the browser reads the server's answer + * from the deployment-shape projection (see {@link isBillingEnabled}). The server + * value decides the grant; the browser value only decides what the credential * pickers advertise and treat as missing. */ export const isSlackExtendedScopesEnabled = typeof window === 'undefined' ? isTruthy(env.SLACK_EXTENDED_SCOPES) - : isTruthy(getEnv('NEXT_PUBLIC_SLACK_EXTENDED_SCOPES')) + : (readProjectedBoolean('slackExtendedScopes') ?? false) /** * Is Trigger.dev enabled for async job processing @@ -555,16 +553,33 @@ export const isAzureConfigured = isTruthy(getEnv('NEXT_PUBLIC_AZURE_CONFIGURED') export const isCohereConfigured = isTruthy(getEnv('NEXT_PUBLIC_COHERE_CONFIGURED')) /** - * Are invitations disabled globally - * When true, workspace invitations are disabled for all users + * Are workspace invitations disabled for every user (`DISABLE_INVITATIONS`). The + * browser reads the server's answer from the deployment-shape projection. */ -export const isInvitationsDisabled = isTruthy(env.DISABLE_INVITATIONS) +export const isInvitationsDisabled = + typeof window === 'undefined' + ? isTruthy(env.DISABLE_INVITATIONS) + : (readProjectedBoolean('invitationsDisabled') ?? false) + +/** + * Is public API access disabled for every workspace (`DISABLE_PUBLIC_API`): the + * public API toggle is hidden and public API access is blocked. The browser reads + * the server's answer from the deployment-shape projection. + */ +export const isPublicApiDisabled = + typeof window === 'undefined' + ? isTruthy(env.DISABLE_PUBLIC_API) + : (readProjectedBoolean('publicApiDisabled') ?? false) /** - * Is public API access disabled globally - * When true, the public API toggle is hidden and public API access is blocked + * Is the E2B code-execution provider switched on (`E2B_ENABLED`). Pi's cloud modes + * run in an E2B sandbox and stay hidden without it. The browser reads the server's + * answer from the deployment-shape projection. */ -export const isPublicApiDisabled = isTruthy(env.DISABLE_PUBLIC_API) +export const isE2bEnabled = + typeof window === 'undefined' + ? isTruthy(env.E2B_ENABLED) + : (readProjectedBoolean('e2bEnabled') ?? false) /** * Is Google OAuth login disabled diff --git a/apps/sim/lib/core/config/env.ts b/apps/sim/lib/core/config/env.ts index 61ae7cc756b..4d77ebc50d8 100644 --- a/apps/sim/lib/core/config/env.ts +++ b/apps/sim/lib/core/config/env.ts @@ -746,22 +746,15 @@ export const env = createEnv({ // Client-side Services NEXT_PUBLIC_SOCKET_URL: z.string().url().optional(), // WebSocket server URL for real-time features - // Billing - NEXT_PUBLIC_BILLING_ENABLED: z.boolean().optional(), // Enable billing enforcement and usage tracking (client-side) - // Analytics & Tracking NEXT_PUBLIC_POSTHOG_ENABLED: z.boolean().optional(), // Enable PostHog analytics (client-side) NEXT_PUBLIC_POSTHOG_KEY: z.string().optional(), // PostHog project API key - NEXT_PUBLIC_E2B_ENABLED: z.string().optional(), NEXT_PUBLIC_BEDROCK_DEFAULT_CREDENTIALS: z.string().optional(), // Hide Bedrock credential fields when deployment uses AWS default credential chain (IAM roles, instance profiles, ECS task roles, IRSA) NEXT_PUBLIC_AZURE_CONFIGURED: z.string().optional(), // Hide Azure credential fields when endpoint/key/version are pre-configured server-side NEXT_PUBLIC_COHERE_CONFIGURED: z.string().optional(), // Hide Cohere API key field on Knowledge block when COHERE_API_KEY is pre-configured server-side // Feature Flags - NEXT_PUBLIC_SLACK_EXTENDED_SCOPES: z.boolean().optional(), // Client twin of SLACK_EXTENDED_SCOPES — set both together - NEXT_PUBLIC_DISABLE_INVITATIONS: z.boolean().optional(), // Disable workspace invitations globally (for self-hosted deployments) - NEXT_PUBLIC_DISABLE_PUBLIC_API: z.boolean().optional(), // Disable public API access UI toggle globally NEXT_PUBLIC_CHAT_DISABLED: z.boolean().optional(), // Hide the Chat module (Chat is shown when unset) NEXT_PUBLIC_STATUS_NOTICE_PREVIEW: z.boolean().optional(), // Force the sidebar service-status notice into its critical preview state NEXT_PUBLIC_TURNSTILE_SITE_KEY: z.string().min(1).optional(), // Cloudflare Turnstile site key for captcha widget @@ -775,15 +768,10 @@ export const env = createEnv({ experimental__runtimeEnv: { NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL, - NEXT_PUBLIC_BILLING_ENABLED: process.env.NEXT_PUBLIC_BILLING_ENABLED, NEXT_PUBLIC_SOCKET_URL: process.env.NEXT_PUBLIC_SOCKET_URL, - NEXT_PUBLIC_SLACK_EXTENDED_SCOPES: process.env.NEXT_PUBLIC_SLACK_EXTENDED_SCOPES, - NEXT_PUBLIC_DISABLE_INVITATIONS: process.env.NEXT_PUBLIC_DISABLE_INVITATIONS, - NEXT_PUBLIC_DISABLE_PUBLIC_API: process.env.NEXT_PUBLIC_DISABLE_PUBLIC_API, NEXT_PUBLIC_CHAT_DISABLED: process.env.NEXT_PUBLIC_CHAT_DISABLED, NEXT_PUBLIC_STATUS_NOTICE_PREVIEW: process.env.NEXT_PUBLIC_STATUS_NOTICE_PREVIEW, NEXT_PUBLIC_TURNSTILE_SITE_KEY: process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY, - NEXT_PUBLIC_E2B_ENABLED: process.env.NEXT_PUBLIC_E2B_ENABLED, NEXT_PUBLIC_BEDROCK_DEFAULT_CREDENTIALS: process.env.NEXT_PUBLIC_BEDROCK_DEFAULT_CREDENTIALS, NEXT_PUBLIC_AZURE_CONFIGURED: process.env.NEXT_PUBLIC_AZURE_CONFIGURED, NEXT_PUBLIC_COHERE_CONFIGURED: process.env.NEXT_PUBLIC_COHERE_CONFIGURED, diff --git a/apps/sim/lib/core/config/redis.test.ts b/apps/sim/lib/core/config/redis.test.ts index 2692a262fc0..3b745d83123 100644 --- a/apps/sim/lib/core/config/redis.test.ts +++ b/apps/sim/lib/core/config/redis.test.ts @@ -320,7 +320,7 @@ describe('redis config', () => { mockRedisInstance.set.mockRejectedValueOnce(new Error('Command timed out')) // Mutates the constructed client, not the shared instance it was copied from. mockRedisInstance.eval.mockImplementationOnce(async () => { - Object.assign(getRedisClient() ?? {}, { status: 'ready' }) + Object.assign(getRedisClient(), { status: 'ready' }) return 1 }) diff --git a/apps/sim/lib/core/network/gateway-runtime.integration.ts b/apps/sim/lib/core/network/gateway-runtime.integration.ts new file mode 100644 index 00000000000..deeb51e3268 --- /dev/null +++ b/apps/sim/lib/core/network/gateway-runtime.integration.ts @@ -0,0 +1,64 @@ +/** + * Proves organization gateway routing under the real Bun runtime, which the Node-hosted unit suite + * cannot: undici and the pinned fetch ride Bun's own `node:net`/`node:tls` shims there. The probe is + * a separate Bun process, so most of its cost is starting Bun and loading the gateway's module graph. + * That cost runs from about 0.1s idle to several seconds on a saturated unit shard, which is why the + * probe lives in this one-file-at-a-time tier rather than inside a unit test's 10s budget. + */ +import { execFile } from 'node:child_process' +import { fileURLToPath } from 'node:url' +import { promisify } from 'node:util' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { + type GatewayTlsFixture, + startGatewayTlsFixture, +} from '@/lib/core/network/gateway-tls.test-helpers' + +const GATEWAY_TOKEN = 'a'.repeat(48) +let fixture: GatewayTlsFixture +beforeAll(async () => { + fixture = await startGatewayTlsFixture([GATEWAY_TOKEN]) +}) +afterAll(() => fixture.close()) + +describe('organization gateways under the Bun runtime', () => { + it('routes and verifies TLS under the actual Bun runtime', async () => { + await promisify(execFile)( + 'bun', + [ + '--no-env-file', + 'run', + fileURLToPath(new URL('./fixtures/gateway-runtime.fixture.ts', import.meta.url)), + String(fixture.proxyPort), + fixture.certificatePath, + ], + { + timeout: 25_000, + env: { + ...process.env, + NODE_EXTRA_CA_CERTS: fixture.certificatePath, + OUTBOUND_ROUTING_SOURCE: 'env', + OUTBOUND_ROUTING_CONFIG: JSON.stringify({ + schemaVersion: 1, + revision: 'test', + organizations: { org_test: { kind: 'gateway', gatewayId: 'synthetic' } }, + }), + OUTBOUND_GATEWAYS: JSON.stringify({ + synthetic: { + organizationId: 'org_test', + url: `https://127.0.0.1:${fixture.proxyPort}`, + servername: 'gateway.invalid', + credentialId: 'synthetic', + }, + }), + OUTBOUND_GATEWAY_CREDENTIALS: JSON.stringify({ + synthetic: { token: GATEWAY_TOKEN, ca: fixture.cert }, + }), + }, + } + ) + expect(fixture.admissions.map((admission) => admission.token)).toEqual( + Array(4).fill(`Bearer ${GATEWAY_TOKEN}`) + ) + }) +}) diff --git a/apps/sim/lib/core/network/gateway-tls.test-helpers.ts b/apps/sim/lib/core/network/gateway-tls.test-helpers.ts new file mode 100644 index 00000000000..906c115f03e --- /dev/null +++ b/apps/sim/lib/core/network/gateway-tls.test-helpers.ts @@ -0,0 +1,151 @@ +/** + * A real TLS CONNECT gateway and the HTTPS origin behind it, on loopback, for the gateway suites. + * One self-signed certificate covers `gateway.invalid` (the proxy), `origin.invalid` and `1.1.1.1` + * (the origin); the proxy admits only `1.1.1.1:443` and only the bearer tokens it was started with. + */ +import { execFile } from 'node:child_process' +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { createServer as httpsServer } from 'node:https' +import { type AddressInfo, connect, type Socket } from 'node:net' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { Duplex } from 'node:stream' +import { promisify } from 'node:util' + +interface GatewayAdmission { + token: string | undefined + destination: string | undefined + sni: string | undefined +} + +export interface GatewayTlsFixture { + cert: string + certificatePath: string + proxyPort: number + /** Every CONNECT the proxy received, admitted or not. */ + admissions: GatewayAdmission[] + /** Each queued entry makes one CONNECT fail: `reset` drops the connection, a number answers with that status. */ + connectFailures: Array<'reset' | number> + /** What the origin last received, and how many requests reached it. */ + origin: { requests: number; headers: Record; target: string } + close: () => Promise +} + +/** + * The origin answers `x-via-proxy: yes` only for a connection the proxy opened, echoes the request + * target in `x-request-target`, echoes POST and PUT bodies, redirects `/redirect`, and never answers + * `/wait`. + */ +export async function startGatewayTlsFixture( + acceptedTokens: readonly string[] +): Promise { + const certificateDirectory = mkdtempSync(join(tmpdir(), 'gateway-tls-')) + const certificatePath = join(certificateDirectory, 'cert.pem') + const keyPath = join(certificateDirectory, 'key.pem') + await promisify(execFile)('openssl', [ + 'req', + '-x509', + '-newkey', + 'rsa:2048', + '-sha256', + '-nodes', + '-keyout', + keyPath, + '-out', + certificatePath, + '-days', + '2', + '-subj', + '/CN=gateway.invalid', + '-addext', + 'subjectAltName=DNS:gateway.invalid,DNS:origin.invalid,IP:1.1.1.1', + '-addext', + 'extendedKeyUsage=serverAuth', + ]) + const cert = readFileSync(certificatePath, 'utf8') + const key = readFileSync(keyPath, 'utf8') + const admittedAuthorizations = new Set(acceptedTokens.map((token) => `Bearer ${token}`)) + const sockets = new Set() + const proxiedPorts = new Set() + const admissions: GatewayAdmission[] = [] + const connectFailures: Array<'reset' | number> = [] + const origin: GatewayTlsFixture['origin'] = { requests: 0, headers: {}, target: '' } + + const secureOrigin = httpsServer({ cert, key }, async (req, res) => { + res.setHeader('x-via-proxy', proxiedPorts.has(req.socket.remotePort ?? 0) ? 'yes' : 'no') + origin.requests++ + origin.headers = req.headers + origin.target = req.url ?? '' + res.setHeader('x-request-target', origin.target) + if (req.url === '/redirect') { + res.writeHead(302, { location: '/done' }) + res.end() + return + } + if (req.url === '/wait') return + const chunks: Buffer[] = [] + for await (const chunk of req) chunks.push(Buffer.from(chunk)) + res.end(req.method === 'POST' || req.method === 'PUT' ? Buffer.concat(chunks) : 'tls reached') + }) + const proxy = httpsServer({ cert, key }) + proxy.on('connect', (req, socket, head) => { + socket.on('error', () => {}) + const tlsSocket = req.socket as Socket & { servername?: string } + const authorization = req.headers['proxy-authorization'] + admissions.push({ token: authorization, destination: req.url, sni: tlsSocket.servername }) + const failure = connectFailures.shift() + if (failure === 'reset') { + socket.destroy() + return + } + if (failure !== undefined) { + socket.end(`HTTP/1.1 ${failure} Gateway Failure\r\nContent-Length: 0\r\n\r\n`) + return + } + if (!authorization || !admittedAuthorizations.has(authorization)) { + socket.end('HTTP/1.1 407 Proxy Authentication Required\r\nContent-Length: 0\r\n\r\n') + return + } + if (req.url !== '1.1.1.1:443') { + socket.end('HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n') + return + } + const upstream = connect((secureOrigin.address() as AddressInfo).port, '127.0.0.1', () => { + if (upstream.localPort) proxiedPorts.add(upstream.localPort) + socket.write('HTTP/1.1 200 Connection Established\r\n\r\n') + if (head.length) upstream.write(head) + socket.pipe(upstream).pipe(socket) + }) + upstream.on('error', () => socket.destroy()) + socket.on('error', () => upstream.destroy()) + socket.on('close', () => upstream.destroy()) + sockets.add(upstream) + upstream.on('close', () => sockets.delete(upstream)) + }) + + for (const server of [secureOrigin, proxy]) { + server.on('connection', (socket) => { + sockets.add(socket) + socket.on('close', () => sockets.delete(socket)) + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + } + + return { + cert, + certificatePath, + proxyPort: (proxy.address() as AddressInfo).port, + admissions, + connectFailures, + origin, + async close() { + for (const socket of sockets) socket.destroy() + await Promise.all( + [secureOrigin, proxy].map( + (server) => new Promise((resolve) => server.close(() => resolve())) + ) + ) + rmSync(certificateDirectory, { recursive: true, force: true }) + }, + } +} diff --git a/apps/sim/lib/core/network/gateway.server.test.ts b/apps/sim/lib/core/network/gateway.server.test.ts index 725919ddbeb..402d7060bfa 100644 --- a/apps/sim/lib/core/network/gateway.server.test.ts +++ b/apps/sim/lib/core/network/gateway.server.test.ts @@ -1,12 +1,5 @@ -import { execFile } from 'node:child_process' -import { mkdtempSync, readFileSync, rmSync } from 'node:fs' -import { createServer as httpsServer } from 'node:https' -import { type AddressInfo, connect, type Socket } from 'node:net' -import { tmpdir } from 'node:os' -import { join } from 'node:path' +import type { Socket } from 'node:net' import { getCACertificates, setDefaultCACertificates } from 'node:tls' -import { fileURLToPath } from 'node:url' -import { promisify } from 'node:util' import { GetCallerIdentityCommand, STSClient } from '@aws-sdk/client-sts' import { resolveHostAddresses } from '@sim/security/dns' import { networkConfigMock, networkConfigMockFns } from '@sim/testing/mocks/network-config.mock' @@ -22,6 +15,10 @@ vi.mock('@sim/security/dns', async (importOriginal) => ({ import { runWithOutboundOrganization } from '@/lib/core/network/context.server' import { openGatewayTunnel, secureOutboundTunnel } from '@/lib/core/network/gateway.server' +import { + type GatewayTlsFixture, + startGatewayTlsFixture, +} from '@/lib/core/network/gateway-tls.test-helpers' import { organizationAwsRequestHandler } from '@/lib/core/network/organization-aws-handler.server' import { outboundFetch } from '@/lib/core/network/outbound-fetch.server' import { isUnavailableFailure } from '@/lib/core/orchestration/types' @@ -42,112 +39,11 @@ networkConfigMockFns.mockResolveOutboundRoute.mockImplementation( } ) -const certificateDirectory = mkdtempSync(join(tmpdir(), 'gateway-tls-')) -const certificatePath = join(certificateDirectory, 'cert.pem') -const keyPath = join(certificateDirectory, 'key.pem') -let cert = '' -const sockets = new Set() -const admissions: Array<{ - token: string | undefined - destination: string | undefined - sni: string | undefined -}> = [] -let originRequests = 0 -let receivedHeaders: Record = {} -let receivedTarget = '' -const proxiedPorts = new Set() -/** Each queued entry makes one CONNECT fail: `reset` drops the connection, a number answers with that status. */ -const connectFailures: Array<'reset' | number> = [] -const secureOrigin = httpsServer(async (req, res) => { - res.setHeader('x-via-proxy', proxiedPorts.has(req.socket.remotePort ?? 0) ? 'yes' : 'no') - originRequests++ - receivedHeaders = req.headers - receivedTarget = req.url ?? '' - res.setHeader('x-request-target', receivedTarget) - if (req.url === '/redirect') { - res.writeHead(302, { location: '/done' }) - res.end() - return - } - if (req.url === '/wait') return - const chunks: Buffer[] = [] - for await (const chunk of req) chunks.push(Buffer.from(chunk)) - res.end(req.method === 'POST' || req.method === 'PUT' ? Buffer.concat(chunks) : 'tls reached') -}) -const proxy = httpsServer() -proxy.on('connect', (req, socket, head) => { - socket.on('error', () => {}) - const tlsSocket = req.socket as Socket & { servername?: string } - admissions.push({ - token: req.headers['proxy-authorization'], - destination: req.url, - sni: tlsSocket.servername, - }) - const failure = connectFailures.shift() - if (failure === 'reset') { - socket.destroy() - return - } - if (failure !== undefined) { - socket.end(`HTTP/1.1 ${failure} Gateway Failure\r\nContent-Length: 0\r\n\r\n`) - return - } - if (!req.headers['proxy-authorization']?.match(/^Bearer (alpha|bravo|a{48})$/)) { - socket.end('HTTP/1.1 407 Proxy Authentication Required\r\nContent-Length: 0\r\n\r\n') - return - } - if (req.url !== '1.1.1.1:443') { - socket.end('HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n') - return - } - const upstream = connect(securePort, '127.0.0.1', () => { - if (upstream.localPort) proxiedPorts.add(upstream.localPort) - socket.write('HTTP/1.1 200 Connection Established\r\n\r\n') - if (head.length) upstream.write(head) - socket.pipe(upstream).pipe(socket) - }) - upstream.on('error', () => socket.destroy()) - socket.on('error', () => upstream.destroy()) - socket.on('close', () => upstream.destroy()) - sockets.add(upstream) - upstream.on('close', () => sockets.delete(upstream)) -}) -let securePort = 0 +let fixture: GatewayTlsFixture const trust = getCACertificates('default') beforeAll(async () => { - await promisify(execFile)('openssl', [ - 'req', - '-x509', - '-newkey', - 'rsa:2048', - '-sha256', - '-nodes', - '-keyout', - keyPath, - '-out', - certificatePath, - '-days', - '2', - '-subj', - '/CN=gateway.invalid', - '-addext', - 'subjectAltName=DNS:gateway.invalid,DNS:origin.invalid,IP:1.1.1.1', - '-addext', - 'extendedKeyUsage=serverAuth', - ]) - cert = readFileSync(certificatePath, 'utf8') - const key = readFileSync(keyPath, 'utf8') - for (const server of [secureOrigin, proxy]) server.setSecureContext({ cert, key }) - setDefaultCACertificates([...trust, cert]) - for (const server of [secureOrigin, proxy]) { - server.on('connection', (socket) => { - sockets.add(socket) - socket.on('close', () => sockets.delete(socket)) - }) - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - } - securePort = (secureOrigin.address() as AddressInfo).port - const proxyPort = (proxy.address() as AddressInfo).port + fixture = await startGatewayTlsFixture(['alpha', 'bravo']) + setDefaultCACertificates([...trust, fixture.cert]) for (const [id, token] of [ ['org_a', 'alpha'], ['org_b', 'bravo'], @@ -156,20 +52,14 @@ beforeAll(async () => { id, organizationId: id, token, - url: `https://127.0.0.1:${proxyPort}`, + url: `https://127.0.0.1:${fixture.proxyPort}`, servername: 'gateway.invalid', - ca: cert, + ca: fixture.cert, }) }) afterAll(async () => { - for (const socket of sockets) socket.destroy() - await Promise.all( - [secureOrigin, proxy].map( - (server) => new Promise((resolve) => server.close(() => resolve())) - ) - ) + await fixture.close() setDefaultCACertificates(trust) - rmSync(certificateDirectory, { recursive: true, force: true }) }) const url = () => 'https://origin.invalid' const gatewayFor = (organizationId: string): OutboundGateway => { @@ -196,10 +86,10 @@ describe('organization gateways over real TLS CONNECT sockets', () => { ) expect(await response.text()).toBe('{"id":"event"}\n') expect(response.headers.get('x-via-proxy')).toBe('yes') - expect(receivedTarget).toBe(target) - expect(receivedHeaders.authorization).toBe('AWS4-HMAC-SHA256 signed-request') - expect(receivedHeaders['proxy-authorization']).toBeUndefined() - expect(admissions.at(-1)?.destination).toBe('1.1.1.1:443') + expect(fixture.origin.target).toBe(target) + expect(fixture.origin.headers.authorization).toBe('AWS4-HMAC-SHA256 signed-request') + expect(fixture.origin.headers['proxy-authorization']).toBeUndefined() + expect(fixture.admissions.at(-1)?.destination).toBe('1.1.1.1:443') }) it('keeps an upgraded tunnel usable after five minutes', async () => { @@ -231,17 +121,17 @@ describe('organization gateways over real TLS CONNECT sockets', () => { }) ) expect(await response.text()).toBe('tls reached') - expect(admissions.at(-1)).toEqual({ + expect(fixture.admissions.at(-1)).toEqual({ token: 'Bearer alpha', destination: '1.1.1.1:443', sni: 'gateway.invalid', }) - expect(receivedHeaders['proxy-authorization']).toBeUndefined() - expect(receivedHeaders.host).toBe('origin.invalid') + expect(fixture.origin.headers['proxy-authorization']).toBeUndefined() + expect(fixture.origin.headers.host).toBe('origin.invalid') }) it('isolates concurrent requests to the same origin and rotates pools when its gateway assignment changes', async () => { const transport = createPinnedFetchWithDispatcher('1.1.1.1', options) - const start = admissions.length + const start = fixture.admissions.length try { expect( await Promise.all( @@ -251,14 +141,14 @@ describe('organization gateways over real TLS CONNECT sockets', () => { ) ).toEqual(['tls reached', 'tls reached']) expect( - admissions + fixture.admissions .slice(start) .map((item) => item.token) .sort() ).toEqual(['Bearer alpha', 'Bearer bravo']) state.gateways.set('org_a', { ...state.gateways.get('org_a')!, id: 'gateway-next' }) await runWithOutboundOrganization('org_a', async () => (await transport.fetch(url())).text()) - expect(admissions.length).toBe(start + 3) + expect(fixture.admissions.length).toBe(start + 3) } finally { await transport.dispatcher.destroy() } @@ -311,16 +201,16 @@ describe('organization gateways over real TLS CONNECT sockets', () => { vi.mocked(resolveHostAddresses).mockRejectedValueOnce( Object.assign(new Error('getaddrinfo ENOTFOUND missing.invalid'), { code: 'ENOTFOUND' }) ) - const start = admissions.length + const start = fixture.admissions.length const failure = await runWithOutboundOrganization('org_a', () => outboundFetch('https://missing.invalid', { redirect: 'error' }) ).catch((error: unknown) => error) expect(isHostNotFound(failure)).toBe(true) expect(isUnavailableFailure(failure)).toBe(false) - expect(admissions.length).toBe(start) + expect(fixture.admissions.length).toBe(start) }) it("sends outboundFetch through the scoped organization's gateway", async () => { - const start = admissions.length + const start = fixture.admissions.length await runWithOutboundOrganization('org_b', async () => { const response = await outboundFetch(url(), { method: 'POST', @@ -330,7 +220,7 @@ describe('organization gateways over real TLS CONNECT sockets', () => { expect(response.headers.get('x-via-proxy')).toBe('yes') await response.body?.cancel() }) - expect(admissions.slice(start)).toEqual([ + expect(fixture.admissions.slice(start)).toEqual([ { token: 'Bearer bravo', destination: '1.1.1.1:443', sni: 'gateway.invalid' }, ]) }) @@ -356,12 +246,12 @@ describe('organization gateways over real TLS CONNECT sockets', () => { } it('tunnels each organization with its own credential and never shares its pooled socket', async () => { - const start = admissions.length + const start = fixture.admissions.length expect(await viaProxy('org_a')).toBe('yes') expect(await viaProxy('org_b')).toBe('yes') expect(await viaProxy('org_a')).toBe('yes') expect(await viaProxy('org_b')).toBe('yes') - expect(admissions.slice(start)).toEqual([ + expect(fixture.admissions.slice(start)).toEqual([ { token: 'Bearer alpha', destination: '1.1.1.1:443', sni: 'gateway.invalid' }, { token: 'Bearer bravo', destination: '1.1.1.1:443', sni: 'gateway.invalid' }, ]) @@ -375,62 +265,17 @@ describe('organization gateways over real TLS CONNECT sockets', () => { token: 'denied', }) const transport = createPinnedFetchWithDispatcher('1.1.1.1', options) - const start = originRequests + const start = fixture.origin.requests try { await runWithOutboundOrganization('denied', async () => { await expect(transport.fetch(url())).rejects.toThrow() await expect(secureFetchWithPinnedIP(url(), '1.1.1.1', options)).rejects.toThrow() }) - expect(originRequests).toBe(start) + expect(fixture.origin.requests).toBe(start) } finally { await transport.dispatcher.destroy() } }) - it('routes and verifies TLS under the actual Bun runtime', async () => { - const start = admissions.length - await promisify(execFile)( - 'bun', - [ - '--no-env-file', - 'run', - fileURLToPath(new URL('./fixtures/gateway-runtime.fixture.ts', import.meta.url)), - String((proxy.address() as AddressInfo).port), - certificatePath, - ], - { - timeout: 15_000, - env: { - ...process.env, - /** This local tunnel fixture must not inherit hosted-mode loopback restrictions. */ - NEXT_PUBLIC_APP_URL: 'http://localhost:3000', - NEXT_PUBLIC_FORCE_HOSTED: 'false', - NODE_EXTRA_CA_CERTS: certificatePath, - OUTBOUND_ROUTING_SOURCE: 'env', - OUTBOUND_ROUTING_CONFIG: JSON.stringify({ - schemaVersion: 1, - revision: 'test', - organizations: { org_test: { kind: 'gateway', gatewayId: 'synthetic' } }, - }), - OUTBOUND_GATEWAYS: JSON.stringify({ - synthetic: { - organizationId: 'org_test', - url: `https://127.0.0.1:${(proxy.address() as AddressInfo).port}`, - servername: 'gateway.invalid', - credentialId: 'synthetic', - }, - }), - OUTBOUND_GATEWAY_CREDENTIALS: JSON.stringify({ - synthetic: { token: 'a'.repeat(48), ca: cert }, - }), - }, - } - ) - expect(admissions.length).toBe(start + 4) - expect( - admissions.slice(start).every((entry) => entry.token === `Bearer ${'a'.repeat(48)}`) - ).toBe(true) - }) - it('supports cancellation without a direct retry', async () => { const transport = createPinnedFetchWithDispatcher('1.1.1.1', options) const controller = new AbortController() @@ -448,38 +293,38 @@ describe('organization gateways over real TLS CONNECT sockets', () => { it.each(['reset', 503] as const)( 'retries a CONNECT that fails with %s before the tunnel opens and completes the request', async (failure) => { - connectFailures.push(failure) - const start = admissions.length + fixture.connectFailures.push(failure) + const start = fixture.admissions.length try { const response = await runWithOutboundOrganization('org_a', () => secureFetchWithPinnedIP(url(), '1.1.1.1', options) ) expect(await response.text()).toBe('tls reached') - expect(admissions.length).toBe(start + 2) + expect(fixture.admissions.length).toBe(start + 2) } finally { - connectFailures.length = 0 + fixture.connectFailures.length = 0 } } ) it('does not retry a rejected proxy credential', async () => { - const start = admissions.length + const start = fixture.admissions.length await expect( openGatewayTunnel({ ...gatewayFor('org_a'), token: 'denied' }, '1.1.1.1', 443) ).rejects.toMatchObject({ code: 'GATEWAY_UNAVAILABLE' }) - expect(admissions.length).toBe(start + 1) + expect(fixture.admissions.length).toBe(start + 1) }) it('gives up after two failed CONNECT attempts', async () => { - connectFailures.push('reset', 503) - const start = admissions.length + fixture.connectFailures.push('reset', 503) + const start = fixture.admissions.length try { await expect(openGatewayTunnel(gatewayFor('org_a'), '1.1.1.1', 443)).rejects.toMatchObject({ code: 'GATEWAY_UNAVAILABLE', }) - expect(admissions.length).toBe(start + 2) + expect(fixture.admissions.length).toBe(start + 2) } finally { - connectFailures.length = 0 + fixture.connectFailures.length = 0 } }) }) diff --git a/apps/sim/lib/core/rate-limiter/provider-admission.ts b/apps/sim/lib/core/rate-limiter/provider-admission.ts index 495afceb274..9360c8fcdaf 100644 --- a/apps/sim/lib/core/rate-limiter/provider-admission.ts +++ b/apps/sim/lib/core/rate-limiter/provider-admission.ts @@ -41,6 +41,7 @@ const HOSTED_RERANK_REQUEST_BURST = 16 const DEFAULT_REQUEST_BURST = 2 function hostedRerankRequestsPerMinute(): number { + // env-number-normalized: parsed with Number() below, and an invalid value throws rather than falling back const configured = env.KB_CONFIG_HOSTED_RERANK_REQUESTS_PER_MINUTE ?? env.KB_CONFIG_RERANK_REQUESTS_PER_MINUTE if (configured === undefined) return 600 @@ -65,8 +66,8 @@ export class ProviderAdmissionTimeoutError extends Error { /** * Shared per-credential admission for indexing workers and interactive callers. * These are deployment operating budgets, not claims about provider quotas. - * Redis and PostgreSQL use the same durable token buckets; storage errors fail - * before the provider request. Capacity is spent only when every dimension and + * The token buckets live in Redis; storage errors fail before the provider + * request. Capacity is spent only when every dimension and * the shared provider cooldown permit the request in one atomic operation. */ export async function waitForProviderAdmission(input: ProviderAdmissionInput): Promise { diff --git a/apps/sim/lib/core/utils/urls.test.ts b/apps/sim/lib/core/utils/urls.test.ts index b145091223e..455fc635d67 100644 --- a/apps/sim/lib/core/utils/urls.test.ts +++ b/apps/sim/lib/core/utils/urls.test.ts @@ -1,7 +1,9 @@ /** * @vitest-environment jsdom */ + import { envMockFns, setEnv } from '@sim/testing/mocks/env.mock' +import { envFlagsMockFns, resetEnvFlagsMock, setEnvFlags } from '@sim/testing/mocks/env-flags.mock' import { beforeEach, describe, expect, it, vi } from 'vitest' vi.unmock('@/lib/core/utils/urls') @@ -11,6 +13,7 @@ import { getSocketUrl, isLocalhostUrl, isNonCanonicalSimHost, + isOllamaAvailable, isSafeHttpUrl, parseOriginList, } from '@/lib/core/utils/urls' @@ -230,3 +233,26 @@ describe('isNonCanonicalSimHost', () => { expect(isNonCanonicalSimHost('')).toBe(false) }) }) + +describe('isOllamaAvailable', () => { + beforeEach(() => { + resetEnvFlagsMock() + setEnv({ OLLAMA_URL: undefined }) + }) + + it('reaches the loopback default on a self-hosted deployment', () => { + expect(isOllamaAvailable()).toBe(true) + }) + + it('needs OLLAMA_URL on the hosted platform', () => { + setEnvFlags({ isHosted: true }) + expect(isOllamaAvailable()).toBe(false) + setEnv({ OLLAMA_URL: 'http://ollama.internal:11434' }) + expect(isOllamaAvailable()).toBe(true) + }) + + it('is never available when the provider is blacklisted', () => { + envFlagsMockFns.getBlacklistedProvidersFromEnv.mockReturnValue(['ollama']) + expect(isOllamaAvailable()).toBe(false) + }) +}) diff --git a/apps/sim/lib/core/utils/urls.ts b/apps/sim/lib/core/utils/urls.ts index 7283966aa82..144bd84faa1 100644 --- a/apps/sim/lib/core/utils/urls.ts +++ b/apps/sim/lib/core/utils/urls.ts @@ -1,7 +1,7 @@ import { isLoopbackHostname } from '@sim/security/hostnames' import { SIM_SITE_URL } from '@sim/utils/site' import { env, getEnv } from '@/lib/core/config/env' -import { isProd } from '@/lib/core/config/env-flags' +import { getBlacklistedProvidersFromEnv, isHosted, isProd } from '@/lib/core/config/env-flags' /** Canonical base URL for the public-facing marketing site. No trailing slash. */ export const SITE_URL = SIM_SITE_URL @@ -299,6 +299,24 @@ export function getOllamaUrl(): string { * back to the loopback default. Callers use this to tell "someone pointed us at * an Ollama" apart from "nobody configured one". */ -export function isOllamaUrlConfigured(): boolean { +function isOllamaUrlConfigured(): boolean { return Boolean(env.OLLAMA_URL) } + +/** + * Whether this deployment has an Ollama server to talk to. Self-hosted deployments run + * alongside their own Ollama, so the loopback default {@link getOllamaUrl} falls back to is a + * working configuration that needs no env var. Hosted Sim runs none, so there the address + * must be stated or there is nothing to reach. + * + * The chat and embedding model lists, the embedding client and the access-request catalog + * all answer through this, so a picker never lists models its client then refuses. + */ +export function isOllamaReachable(): boolean { + return !isHosted || isOllamaUrlConfigured() +} + +/** Whether Ollama can serve a model here: {@link isOllamaReachable}, and not blacklisted. */ +export function isOllamaAvailable(): boolean { + return !getBlacklistedProvidersFromEnv().includes('ollama') && isOllamaReachable() +} diff --git a/apps/sim/lib/desktop/application/executor.integration.ts b/apps/sim/lib/desktop/application/executor.integration.ts index ee051214449..d9f466dbfb8 100644 --- a/apps/sim/lib/desktop/application/executor.integration.ts +++ b/apps/sim/lib/desktop/application/executor.integration.ts @@ -928,12 +928,12 @@ describe('desktop background executor protocol', () => { const desktop = await signedInDesktop() const presenceKey = `desktop:presence:${desktop.deviceId}` const redis = getRedisClient() - await redis?.del(presenceKey) + await redis.del(presenceKey) expect(await isDesktopPresent(desktop.deviceId)).toBe(false) await inbox(desktop) expect(await isDesktopPresent(desktop.deviceId)).toBe(true) - await redis?.del(presenceKey) + await redis.del(presenceKey) const stream = await openDesktopInboxStream.execute({ principal: desktop.principal, input: { deviceId: desktop.deviceId }, @@ -942,7 +942,7 @@ describe('desktop background executor protocol', () => { /** A deploy or rotation closes the stream on the server; only the TTL ends presence. */ stream.subscribe(() => {})() expect(await isDesktopPresent(desktop.deviceId)).toBe(true) - expect(await redis?.ttl(presenceKey)).toBeLessThanOrEqual(45) + expect(await redis.ttl(presenceKey)).toBeLessThanOrEqual(45) }) it('rings only the device whose inbox changed', async () => { diff --git a/apps/sim/lib/embeddings/client.ts b/apps/sim/lib/embeddings/client.ts index 5da2987e9d0..acdcaaef2c5 100644 --- a/apps/sim/lib/embeddings/client.ts +++ b/apps/sim/lib/embeddings/client.ts @@ -25,7 +25,7 @@ import { readResponseJsonWithLimit, readResponseTextWithLimit, } from '@/lib/core/utils/stream-limits' -import { getOllamaUrl } from '@/lib/core/utils/urls' +import { getOllamaUrl, isOllamaReachable } from '@/lib/core/utils/urls' import { EmbeddingAPIError } from '@/lib/embeddings/api-error' import { DEFAULT_EMBEDDING_MODEL, @@ -38,7 +38,6 @@ import { import { EmbeddingConfigurationError } from '@/lib/embeddings/configuration-error' import { getEmbeddingResponseDiagnostic } from '@/lib/embeddings/error-diagnostics' import { resolveProviderKey } from '@/lib/embeddings/keys' -import { isOllamaServerConfigured } from '@/lib/embeddings/ollama-model-catalog.server' import { DEFAULT_OPENROUTER_EMBEDDING_MODEL } from '@/lib/embeddings/openrouter-models' import { getAdapterFactory } from '@/lib/embeddings/providers' import { @@ -406,7 +405,7 @@ async function resolveProvider( * would have made this stricter than the selector that offers the models. */ if (info.provider === 'ollama') { - if (!isOllamaServerConfigured()) { + if (!isOllamaReachable()) { throw new EmbeddingConfigurationError() } const baseUrl = getOllamaUrl().replace(/\/+$/, '') diff --git a/apps/sim/lib/embeddings/ollama-model-catalog.server.ts b/apps/sim/lib/embeddings/ollama-model-catalog.server.ts index 464b9451f5b..b2598340f02 100644 --- a/apps/sim/lib/embeddings/ollama-model-catalog.server.ts +++ b/apps/sim/lib/embeddings/ollama-model-catalog.server.ts @@ -5,9 +5,8 @@ import { ollamaShowUpstreamResponseSchema, ollamaUpstreamResponseSchema, } from '@/lib/api/contracts/providers' -import { isHosted } from '@/lib/core/config/env-flags' import { readResponseJsonWithLimit } from '@/lib/core/utils/stream-limits' -import { getOllamaUrl, isOllamaUrlConfigured } from '@/lib/core/utils/urls' +import { getOllamaUrl, isOllamaReachable } from '@/lib/core/utils/urls' import { isOllamaEmbeddingModel, ollamaEmbeddingModelName } from '@/lib/embeddings/catalog' const logger = createLogger('OllamaEmbeddingCatalog') @@ -27,22 +26,6 @@ export interface OllamaEmbeddingModel { dimensions?: number } -/** - * Whether this deployment has an Ollama server to talk to. - * - * Self-hosted deployments run alongside their own Ollama, so the loopback - * default `getOllamaUrl` falls back to is a working configuration that needs no - * env var — the same rule the chat provider's model route applies. Hosted Sim - * runs none, so there the address must be stated or there is nothing to reach. - * - * Exported because the selector, this module's width lookup, and the embedding - * client all have to answer it identically: a selector that lists models the - * client then refuses to embed with is worse than either behaviour alone. - */ -export function isOllamaServerConfigured(): boolean { - return !isHosted || isOllamaUrlConfigured() -} - export class OllamaEmbeddingModelNotFoundError extends Error { constructor(model: string) { super( @@ -127,7 +110,7 @@ async function loadOllamaEmbeddingModelCatalog( signal?: AbortSignal ): Promise<{ models: OllamaEmbeddingModel[]; unreachable?: string }> { /** Nothing to dial: an unconfigured hosted deployment has no server to reach. */ - if (!isOllamaServerConfigured()) return { models: [] } + if (!isOllamaReachable()) return { models: [] } let names: string[] try { @@ -191,7 +174,7 @@ export async function getOllamaEmbeddingModelMetadata( const name = isOllamaEmbeddingModel(model) ? ollamaEmbeddingModelName(model) : model if (!name) throw new OllamaEmbeddingModelNotFoundError(model) /** The same rule the selector and the embedding client apply. */ - if (!isOllamaServerConfigured()) { + if (!isOllamaReachable()) { throw new OllamaUnreachableError('OLLAMA_URL is not configured') } diff --git a/apps/sim/lib/function-execution/execute-request.test.ts b/apps/sim/lib/function-execution/execute-request.test.ts index 50b80cae62f..d240adfc061 100644 --- a/apps/sim/lib/function-execution/execute-request.test.ts +++ b/apps/sim/lib/function-execution/execute-request.test.ts @@ -3768,6 +3768,214 @@ describe('Function execution request', () => { expect(data.error).toContain('Line 1: `retur `') expect(data.error).not.toContain('globalThis') expect(data.debug.lineContent).toBe('retur ') + expect(data.errorMessage).toBe('Unexpected identifier') + }) + }) + + /** + * `errorMessage` is the thrown message alone; `error` keeps its line, code and type label + * byte for byte. Each case pins both, so a change to either is a visible diff here. + */ + describe('errorMessage beside error', () => { + async function failIsolated(code: string, error: Record) { + mockExecuteInIsolatedVM.mockResolvedValueOnce({ result: null, stdout: '', error }) + const response = await POST(createMockRequest('POST', { code, timeout: 5000 })) + expect(response.status).toBe(422) + return response.json() + } + + async function failRemote( + language: 'javascript' | 'python', + code: string, + error: string, + stdout = '' + ) { + envFlagsMock.isRemoteSandboxEnabled = true + mockExecuteInSandbox.mockResolvedValueOnce({ + result: null, + stdout, + error, + sandboxId: 'sandbox-error', + }) + const response = await POST( + createMockRequest('POST', { + code, + language, + workflowId: 'workflow-1', + workspaceId: 'workspace-1', + executionId: 'execution-1', + }) + ) + expect(response.status).toBe(422) + return response.json() + } + + it('drops the line and code from a runtime error in isolated-vm', async () => { + const data = await failIsolated("const phone = '5'\nthrow new Error('invalid phone')", { + message: 'invalid phone', + name: 'Error', + line: 2, + lineContent: "throw new Error('invalid phone')", + }) + expect(data.error).toBe("Line 2: `throw new Error('invalid phone')` - invalid phone") + expect(data.errorMessage).toBe('invalid phone') + }) + + it('drops the type label error puts before a TypeError', async () => { + const data = await failIsolated('const obj = null\nreturn obj.x', { + message: "Cannot read properties of null (reading 'x')", + name: 'TypeError', + line: 2, + lineContent: 'return obj.x', + }) + expect(data.error).toBe( + "Type Error: Line 2: `return obj.x` - Cannot read properties of null (reading 'x')" + ) + expect(data.errorMessage).toBe("Cannot read properties of null (reading 'x')") + }) + + it('keeps a syntax error message without its location', async () => { + const data = await failIsolated('return {', { + message: 'Unexpected end of input', + name: 'SyntaxError', + line: 1, + lineContent: 'return {', + }) + expect(data.error).toBe('Syntax Error: Line 1: `return {` - Unexpected end of input') + expect(data.errorMessage).toBe('Unexpected end of input') + }) + + it.each([ + { thrown: "throw 'declined'", message: 'declined' }, + { thrown: 'throw {}', message: '[object Object]' }, + ])( + 'treats a non-Error throw ($thrown), which the isolate reports by its string form, like any message', + async ({ thrown, message }) => { + const data = await failIsolated(thrown, { + message, + name: 'Error', + line: 1, + lineContent: thrown, + }) + expect(data.error).toBe(`Line 1: \`${thrown}\` - ${message}`) + expect(data.errorMessage).toBe(message) + } + ) + + it('keeps every line of a multi-line message', async () => { + const data = await failIsolated("throw new Error('bad row\\nrow 3: no email')", { + message: 'bad row\nrow 3: no email', + name: 'Error', + line: 1, + lineContent: "throw new Error('bad row\\nrow 3: no email')", + }) + expect(data.error).toBe( + "Line 1: `throw new Error('bad row\\nrow 3: no email')` - bad row\nrow 3: no email" + ) + expect(data.errorMessage).toBe('bad row\nrow 3: no email') + }) + + it('is the message itself when the error carries no line', async () => { + const data = await failIsolated('return 1', { message: 'quota exceeded', name: 'Error' }) + expect(data.error).toBe('quota exceeded') + expect(data.errorMessage).toBe('quota exceeded') + }) + + it('holds a resolved value only where error holds it, never the code that read it', async () => { + const data = await failIsolated("throw new Error('rejected key ' + )", { + message: 'rejected key sk-live-123', + name: 'Error', + line: 1, + lineContent: "throw new Error('rejected key ' + )", + }) + expect(data.error).toBe( + "Line 1: `throw new Error('rejected key ' + )` - rejected key sk-live-123" + ) + expect(data.errorMessage).toBe('rejected key sk-live-123') + expect(data.error.endsWith(data.errorMessage)).toBe(true) + }) + + it('drops the type label from a JavaScript sandbox error', async () => { + const data = await failRemote( + 'javascript', + 'import "node:path"\nthrow new Error("invalid phone: 555")', + 'Error: invalid phone: 555' + ) + expect(data.error).toBe('Error: invalid phone: 555') + expect(data.errorMessage).toBe('invalid phone: 555') + }) + + it("drops Node's bracketed code label from a JavaScript sandbox error", async () => { + const data = await failRemote( + 'javascript', + 'import "node:path"\nreturn 1', + "Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'left-pad'" + ) + expect(data.error).toBe("Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'left-pad'") + expect(data.errorMessage).toBe("Cannot find module 'left-pad'") + }) + + it('keeps the text before a colon that error cuts from a typed sandbox error', async () => { + const data = await failRemote( + 'javascript', + 'import "node:path"\nthrow new RangeError("invalid phone: 555")', + 'RangeError: invalid phone: 555' + ) + expect(data.error).toBe('RangeError: 555') + expect(data.errorMessage).toBe('invalid phone: 555') + }) + + it('drops the file path a JavaScript sandbox syntax error leads with', async () => { + const data = await failRemote( + 'javascript', + 'import "node:path"\nreturn 1', + 'SyntaxError: /home/user/index.js: Unexpected token (9:8)' + ) + expect(data.error).toBe('SyntaxError: Unexpected token') + expect(data.errorMessage).toBe('Unexpected token') + }) + + it('drops the line, code and exception name from a Python error', async () => { + const data = await failRemote( + 'python', + "phone = '5'\nraise ValueError('invalid phone')", + 'ValueError: invalid phone', + 'Traceback (most recent call last):\n File "", line 2, in \nValueError: invalid phone' + ) + expect(data.error).toBe( + "Line 2: `raise ValueError('invalid phone')` - ValueError: invalid phone" + ) + expect(data.errorMessage).toBe('invalid phone') + }) + + it('keeps a Python syntax error message without its file and line', async () => { + const data = await failRemote( + 'python', + 'def f(:', + 'SyntaxError: invalid syntax (3907239417.py, line 1)' + ) + expect(data.error).toBe('SyntaxError: invalid syntax') + expect(data.errorMessage).toBe('invalid syntax') + }) + + it('labels a Python error with no message rather than leaving it empty', async () => { + const data = await failRemote('python', 'raise KeyError()', 'KeyError: ') + expect(data.error).toBe('KeyError:') + expect(data.errorMessage).toBe('KeyError:') + }) + + it('reports a failure before the code runs by its message', async () => { + const response = await POST( + createMockRequest('POST', { + code: 'return ', + workflowVariables: {}, + timeout: 5000, + }) + ) + const data = await response.json() + expect(response.status).toBe(500) + expect(data.error).toBe('Variable "missing" doesn\'t exist.') + expect(data.errorMessage).toBe('Variable "missing" doesn\'t exist.') }) }) }) diff --git a/apps/sim/lib/function-execution/execute-request.ts b/apps/sim/lib/function-execution/execute-request.ts index 5f44a897b9c..0168f85154b 100644 --- a/apps/sim/lib/function-execution/execute-request.ts +++ b/apps/sim/lib/function-execution/execute-request.ts @@ -568,9 +568,25 @@ function extractEnhancedError( return enhanced } +/** + * A leading absolute file path a sandbox puts before a JavaScript error's message + * (`/home/user/index.js: Unexpected token`). + */ +const SANDBOX_FILE_PATH_PREFIX = /^(?:file:\/\/)?\/\S*:\s*/ + +/** + * The type label a sandbox error leads with, when a message follows: `ValueError: invalid phone`, + * or Node's bracketed form `Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'x'`. + */ +const SANDBOX_ERROR_LABEL = /^[A-Za-z_$][\w$.]*(?: \[[\w.$-]+\])?:\s+(?=\S)/ + /** * Parse and format E2B error message - * Removes E2B-specific line references and adds correct user line numbers + * Removes E2B-specific line references and adds correct user line numbers. + * + * `errorMessage` is the thrown message alone: `formattedError` without its + * `Line N: \`code\` -` location and its error-type label, or the labelled form + * when the error has no message of its own. */ function formatE2BError( errorMessage: string, @@ -578,7 +594,7 @@ function formatE2BError( language: CodeLanguage, userCode: string, prologueLineCount: number -): { formattedError: string; cleanedOutput: string } { +): { formattedError: string; cleanedOutput: string; errorMessage: string } { const wrapperLines = language === CodeLanguage.Python ? E2B_PYTHON_WRAPPER_LINES : E2B_JS_WRAPPER_LINES const totalOffset = prologueLineCount + wrapperLines @@ -586,6 +602,7 @@ function formatE2BError( let userLine: number | undefined let cleanErrorType = '' let cleanErrorMsg = '' + let thrownMessage = '' if (language === CodeLanguage.Python) { const moduleMatch = errorOutput.match(/[^\n]*line (\d+)/) @@ -604,6 +621,7 @@ function formatE2BError( .replace(/\s*\(detected at line \d+\)/g, '') .replace(/\s*\([^)]+\.py, line \d+\)/g, '') .trim() + thrownMessage = cleanErrorMsg.replace(SANDBOX_ERROR_LABEL, '') } else if (language === CodeLanguage.JavaScript) { const firstLineEnd = errorMessage.indexOf('\n') const firstLine = firstLineEnd > 0 ? errorMessage.substring(0, firstLineEnd) : errorMessage @@ -612,6 +630,7 @@ function formatE2BError( if (jsErrorMatch) { cleanErrorType = jsErrorMatch[1] cleanErrorMsg = jsErrorMatch[2].trim() + thrownMessage = cleanErrorMsg const originalLine = Number.parseInt(jsErrorMatch[3], 10) userLine = originalLine - totalOffset } else { @@ -627,8 +646,15 @@ function formatE2BError( .replace(/^[^:]+:\s*/, '') // Remove file path .replace(/\s*\(\d+:\d+\)\s*$/, '') // Remove line:col at end .trim() + // `cleanErrorMsg` also cuts a message's own text before its first colon + // (`invalid phone: 555`); the thrown message drops only a real path. + thrownMessage = errorMatch[2] + .replace(SANDBOX_FILE_PATH_PREFIX, '') + .replace(/\s*\(\d+:\d+\)\s*$/, '') + .trim() } else { cleanErrorMsg = firstLine + thrownMessage = firstLine.replace(SANDBOX_ERROR_LABEL, '') } } } @@ -655,7 +681,7 @@ function formatE2BError( const cleanedOutput = finalErrorMsg - return { formattedError, cleanedOutput } + return { formattedError, cleanedOutput, errorMessage: thrownMessage || finalErrorMsg } } /** @@ -3009,7 +3035,7 @@ export async function executeFunctionRequest( if (e2bError) { const errorDisplayCode = getErrorDisplayCode(sourceCodeForErrors, resolvedCode) - const { formattedError, cleanedOutput } = formatE2BError( + const { formattedError, cleanedOutput, errorMessage } = formatE2BError( scrubInternalIdentifiers( getErrorDisplayMessage(e2bError, sourceCodeForErrors, resolvedCode), compilerInternalIdentifiers @@ -3023,6 +3049,7 @@ export async function executeFunctionRequest( { success: false, error: formattedError, + errorMessage, output: { result: null, stdout: cleanedOutput, @@ -3142,7 +3169,7 @@ export async function executeFunctionRequest( if (e2bError) { const errorDisplayCode = getErrorDisplayCode(sourceCodeForErrors, resolvedCode) - const { formattedError, cleanedOutput } = formatE2BError( + const { formattedError, cleanedOutput, errorMessage } = formatE2BError( scrubInternalIdentifiers( getErrorDisplayMessage(e2bError, sourceCodeForErrors, resolvedCode), compilerInternalIdentifiers @@ -3156,6 +3183,7 @@ export async function executeFunctionRequest( { success: false, error: formattedError, + errorMessage, output: { result: null, stdout: cleanedOutput, @@ -3317,6 +3345,7 @@ export async function executeFunctionRequest( { success: false, error: userFriendlyErrorMessage, + errorMessage: enhancedError.message, output: { result: null, stdout: cleanStdout(isolatedResult.stdout), @@ -3533,6 +3562,7 @@ export async function executeFunctionRequest( const errorResponse = { success: false, error: userFriendlyErrorMessage, + errorMessage: scrubInternalIdentifiers(enhancedError.message, compilerInternalIdentifiers), output: { result: null, stdout: cleanStdout(stdout), diff --git a/apps/sim/lib/guardrails/validate-hallucination.test.ts b/apps/sim/lib/guardrails/validate-hallucination.test.ts index 61b5a60b55f..531d34ed379 100644 --- a/apps/sim/lib/guardrails/validate-hallucination.test.ts +++ b/apps/sim/lib/guardrails/validate-hallucination.test.ts @@ -170,6 +170,20 @@ describe('validateHallucination', () => { expect(mockExecuteProviderRequest).not.toHaveBeenCalled() }) + it('fails with the unresolved-auto error instead of sending sim-auto to Ollama', async () => { + const actual = await vi.importActual('@/providers/utils') + providersUtilsMockFns.mockGetProviderFromModel.mockImplementation(actual.getProviderFromModel) + + const result = await validateHallucination({ + ...createInput(new ResolvedSecretTraceRegistry()), + model: 'sim-auto', + }) + + expect(result.passed).toBe(false) + expect(result.error).toContain('sim-auto has no provider until the model router resolves it') + expect(mockExecuteProviderRequest).not.toHaveBeenCalled() + }) + describe('with a Vertex AI model', () => { const vertexInput = (registry: ResolvedSecretTraceRegistry) => ({ ...createInput(registry), diff --git a/apps/sim/lib/internal/guardrails/operations.test.ts b/apps/sim/lib/internal/guardrails/operations.test.ts index 1f59dd46016..c6d2c3f527e 100644 --- a/apps/sim/lib/internal/guardrails/operations.test.ts +++ b/apps/sim/lib/internal/guardrails/operations.test.ts @@ -150,6 +150,29 @@ describe('executeGuardrailsValidation', () => { expect(mocks.validateHallucination).not.toHaveBeenCalled() }) + it('never treats sim-auto as a Vertex model, so a saved Vertex credential cannot make it throw', async () => { + await expect( + executeGuardrailsValidation( + { + validationType: 'hallucination', + input: 'claim', + knowledgeBaseId: 'knowledge-1', + model: 'sim-auto', + vertexCredential: 'credential-1', + workflowId: 'workflow-1', + }, + { + actorUserId: 'user-1', + executionContext: { workflowId: 'workflow-1', workspaceId: 'workspace-1' }, + headers: new Headers(), + requestId: 'request-1', + } + ) + ).resolves.toMatchObject({ output: { passed: true } }) + expect(mocks.authorizeCredential).not.toHaveBeenCalled() + expect(mocks.validateHallucination).toHaveBeenCalledOnce() + }) + it('does not conceal cancellation during hallucination authorization', async () => { const controller = new AbortController() const abortError = new DOMException('Operation aborted', 'AbortError') diff --git a/apps/sim/lib/internal/guardrails/operations.ts b/apps/sim/lib/internal/guardrails/operations.ts index dc3b1c3a70b..30091ee5b0c 100644 --- a/apps/sim/lib/internal/guardrails/operations.ts +++ b/apps/sim/lib/internal/guardrails/operations.ts @@ -26,6 +26,7 @@ import { ProviderNotAllowedError, } from '@/ee/access-control/utils/permission-check' import type { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' +import { isAutoModel } from '@/providers/models' import { isAbortError } from '@/providers/streaming-tool-loop-shared' import { getProviderFromModel } from '@/providers/utils' @@ -95,7 +96,13 @@ async function authorizeVertexCredential( input: GuardrailsValidationInput, context: GuardrailsOperationContext ): Promise { - if (!input.vertexCredential || !input.model || getProviderFromModel(input.model) !== 'vertex') { + if ( + !input.vertexCredential || + !input.model || + // sim-auto has no provider to look up (the lookup throws for it), so it is never Vertex. + isAutoModel(input.model) || + getProviderFromModel(input.model) !== 'vertex' + ) { return } const access = await authorizeCredentialUseForAuth(authenticatedCaller(context), { diff --git a/apps/sim/lib/internal/mssql/query.test.ts b/apps/sim/lib/internal/mssql/query.test.ts index ed8f576058b..1feef05b4aa 100644 --- a/apps/sim/lib/internal/mssql/query.test.ts +++ b/apps/sim/lib/internal/mssql/query.test.ts @@ -86,6 +86,17 @@ describe('validateReadOnlyQuery', () => { expect(result.error).toMatch(/backslash before a quote/) }) + /** A sequence advances on every evaluation, so even a lone SELECT changes server state. */ + it.each([ + 'SELECT NEXT VALUE FOR dbo.order_number', + 'SELECT id, NEXT VALUE\n FOR dbo.order_number AS n FROM dbo.orders', + ])('rejects the sequence advance %s', (query) => { + const result = validateReadOnlyQuery(query) + + expect(result.isValid).toBe(false) + expect(result.error).toMatch(/NEXT VALUE/) + }) + it('rejects an unpaired quote', () => { expect(validateReadOnlyQuery(`SELECT * FROM dbo.t WHERE a = 'x`).isValid).toBe(false) }) diff --git a/apps/sim/lib/internal/mssql/query.ts b/apps/sim/lib/internal/mssql/query.ts index 6e0fb10f6d1..1a4913bcc42 100644 --- a/apps/sim/lib/internal/mssql/query.ts +++ b/apps/sim/lib/internal/mssql/query.ts @@ -292,6 +292,14 @@ function matchStatementPhrase(masked: string): string | null { return null } +/** + * `NEXT VALUE FOR`, the one expression a single SELECT can use to change server + * state: each evaluation advances the sequence, permanently, even when the + * statement's transaction rolls back. + * @see https://learn.microsoft.com/en-us/sql/t-sql/functions/next-value-for-transact-sql + */ +const MSSQL_SEQUENCE_ADVANCE = /\bnext\s+value\s+for\b/i + /** Extended, OLE-automation, and system stored procedures, called with or without `EXEC`. */ const MSSQL_PROCEDURE_PATTERN = /\b(?:xp_|sp_)\w+/i @@ -389,7 +397,8 @@ function hasUnreliableQuoting(value: string): boolean { * rather than by naming the anything; and it may not mention a * statement-introducing keyword or a stored procedure, which covers both the * semicolon-less batch and the `WITH x AS (...) DELETE FROM x` form that a - * leading-token check alone would miss. + * leading-token check alone would miss, nor `NEXT VALUE FOR`, which advances a + * sequence from inside the SELECT itself. * * All screening runs over literal-masked text, so ordinary prose in a WHERE * clause does not trip it. The screens are lexical rather than a parser, so a @@ -444,6 +453,7 @@ export function validateReadOnlyQuery(query: string): { isValid: boolean; error? const disallowed = MSSQL_STATEMENT_KEYWORDS.exec(masked)?.[0] ?? MSSQL_PROCEDURE_PATTERN.exec(masked)?.[0] ?? + MSSQL_SEQUENCE_ADVANCE.exec(masked)?.[0] ?? matchStatementPhrase(masked) if (disallowed) { return { diff --git a/apps/sim/lib/internal/search/execute-tool.ts b/apps/sim/lib/internal/search/execute-tool.ts index 63e4d3ef696..61ffb74a8b0 100644 --- a/apps/sim/lib/internal/search/execute-tool.ts +++ b/apps/sim/lib/internal/search/execute-tool.ts @@ -1,5 +1,9 @@ import { getErrorMessage } from '@sim/utils/errors' import { z } from 'zod' +import { + HostedKeyRequiresPaidPlanError, + mayUseHostedKey, +} from '@/lib/billing/core/hosted-key-access' import { executeSearchOperation } from '@/lib/internal/search/operations' import type { InternalToolOperationHandler } from '@/lib/internal/tool-operations/types' @@ -24,6 +28,12 @@ export const executeSearchTool: InternalToolOperationHandler = async ({ return Response.json({ success: false, error: 'Invalid request data' }, { status: 400 }) } + // Search always runs on Sim's own key, so it is reserved for paid payers like every hosted tool. + if (!(await mayUseHostedKey(context.workspaceId, context.billingAttribution))) { + const refusal = new HostedKeyRequiresPaidPlanError('Web Search') + return Response.json({ success: false, error: refusal.message }, { status: refusal.statusCode }) + } + try { return Response.json(await executeSearchOperation(parsed.data, signal)) } catch (error) { diff --git a/apps/sim/lib/internal/table/ignored-columns.integration.ts b/apps/sim/lib/internal/table/ignored-columns.integration.ts new file mode 100644 index 00000000000..1ab9bcafcbd --- /dev/null +++ b/apps/sim/lib/internal/table/ignored-columns.integration.ts @@ -0,0 +1,227 @@ +import { db } from '@sim/db' +import { permissions, user, userTableDefinitions, userTableRows, workspace } from '@sim/db/schema' +import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' +import { createExecutorPrincipal } from '@sim/testing/factories/principal.factory' +import { storageServiceMock } from '@sim/testing/mocks/storage-service.mock' +import { tableBillingMock, tableBillingMockFns } from '@sim/testing/mocks/table-billing.mock' +import { tableEventsMock } from '@sim/testing/mocks/table-events.mock' +import { tableTriggerMock } from '@sim/testing/mocks/table-trigger.mock' +import { tableWorkflowColumnsMock } from '@sim/testing/mocks/table-workflow-columns.mock' +import { generateId } from '@sim/utils/id' +import { asc, eq } from 'drizzle-orm' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@/lib/table/billing', () => tableBillingMock) +vi.mock('@/lib/table/events', () => tableEventsMock) +vi.mock('@/lib/table/trigger', () => tableTriggerMock) +vi.mock('@/lib/table/workflow-columns', () => tableWorkflowColumnsMock) +vi.mock('@/lib/uploads/core/storage-service', () => storageServiceMock) + +import { + insertTableRowsContract, + updateTableRowContract, + updateTableRowsByFilterContract, + upsertTableRowContract, +} from '@/lib/api/contracts/tables' +import { + executeTableInsertRows, + executeTableUpdateRow, + executeTableUpdateRowsByFilter, + executeTableUpsertRow, + type TableToolOperationContext, + type TableToolOperationResult, +} from '@/lib/internal/table/operations' +import type { RowData } from '@/lib/table' + +/** + * The workflow Table tools write leniently: a key naming no column is dropped, not refused. These + * runs go through the tool operations against PostgreSQL and parse each body with its route + * contract, as `executeTableTool` does, so a key the write dropped must survive to the tool as + * `ignoredColumns` while the stored row stays exactly what it was before the field existed. + */ +describe('Table tool writes report the keys they drop', () => { + let userId: string + let workspaceId: string + let tableId: string + + beforeEach(async () => { + userId = generateId() + workspaceId = generateId() + tableId = generateId() + const now = new Date() + tableBillingMockFns.mockAssertRowCapacity.mockResolvedValue(10_000) + await db.insert(user).values({ + id: userId, + name: 'Ignored columns fixture', + email: `${userId}@ignored-columns.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + await insertWorkspaceFixture(db, { + id: workspaceId, + name: 'Ignored columns fixture', + ownerId: userId, + billedAccountUserId: userId, + }) + await db.insert(permissions).values({ + id: generateId(), + userId, + entityType: 'workspace', + entityId: workspaceId, + permissionType: 'admin', + }) + await db.insert(userTableDefinitions).values({ + id: tableId, + workspaceId, + name: 'Leads', + createdBy: userId, + schema: { + columns: [ + { id: 'col_email', name: 'email', type: 'string', unique: true }, + { id: 'col_score', name: 'score', type: 'number' }, + ], + }, + }) + }) + + afterEach(async () => { + await deleteWorkspaceFixture(db, eq(workspace.id, workspaceId)) + await db.delete(user).where(eq(user.id, userId)) + }) + + function context(): TableToolOperationContext { + return { + principal: createExecutorPrincipal({ + subjectUserId: userId, + workspaceId, + delegationId: generateId(), + audience: 'sim:tables', + resourceScope: { tableId }, + delegationContext: { kind: 'workflow_execution', workflowId: 'wf-ignored-columns' }, + }), + headers: new Headers(), + requestId: 'request-ignored-columns', + } + } + + /** The body the tool receives: what `executeTableTool` returns after its contract parse. */ + function delivered( + contract: { response: { schema: { parse: (body: unknown) => unknown } } }, + result: TableToolOperationResult + ) { + return (contract.response.schema.parse(result.body) as { data: Record }).data + } + + async function storedRows() { + const rows = await db + .select({ data: userTableRows.data }) + .from(userTableRows) + .where(eq(userTableRows.tableId, tableId)) + .orderBy(asc(userTableRows.orderKey)) + return rows.map((row) => row.data) + } + + async function seed(email: string) { + const result = await executeTableInsertRows( + tableId, + { workspaceId, data: { email, score: 1 } }, + context() + ) + return (result.body.data as { row: { id: string } }).row.id + } + + it.each<{ name: string; data: RowData; ignored: string[]; stored: RowData }>([ + { + name: 'no key unknown', + data: { email: 'a@x.co', score: 3 }, + ignored: [], + stored: { col_email: 'a@x.co', col_score: 3 }, + }, + { + name: 'some keys unknown', + data: { email: 'a@x.co', nickname: 'A' }, + ignored: ['nickname'], + stored: { col_email: 'a@x.co' }, + }, + { + name: 'every key unknown', + data: { nickname: 'A', tier: 'gold' }, + ignored: ['nickname', 'tier'], + stored: {}, + }, + ])('a single insert with $name', async ({ data, ignored, stored }) => { + const result = await executeTableInsertRows(tableId, { workspaceId, data }, context()) + + expect(delivered(insertTableRowsContract, result).ignoredColumns).toEqual(ignored) + expect(await storedRows()).toEqual([stored]) + }) + + it('a batch insert names each dropped key once, in the order first sent', async () => { + const result = await executeTableInsertRows( + tableId, + { + workspaceId, + rows: [ + { email: 'a@x.co', nickname: 'A' }, + { email: 'b@x.co', tier: 'gold', nickname: 'B' }, + ], + }, + context() + ) + + const data = delivered(insertTableRowsContract, result) + expect(data.ignoredColumns).toEqual(['nickname', 'tier']) + expect(data.insertedCount).toBe(2) + expect(await storedRows()).toEqual([{ col_email: 'a@x.co' }, { col_email: 'b@x.co' }]) + }) + + it.each([ + { operation: 'insert', existing: false }, + { operation: 'update', existing: true }, + ])('an upsert that resolves to an $operation', async ({ operation, existing }) => { + if (existing) await seed('a@x.co') + + const result = await executeTableUpsertRow( + tableId, + { workspaceId, data: { email: 'a@x.co', score: 5, nickname: 'A' }, conflictTarget: 'email' }, + context() + ) + + const data = delivered(upsertTableRowContract, result) + expect(data.operation).toBe(operation) + expect(data.ignoredColumns).toEqual(['nickname']) + expect(await storedRows()).toEqual([{ col_email: 'a@x.co', col_score: 5 }]) + }) + + it('an update of one row', async () => { + const rowId = await seed('a@x.co') + + const result = await executeTableUpdateRow( + tableId, + rowId, + { workspaceId, data: { score: 9, tier: 'gold' } }, + context() + ) + + expect(delivered(updateTableRowContract, result).ignoredColumns).toEqual(['tier']) + expect(await storedRows()).toEqual([{ col_email: 'a@x.co', col_score: 9 }]) + }) + + it('an update by filter, whether or not a row matches', async () => { + await seed('a@x.co') + const update = (email: string) => + executeTableUpdateRowsByFilter( + tableId, + { workspaceId, filter: { email }, data: { score: 7, tier: 'gold' } }, + context() + ) + + const matched = delivered(updateTableRowsByFilterContract, await update('a@x.co')) + const unmatched = delivered(updateTableRowsByFilterContract, await update('none@x.co')) + + expect(matched).toMatchObject({ updatedCount: 1, ignoredColumns: ['tier'] }) + expect(unmatched).toMatchObject({ updatedCount: 0, ignoredColumns: ['tier'] }) + expect(await storedRows()).toEqual([{ col_email: 'a@x.co', col_score: 7 }]) + }) +}) diff --git a/apps/sim/lib/internal/table/operations.ts b/apps/sim/lib/internal/table/operations.ts index a997411855a..55e199e7957 100644 --- a/apps/sim/lib/internal/table/operations.ts +++ b/apps/sim/lib/internal/table/operations.ts @@ -192,6 +192,7 @@ export async function executeTableInsertRows( data: { row: presentNamedTableQueryRow(result.row, result.table), message: 'Row inserted successfully', + ignoredColumns: result.ignoredColumns, }, }, provenance: result.secretProvenance, @@ -205,6 +206,7 @@ export async function executeTableInsertRows( rows: result.rows.map((row) => presentNamedTableQueryRow(row, result.table)), insertedCount: result.rows.length, message: `Successfully inserted ${result.rows.length} rows`, + ignoredColumns: result.ignoredColumns, }, }, provenance: result.secretProvenance, @@ -322,6 +324,7 @@ export async function executeTableUpdateRow( data: { row: presentNamedTableRow(result.row, result.table), message: 'Row updated successfully', + ignoredColumns: result.ignoredColumns, }, }, provenance: result.secretProvenance, @@ -356,6 +359,7 @@ export async function executeTableUpdateRowsByFilter( message: matched ? 'Rows updated successfully' : 'No rows matched the filter criteria', updatedCount: result.affectedCount, ...(matched ? { updatedRowIds: result.affectedRowIds } : {}), + ignoredColumns: result.ignoredColumns, }, }, }) @@ -470,6 +474,7 @@ export async function executeTableUpsertRow( row: presentNamedTableRow(result.row, result.table), operation: result.operation, message: `Row ${result.operation === 'update' ? 'updated' : 'inserted'} successfully`, + ignoredColumns: result.ignoredColumns, }, }, provenance: result.secretProvenance, diff --git a/apps/sim/lib/invitations/__integration__/scim-locked-invitations.integration.ts b/apps/sim/lib/invitations/__integration__/scim-locked-invitations.integration.ts new file mode 100644 index 00000000000..2c7c7fabb9a --- /dev/null +++ b/apps/sim/lib/invitations/__integration__/scim-locked-invitations.integration.ts @@ -0,0 +1,210 @@ +/** + * Inviting a directory-provisioned member when the organization has locked + * managed membership: the directory owns workspaces a group is mapped to, and + * nothing else, so an unmapped workspace stays shareable by hand. + */ + +import { db } from '@sim/db' +import { + auditLog, + invitation, + member, + organization, + permissions, + scimConnection, + scimGroupMapping, + user, + workspace, +} from '@sim/db/schema' +import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' +import { envFlagsMock } from '@sim/testing/mocks/env-flags.mock' +import { generateId } from '@sim/utils/id' +import { and, eq, inArray } from 'drizzle-orm' +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' +import { withWorkspaceInvocationScope } from '@/lib/core/application/workspace-invocation-scope' +import { createScopedCliTransport } from '@/lib/mothership/agent-cli/scoped-transport' +import { addGroupMember, insertScimGroup } from '@/ee/scim/lib/repository/groups' +import { insertScimUser } from '@/ee/scim/lib/repository/users' +import '@/app/api/v2/workspaces/[workspaceId]/invitations/route' + +/** Directory provisioning on a self-hosted deployment, so a locked connection is enforced. */ +vi.mock('@/lib/core/config/env-flags', () => ({ ...envFlagsMock, isScimEnabled: true })) + +const ORIGIN = 'http://localhost:3000' +const organizationId = generateId() +const connectionId = generateId() +const unmappedWorkspaceId = generateId() +const mappedWorkspaceId = generateId() +const adminId = generateId() +const managedMemberId = generateId() +/** Provisioned and in the organization, but in no group mapped to anything. */ +const ungroupedMemberId = generateId() +const managedOutsiderId = generateId() +const fixtureDomain = `${generateId()}.scim-invite.test` +const emailOf = (id: string) => `${id}@${fixtureDomain}` + +function invite(workspaceId: string, email: string) { + const transport = createScopedCliTransport(ORIGIN, { + userId: adminId, + workspaceId, + chatId: generateId(), + }) + return withWorkspaceInvocationScope({ workspaceId, organizationId }, () => + transport(`${ORIGIN}/api/v2/workspaces/${workspaceId}/invitations`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ emails: [email], permission: 'write', membership: 'member' }), + }) + ) +} + +async function permissionOf(userId: string, workspaceId: string) { + const [row] = await db + .select({ permission: permissions.permissionType }) + .from(permissions) + .where( + and( + eq(permissions.entityType, 'workspace'), + eq(permissions.entityId, workspaceId), + eq(permissions.userId, userId) + ) + ) + return row?.permission ?? null +} + +/** The batch route answers 200 and lists each refused email with its reason. */ +async function refusalOf(response: Response) { + expect(response.status).toBe(200) + const body = (await response.json()) as { + data: { successful: string[]; failed: { error: string }[] } + } + expect(body.data.successful).toEqual([]) + return body.data.failed[0]?.error +} + +async function provision(userId: string) { + const { id } = await insertScimUser(db, { + connectionId, + userId, + active: true, + attributes: { + userName: emailOf(userId), + active: true, + displayName: 'Provisioned', + name: { formatted: 'Provisioned' }, + emails: [{ value: emailOf(userId), primary: true, type: 'work' }], + }, + }) + return id +} + +describe('workspace invitations under a locked directory connection', () => { + beforeAll(async () => { + const now = new Date() + await db.insert(user).values( + [adminId, managedMemberId, ungroupedMemberId, managedOutsiderId].map((id) => ({ + id, + name: 'SCIM invitation fixture', + email: emailOf(id), + emailVerified: true, + createdAt: now, + updatedAt: now, + })) + ) + await db.insert(organization).values({ + id: organizationId, + name: 'SCIM invitation fixture', + slug: organizationId, + createdAt: now, + updatedAt: now, + }) + await db.insert(member).values( + [adminId, managedMemberId, ungroupedMemberId].map((userId) => ({ + id: generateId(), + userId, + organizationId, + role: 'member', + createdAt: now, + })) + ) + for (const id of [unmappedWorkspaceId, mappedWorkspaceId]) { + await insertWorkspaceFixture(db, { + id, + name: 'SCIM invitation fixture', + ownerId: adminId, + billedAccountUserId: adminId, + organizationId, + workspaceMode: 'organization', + }) + await db.insert(permissions).values({ + id: generateId(), + userId: adminId, + entityType: 'workspace', + entityId: id, + permissionType: 'admin', + }) + } + await db.insert(scimConnection).values({ + id: connectionId, + organizationId, + status: 'active', + settings: { lockManualMembership: true }, + }) + const group = await insertScimGroup(db, { connectionId, displayName: 'Mapped group' }) + await db.insert(scimGroupMapping).values({ + id: generateId(), + groupId: group.id, + targetKind: 'workspace', + workspaceId: mappedWorkspaceId, + permissionType: 'read', + }) + await addGroupMember(db, { groupId: group.id, scimUserId: await provision(managedMemberId) }) + await provision(ungroupedMemberId) + await provision(managedOutsiderId) + }) + + afterAll(async () => { + const workspaceIds = [unmappedWorkspaceId, mappedWorkspaceId] + await db.delete(invitation).where(eq(invitation.organizationId, organizationId)) + await db.delete(auditLog).where(inArray(auditLog.workspaceId, workspaceIds)) + await db.delete(scimConnection).where(eq(scimConnection.id, connectionId)) + await deleteWorkspaceFixture(db, inArray(workspace.id, workspaceIds)) + await db.delete(organization).where(eq(organization.id, organizationId)) + await db + .delete(user) + .where(inArray(user.id, [adminId, managedMemberId, ungroupedMemberId, managedOutsiderId])) + }) + + it('grants a provisioned member access to a workspace no group is mapped to', async () => { + const response = await invite(unmappedWorkspaceId, emailOf(managedMemberId)) + + expect(response.status).toBe(200) + expect(await permissionOf(managedMemberId, unmappedWorkspaceId)).toBe('write') + }) + + it('refuses a manual grant on a workspace the member’s directory group is mapped to', async () => { + const response = await invite(mappedWorkspaceId, emailOf(managedMemberId)) + + expect(await refusalOf(response)).toMatch(/identity provider/) + expect(await permissionOf(managedMemberId, mappedWorkspaceId)).toBeNull() + }) + + it('grants a mapped workspace to a provisioned member outside its mapped group', async () => { + const response = await invite(mappedWorkspaceId, emailOf(ungroupedMemberId)) + + expect(response.status).toBe(200) + expect(await permissionOf(ungroupedMemberId, mappedWorkspaceId)).toBe('write') + }) + + it('refuses inviting a provisioned person who is not an organization member', async () => { + const response = await invite(unmappedWorkspaceId, emailOf(managedOutsiderId)) + + expect(await refusalOf(response)).toMatch(/identity provider/) + const pending = await db + .select({ id: invitation.id }) + .from(invitation) + .where(eq(invitation.email, emailOf(managedOutsiderId))) + expect(pending).toEqual([]) + expect(await permissionOf(managedOutsiderId, unmappedWorkspaceId)).toBeNull() + }) +}) diff --git a/apps/sim/lib/invitations/core.ts b/apps/sim/lib/invitations/core.ts index 4574b5343b9..2c2f88b281d 100644 --- a/apps/sim/lib/invitations/core.ts +++ b/apps/sim/lib/invitations/core.ts @@ -34,7 +34,10 @@ import { } from '@/lib/billing/organizations/provision-seat' import { reconcileOrganizationSeats } from '@/lib/billing/organizations/seats' import { isPro, isTeam } from '@/lib/billing/plan-helpers' -import { hasUsableSubscriptionStatus } from '@/lib/billing/subscriptions/utils' +import { + hasUsableSubscriptionStatus, + isTrialingSubscription, +} from '@/lib/billing/subscriptions/utils' import { ForbiddenOperationError } from '@/lib/core/application/forbidden' import { isBillingEnabled } from '@/lib/core/config/env-flags' import { syncWorkspaceEnvCredentials } from '@/lib/credentials/environment' @@ -525,6 +528,7 @@ export async function getInvitationJoinPreview( if ( !personalSub || !hasUsableSubscriptionStatus(personalSub.status) || + isTrialingSubscription(personalSub) || !(isPro(personalSub.plan) || isTeam(personalSub.plan)) ) { return withOutcome('blocked') diff --git a/apps/sim/lib/invitations/direct-grant.ts b/apps/sim/lib/invitations/direct-grant.ts index 56877067ad1..12fa2111dfe 100644 --- a/apps/sim/lib/invitations/direct-grant.ts +++ b/apps/sim/lib/invitations/direct-grant.ts @@ -39,7 +39,7 @@ import { type WorkspaceWithOwner, } from '@/lib/workspaces/permissions/utils' import type { WorkspaceInvitePolicy } from '@/lib/workspaces/policy' -import { assertMembershipNotScimManaged } from '@/ee/scim/lib/managed-membership' +import { assertWorkspaceAccessNotScimManaged } from '@/ee/scim/lib/managed-membership' const logger = createLogger('InvitationDirectGrant') @@ -152,10 +152,11 @@ export async function grantWorkspaceAccessDirectly( userId: input.userId, organizationIds: [input.organizationId], }) - /** A member the directory manages gets workspace access from the directory, not by hand. */ - await assertMembershipNotScimManaged({ + /** Access to a workspace a directory group is mapped to comes from the directory, not by hand. */ + await assertWorkspaceAccessNotScimManaged({ organizationId: input.organizationId, userId: input.userId, + workspaceIds: [input.workspaceId], executor: tx, }) diff --git a/apps/sim/lib/invitations/workspace-invitations.ts b/apps/sim/lib/invitations/workspace-invitations.ts index efdc042feba..72c2a654459 100644 --- a/apps/sim/lib/invitations/workspace-invitations.ts +++ b/apps/sim/lib/invitations/workspace-invitations.ts @@ -54,6 +54,8 @@ import { validateInvitationsAllowed } from '@/ee/access-control/utils/permission import { isScimDeploymentEnabled } from '@/ee/scim/lib/entitlement' import { assertInviteeNotScimManaged, + assertMembershipNotScimManaged, + assertWorkspaceAccessNotScimManaged, scimManagedUserPredicate, } from '@/ee/scim/lib/managed-membership' @@ -179,6 +181,10 @@ async function ensureExistingMemberOrganizationRole({ email, }) } + /** The directory owns a provisioned member's organization role. */ + if (needsPromotion) { + await assertMembershipNotScimManaged({ organizationId, userId, executor: tx }) + } for (const workspaceId of context.targets.map((target) => target.workspaceId).sort()) { const workspaceDetails = await getWorkspaceWithOwner(workspaceId, { executor: tx, @@ -563,17 +569,23 @@ export async function createWorkspaceInvitation({ .where(eq(foldedEmail(user.email), normalizedEmail)) .then((rows) => rows[0]) + const existingMembership = existingUser ? await getUserOrganization(existingUser.id) : null + const isExistingMember = + organizationId !== null && existingMembership?.organizationId === organizationId + /** * When the organization has made its identity provider the source of truth for - * membership, a Sim invitation to someone the directory already provisions is - * redundant at best and reverted at worst. Read as part of the lookup above so - * the common case costs no extra query. + * membership, an invitation that would add someone the directory provisions to + * the organization is reverted by the next sync. Read as part of the lookup + * above so the common case costs no extra query. A provisioned member who + * already belongs is checked per workspace below, before any grant is written. */ if (organizationId) { - await assertInviteeNotScimManaged({ organizationId, managed: existingUser?.scimManaged }) + await assertInviteeNotScimManaged({ + organizationId, + managed: existingUser?.scimManaged && !isExistingMember, + }) } - - const existingMembership = existingUser ? await getUserOrganization(existingUser.id) : null let existingOrganizationRole = existingMembership?.role let organizationRoleUpdated = false if ( @@ -600,10 +612,7 @@ export async function createWorkspaceInvitation({ let pendingTargets = context.targets if (existingUser) { - const inheritsWorkspaceAdmin = - organizationId !== null && - existingMembership?.organizationId === organizationId && - isOrgAdminRole(existingOrganizationRole) + const inheritsWorkspaceAdmin = isExistingMember && isOrgAdminRole(existingOrganizationRole) const accessibleRows = await db .select({ workspaceId: permissions.entityId, permission: permissions.permissionType }) .from(permissions) @@ -635,11 +644,7 @@ export async function createWorkspaceInvitation({ (target) => !accessibleWorkspaceIds.has(target.workspaceId) ) if (pendingTargets.length === 0) { - if ( - existingAccessPolicy === 'ensure-at-least' && - organizationId && - existingMembership?.organizationId === organizationId - ) { + if (existingAccessPolicy === 'ensure-at-least' && isExistingMember) { return { id: existingUser.id, email: normalizedEmail, @@ -663,7 +668,20 @@ export async function createWorkspaceInvitation({ * Already in this organization: they hold a seat, so grant access directly * with no invitation or acceptance step. */ - if (organizationId && existingMembership?.organizationId === organizationId) { + if (organizationId && isExistingMember) { + /** + * Refuse up front when any selected workspace's access is directory-owned, + * so a multi-workspace invite does not grant some and then fail. Each grant + * rechecks under its own locks. + */ + if (existingUser.scimManaged) { + await assertWorkspaceAccessNotScimManaged({ + organizationId, + userId: existingUser.id, + workspaceIds: pendingTargets.map((target) => target.workspaceId), + executor: db, + }) + } let outcome: DirectGrantOutcome['outcome'] = organizationRoleUpdated ? 'updated' : 'unchanged' const grantedWorkspaceIds: string[] = [] for (const target of pendingTargets) { diff --git a/apps/sim/lib/knowledge/__integration__/permission-import-cleanup.integration.ts b/apps/sim/lib/knowledge/__integration__/permission-import-cleanup.integration.ts index 0dd7986848f..6085a38519a 100644 --- a/apps/sim/lib/knowledge/__integration__/permission-import-cleanup.integration.ts +++ b/apps/sim/lib/knowledge/__integration__/permission-import-cleanup.integration.ts @@ -75,9 +75,10 @@ describe('permission import reclamation through the PostgreSQL outbox', () => { manifest: {}, expiresAt: options.expiresAt ?? new Date(0), }) + // Zero-padded ids insert in index order, so both btrees append instead of splitting. await db.execute(sql` insert into ${grants} (import_id, project_path, user_id, group_key) - select ${id}, 'fixture/project', series::text, 'project' + select ${id}, 'fixture/project', lpad(series::text, ${String(count).length}::integer, '0'), 'project' from generate_series(1, ${count}) series`) if (options.active) { await db.insert(snapshots).values({ diff --git a/apps/sim/lib/knowledge/embeddings.ts b/apps/sim/lib/knowledge/embeddings.ts index e12a007ecbd..3979d78a423 100644 --- a/apps/sim/lib/knowledge/embeddings.ts +++ b/apps/sim/lib/knowledge/embeddings.ts @@ -73,6 +73,7 @@ function resolveConfiguredEmbeddingModel(): string { * a working width is recoverable and one that could not be created is not. */ function resolveConfiguredEmbeddingDimensions(model: string): KbEmbeddingDimensions { + // env-number-normalized: only tested for unset here; the width itself is read through envNumber below const raw = env.EMBEDDING_OUTPUT_DIMS if (raw === undefined || String(raw).trim() === '') return defaultKbEmbeddingDimensions(model) @@ -111,6 +112,7 @@ function resolveConfiguredEmbeddingDimensions(model: string): KbEmbeddingDimensi */ export async function getConfiguredKbEmbedding(): Promise { const model = resolveConfiguredEmbeddingModel() + // env-number-normalized: only tested for unset here; resolveConfiguredEmbeddingDimensions reads the width through envNumber const configured = env.EMBEDDING_OUTPUT_DIMS const stated = configured !== undefined && String(configured).trim() !== '' diff --git a/apps/sim/lib/logs/execution/logger.ts b/apps/sim/lib/logs/execution/logger.ts index 9bb4422fd31..167cb7a2a8f 100644 --- a/apps/sim/lib/logs/execution/logger.ts +++ b/apps/sim/lib/logs/execution/logger.ts @@ -34,6 +34,7 @@ import { stableEventKey, } from '@/lib/billing/core/usage-log' import { resolveEffectivePiiRedaction } from '@/lib/billing/retention' +import { isTrialingSubscription } from '@/lib/billing/subscriptions/utils' import { checkAndBillPayerOverageThreshold } from '@/lib/billing/threshold-billing' import { isBillingEnabled } from '@/lib/core/config/env-flags' import { FOREIGN_KEY_VIOLATION } from '@/lib/core/errors/database-query-error' @@ -133,6 +134,8 @@ type UsageThresholdEmailContext = planName: string periodStart: Date before: Awaited> + /** Set during a free trial, whose allowance is fixed until it ends. */ + trialEnd: Date | null } | { scope: 'organization' @@ -1244,7 +1247,12 @@ export class ExecutionLogger { const payerSubscription = billingAttribution.payerSubscription const [{ getDisplayPlanName }, { limit: orgLimit }, orgUsageBefore] = await Promise.all([ import('@/lib/billing/plan-helpers'), - getOrgUsageLimit(organizationId, payerSubscription.plan, payerSubscription.seats), + getOrgUsageLimit(organizationId, { + id: payerSubscription.id, + plan: payerSubscription.plan, + seats: payerSubscription.seats, + billingInterval: payerSubscription.billingInterval, + }), readSoftGateUsageCost( billingAttribution.billingEntity, exactBillingContext.billingPeriod @@ -1273,6 +1281,7 @@ export class ExecutionLogger { planName: getDisplayPlanName(sub?.plan), periodStart: exactBillingContext.billingPeriod.start, before: await checkResolvedUsageStatus(usr.id, sub, exactBillingContext), + trialEnd: isTrialingSubscription(sub) ? (sub?.trialEnd ?? null) : null, } } } catch (e) { @@ -1397,6 +1406,7 @@ export class ExecutionLogger { usageBefore: emailContext.before.currentUsage, costDelta, limit: emailContext.before.limit, + trialEnd: emailContext.trialEnd, }) } else { await maybeSendUsageThresholdEmail({ diff --git a/apps/sim/lib/logs/execution/trace-spans/factory.ts b/apps/sim/lib/logs/execution/trace-spans/factory.ts index af9b981aed5..63e3f1849a1 100644 --- a/apps/sim/lib/logs/execution/trace-spans/factory.ts +++ b/apps/sim/lib/logs/execution/trace-spans/factory.ts @@ -1,5 +1,5 @@ import { createLogger } from '@sim/logger' -import { isRecordLike } from '@sim/utils/object' +import { isRecordLike, omit } from '@sim/utils/object' import type { ProviderTiming, TraceSpan } from '@/lib/logs/types' import { CHILD_EXECUTION_ID_OUTPUT_KEY, @@ -17,6 +17,9 @@ import type { const logger = createLogger('SpanFactory') +/** The Agent tool that runs a workflow in-process through the workflow block handler. */ +const WORKFLOW_TOOL_ID = 'workflow_executor' + /** A BlockLog that has already passed the id/type validity check. */ type ValidBlockLog = BlockLog & { blockType: string } @@ -95,7 +98,7 @@ export function createSpanFromLog(log: BlockLog): TraceSpan | null { function createBaseSpan(log: ValidBlockLog): TraceSpan { const spanId = `${log.blockId}-${new Date(log.startedAt).getTime()}` const output = extractDisplayOutput(log) - const childIds = extractChildWorkflowIds(log.output) + const childIds = extractChildWorkflowIds(log) return { id: spanId, @@ -141,22 +144,54 @@ function extractDisplayOutput(log: ValidBlockLog): Record { childTraceSpans: _childTraceSpans, ...rest } = log.output ?? {} - return log.error ? { ...rest, error: log.error } : rest + const display = isWorkflowBlockType(log.blockType) + ? omit(rest, ['childDeploymentVersionId']) + : rest + return log.error ? { ...display, error: log.error } : display } -/** Pulls child-workflow identifiers off the output so they can live on the span. */ -function extractChildWorkflowIds( - output: NormalizedBlockOutput | undefined -): { childWorkflowSnapshotId?: string; childWorkflowId?: string } | undefined { +type ChildWorkflowIds = Pick< + TraceSpan, + 'childWorkflowSnapshotId' | 'childWorkflowId' | 'childDeploymentVersionId' +> + +/** + * Pulls child-workflow identifiers off the output so they can live on the span. The deployment + * version is taken only from a workflow block, so no other block can claim one by returning the key. + */ +function extractChildWorkflowIds(log: ValidBlockLog): ChildWorkflowIds | undefined { + const output = log.output if (!output) return undefined - const ids: { childWorkflowSnapshotId?: string; childWorkflowId?: string } = {} + const ids: ChildWorkflowIds = {} if (typeof output.childWorkflowSnapshotId === 'string') { ids.childWorkflowSnapshotId = output.childWorkflowSnapshotId } if (typeof output.childWorkflowId === 'string') { ids.childWorkflowId = output.childWorkflowId } - return ids.childWorkflowSnapshotId || ids.childWorkflowId ? ids : undefined + if (isWorkflowBlockType(log.blockType)) { + Object.assign(ids, childDeploymentVersionOf(output)) + } + return Object.keys(ids).length > 0 ? ids : undefined +} + +/** The deployment version a child workflow run reports, as a span field. */ +function childDeploymentVersionOf( + output: Record | undefined +): Pick { + const versionId = output?.childDeploymentVersionId + return typeof versionId === 'string' ? { childDeploymentVersionId: versionId } : {} +} + +/** + * The deployment version a workflow run as an Agent tool reported. Read only for + * `workflow_executor`, so another tool returning the same key records nothing. + */ +function workflowToolVersion( + toolName: string, + output: Record | undefined +): Pick { + return toolName === WORKFLOW_TOOL_ID ? childDeploymentVersionOf(output) : {} } /** Enriches a span with provider timing, cost, tokens, and model from block output. */ @@ -263,6 +298,7 @@ function buildChildrenFromTimeSegments( input: match?.arguments ?? match?.input, output: match?.error ? { error: match.error, ...output } : output, ...handle, + ...workflowToolVersion(normalizedName, output), } if (segment.toolCallId) toolChild.toolCallId = segment.toolCallId if (segment.errorType) toolChild.errorType = segment.errorType @@ -330,9 +366,10 @@ function buildChildrenFromToolCalls(span: TraceSpan, log: ValidBlockLog): TraceS const startTime = tc.startTime ?? log.startedAt const endTime = tc.endTime ?? log.endedAt const { output, handle } = liftChildTraceHandle(normalizeTraceOutput(tc.result ?? tc.output)) + const name = stripCustomToolPrefix(tc.name ?? 'unnamed-tool') return { id: `${span.id}-tool-${index}`, - name: stripCustomToolPrefix(tc.name ?? 'unnamed-tool'), + name, type: 'tool', duration: tc.duration ?? 0, startTime, @@ -341,6 +378,7 @@ function buildChildrenFromToolCalls(span: TraceSpan, log: ValidBlockLog): TraceS input: tc.arguments ?? tc.input, output: tc.error ? { error: tc.error, ...output } : output, ...handle, + ...workflowToolVersion(name, output), } }) } diff --git a/apps/sim/lib/logs/execution/trace-spans/trace-spans.test.ts b/apps/sim/lib/logs/execution/trace-spans/trace-spans.test.ts index 85c66c845f3..a6bd517ff9f 100644 --- a/apps/sim/lib/logs/execution/trace-spans/trace-spans.test.ts +++ b/apps/sim/lib/logs/execution/trace-spans/trace-spans.test.ts @@ -1639,3 +1639,128 @@ describe('findFailedTraceBlock', () => { expect(findFailedTraceBlock(root([span({ blockId: 'ok', status: 'success' })]))).toBeNull() }) }) + +describe('child deployment version on spans', () => { + const baseLog = { + startedAt: '2024-01-01T10:00:00.000Z', + endedAt: '2024-01-01T10:00:02.000Z', + durationMs: 2000, + executionOrder: 1, + input: {}, + } + + function spanFor(log: Record): TraceSpan { + const { traceSpans } = buildTraceSpans({ + success: true, + output: {}, + logs: [{ ...baseLog, ...log }], + } as unknown as ExecutionResult) + return traceSpans[0].children?.find((s) => s.blockId === log.blockId) ?? traceSpans[0] + } + + function agentToolSpan(name: string, result: Record, withSegments: boolean) { + const toolCall = { + name, + arguments: {}, + result, + startTime: '2024-01-01T10:00:00.500Z', + endTime: '2024-01-01T10:00:01.500Z', + duration: 1000, + } + const agent = spanFor({ + blockId: 'agent-1', + blockName: 'Agent 1', + blockType: 'agent', + success: true, + output: { + content: 'done', + toolCalls: { list: [toolCall], count: 1 }, + ...(withSegments + ? { + providerTiming: { + duration: 2000, + startTime: baseLog.startedAt, + endTime: baseLog.endedAt, + timeSegments: [ + { + type: 'tool', + name, + startTime: Date.parse(toolCall.startTime), + endTime: Date.parse(toolCall.endTime), + duration: 1000, + }, + ], + }, + } + : {}), + }, + }) + return agent.children?.find((s) => s.type === 'tool') + } + + it('records the version a workflow block ran, on success and on failure', () => { + const succeeded = spanFor({ + blockId: 'wf-1', + blockName: 'Score', + blockType: 'workflow_input', + success: true, + output: { + result: { score: 3 }, + childWorkflowId: 'child-1', + childDeploymentVersionId: 'dv-7', + }, + }) + const failed = spanFor({ + blockId: 'wf-2', + blockName: 'Score', + blockType: 'workflow', + success: false, + error: 'boom', + output: { error: 'boom', childDeploymentVersionId: 'dv-8' }, + }) + + expect(succeeded.childDeploymentVersionId).toBe('dv-7') + expect(succeeded.output).not.toHaveProperty('childDeploymentVersionId') + expect(failed.childDeploymentVersionId).toBe('dv-8') + }) + + it('does not take the version from a non-workflow block that returns the same key', () => { + const span = spanFor({ + blockId: 'fn-1', + blockName: 'Function 1', + blockType: 'function', + success: true, + output: { result: 1, childDeploymentVersionId: 'forged' }, + }) + + expect(span.childDeploymentVersionId).toBeUndefined() + expect(span.output?.childDeploymentVersionId).toBe('forged') + }) + + it.each([true, false])( + 'records the version a workflow Agent tool ran (time segments: %s)', + (withSegments) => { + const toolSpan = agentToolSpan( + 'workflow_executor', + { success: true, result: {}, childDeploymentVersionId: 'dv-9' }, + withSegments + ) + + expect(toolSpan?.childDeploymentVersionId).toBe('dv-9') + } + ) + + it.each([true, false])( + 'ignores the key on any other Agent tool (time segments: %s)', + (withSegments) => { + const toolSpan = agentToolSpan( + 'http_request', + { childDeploymentVersionId: 'forged' }, + withSegments + ) + + expect(toolSpan).toBeDefined() + expect(toolSpan?.childDeploymentVersionId).toBeUndefined() + } + ) +}) diff --git a/apps/sim/lib/logs/execution/trace-spans/trace-spans.ts b/apps/sim/lib/logs/execution/trace-spans/trace-spans.ts index f8929473f39..f56f2d8e732 100644 --- a/apps/sim/lib/logs/execution/trace-spans/trace-spans.ts +++ b/apps/sim/lib/logs/execution/trace-spans/trace-spans.ts @@ -233,6 +233,8 @@ interface FailedSpanCandidate { endedAt: number /** The block log's error, which the span builder merges into its output. */ recordedError: string | undefined + /** A Function block's thrown message alone, which its failed output also carries. */ + recordedErrorMessage: string | undefined } /** The innermost unhandled-error block spans: a container whose failure came from a block inside it yields that block. */ @@ -258,6 +260,10 @@ function collectFailedBlockSpans(nodes: unknown, into: FailedSpanCandidate[]): v isRecordLike(span.output) && typeof span.output.error === 'string' ? span.output.error : undefined, + recordedErrorMessage: + isRecordLike(span.output) && typeof span.output.errorMessage === 'string' + ? span.output.errorMessage + : undefined, }) } } @@ -287,6 +293,32 @@ function collectFailedBlockSpans(nodes: unknown, into: FailedSpanCandidate[]): v * was compacted, or is unavailable. */ export function findFailedTraceBlock(spans: unknown, runError?: string): FailedTraceBlock | null { + return selectFailedSpan(spans, runError)?.block ?? null +} + +/** A failed run's block with the error its output recorded, as a log read leads with it. */ +export interface TraceFailure extends FailedTraceBlock { + /** The block's error as recorded: a Function's leads with the line and code that threw. */ + error: string | null + /** The block's declared `errorMessage` output (a Function's thrown message alone), else null. */ + errorMessage: string | null +} + +/** + * {@link findFailedTraceBlock} with the error the block recorded, so a reader of a run's log sees + * what failed before the rest of the record. Null on the same conditions. + */ +export function findTraceFailure(spans: unknown, runError?: string): TraceFailure | null { + const failed = selectFailedSpan(spans, runError) + if (!failed) return null + return { + ...failed.block, + error: failed.recordedError ?? null, + errorMessage: failed.recordedErrorMessage ?? null, + } +} + +function selectFailedSpan(spans: unknown, runError?: string): FailedSpanCandidate | null { const candidates: FailedSpanCandidate[] = [] collectFailedBlockSpans(spans, candidates) const pool = runError @@ -294,10 +326,10 @@ export function findFailedTraceBlock(spans: unknown, runError?: string): FailedT (span) => errorNamesBlock(runError, span.block.blockName) || span.recordedError === runError ) : candidates - if (pool.length <= 1) return pool[0]?.block ?? null + if (pool.length <= 1) return pool[0] ?? null if (!pool.every((span) => Number.isFinite(span.endedAt))) return null const [first, second] = pool.sort((a, b) => a.endedAt - b.endedAt) - return first.endedAt < second.endedAt ? first.block : null + return first.endedAt < second.endedAt ? first : null } interface DurationBearingSpan { diff --git a/apps/sim/lib/logs/types.ts b/apps/sim/lib/logs/types.ts index 186a7140ced..8929615d21c 100644 --- a/apps/sim/lib/logs/types.ts +++ b/apps/sim/lib/logs/types.ts @@ -296,6 +296,12 @@ export interface TraceSpan { output?: Record childWorkflowSnapshotId?: string childWorkflowId?: string + /** + * The deployment version a child workflow call ran, on a workflow block's span or a + * `workflow_executor` Agent tool span. Absent for draft children and custom blocks. It names the + * stored version, not later variable edits or block migrations applied when it was loaded. + */ + childDeploymentVersionId?: string /** * For a custom-block span: the child run's own execution id, in the SOURCE * workspace. Only this opaque handle is persisted — the child's spans are diff --git a/apps/sim/lib/model-router/resolve.test.ts b/apps/sim/lib/model-router/resolve.test.ts index 98542cb5202..5226bd2778c 100644 --- a/apps/sim/lib/model-router/resolve.test.ts +++ b/apps/sim/lib/model-router/resolve.test.ts @@ -27,6 +27,7 @@ import { addAutoRoutingCost, resolveAutoModel, } from '@/lib/model-router/resolve' +import { ModelRouterRequest } from '@/lib/mothership/generated/model-router' import type { ExecutionContext } from '@/executor/types' import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' @@ -173,6 +174,21 @@ describe('resolveAutoModel', () => { expect(result.billableRoutingCost).toBeCloseTo(0.002) }) + it('sends a request body the worker contract accepts', async () => { + // The worker answers 400 to a body its contract rejects, e.g. a tier id outside its alphabet. + mockFetchWorker.mockResolvedValue(routerResponse(null, false, 503)) + await resolveAutoModel({ + ctx, + blockId: 'b1', + signals: makeSignals(), + fallbackModel: 'claude-sonnet-5', + }) + const init = mockFetchWorker.mock.lastCall?.[1] as RequestInit | undefined + const parsed = ModelRouterRequest.safeParse(JSON.parse(String(init?.body))) + expect(parsed.error).toBeUndefined() + expect(parsed.data?.candidates.map((c) => c.id)).toEqual(['1', '2', '3']) + }) + it('does not bill when the response omits billable (fail-safe)', async () => { mockFetchWorker.mockResolvedValue( routerResponse({ @@ -210,7 +226,9 @@ describe('resolveAutoModel', () => { it('falls back when every pool model is denied by workspace permissions', async () => { mockFetchWorker.mockResolvedValue(routerResponse({ choice: '1' })) - mockValidateModelProvider.mockRejectedValue(new Error('provider blocked')) + mockValidateModelProvider.mockImplementation(async (_userId, _workspaceId, model) => { + if (model !== 'sim-auto') throw new Error('provider blocked') + }) const result = await resolveAutoModel({ ctx, blockId: 'b1', @@ -220,4 +238,36 @@ describe('resolveAutoModel', () => { expect(result.model).toBe('claude-sonnet-5') expect(result.decidedBy).toBe('fallback') }) + + it('refuses a denied sim-auto instead of running a pool or fallback model', async () => { + mockFetchWorker.mockResolvedValue(routerResponse({ choice: '1' })) + const denied = new Error('Model sim-auto is not allowed') + mockValidateModelProvider.mockImplementation(async (_userId, _workspaceId, model) => { + if (model === 'sim-auto') throw denied + }) + + await expect( + resolveAutoModel({ + ctx, + blockId: 'b1', + signals: makeSignals(), + fallbackModel: 'claude-sonnet-5', + }) + ).rejects.toBe(denied) + expect(mockFetchWorker).not.toHaveBeenCalled() + + setEnvFlags({ isHosted: false }) + try { + await expect( + resolveAutoModel({ + ctx, + blockId: 'b1', + signals: makeSignals(), + fallbackModel: 'claude-sonnet-5', + }) + ).rejects.toBe(denied) + } finally { + setEnvFlags({ isHosted: true }) + } + }) }) diff --git a/apps/sim/lib/model-router/resolve.ts b/apps/sim/lib/model-router/resolve.ts index 327c4624ad0..b087e5c073e 100644 --- a/apps/sim/lib/model-router/resolve.ts +++ b/apps/sim/lib/model-router/resolve.ts @@ -13,6 +13,7 @@ import { getMothershipBaseURL } from '@/lib/mothership/server/agent-url' import { validateModelProvider } from '@/ee/access-control/utils/permission-check' import type { ExecutionContext } from '@/executor/types' import type { ModelCost } from '@/providers/cost-policy' +import { SIM_AUTO_MODEL_ID } from '@/providers/models' import { getProviderFromModel } from '@/providers/utils' const logger = createLogger('ModelRouter') @@ -247,11 +248,13 @@ async function callModelRouter( } /** - * Resolves the sim-auto pseudo-model to a concrete model for one block - * execution. Never throws and never fails the workflow: any error, timeout, - * non-hosted deployment, or fully unavailable pool column falls back to - * `fallbackModel` (the block's standard default). Callers must supply the same already-projected - * model-facing signals they pass to their provider boundary; this router never rescans them. + * Resolves the sim-auto pseudo-model to a concrete model for one block execution. Like any + * model check it throws when the workspace's permission group denies sim-auto itself or its + * permission config cannot be loaded. Otherwise it never fails the workflow: any error, + * timeout, non-hosted deployment, or fully unavailable pool column falls back to + * `fallbackModel` (the block's standard default). Callers must supply the same + * already-projected model-facing signals they pass to their provider boundary; this router + * never rescans them. */ export async function resolveAutoModel(args: { ctx: ExecutionContext @@ -260,6 +263,8 @@ export async function resolveAutoModel(args: { fallbackModel: string }): Promise { const { ctx, blockId, signals, fallbackModel } = args + // Before any fallback: a denied sim-auto must not run as whichever model is allowed. + await validateModelProvider(ctx.userId, ctx.workspaceId ?? undefined, SIM_AUTO_MODEL_ID, ctx) const fallback: AutoRoutingResult = { model: fallbackModel, tier: null, diff --git a/apps/sim/lib/mothership/agent-cli/curation.test.ts b/apps/sim/lib/mothership/agent-cli/curation.test.ts index 4d4b5b9d583..5392f3cce67 100644 --- a/apps/sim/lib/mothership/agent-cli/curation.test.ts +++ b/apps/sim/lib/mothership/agent-cli/curation.test.ts @@ -56,6 +56,7 @@ function blockDetail(): V2BlockDetail { }, tools: ['slack_send', 'slack_canvas'].map((id) => ({ id, + effect: 'write', name: id, description: '', hostedApiKey: 'none', diff --git a/apps/sim/lib/mothership/agent-cli/resource-effects.test.ts b/apps/sim/lib/mothership/agent-cli/resource-effects.test.ts index 25287a6e7cf..3fcda7f859f 100644 --- a/apps/sim/lib/mothership/agent-cli/resource-effects.test.ts +++ b/apps/sim/lib/mothership/agent-cli/resource-effects.test.ts @@ -206,6 +206,7 @@ describe('confirmed CLI resource effects', () => { startedAt: table.createdAt, endedAt: table.updatedAt, totalDurationMs: 10, + failure: null, files: null, executedByEmail: null, workflow: { diff --git a/apps/sim/lib/mothership/assistant/tool-policy.test.ts b/apps/sim/lib/mothership/assistant/tool-policy.test.ts index c56349cadce..8624b1d913e 100644 --- a/apps/sim/lib/mothership/assistant/tool-policy.test.ts +++ b/apps/sim/lib/mothership/assistant/tool-policy.test.ts @@ -7,7 +7,8 @@ import type { ToolMetadata } from '@/tools/metadata' const tool: ToolMetadata = { id: 'google_drive_get_file', - assistant: { effect: 'read', version: 1 }, + effect: 'read', + assistant: { version: 1 }, oauth: { required: true, provider: 'google-drive', authoritativeParams: ['instanceUrl'] }, params: { credential: { type: 'string', visibility: 'user-only' }, @@ -21,7 +22,8 @@ const tool: ToolMetadata = { describe('Assistant integration policy', () => { const tokenTool: ToolMetadata = { id: 'gitlab_list_projects', - assistant: { effect: 'read', version: 1 }, + effect: 'read', + assistant: { version: 1 }, personalToken: { provider: 'gitlab', tokenParam: 'accessToken', hostParam: 'host' }, params: { accessToken: { type: 'string', required: true, visibility: 'user-only' }, @@ -66,12 +68,16 @@ describe('Assistant integration policy', () => { const writeTool: ToolMetadata = { ...tool, id: 'gmail_draft_v2', - assistant: { effect: 'write', version: 1 }, + effect: 'write', + assistant: { version: 1 }, oauth: { required: true, provider: 'google-email' }, } - expect(() => + expect( assertAssistantIntegrationCall(writeTool, { credential: 'mine', body: 'Reviewed draft' }) - ).not.toThrow() + ).toEqual({ credentialId: 'mine', operation: { effect: 'write', version: 1 } }) + expect(assertAssistantIntegrationCall(tool, { credential: 'mine' }).operation.effect).toBe( + 'read' + ) expect(() => assertAssistantIntegrationCall(writeTool, { body: 'Missing account' })).toThrow( 'Select one' ) diff --git a/apps/sim/lib/mothership/assistant/tool-policy.ts b/apps/sim/lib/mothership/assistant/tool-policy.ts index 00b4bbb83fc..b8babcc8cb0 100644 --- a/apps/sim/lib/mothership/assistant/tool-policy.ts +++ b/apps/sim/lib/mothership/assistant/tool-policy.ts @@ -82,5 +82,5 @@ export function assertAssistantIntegrationCall( 'Select one of your connected accounts for this integration.' ) } - return { credentialId, operation: tool.assistant } + return { credentialId, operation: { effect: tool.effect, version: tool.assistant.version } } } diff --git a/apps/sim/lib/mothership/chat/payload.test.ts b/apps/sim/lib/mothership/chat/payload.test.ts index d4c211bc017..36aaace318b 100644 --- a/apps/sim/lib/mothership/chat/payload.test.ts +++ b/apps/sim/lib/mothership/chat/payload.test.ts @@ -108,6 +108,7 @@ vi.mocked(getToolMetadata).mockImplementation((id) => : id === 'gmail_send' ? { id, + effect: 'write', params: { accessToken: { type: 'string', visibility: 'hidden', required: true } }, oauth: { required: true, provider: 'google-email' }, } diff --git a/apps/sim/lib/mothership/chat/payload.ts b/apps/sim/lib/mothership/chat/payload.ts index d9f632113e4..94b779de87c 100644 --- a/apps/sim/lib/mothership/chat/payload.ts +++ b/apps/sim/lib/mothership/chat/payload.ts @@ -335,7 +335,7 @@ async function buildIntegrationToolSchemaVariant( ...(options.personalAccountsOnly && toolConfig.assistant ? { assistant: { - effect: toolConfig.assistant.effect, + effect: toolConfig.effect, version: toolConfig.assistant.version, }, } diff --git a/apps/sim/lib/mothership/chat/post.test.ts b/apps/sim/lib/mothership/chat/post.test.ts index d26c4fca429..e1614835d23 100644 --- a/apps/sim/lib/mothership/chat/post.test.ts +++ b/apps/sim/lib/mothership/chat/post.test.ts @@ -904,7 +904,7 @@ describe('handleUnifiedChatPost', () => { it('routes workflow-attached chat requests through the copilot backend path', async () => { const response = await handleUnifiedChatPost( - new NextRequest('http://localhost/api/copilot/chat', { + new NextRequest('http://localhost/api/mothership/chat', { method: 'POST', body: JSON.stringify({ message: 'Hello', @@ -976,7 +976,7 @@ describe('handleUnifiedChatPost', () => { it('routes workspace chat requests through the mothership backend path', async () => { const response = await handleUnifiedChatPost( - new NextRequest('http://localhost/api/copilot/chat', { + new NextRequest('http://localhost/api/mothership/chat', { method: 'POST', body: JSON.stringify({ message: 'Hello', @@ -1023,7 +1023,7 @@ describe('handleUnifiedChatPost', () => { it('never persists browser tab attachments, which the desktop app restores itself', async () => { const response = await handleUnifiedChatPost( - new NextRequest('http://localhost/api/copilot/chat', { + new NextRequest('http://localhost/api/mothership/chat', { method: 'POST', body: JSON.stringify({ message: 'Continue in this browser', @@ -1059,7 +1059,7 @@ describe('handleUnifiedChatPost', () => { active: index === 11, })) const response = await handleUnifiedChatPost( - new NextRequest('http://localhost/api/copilot/chat', { + new NextRequest('http://localhost/api/mothership/chat', { method: 'POST', body: JSON.stringify({ message: 'Inspect every open shell', @@ -1085,7 +1085,7 @@ describe('handleUnifiedChatPost', () => { content: 'authorized table', }) const response = await handleUnifiedChatPost( - new NextRequest('http://localhost/api/copilot/chat', { + new NextRequest('http://localhost/api/mothership/chat', { method: 'POST', body: JSON.stringify({ message: 'Summarize this view', @@ -1138,7 +1138,7 @@ describe('handleUnifiedChatPost', () => { }) const currentView = { viewId: 'all-view', filter: null, sort: null } const response = await handleUnifiedChatPost( - new NextRequest('http://localhost/api/copilot/chat', { + new NextRequest('http://localhost/api/mothership/chat', { method: 'POST', body: JSON.stringify({ message: 'This view', @@ -1171,7 +1171,7 @@ describe('handleUnifiedChatPost', () => { it('validates selection snapshots and omits unsafe browser source URLs', async () => { const response = await handleUnifiedChatPost( - new NextRequest('http://localhost/api/copilot/chat', { + new NextRequest('http://localhost/api/mothership/chat', { method: 'POST', body: JSON.stringify({ message: 'Explain these selections', @@ -1238,7 +1238,7 @@ describe('handleUnifiedChatPost', () => { it('rejects invalid terminal selection line ranges', async () => { const response = await handleUnifiedChatPost( - new NextRequest('http://localhost/api/copilot/chat', { + new NextRequest('http://localhost/api/mothership/chat', { method: 'POST', body: JSON.stringify({ message: 'Explain this selection', @@ -1266,7 +1266,7 @@ describe('handleUnifiedChatPost', () => { it('passes browser attachment metadata without advertising an unavailable browser agent', async () => { const response = await handleUnifiedChatPost( - new NextRequest('http://localhost/api/copilot/chat', { + new NextRequest('http://localhost/api/mothership/chat', { method: 'POST', body: JSON.stringify({ message: 'Explain the selected page', @@ -1300,7 +1300,7 @@ describe('handleUnifiedChatPost', () => { async function sendBrowserTab(tab: { title: string; url: string }): Promise { const response = await handleUnifiedChatPost( - new NextRequest('http://localhost/api/copilot/chat', { + new NextRequest('http://localhost/api/mothership/chat', { method: 'POST', body: JSON.stringify({ message: 'What is this page?', @@ -1345,7 +1345,7 @@ describe('handleUnifiedChatPost', () => { loadChatMcpServerIds.mockResolvedValue(['mcp-server-1']) const response = await handleUnifiedChatPost( - new NextRequest('http://localhost/api/copilot/chat', { + new NextRequest('http://localhost/api/mothership/chat', { method: 'POST', body: JSON.stringify({ message: 'now search billing', @@ -1374,7 +1374,7 @@ describe('handleUnifiedChatPost', () => { loadChatMcpServerIds.mockResolvedValue(['mcp-server-1']) const response = await handleUnifiedChatPost( - new NextRequest('http://localhost/api/copilot/chat', { + new NextRequest('http://localhost/api/mothership/chat', { method: 'POST', body: JSON.stringify({ message: '/Docs /Issues cross-reference', @@ -1396,7 +1396,7 @@ describe('handleUnifiedChatPost', () => { it('persists cancelled partial responses from the server lifecycle', async () => { await handleUnifiedChatPost( - new NextRequest('http://localhost/api/copilot/chat', { + new NextRequest('http://localhost/api/mothership/chat', { method: 'POST', body: JSON.stringify({ message: 'Hello', @@ -1438,7 +1438,7 @@ describe('handleUnifiedChatPost', () => { it('persists partial responses when the server lifecycle throws (onError)', async () => { await handleUnifiedChatPost( - new NextRequest('http://localhost/api/copilot/chat', { + new NextRequest('http://localhost/api/mothership/chat', { method: 'POST', body: JSON.stringify({ message: 'Hello', @@ -1485,7 +1485,7 @@ describe('handleUnifiedChatPost', () => { 'persists an empty failure with result metadata present=%s', async (hasResult) => { await handleUnifiedChatPost( - new NextRequest('http://localhost/api/copilot/chat', { + new NextRequest('http://localhost/api/mothership/chat', { method: 'POST', body: JSON.stringify({ message: 'Hello', @@ -1528,7 +1528,7 @@ describe('handleUnifiedChatPost', () => { it('republishes completed status when cancelled lifecycle persistence already ran', async () => { await handleUnifiedChatPost( - new NextRequest('http://localhost/api/copilot/chat', { + new NextRequest('http://localhost/api/mothership/chat', { method: 'POST', body: JSON.stringify({ message: 'Hello', @@ -1572,7 +1572,7 @@ describe('handleUnifiedChatPost', () => { it('rejects requests that have neither workflow nor workspace attachment', async () => { const response = await handleUnifiedChatPost( - new NextRequest('http://localhost/api/copilot/chat', { + new NextRequest('http://localhost/api/mothership/chat', { method: 'POST', body: JSON.stringify({ message: 'Hello', @@ -1820,7 +1820,7 @@ describe('handleUnifiedChatPost copilot.use capability gate', () => { function chatRequest(body: Record = {}) { return createMockRequest({ method: 'POST', - url: 'http://localhost/api/copilot/chat', + url: 'http://localhost/api/mothership/chat', body: { message: 'Hello', workspaceId: 'ws-1', ...body }, }) } @@ -1918,7 +1918,7 @@ describe('handleUnifiedChatPost copilot.use capability gate', () => { }) const response = await handleUnifiedChatPost( - new NextRequest('http://localhost/api/copilot/chat', { + new NextRequest('http://localhost/api/mothership/chat', { method: 'POST', body: JSON.stringify({ message: 'Hello', workflowId: 'wf-1', createNewChat: true }), }) @@ -2028,7 +2028,7 @@ describe('handleUnifiedChatPost copilot.use capability gate', () => { }) const response = await handleUnifiedChatPost( - new NextRequest('http://localhost/api/copilot/chat', { + new NextRequest('http://localhost/api/mothership/chat', { method: 'POST', body: JSON.stringify({ message: 'Hello', workflowId: 'wf-1', createNewChat: true }), }) diff --git a/apps/sim/lib/mothership/generated/docs-manifest.ts b/apps/sim/lib/mothership/generated/docs-manifest.ts index cb6256a2947..48599cca1b1 100644 --- a/apps/sim/lib/mothership/generated/docs-manifest.ts +++ b/apps/sim/lib/mothership/generated/docs-manifest.ts @@ -500,6 +500,21 @@ export const DOCS_MANIFEST: readonly string[] = [ 'workflows/blocks/webhook.mdx', 'workflows/blocks/workflow.mdx', 'workflows/code.mdx', + 'workflows/code/adopt.mdx', + 'workflows/code/ci.mdx', + 'workflows/code/coding-agents.mdx', + 'workflows/code/create.mdx', + 'workflows/code/diagnostics.mdx', + 'workflows/code/directory.mdx', + 'workflows/code/edit.mdx', + 'workflows/code/exit-codes.mdx', + 'workflows/code/get-started.mdx', + 'workflows/code/how-it-works.mdx', + 'workflows/code/limits.mdx', + 'workflows/code/promote.mdx', + 'workflows/code/syntax.mdx', + 'workflows/code/troubleshooting.mdx', + 'workflows/code/workspace.mdx', 'workflows/connections.mdx', 'workflows/data-flow.mdx', 'workflows/deployment.mdx', @@ -516,5 +531,4 @@ export const DOCS_MANIFEST: readonly string[] = [ 'workflows/triggers/table.mdx', 'workflows/triggers/webhook.mdx', 'workflows/variables.mdx', - 'workflows/workspace-code.mdx', ] diff --git a/apps/sim/lib/mothership/generated/model-router.ts b/apps/sim/lib/mothership/generated/model-router.ts index 27fa5425a51..30f40e4a71f 100644 --- a/apps/sim/lib/mothership/generated/model-router.ts +++ b/apps/sim/lib/mothership/generated/model-router.ts @@ -10,8 +10,19 @@ import { z } from "zod"; * Internal-key only: customer keys never reach it. */ export const ModelRouterCandidate = z.strictObject({ - /** The token the classifier answers with, e.g. "1". */ - id: z.string().trim().min(1).max(32).regex(/^\S+$/, "a candidate id is a single token"), + /** + * The token the classifier answers with, e.g. "1": ASCII letters, digits, `_` and `-`, starting + * and ending with a letter or digit. Edge punctuation is reserved for the wrapping a model puts + * around its answer (`"2".`, `**fast**`), so the worker strips it without ever turning one + * candidate's id into another's. + */ + id: z + .string() + .max(32) + .regex( + /^[A-Za-z0-9](?:[\w-]*[A-Za-z0-9])?$/, + "a candidate id is letters, digits, _ and -, starting and ending with a letter or digit", + ), /** One line saying when this candidate fits. */ hint: z.string().max(500), }); diff --git a/apps/sim/lib/mothership/generated/mothership-stream-v1.ts b/apps/sim/lib/mothership/generated/mothership-stream-v1.ts index 9ed51b1338f..9fd393fe5d2 100644 --- a/apps/sim/lib/mothership/generated/mothership-stream-v1.ts +++ b/apps/sim/lib/mothership/generated/mothership-stream-v1.ts @@ -4,233 +4,353 @@ // The mothership-stream-v1 SSE wire: every `data:` frame the worker emits to Sim (each leg // ends with a literal `data: [DONE]` line), and the vocabulary Sim re-emits to the browser // (Sim adds `session` chat/title frames of its own). -// The worker's emitter (apps/server/src/protocol/envelope.ts) builds these envelopes, so a -// frame that drifts from what Sim parses fails typecheck. Each discriminant const below is -// checked against its payload union, because Sim's reader accepts exactly the const's values. - -import type { - StreamActivityCheckpoint, - StreamTextCompletion, - StreamTextPosition, - StreamToolDeadline, - StreamToolReplay, +// The zod schemas below are the single source (D122): every payload type is inferred from them, +// so the worker's emitter (apps/server/src/protocol/envelope.ts) fails typecheck on a frame that +// drifts, and a reader can validate a frame at runtime against the same definition. Each +// discriminant const below is checked against its payload union, because Sim's reader accepts +// exactly the const's values. Objects strip unknown keys: a newer emitter's extra field never +// fails a reader, except in a `resource` payload's `resource.search.nativeQueries` entries, which +// reuse Sim's strict model tool-input schema. +// Its own optional fields are `?: T` (`.exactOptional()`); the protocol.ts fields it spreads +// are `?: T | undefined`. + +import { z } from "zod"; +import { + StreamActivityCheckpointSchema, + StreamTextCompletionSchema, + StreamTextPositionSchema, + StreamToolDeadlineSchema, + StreamToolReplaySchema, } from "./protocol"; -import type { ResourcePayload } from "./resources"; +import { ResourcePayload } from "./resources"; -/** The shell every frame shares. */ -export interface MothershipStreamV1Envelope { - payload: TPayload; - scope?: MothershipStreamV1StreamScope; - seq: number; - stream: MothershipStreamV1StreamRef; - trace?: MothershipStreamV1Trace; - ts: string; - type: TType; - v: 1; -} +// Each value enum's const is its single source; its schema reads the const. -/** Every frame on the wire, one member per payload shape. */ -export type MothershipStreamV1EventEnvelope = - | MothershipStreamV1Envelope<"session", MothershipStreamV1SessionStartPayload> - | MothershipStreamV1Envelope<"session", MothershipStreamV1SessionChatPayload> - | MothershipStreamV1Envelope<"session", MothershipStreamV1SessionTitlePayload> - | MothershipStreamV1Envelope<"text", MothershipStreamV1TextPayload> - | MothershipStreamV1Envelope<"tool", MothershipStreamV1ToolCallDescriptor> - | MothershipStreamV1Envelope<"tool", MothershipStreamV1ToolArgsDeltaPayload> - | MothershipStreamV1Envelope<"tool", MothershipStreamV1ToolResultPayload> - | MothershipStreamV1Envelope<"span", MothershipStreamV1SubagentSpanPayload> - | MothershipStreamV1Envelope<"resource", ResourcePayload> - | MothershipStreamV1Envelope<"run", MothershipStreamV1CheckpointPausePayload> - | MothershipStreamV1Envelope<"run", MothershipStreamV1CompactionStartPayload> - | MothershipStreamV1Envelope<"run", MothershipStreamV1CompactionDonePayload> - | MothershipStreamV1Envelope<"run", MothershipStreamV1SteeringAppliedPayload> - | MothershipStreamV1Envelope<"run", MothershipStreamV1TaskArmedPayload> - | MothershipStreamV1Envelope<"run", MothershipStreamV1TaskDeliveredPayload> - | MothershipStreamV1Envelope<"error", MothershipStreamV1ErrorPayload> - | MothershipStreamV1Envelope<"complete", MothershipStreamV1CompletePayload>; - -/** The payload a frame of `type` carries. */ -type PayloadOf = Extract< - MothershipStreamV1EventEnvelope, - { type: TType } ->["payload"]; +export const MothershipStreamV1TextChannel = { + assistant: "assistant", + thinking: "thinking", +} as const; +export type MothershipStreamV1TextChannel = + (typeof MothershipStreamV1TextChannel)[keyof typeof MothershipStreamV1TextChannel]; -export type MothershipStreamV1TextChannel = "assistant" | "thinking"; /** * Where a tool call executes. `go` means the worker executes it: the name is a persisted * historical value (stored chat blocks and self-hosted Sims read it), so it stays on the wire. */ -export type MothershipStreamV1ToolExecutor = "go" | "sim" | "client"; -export type MothershipStreamV1ToolMode = "sync" | "async"; +export const MothershipStreamV1ToolExecutor = { + go: "go", + sim: "sim", + client: "client", +} as const; +export type MothershipStreamV1ToolExecutor = + (typeof MothershipStreamV1ToolExecutor)[keyof typeof MothershipStreamV1ToolExecutor]; + +export const MothershipStreamV1ToolMode = { + sync: "sync", + async: "async", +} as const; +export type MothershipStreamV1ToolMode = + (typeof MothershipStreamV1ToolMode)[keyof typeof MothershipStreamV1ToolMode]; + +export const MothershipStreamV1ToolStatus = { + generating: "generating", + awaiting_approval: "awaiting_approval", + executing: "executing", + success: "success", + error: "error", + cancelled: "cancelled", + skipped: "skipped", + rejected: "rejected", +} as const; export type MothershipStreamV1ToolStatus = - | "generating" - | "awaiting_approval" - | "executing" - | "success" - | "error" - | "cancelled" - | "skipped" - | "rejected"; -export type MothershipStreamV1CompletionStatus = "complete" | "error" | "cancelled"; - -export interface MothershipStreamV1StreamScope { - agentId?: string; - lane: "subagent"; - parentSpanId?: string; - parentToolCallId?: string; - spanId?: string; -} -export interface MothershipStreamV1StreamRef { - chatId?: string; - cursor?: string; - streamId: string; -} -export interface MothershipStreamV1Trace { - requestId: string; - spanId?: string; -} + (typeof MothershipStreamV1ToolStatus)[keyof typeof MothershipStreamV1ToolStatus]; -export interface MothershipStreamV1SessionStartPayload { - data?: MothershipStreamV1SessionStartData; - kind: "start"; -} -export interface MothershipStreamV1SessionStartData { - responseId?: string; -} -/** Emitted by Sim, not the worker. */ -export interface MothershipStreamV1SessionChatPayload { - chatId: string; - kind: "chat"; +export const MothershipStreamV1SpanLifecycleEvent = { + start: "start", + end: "end", +} as const; +export type MothershipStreamV1SpanLifecycleEvent = + (typeof MothershipStreamV1SpanLifecycleEvent)[keyof typeof MothershipStreamV1SpanLifecycleEvent]; + +export const MothershipStreamV1CompletionStatus = { + complete: "complete", + error: "error", + cancelled: "cancelled", +} as const; +export type MothershipStreamV1CompletionStatus = + (typeof MothershipStreamV1CompletionStatus)[keyof typeof MothershipStreamV1CompletionStatus]; + +const StreamScopeSchema = z.object({ + agentId: z.string().exactOptional(), + lane: z.literal("subagent"), + parentSpanId: z.string().exactOptional(), + parentToolCallId: z.string().exactOptional(), + spanId: z.string().exactOptional(), +}); +export type MothershipStreamV1StreamScope = z.infer; + +const StreamRefSchema = z.object({ + chatId: z.string().exactOptional(), + cursor: z.string().exactOptional(), + streamId: z.string().min(1), +}); +export type MothershipStreamV1StreamRef = z.infer; + +const TraceSchema = z.object({ + requestId: z.string(), + spanId: z.string().exactOptional(), +}); +export type MothershipStreamV1Trace = z.infer; + +const EnvelopeShellSchema = z.object({ + scope: StreamScopeSchema.exactOptional(), + seq: z.number(), + stream: StreamRefSchema, + trace: TraceSchema.exactOptional(), + ts: z.string(), + v: z.literal(1), +}); + +/** The shell every frame shares. */ +export interface MothershipStreamV1Envelope + extends z.infer { + payload: TPayload; + type: TType; } + +const SessionStartDataSchema = z.object({ responseId: z.string().exactOptional() }); +export type MothershipStreamV1SessionStartData = z.infer; + +const SessionStartPayloadSchema = z.object({ + data: SessionStartDataSchema.exactOptional(), + kind: z.literal("start"), +}); +export type MothershipStreamV1SessionStartPayload = z.infer; + /** Emitted by Sim, not the worker. */ -export interface MothershipStreamV1SessionTitlePayload { - kind: "title"; - title: string; -} +const SessionChatPayloadSchema = z.object({ chatId: z.string(), kind: z.literal("chat") }); +export type MothershipStreamV1SessionChatPayload = z.infer; -export interface MothershipStreamV1TextPayload extends StreamTextPosition { - channel: MothershipStreamV1TextChannel; - text: string; -} +/** Emitted by Sim, not the worker. */ +const SessionTitlePayloadSchema = z.object({ kind: z.literal("title"), title: z.string() }); +export type MothershipStreamV1SessionTitlePayload = z.infer; + +const TextPayloadSchema = z.object({ + ...StreamTextPositionSchema.shape, + channel: z.enum(MothershipStreamV1TextChannel), + text: z.string(), +}); +export type MothershipStreamV1TextPayload = z.infer; + +const ToolUISchema = z.object({ + clientExecutable: z.boolean().exactOptional(), + hidden: z.boolean().exactOptional(), + inbandOwned: z.boolean().exactOptional(), + internal: z.boolean().exactOptional(), + simExecutable: z.boolean().exactOptional(), +}); +export type MothershipStreamV1ToolUI = z.infer; + +const ToolCallDescriptorSchema = z.object({ + ...StreamToolReplaySchema.shape, + ...StreamToolDeadlineSchema.shape, + activityDescription: z.string().exactOptional(), + arguments: z.record(z.string(), z.unknown()).exactOptional(), + execName: z.string().exactOptional(), + executor: z.enum(MothershipStreamV1ToolExecutor), + mode: z.enum(MothershipStreamV1ToolMode), + partial: z.boolean().exactOptional(), + phase: z.literal("call"), + status: z.enum(MothershipStreamV1ToolStatus).exactOptional(), + toolCallId: z.string(), + toolName: z.string(), + ui: ToolUISchema.exactOptional(), +}); +export type MothershipStreamV1ToolCallDescriptor = z.infer; -export interface MothershipStreamV1ToolCallDescriptor extends StreamToolReplay, StreamToolDeadline { - activityDescription?: string; - arguments?: Record; - execName?: string; - executor: MothershipStreamV1ToolExecutor; - mode: MothershipStreamV1ToolMode; - partial?: boolean; - phase: "call"; - status?: MothershipStreamV1ToolStatus; - toolCallId: string; - toolName: string; - ui?: MothershipStreamV1ToolUI; -} -export interface MothershipStreamV1ToolUI { - clientExecutable?: boolean; - hidden?: boolean; - inbandOwned?: boolean; - internal?: boolean; - simExecutable?: boolean; -} /** Draw-only argument text as it generates; never replayed, never dispatched on. */ -export interface MothershipStreamV1ToolArgsDeltaPayload { - argumentsDelta: string; - phase: "args_delta"; - toolCallId: string; - toolName: string; -} -export interface MothershipStreamV1ToolResultPayload extends StreamToolReplay { - error?: string; - executor: MothershipStreamV1ToolExecutor; - mode: MothershipStreamV1ToolMode; - output?: unknown; - phase: "result"; - status?: MothershipStreamV1ToolStatus; - success: boolean; - toolCallId: string; - toolName: string; -} +const ToolArgsDeltaPayloadSchema = z.object({ + argumentsDelta: z.string(), + phase: z.literal("args_delta"), + toolCallId: z.string(), + toolName: z.string(), +}); +export type MothershipStreamV1ToolArgsDeltaPayload = z.infer; + +const ToolResultPayloadSchema = z.object({ + ...StreamToolReplaySchema.shape, + error: z.string().exactOptional(), + executor: z.enum(MothershipStreamV1ToolExecutor), + mode: z.enum(MothershipStreamV1ToolMode), + output: z.unknown().exactOptional(), + phase: z.literal("result"), + status: z.enum(MothershipStreamV1ToolStatus).exactOptional(), + success: z.boolean(), + toolCallId: z.string(), + toolName: z.string(), +}); +export type MothershipStreamV1ToolResultPayload = z.infer; /** A subagent lane's display title (on start) or failure (on end). */ -export interface MothershipStreamV1SubagentSpanData { - name?: string; - error?: string; -} +const SubagentSpanDataSchema = z.object({ + name: z.string().exactOptional(), + error: z.string().exactOptional(), +}); +export type MothershipStreamV1SubagentSpanData = z.infer; + +const SubagentSpanPayloadSchema = z.object({ + agent: z.string().exactOptional(), + data: SubagentSpanDataSchema.exactOptional(), + event: z.enum(MothershipStreamV1SpanLifecycleEvent), + kind: z.literal("subagent"), +}); +export type MothershipStreamV1SubagentSpanPayload = z.infer; + +const CheckpointPausePayloadSchema = z.object({ + ...StreamActivityCheckpointSchema.shape, + checkpointId: z.string(), + executionId: z.string(), + kind: z.literal("checkpoint_pause"), + pendingToolCallIds: z.array(z.string()), + runId: z.string(), +}); +export type MothershipStreamV1CheckpointPausePayload = z.infer; + +const CompactionStartPayloadSchema = z.object({ kind: z.literal("compaction_start") }); +export type MothershipStreamV1CompactionStartPayload = z.infer; + +const CompactionDonePayloadSchema = z.object({ kind: z.literal("compaction_done") }); +export type MothershipStreamV1CompactionDonePayload = z.infer; -export interface MothershipStreamV1SubagentSpanPayload { - agent?: string; - data?: MothershipStreamV1SubagentSpanData; - event: "start" | "end"; - kind: "subagent"; -} +/** + * A steer reached the run's model input (the loss-free ack for POST /api/streams/steer). + * `eventSeq` is as in SteerV2Response's `applied`; absent only on frames from workers without + * steer v2. + */ +const SteeringAppliedPayloadSchema = z.object({ + eventSeq: z.number().exactOptional(), + kind: z.literal("steering_applied"), + steeringId: z.string(), + textOffset: z.number().exactOptional(), +}); +export type MothershipStreamV1SteeringAppliedPayload = z.infer; + +const TaskArmedPayloadSchema = z.object({ + kind: z.literal("task_armed"), + note: z.string(), + target: z.record(z.string(), z.unknown()), + taskId: z.string(), + taskKind: z.enum(["timer", "workflow_run"]), +}); +export type MothershipStreamV1TaskArmedPayload = z.infer; + +const TaskDeliveredPayloadSchema = z.object({ + kind: z.literal("task_delivered"), + status: z.enum(["completed", "failed", "stopped", "expired"]), + summary: z.string(), + taskId: z.string(), +}); +export type MothershipStreamV1TaskDeliveredPayload = z.infer; -export interface MothershipStreamV1CheckpointPausePayload extends StreamActivityCheckpoint { - checkpointId: string; - executionId: string; - kind: "checkpoint_pause"; - pendingToolCallIds: string[]; - runId: string; -} -export interface MothershipStreamV1CompactionStartPayload { - kind: "compaction_start"; -} -export interface MothershipStreamV1CompactionDonePayload { - kind: "compaction_done"; -} -/** A steer reached the run's model input (the loss-free ack for POST /api/streams/steer). */ -export interface MothershipStreamV1SteeringAppliedPayload { - /** As in SteerV2Response's `applied`; absent only on frames from workers without steer v2. */ - eventSeq?: number; - kind: "steering_applied"; - steeringId: string; - textOffset?: number; -} -export interface MothershipStreamV1TaskArmedPayload { - kind: "task_armed"; - note: string; - target: Record; - taskId: string; - taskKind: "timer" | "workflow_run"; -} -export interface MothershipStreamV1TaskDeliveredPayload { - kind: "task_delivered"; - status: "completed" | "failed" | "stopped" | "expired"; - summary: string; - taskId: string; -} +/** + * `message` is required. `error` is a Sim-emitted copy of it (Sim's terminal-failure frame sets + * both) and `data` Sim-emitted detail (e.g. the replay-gap bounds); the worker sends neither. + * Sim's own emitters are typed by this schema, so none sends `error` without `message` (D122). + */ +const ErrorPayloadSchema = z.object({ + code: z.string().exactOptional(), + data: z.unknown().exactOptional(), + displayMessage: z.string().exactOptional(), + error: z.string().exactOptional(), + message: z.string(), + provider: z.string().exactOptional(), +}); +export type MothershipStreamV1ErrorPayload = z.infer; + +const CostDataSchema = z.object({ + input: z.number().exactOptional(), + output: z.number().exactOptional(), + total: z.number().exactOptional(), +}); +export type MothershipStreamV1CostData = z.infer; + +const UsageDataSchema = z.object({ + cache_creation_input_tokens: z.number().exactOptional(), + cache_read_input_tokens: z.number().exactOptional(), + input_tokens: z.number().exactOptional(), + model: z.string().exactOptional(), + output_tokens: z.number().exactOptional(), + total_tokens: z.number().exactOptional(), +}); +export type MothershipStreamV1UsageData = z.infer; + +const CompletePayloadSchema = z.object({ + ...StreamTextCompletionSchema.shape, + ...StreamActivityCheckpointSchema.shape, + cost: CostDataSchema.exactOptional(), + reason: z.string().exactOptional(), + response: z.unknown().exactOptional(), + status: z.enum(MothershipStreamV1CompletionStatus), + usage: UsageDataSchema.exactOptional(), +}); +export type MothershipStreamV1CompletePayload = z.infer; + +const SessionPayloadSchema = z.discriminatedUnion("kind", [ + SessionStartPayloadSchema, + SessionChatPayloadSchema, + SessionTitlePayloadSchema, +]); +const ToolPayloadSchema = z.discriminatedUnion("phase", [ + ToolCallDescriptorSchema, + ToolArgsDeltaPayloadSchema, + ToolResultPayloadSchema, +]); +const RunPayloadSchema = z.discriminatedUnion("kind", [ + CheckpointPausePayloadSchema, + CompactionStartPayloadSchema, + CompactionDonePayloadSchema, + SteeringAppliedPayloadSchema, + TaskArmedPayloadSchema, + TaskDeliveredPayloadSchema, +]); -export interface MothershipStreamV1ErrorPayload { - code?: string; - /** Sim-emitted detail (e.g. the replay-gap bounds); the worker sends none. */ - data?: unknown; - displayMessage?: string; - /** Sim-emitted alias of `message`; the worker sends none. */ - error?: string; - message: string; - provider?: string; -} +/** + * Every live frame on the wire. On success a reader keeps its own value, not the parsed copy: + * the copy has unknown keys stripped. Its inferred type is not distributed over the payloads; + * readers type a frame as {@link MothershipStreamV1EventEnvelope}. + */ +export const MothershipStreamV1EventEnvelopeSchema = z.discriminatedUnion("type", [ + EnvelopeShellSchema.extend({ type: z.literal("session"), payload: SessionPayloadSchema }), + EnvelopeShellSchema.extend({ type: z.literal("text"), payload: TextPayloadSchema }), + EnvelopeShellSchema.extend({ type: z.literal("tool"), payload: ToolPayloadSchema }), + EnvelopeShellSchema.extend({ type: z.literal("span"), payload: SubagentSpanPayloadSchema }), + EnvelopeShellSchema.extend({ type: z.literal("resource"), payload: ResourcePayload }), + EnvelopeShellSchema.extend({ type: z.literal("run"), payload: RunPayloadSchema }), + EnvelopeShellSchema.extend({ type: z.literal("error"), payload: ErrorPayloadSchema }), + EnvelopeShellSchema.extend({ type: z.literal("complete"), payload: CompletePayloadSchema }), +]); + +/** One envelope member per payload variant, so `Extract<…, { payload: { phase: "call" } }>` works. */ +type EnvelopesOf = TPayload extends unknown + ? MothershipStreamV1Envelope + : never; -export interface MothershipStreamV1CompletePayload extends StreamTextCompletion, StreamActivityCheckpoint { - cost?: MothershipStreamV1CostData; - reason?: string; - response?: unknown; - status: MothershipStreamV1CompletionStatus; - usage?: MothershipStreamV1UsageData; -} -export interface MothershipStreamV1CostData { - input?: number; - output?: number; - total?: number; -} -export interface MothershipStreamV1UsageData { - cache_creation_input_tokens?: number; - cache_read_input_tokens?: number; - input_tokens?: number; - model?: string; - output_tokens?: number; - total_tokens?: number; -} +/** Every frame on the wire, one member per payload shape. */ +export type MothershipStreamV1EventEnvelope = + | EnvelopesOf<"session", z.infer> + | EnvelopesOf<"text", MothershipStreamV1TextPayload> + | EnvelopesOf<"tool", z.infer> + | EnvelopesOf<"span", MothershipStreamV1SubagentSpanPayload> + | MothershipStreamV1Envelope<"resource", ResourcePayload> + | EnvelopesOf<"run", z.infer> + | EnvelopesOf<"error", MothershipStreamV1ErrorPayload> + | EnvelopesOf<"complete", MothershipStreamV1CompletePayload>; + +/** The payload a frame of `type` carries. */ +type PayloadOf = Extract< + MothershipStreamV1EventEnvelope, + { type: TType } +>["payload"]; export type MothershipStreamV1EventType = MothershipStreamV1EventEnvelope["type"]; @@ -253,11 +373,6 @@ export const MothershipStreamV1SessionKind = { start: "start", } as const satisfies { [K in MothershipStreamV1SessionKind]: K }; -export const MothershipStreamV1TextChannel = { - assistant: "assistant", - thinking: "thinking", -} as const satisfies { [K in MothershipStreamV1TextChannel]: K }; - export type MothershipStreamV1ToolPhase = PayloadOf<"tool">["phase"]; export const MothershipStreamV1ToolPhase = { @@ -266,41 +381,12 @@ export const MothershipStreamV1ToolPhase = { result: "result", } as const satisfies { [K in MothershipStreamV1ToolPhase]: K }; -export const MothershipStreamV1ToolExecutor = { - go: "go", - sim: "sim", - client: "client", -} as const satisfies { [K in MothershipStreamV1ToolExecutor]: K }; - -export const MothershipStreamV1ToolMode = { - sync: "sync", - async: "async", -} as const satisfies { [K in MothershipStreamV1ToolMode]: K }; - -export const MothershipStreamV1ToolStatus = { - generating: "generating", - awaiting_approval: "awaiting_approval", - executing: "executing", - success: "success", - error: "error", - cancelled: "cancelled", - skipped: "skipped", - rejected: "rejected", -} as const satisfies { [K in MothershipStreamV1ToolStatus]: K }; - export type MothershipStreamV1SpanPayloadKind = PayloadOf<"span">["kind"]; export const MothershipStreamV1SpanPayloadKind = { subagent: "subagent", } as const satisfies { [K in MothershipStreamV1SpanPayloadKind]: K }; -export type MothershipStreamV1SpanLifecycleEvent = PayloadOf<"span">["event"]; - -export const MothershipStreamV1SpanLifecycleEvent = { - start: "start", - end: "end", -} as const satisfies { [K in MothershipStreamV1SpanLifecycleEvent]: K }; - export type MothershipStreamV1ResourceOp = ResourcePayload["op"]; export const MothershipStreamV1ResourceOp = { @@ -321,12 +407,6 @@ export const MothershipStreamV1RunKind = { task_delivered: "task_delivered", } as const satisfies { [K in MothershipStreamV1RunKind]: K }; -export const MothershipStreamV1CompletionStatus = { - complete: "complete", - error: "error", - cancelled: "cancelled", -} as const satisfies { [K in MothershipStreamV1CompletionStatus]: K }; - /** The terminal outcomes Sim reports for a tool call it executed (a subset of the tool status). */ export type MothershipStreamV1ToolOutcome = Extract< MothershipStreamV1ToolStatus, @@ -340,3 +420,49 @@ export const MothershipStreamV1ToolOutcome = { skipped: "skipped", rejected: "rejected", } as const satisfies { [K in MothershipStreamV1ToolOutcome]: K }; + +// The replay-end control frame (D117, D121). POST /api/streams/replay ends a leg short of the run's +// terminal with this one `run` frame. It is deliberately NOT a member of +// `MothershipStreamV1EventEnvelope` and its kind is NOT in `MothershipStreamV1RunKind`: Sim's live +// reader accepts exactly that const's kinds, so a replay_end arriving on a live stream is rejected, +// and only Sim's replay reader, which checks for this frame before its v1 validation, accepts it. + +export const MothershipStreamV1ReplayEndKind = "replay_end"; + +/** + * Why a replay leg ended before the run's terminal. `parked`: the run waits on tool results the + * owner's leg handed Sim. `cap`: the connection reached its length cap; replay again. `stalled`: no + * instance drives the run (stale heartbeat, not parked); replay again later, once a takeover can + * have resumed it. + */ +export const MothershipStreamV1ReplayEndReason = { + parked: "parked", + cap: "cap", + stalled: "stalled", +} as const; +export type MothershipStreamV1ReplayEndReason = + (typeof MothershipStreamV1ReplayEndReason)[keyof typeof MothershipStreamV1ReplayEndReason]; + +/** + * `textLength` is the main text this leg's log reached — diagnostic only. A later replay sends + * Sim's OWN received length as `receivedTextChars`, never this value: the log trails live text, and + * resending from the durable end is what exposes divergence. Replayed tool activity is presentation + * only (`replay: true`) and never authorizes execution. + */ +export const MothershipStreamV1ReplayEndPayloadSchema = z.object({ + kind: z.literal(MothershipStreamV1ReplayEndKind), + reason: z.enum(MothershipStreamV1ReplayEndReason), + textLength: z.number().int().nonnegative(), +}); +export type MothershipStreamV1ReplayEndPayload = z.infer; + +/** The replay-end frame, validated on its own: it is outside the live envelope union. */ +export const MothershipStreamV1ReplayEndEnvelopeSchema = EnvelopeShellSchema.extend({ + type: z.literal(MothershipStreamV1EventType.run), + payload: MothershipStreamV1ReplayEndPayloadSchema, +}); + +export type MothershipStreamV1ReplayEndEnvelope = MothershipStreamV1Envelope< + typeof MothershipStreamV1EventType.run, + MothershipStreamV1ReplayEndPayload +>; diff --git a/apps/sim/lib/mothership/generated/protocol.ts b/apps/sim/lib/mothership/generated/protocol.ts index 9c4d1f00e1b..4cd2319d58d 100644 --- a/apps/sim/lib/mothership/generated/protocol.ts +++ b/apps/sim/lib/mothership/generated/protocol.ts @@ -271,27 +271,36 @@ export const ChatPayloadSchema = z ctx.addIssue({ code: "custom", message: "Assistant context requires Assistant mode" }); }); +// The stream fields mothership-stream-v1 payloads share. Each is `?: T | undefined`, so +// `.optional()`; the stream file spreads these shapes into its payload schemas. + /** A pause or terminal acknowledges all preceding activity only after the receiver handles it. */ -export interface StreamActivityCheckpoint { - activityReceipt?: StreamActivityReceipt | undefined; -} +export const StreamActivityCheckpointSchema = z.object({ + activityReceipt: ActivityReceiptSchema.optional(), +}); +export type StreamActivityCheckpoint = z.infer; /** Main-assistant text position within this run, measured in UTF-16 code units. */ -export interface StreamTextPosition { - textOffset?: number | undefined; -} +export const StreamTextPositionSchema = z.object({ + textOffset: z.number().int().nonnegative().safe().optional(), +}); +export type StreamTextPosition = z.infer; /** Successful completion states the complete main-answer size, including any replayed prefix. */ -export interface StreamTextCompletion { - textLength?: number | undefined; -} +export const StreamTextCompletionSchema = z.object({ + textLength: z.number().int().nonnegative().safe().optional(), +}); +export type StreamTextCompletion = z.infer; -/** Replayed tool activity is presentation only; it never authorizes execution or approval. */ -export interface StreamToolReplay { - replay?: true | undefined; - /** Requested operation target, authorized independently by Sim. */ - workspaceId?: string | undefined; -} +/** + * Replayed tool activity is presentation only; it never authorizes execution or approval. + * `workspaceId` is the requested operation target, authorized independently by Sim. + */ +export const StreamToolReplaySchema = z.object({ + replay: z.literal(true).optional(), + workspaceId: z.string().optional(), +}); +export type StreamToolReplay = z.infer; /** * How long the worker waits for one handed tool call's result, measured from the hand-off. @@ -299,19 +308,17 @@ export interface StreamToolReplay { * re-run inherits what remains) and settles the call, cancellation included, by * `deadlineMs - TOOL_DEADLINE_SETTLE_MARGIN_MS`: approval wait, pickup, execution and lease * extensions all fit inside it. Sim policy may only end a call sooner. Absent = the - * receiver's own bounds. + * receiver's own bounds. `waitTimeoutMs`, for a workflow tool (`run_workflow`, + * `run_workflow_until_block`, `run_from_block`, `run_block`) on a Sim that declares + * {@link WORKFLOW_TOOL_WAIT_TIMEOUT_CAPABILITY}: how long Sim waits for the call's run to + * settle once it starts waiting on it. A run still going then keeps going and the call settles + * with a {@link WorkflowToolRunningResult}. Absent = held until the run settles. */ -export interface StreamToolDeadline { - deadlineMs?: number | undefined; - /** - * For a workflow tool (`run_workflow`, `run_workflow_until_block`, `run_from_block`, - * `run_block`) on a Sim that declares {@link WORKFLOW_TOOL_WAIT_TIMEOUT_CAPABILITY}: how long - * Sim waits for the call's run to settle once it starts waiting on it. A run still going then - * keeps going and the call settles with a {@link WorkflowToolRunningResult}. Absent = held - * until the run settles. - */ - waitTimeoutMs?: number | undefined; -} +export const StreamToolDeadlineSchema = z.object({ + deadlineMs: z.number().int().positive().optional(), + waitTimeoutMs: z.number().int().positive().optional(), +}); +export type StreamToolDeadline = z.infer; /** * Room between Sim settling a call and the worker's own bound for it: Sim's resume-gate @@ -474,7 +481,7 @@ export type AbortRequest = z.infer; * durable log for a reader whose cursor fell off sim's replay ring. Read-only: the owner, * its emitter, its lease and its parked calls are untouched. The SSE leg restores what * the receipt lacks, follows the log, and ends with `complete` at a terminal or with one - * `run` frame of kind `replay_end` otherwise. + * `MothershipStreamV1ReplayEndEnvelope` (mothership-stream-v1.ts) otherwise. */ export const StreamReplayRequest = z.strictObject({ streamId: z.uuid(), @@ -485,23 +492,6 @@ export const StreamReplayRequest = z.strictObject({ }); export type StreamReplayRequest = z.infer; -/** - * A replay leg that ended before the run's terminal. `parked`: the run waits on tool - * results the owner's leg handed sim. `cap`: the connection reached its length cap; - * replay again. `stalled`: no instance drives the run (stale heartbeat, not parked); - * replay again later, once a takeover can have resumed it. - * `textLength` is the main text this leg's log reached — diagnostic only. A later - * replay sends sim's OWN received length as `receivedTextChars`, never this value: the - * log trails live text, and resending from the durable end is what exposes divergence. - * Replayed tool activity is presentation only (`replay: true`) and never authorizes - * execution. - */ -export interface StreamReplayEnd extends StreamTextCompletion { - kind: "replay_end"; - reason: "parked" | "cap" | "stalled"; - textLength: number; -} - /** Accepted Stop intent is distinct from an observed terminal worker run. */ export interface AbortResponse { stopped: boolean; diff --git a/apps/sim/lib/mothership/generated/resources.ts b/apps/sim/lib/mothership/generated/resources.ts index db50ef5b859..67c322ab540 100644 --- a/apps/sim/lib/mothership/generated/resources.ts +++ b/apps/sim/lib/mothership/generated/resources.ts @@ -41,8 +41,11 @@ export const SearchResource = z.object({ }); export type SearchResource = z.infer; +/** Resource frames and tool output cross versions, so an owner's unknown keys strip. */ +const ResourceOwner = z.object(FileOwner.shape); + export const ResourceAddress = z.object({ - owner: FileOwner.optional(), + owner: ResourceOwner.optional(), workspaceId: z.uuid().optional(), workspaceName: z.string().optional(), type: ResourceType, @@ -93,7 +96,7 @@ export const ResourceChange = z.discriminatedUnion("op", [ resource: z.union([ z.object({ type: ResourceType, - owner: FileOwner.optional(), + owner: ResourceOwner.optional(), workspaceId: z.uuid().optional(), id: z.string().regex(/\S/).optional(), }), diff --git a/apps/sim/lib/mothership/observability/metric-names.ts b/apps/sim/lib/mothership/observability/metric-names.ts index d26fe095e38..95f46aebfef 100644 --- a/apps/sim/lib/mothership/observability/metric-names.ts +++ b/apps/sim/lib/mothership/observability/metric-names.ts @@ -5,6 +5,7 @@ export const Metric = { CopilotDegradedCount: 'copilot.degraded.count', + CopilotStreamContractDisagreements: 'copilot.stream_contract.disagreements', CopilotToolCalls: 'copilot.tool.calls', CopilotToolDuration: 'copilot.tool.duration', } as const diff --git a/apps/sim/lib/mothership/observability/trace-attribute-values.ts b/apps/sim/lib/mothership/observability/trace-attribute-values.ts index 830bcffa42f..cb392fc4d39 100644 --- a/apps/sim/lib/mothership/observability/trace-attribute-values.ts +++ b/apps/sim/lib/mothership/observability/trace-attribute-values.ts @@ -113,6 +113,19 @@ export const CopilotStopOutcome = { ValidationError: 'validation_error', } as const +/** + * Which way the generated stream-contract schema disagrees with Sim's ingest validator on one + * worker frame: `schema_rejects` frames would start failing were the schema the validator. + */ +export const CopilotStreamContractDirection = { + SchemaAccepts: 'schema_accepts', + SchemaRejects: 'schema_rejects', +} as const + +/** One {@link CopilotStreamContractDirection} value, as the metric label carries it. */ +export type CopilotStreamContractDirectionValue = + (typeof CopilotStreamContractDirection)[keyof typeof CopilotStreamContractDirection] + export const CopilotSurface = { Copilot: 'copilot', Mothership: 'mothership', diff --git a/apps/sim/lib/mothership/observability/trace-attributes.ts b/apps/sim/lib/mothership/observability/trace-attributes.ts index def75de8727..3a1207fea16 100644 --- a/apps/sim/lib/mothership/observability/trace-attributes.ts +++ b/apps/sim/lib/mothership/observability/trace-attributes.ts @@ -122,6 +122,9 @@ export const TraceAttr = { CopilotStopContentLength: 'copilot.stop.content_length', CopilotStopOutcome: 'copilot.stop.outcome', CopilotStream: 'copilot.stream', + CopilotStreamContractDirection: 'copilot.stream_contract.direction', + CopilotStreamContractEventType: 'copilot.stream_contract.event_type', + CopilotStreamContractVariant: 'copilot.stream_contract.variant', CopilotSurface: 'copilot.surface', CopilotTableId: 'copilot.table.id', CopilotTableOutcome: 'copilot.table.outcome', diff --git a/apps/sim/lib/mothership/request/lifecycle/admission.ts b/apps/sim/lib/mothership/request/lifecycle/admission.ts index 9ab54475201..9fc13ac011e 100644 --- a/apps/sim/lib/mothership/request/lifecycle/admission.ts +++ b/apps/sim/lib/mothership/request/lifecycle/admission.ts @@ -6,7 +6,7 @@ import { COPILOT_BILLING_PROTOCOL_HEADER, requireBillingCallbackAttribution, } from '@/lib/billing/core/attribution' -import { isFreeRunPayer, readMidRunUsageVerdict } from '@/lib/billing/core/mid-run-usage' +import { isCappedRunPayer, readMidRunUsageVerdict } from '@/lib/billing/core/mid-run-usage' import { isHosted } from '@/lib/core/config/env-flags' import { OrchestrationError } from '@/lib/core/orchestration/types' import { @@ -84,8 +84,8 @@ export async function authorizeLifecycleContinuation( if (usage.status === 'blocked') throw new OrchestrationError('forbidden', 'Continuation billing account is blocked') if (usage.status === 'exceeded') throw new BillingLimitError(context.userId, usage.scope) - // A free payer's spend past its limit is never billed, so an unreadable standing refuses it. - if (usage.status === 'unknown' && isFreeRunPayer(context.billingAttribution)) { + // A capped payer's spend past its limit is never billed, so an unreadable standing refuses it. + if (usage.status === 'unknown' && isCappedRunPayer(context.billingAttribution)) { throw new BillingLimitError(context.userId) } } diff --git a/apps/sim/lib/mothership/request/lifecycle/start.test.ts b/apps/sim/lib/mothership/request/lifecycle/start.test.ts index e3a41c071f8..e1746d03ea4 100644 --- a/apps/sim/lib/mothership/request/lifecycle/start.test.ts +++ b/apps/sim/lib/mothership/request/lifecycle/start.test.ts @@ -7,6 +7,7 @@ import { billingAttributionMock, billingAttributionMockFns, } from '@sim/testing/mocks/billing-attribution.mock' +import { getMockLogger } from '@sim/testing/mocks/logger.mock' import { mothershipAgentUrlMock, mothershipAgentUrlMockFns, @@ -27,6 +28,7 @@ import { MothershipStreamV1EventType, } from '@/lib/mothership/generated/mothership-stream-v1' import { TitleRequest } from '@/lib/mothership/generated/protocol' +import { isExplicitStopReason } from '@/lib/mothership/request/session/abort-reason' import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' const { @@ -113,7 +115,7 @@ vi.mock('@/lib/mothership/request/session', () => ({ unregisterActiveStream, hasStreamViewer, startAbortPoller: vi.fn().mockReturnValue(setInterval(() => {}, 999999)), - isExplicitStopReason: (reason: unknown) => reason === 'user_stop:abortActiveStream', + isExplicitStopReason: (reason: unknown) => isExplicitStopReason(reason), SSE_RESPONSE_HEADERS: {}, StreamWriter: class { attach = vi.fn().mockImplementation((ctrl: ReadableStreamDefaultController) => { @@ -609,7 +611,9 @@ describe('createSSEStream terminal error handling', () => { expect(scheduleBufferCleanup).toHaveBeenCalledWith('stream-1') }) - it('publishes a cancelled completion (not an error) when the orchestrator reports cancelled without abortSignal aborted', async () => { + it('publishes a cancelled completion and classifies it as a Stop when the orchestrator reports cancelled without abortSignal aborted', async () => { + // Regression: the worker's cancelled terminal (live or replayed) left this node's signal + // unaborted, so the turn was logged as "Stream cancelled with unknown abort reason". runCopilotLifecycle.mockResolvedValue({ success: false, cancelled: true, @@ -646,6 +650,10 @@ describe('createSSEStream terminal error handling', () => { }), }) ) + expect(getMockLogger('CopilotChatStreaming').error).not.toHaveBeenCalledWith( + 'Stream cancelled with unknown abort reason', + expect.anything() + ) }) it('releases the stream registration and pollers when preview initialization fails before the lifecycle starts', async () => { diff --git a/apps/sim/lib/mothership/request/lifecycle/start.ts b/apps/sim/lib/mothership/request/lifecycle/start.ts index 23e86ebbbc3..cdbb9184670 100644 --- a/apps/sim/lib/mothership/request/lifecycle/start.ts +++ b/apps/sim/lib/mothership/request/lifecycle/start.ts @@ -186,7 +186,11 @@ export function createSSEStream(params: StreamingOrchestrationParams): ReadableS // Only explicit cancellation affects the run; browser attachment is independent. const recordCancelled = (errorMessage?: string): CopilotRequestCancelReasonValue => { - const rawReason = abortController.signal.reason + // A cancelled verdict with this node's signal still live came from the worker's terminal + // (live or replayed in recovery): a Stop that reached the worker before this node saw it. + const rawReason = abortController.signal.aborted + ? abortController.signal.reason + : AbortReason.WorkerTerminalStop let cancelReason: CopilotRequestCancelReasonValue if (isExplicitStopReason(rawReason)) { cancelReason = CopilotRequestCancelReason.ExplicitStop diff --git a/apps/sim/lib/mothership/request/metrics.ts b/apps/sim/lib/mothership/request/metrics.ts index e66ddeb42ba..7d0fe33e4c3 100644 --- a/apps/sim/lib/mothership/request/metrics.ts +++ b/apps/sim/lib/mothership/request/metrics.ts @@ -11,6 +11,7 @@ import { TOOL_CATALOG } from '@/lib/mothership/generated/tool-catalog-v1' import { Metric } from '@/lib/mothership/observability/metric-names' import { type CopilotDegradedReasonValue, + type CopilotStreamContractDirectionValue, ToolExecutor, } from '@/lib/mothership/observability/trace-attribute-values' import { TraceAttr } from '@/lib/mothership/observability/trace-attributes' @@ -25,6 +26,7 @@ interface CopilotMeterInstruments { toolDuration: Histogram toolCalls: Counter degradedCount: Counter + streamContractDisagreements: Counter } let cached: CopilotMeterInstruments | undefined @@ -42,6 +44,7 @@ function instruments(): CopilotMeterInstruments { }), toolCalls: meter.createCounter(Metric.CopilotToolCalls), degradedCount: meter.createCounter(Metric.CopilotDegradedCount), + streamContractDisagreements: meter.createCounter(Metric.CopilotStreamContractDisagreements), } return cached } @@ -92,3 +95,20 @@ export function recordDegraded(reason: CopilotDegradedReasonValue): void { [TraceAttr.CopilotDegradedReason]: reason, }) } + +/** + * Counts one worker frame on which Sim's ingest validator and the generated contract schema + * disagree. `eventType` and `variant` must already be capped to the contract's own + * vocabularies (else "other"). + */ +export function recordStreamContractDisagreement( + direction: CopilotStreamContractDirectionValue, + eventType: string, + variant: string +): void { + instruments().streamContractDisagreements.add(1, { + [TraceAttr.CopilotStreamContractDirection]: direction, + [TraceAttr.CopilotStreamContractEventType]: eventType, + [TraceAttr.CopilotStreamContractVariant]: variant, + }) +} diff --git a/apps/sim/lib/mothership/request/otel.ts b/apps/sim/lib/mothership/request/otel.ts index 711de10f36d..c79036288b3 100644 --- a/apps/sim/lib/mothership/request/otel.ts +++ b/apps/sim/lib/mothership/request/otel.ts @@ -51,7 +51,7 @@ function isGenAIMessageCaptureEnabled(): boolean { // // - Plain-string reject value: `controller.abort('user_stop:...')` // rejects fetch() with the reason STRING directly. Matches -// `isExplicitStopReason()` exactly (UserStop / RedisPoller). +// `isExplicitStopReason()` exactly (any reason it accepts). // - DOMException / Error object: `controller.abort()` with no arg // (or older runtimes) rejects with an AbortError whose `.cause` // or `.message` may carry the reason. We inspect both. diff --git a/apps/sim/lib/mothership/request/session/abort-reason.ts b/apps/sim/lib/mothership/request/session/abort-reason.ts index 25e6a952af6..d761051e7c5 100644 --- a/apps/sim/lib/mothership/request/session/abort-reason.ts +++ b/apps/sim/lib/mothership/request/session/abort-reason.ts @@ -28,6 +28,12 @@ export const AbortReason = { * 250ms poller's next tick) rather than by the polling timer. */ MarkerObservedAtBodyClose: 'redis_abort_marker:body_close', + /** + * The turn's cancelled verdict came from the worker's terminal, which it sends only for a + * Stop, while this node's signal never fired: the Stop reached the worker another way. + * Classification only; nothing aborts with it. + */ + WorkerTerminalStop: 'worker_terminal:cancelled', /** Internal timeout on the outbound explicit-abort fetch to the worker. */ ExplicitAbortFetchTimeout: 'timeout:explicit_abort_fetch', } as const @@ -47,6 +53,7 @@ export function isExplicitStopReason(reason: unknown): boolean { return ( reason === AbortReason.UserStop || reason === AbortReason.RedisPoller || - reason === AbortReason.MarkerObservedAtBodyClose + reason === AbortReason.MarkerObservedAtBodyClose || + reason === AbortReason.WorkerTerminalStop ) } diff --git a/apps/sim/lib/mothership/request/session/contract-shadow.test.ts b/apps/sim/lib/mothership/request/session/contract-shadow.test.ts new file mode 100644 index 00000000000..0b676bd0f26 --- /dev/null +++ b/apps/sim/lib/mothership/request/session/contract-shadow.test.ts @@ -0,0 +1,290 @@ +/** + * @vitest-environment node + */ +import { getMockLogger } from '@sim/testing/mocks/logger.mock' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { parsePersistedStreamEventEnvelope } from '@/lib/mothership/request/session/contract' +import { parseIngestedStreamEventEnvelope } from '@/lib/mothership/request/session/contract-shadow' + +const { recordStreamContractDisagreement } = vi.hoisted(() => ({ + recordStreamContractDisagreement: vi.fn(), +})) +vi.mock('@/lib/mothership/request/metrics', () => ({ recordStreamContractDisagreement })) + +const logger = getMockLogger('StreamContractShadow') + +const shell = { + v: 1, + seq: 7, + ts: '2026-11-23T00:00:00.000Z', + stream: { streamId: 'stream-1', chatId: 'chat-1' }, + trace: { requestId: 'req-1' }, +} +const toolCall = { + phase: 'call', + toolCallId: 'tool-1', + toolName: 'sim_cli', + executor: 'sim', + mode: 'async', + status: 'executing', + arguments: { argv: ['tables', 'list'] }, + deadlineMs: 600_000, +} +const toolResult = { + phase: 'result', + toolCallId: 'tool-1', + toolName: 'sim_cli', + executor: 'sim', + mode: 'async', + success: true, +} +const argsDelta = { phase: 'args_delta', toolCallId: 'tool-1', toolName: 'sim_cli' } +const spanStart = { kind: 'subagent', event: 'start', agent: 'research' } +const checkpoint = { + kind: 'checkpoint_pause', + checkpointId: 'ckpt-1', + executionId: 'exec-1', + runId: 'run-1', + pendingToolCallIds: ['tool-1'], +} +const complete = { status: 'complete', usage: { input_tokens: 12, output_tokens: 3 } } + +const frame = (type: string, payload: Record, extra: object = {}) => ({ + ...shell, + ...extra, + type, + payload, +}) + +/** + * A representative set of frames the stream validator accepts today that the contract schema + * rejects, one per kind of gap (missing or mistyped field, unknown enum value, the `error`-only + * alias), not an exhaustive list. Each row names the issue path the schema reports. + */ +const SCHEMA_ONLY_REJECTS: Array<[string, Record, string, string]> = [ + [ + 'args_delta without argumentsDelta', + frame('tool', argsDelta), + 'args_delta', + 'payload.argumentsDelta', + ], + [ + 'args_delta with a numeric argumentsDelta', + frame('tool', { ...argsDelta, argumentsDelta: 42 }), + 'args_delta', + 'payload.argumentsDelta', + ], + [ + 'tool call without executor or mode', + frame('tool', { ...toolCall, executor: undefined, mode: undefined }), + 'call', + 'payload.executor', + ], + [ + 'tool call with string arguments', + frame('tool', { ...toolCall, arguments: 'str' }), + 'call', + 'payload.arguments', + ], + [ + 'tool call with a string deadlineMs', + frame('tool', { ...toolCall, deadlineMs: 'soon' }), + 'call', + 'payload.deadlineMs', + ], + [ + 'tool call with an unknown status', + frame('tool', { ...toolCall, status: 'bogus' }), + 'call', + 'payload.status', + ], + [ + 'tool result without success', + frame('tool', { ...toolResult, success: undefined }), + 'result', + 'payload.success', + ], + [ + 'span with an unknown event', + frame('span', { ...spanStart, event: 'middle' }), + 'subagent', + 'payload.event', + ], + ['span with string data', frame('span', { ...spanStart, data: 'x' }), 'subagent', 'payload.data'], + [ + 'checkpoint_pause without checkpointId', + frame('run', { ...checkpoint, checkpointId: undefined }), + 'checkpoint_pause', + 'payload.checkpointId', + ], + [ + 'checkpoint_pause with string pendingToolCallIds', + frame('run', { ...checkpoint, pendingToolCallIds: 'tool-1' }), + 'checkpoint_pause', + 'payload.pendingToolCallIds', + ], + [ + 'steering_applied without steeringId', + frame('run', { kind: 'steering_applied', eventSeq: 3 }), + 'steering_applied', + 'payload.steeringId', + ], + [ + 'complete with an unknown status', + frame('complete', { ...complete, status: 'done' }), + 'none', + 'payload.status', + ], + [ + 'complete with string usage tokens', + frame('complete', { ...complete, usage: { input_tokens: '12' } }), + 'none', + 'payload.usage.input_tokens', + ], + [ + 'error carrying only the `error` alias', + frame('error', { error: 'boom' }), + 'none', + 'payload.message', + ], + [ + 'session start with string data', + frame('session', { kind: 'start', data: 'x' }), + 'start', + 'payload.data', + ], + [ + 'scope with a numeric spanId', + frame( + 'text', + { channel: 'assistant', text: 'hi' }, + { scope: { lane: 'subagent', agentId: 'research', spanId: 7 } } + ), + 'none', + 'scope.spanId', + ], +] + +let clock = Date.UTC(2026, 10, 23) + +describe('parseIngestedStreamEventEnvelope', () => { + beforeEach(() => { + // Each test starts past the previous one's log window, so no test sees another's dedupe. + vi.useFakeTimers() + clock += 24 * 60 * 60 * 1000 + vi.setSystemTime(clock) + }) + + it.each(SCHEMA_ONLY_REJECTS)( + 'keeps accepting %s and reports the schema rejecting it', + (_name, value, variant, path) => { + const result = parseIngestedStreamEventEnvelope(value) + + expect(result).toEqual(parsePersistedStreamEventEnvelope(value)) + expect(result.ok && result.event).toBe(value) + expect(recordStreamContractDisagreement).toHaveBeenCalledExactlyOnceWith( + 'schema_rejects', + value.type, + variant + ) + expect(logger.warn).toHaveBeenCalledExactlyOnceWith( + 'Stream contract schema disagrees with the stream validator', + expect.objectContaining({ + direction: 'schema_rejects', + eventType: value.type, + issues: expect.arrayContaining([expect.stringMatching(new RegExp(`^${path}: `))]), + }) + ) + } + ) + + it('keeps a rejection the schema would accept and reports it', () => { + // The validator rejects a null activityReceipt; the schema does not declare the key and + // strips it. This fails by design once the two are aligned: then pick another real split. + const value = frame('run', { kind: 'compaction_start', activityReceipt: null }) + const result = parseIngestedStreamEventEnvelope(value) + + expect(result.ok).toBe(false) + expect(result).toEqual(parsePersistedStreamEventEnvelope(value)) + expect(recordStreamContractDisagreement).toHaveBeenCalledExactlyOnceWith( + 'schema_accepts', + 'run', + 'compaction_start' + ) + expect(logger.warn).toHaveBeenCalledExactlyOnceWith( + 'Stream contract schema disagrees with the stream validator', + expect.objectContaining({ + direction: 'schema_accepts', + eventType: 'run', + variant: 'compaction_start', + }) + ) + }) + + it('reports nothing when both accept or both reject', () => { + const accepted = frame('tool', toolCall) + expect(parseIngestedStreamEventEnvelope(accepted)).toEqual({ ok: true, event: accepted }) + expect(parseIngestedStreamEventEnvelope(frame('nope', { kind: 'start' })).ok).toBe(false) + expect( + parseIngestedStreamEventEnvelope(frame('run', { kind: 'replay_end', reason: 'cap' })).ok + ).toBe(false) + + expect(recordStreamContractDisagreement).not.toHaveBeenCalled() + expect(logger.warn).not.toHaveBeenCalled() + }) + + it('skips Sim synthetic file-preview frames, which are outside the contract', () => { + const preview = frame('tool', { + previewPhase: 'file_preview_start', + toolCallId: 'tool-1', + toolName: 'prepare_file_edit', + }) + expect(parseIngestedStreamEventEnvelope(preview).ok).toBe(true) + expect(recordStreamContractDisagreement).not.toHaveBeenCalled() + }) + + it('still compares a worker frame that carries a stray previewPhase', () => { + // Shaped to pass the synthetic check too, but the contract check accepts it first. + const stray = frame('tool', { + phase: 'call', + previewPhase: 'file_preview_start', + toolCallId: 'tool-stray', + toolName: 'prepare_file_edit', + }) + expect(parseIngestedStreamEventEnvelope(stray)).toEqual({ ok: true, event: stray }) + expect(recordStreamContractDisagreement).toHaveBeenCalledExactlyOnceWith( + 'schema_rejects', + 'tool', + 'call' + ) + }) + + it('logs a repeated disagreement once per window but counts every frame', () => { + const value = frame('complete', { status: 'complete', usage: { output_tokens: 'many' } }) + + for (let i = 0; i < 3; i++) parseIngestedStreamEventEnvelope(value) + expect(recordStreamContractDisagreement).toHaveBeenCalledTimes(3) + expect(logger.warn).toHaveBeenCalledTimes(1) + + vi.advanceTimersByTime(10 * 60 * 1000 + 1) + parseIngestedStreamEventEnvelope(value) + expect(recordStreamContractDisagreement).toHaveBeenCalledTimes(4) + expect(logger.warn).toHaveBeenCalledTimes(2) + expect(logger.warn).toHaveBeenLastCalledWith( + 'Stream contract schema disagrees with the stream validator', + expect.objectContaining({ suppressedSinceLastLog: 2 }) + ) + }) + + it('rate-limits the warning when the shadow check itself keeps failing', () => { + recordStreamContractDisagreement.mockImplementation(() => { + throw new Error('meter unavailable') + }) + const value = frame('tool', { ...argsDelta, argumentsDelta: 7, toolCallId: 'tool-meter' }) + + for (let i = 0; i < 3; i++) expect(parseIngestedStreamEventEnvelope(value).ok).toBe(true) + expect(logger.warn).toHaveBeenCalledExactlyOnceWith('Stream contract shadow check failed', { + error: 'meter unavailable', + }) + }) +}) diff --git a/apps/sim/lib/mothership/request/session/contract-shadow.ts b/apps/sim/lib/mothership/request/session/contract-shadow.ts new file mode 100644 index 00000000000..2484e77b0a6 --- /dev/null +++ b/apps/sim/lib/mothership/request/session/contract-shadow.ts @@ -0,0 +1,152 @@ +import { createLogger } from '@sim/logger' +import { getErrorMessage } from '@sim/utils/errors' +import { isRecordLike, toRecord } from '@sim/utils/object' +import { LRUCache } from 'lru-cache' +import { + MothershipStreamV1EventEnvelopeSchema, + MothershipStreamV1ResourceOp, + MothershipStreamV1RunKind, + MothershipStreamV1SessionKind, + MothershipStreamV1SpanPayloadKind, + MothershipStreamV1ToolPhase, +} from '@/lib/mothership/generated/mothership-stream-v1' +import { CopilotStreamContractDirection } from '@/lib/mothership/observability/trace-attribute-values' +import { recordStreamContractDisagreement } from '@/lib/mothership/request/metrics' +import { + isContractStreamEventEnvelope, + KNOWN_EVENT_TYPES, + type ParseStreamEventEnvelopeResult, + parsePersistedStreamEventEnvelope, +} from '@/lib/mothership/request/session/contract' + +/** + * Server-side ingest of worker stream frames, with a shadow check of the generated + * contract schema (mothership-stream-v1, its zod schemas the single source). + * + * `parsePersistedStreamEventEnvelope` keeps deciding every frame. The schema runs beside it + * on the frames the worker sends Sim (the live leg and the run replay), never in the browser, + * and each disagreement is counted and logged, so the frames the schema would newly reject + * are known before it becomes the validator. + */ + +const logger = createLogger('StreamContractShadow') + +/** One log line per distinct disagreement per window; the counter still sees every frame. */ +const LOG_WINDOW_MS = 10 * 60 * 1000 +/** Memory backstop on distinct disagreements tracked within one window. */ +const MAX_TRACKED_DISAGREEMENTS = 256 +/** Issue paths kept per log line. */ +const MAX_LOGGED_ISSUES = 8 + +const KNOWN_VARIANTS: ReadonlySet = new Set([ + ...Object.values(MothershipStreamV1SessionKind), + ...Object.values(MothershipStreamV1ToolPhase), + ...Object.values(MothershipStreamV1SpanPayloadKind), + ...Object.values(MothershipStreamV1RunKind), + ...Object.values(MothershipStreamV1ResourceOp), +]) + +/** Each logged disagreement, live for its window, with the repeats skipped since it logged. */ +const recentDisagreements = new LRUCache({ + max: MAX_TRACKED_DISAGREEMENTS, + ttl: LOG_WINDOW_MS, + // Wall-clock windows read fresh on every check (no timer-cached `now`): one clock read per + // disagreement costs nothing, and it is the clock tests move. + perf: { now: () => Date.now() }, + ttlResolution: 0, +}) + +/** + * Parses one stream frame a worker sent this server. The verdict is exactly + * `parsePersistedStreamEventEnvelope`'s; the shadow check only observes. + */ +export function parseIngestedStreamEventEnvelope(value: unknown): ParseStreamEventEnvelopeResult { + const result = parsePersistedStreamEventEnvelope(value) + try { + shadowCheck(value, result) + } catch (error) { + const message = getErrorMessage(error) + const suppressed = takeLogSlot(`shadow_check_failed|${message}`) + if (suppressed !== null) { + logger.warn('Stream contract shadow check failed', { + error: message, + ...(suppressed > 0 ? { suppressedSinceLastLog: suppressed } : {}), + }) + } + } + return result +} + +function shadowCheck(value: unknown, result: ParseStreamEventEnvelopeResult): void { + if (result.ok && acceptedAsSyntheticPreview(value)) return + const schema = MothershipStreamV1EventEnvelopeSchema.safeParse(value) + if (schema.success === result.ok) return + + const direction = result.ok + ? CopilotStreamContractDirection.SchemaRejects + : CopilotStreamContractDirection.SchemaAccepts + const { eventType, variant } = describeFrame(value) + recordStreamContractDisagreement(direction, eventType, variant) + + const issues = schema.success + ? [] + : schema.error.issues + .slice(0, MAX_LOGGED_ISSUES) + .map((issue) => `${issue.path.map(String).join('.') || '(root)'}: ${issue.code}`) + const validatorErrors = result.ok ? [] : (result.errors ?? []) + const key = [direction, eventType, variant, ...issues, ...validatorErrors].join('|') + const suppressed = takeLogSlot(key) + if (suppressed === null) return + + logger.warn('Stream contract schema disagrees with the stream validator', { + direction, + eventType, + variant, + ...(issues.length > 0 ? { issues } : {}), + ...(validatorErrors.length > 0 ? { validatorErrors } : {}), + ...(suppressed > 0 ? { suppressedSinceLastLog: suppressed } : {}), + }) +} + +/** + * Whether the validator accepted this frame as one of Sim's synthetic file-preview frames, + * which are outside the contract. It tries the contract first, so that is exactly a frame the + * contract check rejects; only a payload with `previewPhase` can be one, which keeps the + * re-check off every other frame. A worker frame with a stray `previewPhase` that passes the + * contract check is still compared. + */ +function acceptedAsSyntheticPreview(value: unknown): boolean { + return ( + isRecordLike(value) && + toRecord(value.payload).previewPhase !== undefined && + !isContractStreamEventEnvelope(value) + ) +} + +/** The frame's type and payload discriminant, each capped to the contract's vocabulary. */ +function describeFrame(value: unknown): { eventType: string; variant: string } { + if (!isRecordLike(value)) return { eventType: 'other', variant: 'none' } + const eventType = + typeof value.type === 'string' && KNOWN_EVENT_TYPES.has(value.type) ? value.type : 'other' + const payload = toRecord(value.payload) + const discriminant = payload.phase ?? payload.kind ?? payload.op + if (discriminant === undefined) return { eventType, variant: 'none' } + const variant = + typeof discriminant === 'string' && KNOWN_VARIANTS.has(discriminant) ? discriminant : 'other' + return { eventType, variant } +} + +/** + * Whether this disagreement may be logged now: the number of repeats skipped since its last + * line, or `null` while its window is still open. + */ +function takeLogSlot(key: string): number | null { + const live = recentDisagreements.peek(key) + if (live) { + live.suppressed += 1 + return null + } + const expired = recentDisagreements.peek(key, { allowStale: true }) + recentDisagreements.set(key, { suppressed: 0 }) + return expired?.suppressed ?? 0 +} diff --git a/apps/sim/lib/mothership/request/session/contract.test.ts b/apps/sim/lib/mothership/request/session/contract.test.ts index 74701e1f595..e88cfd59435 100644 --- a/apps/sim/lib/mothership/request/session/contract.test.ts +++ b/apps/sim/lib/mothership/request/session/contract.test.ts @@ -1,5 +1,9 @@ import { describe, expect, it } from 'vitest' -import { MothershipStreamV1RunKind } from '@/lib/mothership/generated/mothership-stream-v1' +import { + type MothershipStreamV1ReplayEndEnvelope, + MothershipStreamV1ReplayEndKind, + MothershipStreamV1RunKind, +} from '@/lib/mothership/generated/mothership-stream-v1' import { isContractStreamEventEnvelope, isSyntheticFilePreviewEventEnvelope, @@ -53,6 +57,17 @@ describe('stream session contract parser', () => { } }) + it('rejects the replay-end control frame as a live stream event', () => { + // D121. + const event: MothershipStreamV1ReplayEndEnvelope = { + ...BASE_ENVELOPE, + type: 'run', + payload: { kind: MothershipStreamV1ReplayEndKind, reason: 'stalled', textLength: 6 }, + } + expect(isContractStreamEventEnvelope(event)).toBe(false) + expect(parsePersistedStreamEventEnvelope(event).ok).toBe(false) + }) + it.each(['run', 'complete'])('validates activity acknowledgement on %s boundaries', (type) => { const payload = type === 'run' ? { kind: 'checkpoint_pause' } : { status: 'complete' } const event = { diff --git a/apps/sim/lib/mothership/request/session/contract.ts b/apps/sim/lib/mothership/request/session/contract.ts index 17fc7e16ad0..b6f213e2582 100644 --- a/apps/sim/lib/mothership/request/session/contract.ts +++ b/apps/sim/lib/mothership/request/session/contract.ts @@ -185,11 +185,17 @@ function isStreamScope(value: unknown): value is MothershipStreamV1StreamScope { // // Validates the envelope shell (v, seq, ts, stream, trace?, scope?) and that // `type` is one of the known event types with a non-null payload object. -// Per-payload-variant validation is intentionally lightweight: the server -// already performs strict schema validation; the client only needs enough -// structural checking to safely dispatch inside the switch statement. - -const KNOWN_EVENT_TYPES: ReadonlySet = new Set(Object.values(MothershipStreamV1EventType)) +// This is the one verdict on every stream frame: on Sim's server (worker ingest, +// Redis buffer reads) and in the browser. Only a resource payload is checked +// against its generated schema (ResourcePayload). The generated envelope schema +// (MothershipStreamV1EventEnvelopeSchema) is not enforced at runtime: the +// worker's emitter is only typed against it, and on worker ingest it only +// shadows this verdict, counting disagreements (contract-shadow.ts). + +/** The event types the contract names; a frame of any other type is invalid. */ +export const KNOWN_EVENT_TYPES: ReadonlySet = new Set( + Object.values(MothershipStreamV1EventType) +) function isValidEnvelopeShell(value: unknown): value is JsonRecord & { v: 1 diff --git a/apps/sim/lib/mothership/request/session/run-replay.ts b/apps/sim/lib/mothership/request/session/run-replay.ts index 5271833e3da..582e18e61c2 100644 --- a/apps/sim/lib/mothership/request/session/run-replay.ts +++ b/apps/sim/lib/mothership/request/session/run-replay.ts @@ -2,17 +2,21 @@ import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' import { sleep } from '@sim/utils/helpers' import { isRecordLike, toRecord } from '@sim/utils/object' -import { z } from 'zod' import { WORKER_STREAM_IDLE_TIMEOUT_MS } from '@/lib/mothership/constants' -import { MothershipStreamV1EventType } from '@/lib/mothership/generated/mothership-stream-v1' -import { type StreamReplayEnd, StreamReplayRequest } from '@/lib/mothership/generated/protocol' +import { + MothershipStreamV1EventType, + MothershipStreamV1ReplayEndKind, + MothershipStreamV1ReplayEndPayloadSchema, + type MothershipStreamV1ReplayEndReason, +} from '@/lib/mothership/generated/mothership-stream-v1' +import { StreamReplayRequest } from '@/lib/mothership/generated/protocol' import { TraceAttr } from '@/lib/mothership/observability/trace-attributes' import { mothershipRequestHeaders } from '@/lib/mothership/request/headers' import { isTerminalStreamStatus, type PersistedStreamEventEnvelope, - parsePersistedStreamEventEnvelope, } from '@/lib/mothership/request/session/contract' +import { parseIngestedStreamEventEnvelope } from '@/lib/mothership/request/session/contract-shadow' import { toReplayEnvelope } from '@/lib/mothership/request/session/types' import { fetchWorker } from '@/lib/mothership/request/worker/fetch' import { FatalSseEventError, processSSEStream } from '@/lib/mothership/request/worker/parser' @@ -29,7 +33,7 @@ const REPLAY_HOLD_POLL_MS = 1_000 const PARKED_RUN_STATUS = 'paused_waiting_for_tool' /** How a worker replay leg ended: at the run's terminal, short of it, or cut off. */ -export type RunReplayEnd = 'complete' | StreamReplayEnd['reason'] | 'closed' +export type RunReplayEnd = 'complete' | MothershipStreamV1ReplayEndReason | 'closed' /** The worker could not serve the replay; the reader should retry later. */ export class RunReplayUnavailableError extends Error { @@ -93,35 +97,21 @@ export async function openRunReplay(params: { return response.body } -/** Every reason the worker may end a replay with; a reason added to the contract fails here. */ -const REPLAY_END_REASONS = { - parked: true, - cap: true, - stalled: true, -} as const satisfies Record - -const StreamReplayEndSchema = z.object({ - kind: z.literal('replay_end'), - reason: z - .string() - .refine((reason): reason is StreamReplayEnd['reason'] => - Object.hasOwn(REPLAY_END_REASONS, reason) - ), - textLength: z.number().int().nonnegative(), -}) satisfies z.ZodType - /** - * The end a `replay_end` frame reports: its reason, `closed` for a reason this build - * does not know, or `null` for any other frame. It is worker-to-Sim control, never a - * stream event, whatever reason it carries. + * The end a `replay_end` frame reports: its reason, `closed` for a frame this build cannot + * parse (an unknown reason, a missing length), or `null` for any other frame. It is + * worker-to-Sim control, never a stream event, whatever reason it carries. */ function replayEnd(value: unknown): RunReplayEnd | null { if (!isRecordLike(value) || value.type !== MothershipStreamV1EventType.run) return null const payload = toRecord(value.payload) - if (payload.kind !== 'replay_end') return null - const parsed = StreamReplayEndSchema.safeParse(payload) + if (payload.kind !== MothershipStreamV1ReplayEndKind) return null + const parsed = MothershipStreamV1ReplayEndPayloadSchema.safeParse(payload) if (parsed.success) return parsed.data.reason - logger.warn('Run replay ended with an unknown reason', { reason: payload.reason }) + logger.warn('Run replay ended with a malformed replay-end frame', { + reason: payload.reason, + issues: parsed.error.issues.map((issue) => issue.path.join('.') || '(root)'), + }) return 'closed' } @@ -145,7 +135,7 @@ async function readRunReplay( end = control return true } - const parsed = parsePersistedStreamEventEnvelope(raw) + const parsed = parseIngestedStreamEventEnvelope(raw) if (!parsed.ok) throw new FatalSseEventError(`Invalid run replay event: ${parsed.message}`) if (!onEvent(parsed.event)) return true if (parsed.event.type === MothershipStreamV1EventType.complete) { diff --git a/apps/sim/lib/mothership/request/worker/stream.ts b/apps/sim/lib/mothership/request/worker/stream.ts index 8d4ea9bddca..0e278b0b564 100644 --- a/apps/sim/lib/mothership/request/worker/stream.ts +++ b/apps/sim/lib/mothership/request/worker/stream.ts @@ -17,12 +17,8 @@ import { flushThinkingBlock, } from '@/lib/mothership/request/handlers/types' import { getCopilotTracer } from '@/lib/mothership/request/otel' -import { - AbortReason, - eventToStreamEvent, - hasAbortMarker, - parsePersistedStreamEventEnvelope, -} from '@/lib/mothership/request/session' +import { AbortReason, eventToStreamEvent, hasAbortMarker } from '@/lib/mothership/request/session' +import { parseIngestedStreamEventEnvelope } from '@/lib/mothership/request/session/contract-shadow' import { forgetToolCallEvent, shouldSkipToolCallEvent, @@ -373,7 +369,7 @@ export async function runStreamLoop( } await options.assertControllerOwnership?.() - const parsedEvent = parsePersistedStreamEventEnvelope(raw) + const parsedEvent = parseIngestedStreamEventEnvelope(raw) if (!parsedEvent.ok) { const detail = [parsedEvent.message, ...(parsedEvent.errors ?? [])] .filter(Boolean) diff --git a/apps/sim/lib/mothership/tools/display.ts b/apps/sim/lib/mothership/tools/display.ts index 52f2f52ada0..8f47aa93c93 100644 --- a/apps/sim/lib/mothership/tools/display.ts +++ b/apps/sim/lib/mothership/tools/display.ts @@ -1497,7 +1497,9 @@ export function getToolDisplayTitle(name: string, args?: Record } } - return TOOL_TITLES[name] ?? CLI_TOOL_TITLES[name] ?? humanizeToolName(name) + if (Object.hasOwn(TOOL_TITLES, name)) return TOOL_TITLES[name] + if (Object.hasOwn(CLI_TOOL_TITLES, name)) return CLI_TOOL_TITLES[name] + return humanizeToolName(name) } /** First positional after the synthetic CLI command path; shared by resource and operation labels. */ diff --git a/apps/sim/lib/oauth/token-resolution.test.ts b/apps/sim/lib/oauth/token-resolution.test.ts index 232ce5a7fb2..ed85b2596c0 100644 --- a/apps/sim/lib/oauth/token-resolution.test.ts +++ b/apps/sim/lib/oauth/token-resolution.test.ts @@ -260,6 +260,7 @@ describe('resolveCredentialAccessToken', () => { resolveManagedPrincipal.mockResolvedValue(EXECUTOR_PRINCIPAL) mockGetToolMetadata.mockReturnValue({ id: 'gmail_send', + effect: 'write', params: {}, oauth: { required: true, provider: 'google', requiredScopes: ['scope-a'] }, }) @@ -325,7 +326,12 @@ describe('resolveCredentialAccessToken', () => { it('rejects tools without managed OAuth support', async () => { mockResolveOAuthAccountId.mockResolvedValue(MANAGED_RESOLVED) - mockGetToolMetadata.mockReturnValue({ id: 'http_request', params: {}, oauth: undefined }) + mockGetToolMetadata.mockReturnValue({ + id: 'http_request', + effect: 'write', + params: {}, + oauth: undefined, + }) const result = await resolveCredentialAccessToken({ requestId: 'req-1', @@ -351,6 +357,7 @@ describe('resolveCredentialAccessToken', () => { }) mockGetToolMetadata.mockReturnValueOnce({ id: 'slack_add_bookmark', + effect: 'write', params: {}, oauth: { required: true, @@ -382,6 +389,7 @@ describe('resolveCredentialAccessToken', () => { mockResolveOAuthAccountId.mockResolvedValue(MANAGED_RESOLVED) mockGetToolMetadata.mockReturnValue({ id: 'fixture-tool', + effect: 'write', params: {}, oauth: { required: true, provider: 'oracle-fusion' }, }) @@ -496,6 +504,7 @@ describe('ordinary tool credential binding', () => { mockRefreshTokenIfNeeded.mockResolvedValue({ accessToken: 'oauth-token' }) mockGetToolMetadata.mockReturnValue({ id: 'fixture-tool', + effect: 'write', params: {}, oauth: { required: true, provider: 'oracle-fusion', credentialKind: 'service-account' }, }) @@ -534,6 +543,7 @@ describe('ordinary tool credential binding', () => { beforeEach(() => { mockGetToolMetadata.mockReturnValue({ id: 'dynamodb_get', + effect: 'write', params: {}, oauth: { required: false, provider: 'aws', credentialKind: 'service-account' }, }) @@ -605,6 +615,7 @@ describe('ordinary tool credential binding', () => { it('releases the application key a Datadog key pair resolves beside its API key', async () => { mockGetToolMetadata.mockReturnValue({ id: 'fixture-tool', + effect: 'write', params: {}, oauth: { required: false, provider: 'datadog', credentialKind: 'service-account' }, }) @@ -652,6 +663,7 @@ describe('ordinary tool credential binding', () => { async (provider, providerId) => { mockGetToolMetadata.mockReturnValue({ id: 'fixture-tool', + effect: 'write', params: {}, oauth: { required: true, provider }, }) @@ -679,6 +691,7 @@ describe('ordinary tool credential binding', () => { async (provider, providerId, allowed) => { mockGetToolMetadata.mockReturnValue({ id: 'fixture-tool', + effect: 'write', params: {}, oauth: { required: true, provider }, }) @@ -723,6 +736,7 @@ describe('Microsoft app credential binding', () => { function toolFor(provider: OAuthService) { mockGetToolMetadata.mockReturnValue({ id: `${provider}-tool`, + effect: 'write', params: {}, oauth: { required: true, provider }, }) @@ -802,6 +816,7 @@ describe('keyless Google Cloud credential refusals', () => { }) mockGetToolMetadata.mockReturnValue({ id: 'google-drive-tool', + effect: 'write', params: {}, oauth: { required: true, provider: 'google-drive' }, }) @@ -857,6 +872,7 @@ describe('Microsoft app credential cloud refusals', () => { }) mockGetToolMetadata.mockReturnValue({ id: 'powerbi-tool', + effect: 'write', params: {}, oauth: { required: true, provider: 'microsoft-powerbi' }, }) diff --git a/apps/sim/lib/projects/files/__integration__/uploads.integration.ts b/apps/sim/lib/projects/files/__integration__/uploads.integration.ts index ef7f9748f5e..8a284781337 100644 --- a/apps/sim/lib/projects/files/__integration__/uploads.integration.ts +++ b/apps/sim/lib/projects/files/__integration__/uploads.integration.ts @@ -934,7 +934,7 @@ afterAll(async () => { await db.delete(user).where(inArray(user.id, [f.ownerId, f.editorId])) } await rm(storageRoot, { recursive: true, force: true }) - if (redisKeys.length) await getRedisClient()?.del(...redisKeys) + if (redisKeys.length) await getRedisClient().del(...redisKeys) await closeRedisConnection() const report = process.env.PROJECT_UPLOAD_REPORT_PATH ?? 'test-results/project-upload.json' await mkdir(dirname(report), { recursive: true }) diff --git a/apps/sim/lib/table/application/rows.ts b/apps/sim/lib/table/application/rows.ts index 11df8778be5..58080e877ba 100644 --- a/apps/sim/lib/table/application/rows.ts +++ b/apps/sim/lib/table/application/rows.ts @@ -280,8 +280,9 @@ function actorUserId( } /** - * Refuses a wire row naming a column the table does not have. Applied only to a - * `strictWrite` caller — see {@link rowWriteOptions}. + * Refuses a wire row naming a column the table does not have, on either wire. + * Applied only to a `strictWrite` caller — see {@link rowWriteOptions}. Shared so + * the two keyings cannot drift in how they name the offending keys. * * The name→id remap drops unrecognised keys, so without this an insert of * `{"nosuchcol":"x"}` created an empty row under a 201, and a patch of @@ -290,18 +291,6 @@ function actorUserId( * succeeded. Naming the offending columns is the only answer that lets a caller * tell a typo apart from an empty match. */ -function assertKnownColumnNames( - data: RowData, - idByName: ReadonlyMap, - rowLabel?: string -): void { - assertNoUnknownColumns(unknownColumnNames(data, idByName), rowLabel) -} - -/** - * Refuses a wire row naming a column the table does not have, on either wire. - * Shared so the two keyings cannot drift in how they name the offending keys. - */ function assertNoUnknownColumns(unknown: string[], rowLabel?: string): void { if (unknown.length === 0) return const where = rowLabel ? `${rowLabel}: ` : '' @@ -334,7 +323,7 @@ function assertNoUnknownColumns(unknown: string[], rowLabel?: string): void { export type TableRowDataKeying = 'names' | 'ids' /** - * The id-keyed counterpart of {@link assertKnownColumnNames}, applied on the same + * The id-keyed check {@link assertNoUnknownColumns} makes, applied on the same * `strictWrite` condition so strictness means the same thing on either wire. * * `buildColumnNameById` keys by {@link getColumnId}, so a legacy pre-backfill @@ -348,53 +337,72 @@ function assertKnownColumnIds(data: RowData, table: TableDefinition, rowLabel?: ) } +/** + * Wire keys naming no column of the table, which a lax name-keyed write drops + * instead of refusing (see {@link rowWriteOptions}), in the order first sent. + * Always empty for a `strictWrite` or id-keyed write, which drops nothing. + */ +interface IgnoredColumns { + ignoredColumns: string[] +} + /** * Normalizes one wire row to storage keying. See {@link TableRowDataKeying}. * * Note the asymmetry a lax (non-`strictWrite`) caller sees: the name path drops * keys naming no column, while the id path stores what it is given. That * matches what each wire did before this discriminator existed, and only - * `strictWrite` makes the two agree. + * `strictWrite` makes the two agree. The dropped keys come back as + * `ignoredColumns`, so the caller can report them. */ function rowDataToStorage( data: RowData, table: TableDefinition, keying: TableRowDataKeying, strict = false -): RowData { +): IgnoredColumns & { data: RowData } { if (keying === 'ids') { if (strict) assertKnownColumnIds(data, table) - return data + return { data, ignoredColumns: [] } } const idByName = buildIdByName(table.schema) - if (strict) assertKnownColumnNames(data, idByName) - return rowDataNameToId(data, idByName) + const ignoredColumns = unknownColumnNames(data, idByName) + if (strict) assertNoUnknownColumns(ignoredColumns) + return { data: rowDataNameToId(data, idByName), ignoredColumns } } /** * {@link rowDataToStorage} over a batch. Either index is built once for the * whole batch rather than per row — these paths run over up to - * `MAX_BATCH_INSERT_SIZE` rows. + * `MAX_BATCH_INSERT_SIZE` rows. `ignoredColumns` is every row's dropped keys, + * each once. */ function rowsToStorage( rows: readonly RowData[], table: TableDefinition, keying: TableRowDataKeying, strict = false -): RowData[] { +): IgnoredColumns & { rows: RowData[] } { if (keying === 'ids') { - if (!strict) return [...rows] + if (!strict) return { rows: [...rows], ignoredColumns: [] } const nameById = buildColumnNameById(table.schema.columns) - return rows.map((row, index) => { - assertNoUnknownColumns(unknownColumnNames(row, nameById), `Row ${index + 1}`) - return row - }) + return { + rows: rows.map((row, index) => { + assertNoUnknownColumns(unknownColumnNames(row, nameById), `Row ${index + 1}`) + return row + }), + ignoredColumns: [], + } } const idByName = buildIdByName(table.schema) - return rows.map((row, index) => { - if (strict) assertKnownColumnNames(row, idByName, `Row ${index + 1}`) + const ignoredColumns = new Set() + const storageRows = rows.map((row, index) => { + const unknown = unknownColumnNames(row, idByName) + if (strict) assertNoUnknownColumns(unknown, `Row ${index + 1}`) + for (const key of unknown) ignoredColumns.add(key) return rowDataNameToId(row, idByName) }) + return { rows: storageRows, ignoredColumns: [...ignoredColumns] } } /** @@ -899,8 +907,10 @@ interface CreateBatchTableRowsInput extends TableScopedInput { export type CreateTableRowsInput = CreateSingleTableRowInput | CreateBatchTableRowsInput export type CreateTableRowsResult = - | (TableResult & { kind: 'single'; row: TableRow; secretProvenance?: TableRowsProvenance }) - | (TableResult & { kind: 'batch'; rows: TableRow[]; secretProvenance?: TableRowsProvenance }) + | (TableResult & + IgnoredColumns & { kind: 'single'; row: TableRow; secretProvenance?: TableRowsProvenance }) + | (TableResult & + IgnoredColumns & { kind: 'batch'; rows: TableRow[]; secretProvenance?: TableRowsProvenance }) export const createTableRows = defineAuthorizedTableUseCase({ operation: tableOperations.createRows, @@ -923,7 +933,12 @@ export const createTableRows = defineAuthorizedTableUseCase({ ) { throw new TableRowsValidationError('Position must be 0 or greater') } - const data = rowDataToStorage(input.data, context.table, input.dataKeying, input.strictWrite) + const { data, ignoredColumns } = rowDataToStorage( + input.data, + context.table, + input.dataKeying, + input.strictWrite + ) const secretProvenance = singleRowWriteProvenance({ principal, workspaceId: context.workspaceId, @@ -961,6 +976,7 @@ export const createTableRows = defineAuthorizedTableUseCase({ kind: 'single', table: context.table, row, + ignoredColumns, ...(input.includePersistedSecretProvenance && readProvenance ? { secretProvenance: readProvenance.exportProvenance() } : {}), @@ -977,7 +993,12 @@ export const createTableRows = defineAuthorizedTableUseCase({ if (input.orderKeys && input.orderKeys.length !== input.rows.length) { throw new TableRowsValidationError('orderKeys must align one-to-one with rows') } - const rows = rowsToStorage(input.rows, context.table, input.dataKeying, input.strictWrite) + const { rows, ignoredColumns } = rowsToStorage( + input.rows, + context.table, + input.dataKeying, + input.strictWrite + ) const secretProvenance = input.secretProvenanceEnvelope ? resolveRowWriteProvenance({ envelope: input.secretProvenanceEnvelope, @@ -1017,6 +1038,7 @@ export const createTableRows = defineAuthorizedTableUseCase({ kind: 'batch', table: context.table, rows: created, + ignoredColumns, ...(input.includePersistedSecretProvenance && readProvenance ? { secretProvenance: readProvenance.exportProvenance() } : {}), @@ -1078,7 +1100,7 @@ export const replaceTableRows = defineAuthorizedTableUseCase({ throw new TableRowsValidationError('Secret provenance must align one-to-one with rows') } - const rows = rowsToStorage(input.rows, context.table, input.dataKeying, input.strictWrite) + const { rows } = rowsToStorage(input.rows, context.table, input.dataKeying, input.strictWrite) const result = await replaceTableRowsPrimitive( { tableId: context.tableId, @@ -1316,7 +1338,7 @@ export interface UpdateTableRowInput extends TableScopedInput { actorClientId?: string } -export interface UpdateTableRowResult extends TableResult { +export interface UpdateTableRowResult extends TableResult, IgnoredColumns { row: TableRow changed: boolean secretProvenance?: TableRowsProvenance @@ -1332,7 +1354,12 @@ export const updateTableRow = defineAuthorizedTableUseCase({ actorUserId(principal, context.billedAccountUserId), input.includePersistedSecretProvenance ) - const data = rowDataToStorage(input.data, context.table, input.dataKeying, input.strictWrite) + const { data, ignoredColumns } = rowDataToStorage( + input.data, + context.table, + input.dataKeying, + input.strictWrite + ) const secretProvenance = singleRowWriteProvenance({ principal, workspaceId: context.workspaceId, @@ -1360,6 +1387,7 @@ export const updateTableRow = defineAuthorizedTableUseCase({ table: context.table, row, changed: Object.keys(data).length > 0, + ignoredColumns, ...(input.includePersistedSecretProvenance && readProvenance ? { secretProvenance: readProvenance.exportProvenance() } : {}), @@ -1395,7 +1423,7 @@ export interface UpdateTableRowsInput extends TableScopedInput { secretProvenanceEnvelope?: TableRowProvenanceEnvelope } -export interface UpdateTableRowsResult extends TableResult, BulkOperationResult {} +export interface UpdateTableRowsResult extends TableResult, BulkOperationResult, IgnoredColumns {} export const updateTableRows = defineAuthorizedTableUseCase({ operation: tableOperations.updateRows, @@ -1405,7 +1433,12 @@ export const updateTableRows = defineAuthorizedTableUseCase({ if (input.limit !== undefined) { requireIntegerInRange(input.limit, 1, TABLE_LIMITS.MAX_BULK_OPERATION_SIZE, 'Limit') } - const data = rowDataToStorage(input.data, context.table, input.dataKeying, input.strictWrite) + const { data, ignoredColumns } = rowDataToStorage( + input.data, + context.table, + input.dataKeying, + input.strictWrite + ) const secretProvenance = singleRowWriteProvenance({ principal, workspaceId: context.workspaceId, @@ -1431,7 +1464,7 @@ export const updateTableRows = defineAuthorizedTableUseCase({ requestId(input), rowWriteOptions(input) ) - return { table: context.table, ...result } + return { table: context.table, ...result, ignoredColumns } } catch (error) { rethrowQueryValidation(error) } @@ -1503,7 +1536,7 @@ export const batchUpdateTableRows = defineAuthorizedTableUseCase({ `Batch update count must be between 1 and ${CSV_MAX_BATCH_SIZE}` ) } - const storageData = rowsToStorage( + const { rows: storageData } = rowsToStorage( input.updates.map((update) => update.data), context.table, input.dataKeying, @@ -1682,7 +1715,7 @@ export interface UpsertTableRowInput extends TableScopedInput { includePersistedSecretProvenance?: boolean } -export interface UpsertTableRowResult extends TableResult { +export interface UpsertTableRowResult extends TableResult, IgnoredColumns { /** Without the executions sidecar — see {@link UpsertResult.row}. */ row: TableRowSummary operation: 'insert' | 'update' @@ -1705,7 +1738,12 @@ export const upsertTableRow = defineAuthorizedTableUseCase({ input.conflictTarget && input.dataKeying !== 'ids' ? (buildIdByName(context.table.schema).get(input.conflictTarget) ?? input.conflictTarget) : input.conflictTarget - const data = rowDataToStorage(input.data, context.table, input.dataKeying, input.strictWrite) + const { data, ignoredColumns } = rowDataToStorage( + input.data, + context.table, + input.dataKeying, + input.strictWrite + ) const secretProvenance = singleRowWriteProvenance({ principal, workspaceId: context.workspaceId, @@ -1732,6 +1770,7 @@ export const upsertTableRow = defineAuthorizedTableUseCase({ table: context.table, row: result.row, operation: result.operation, + ignoredColumns, ...(input.includePersistedSecretProvenance && readProvenance ? { secretProvenance: readProvenance.exportProvenance() } : {}), diff --git a/apps/sim/lib/table/rows/writes.integration.ts b/apps/sim/lib/table/rows/writes.integration.ts index 15d293371e6..6456cd37999 100644 --- a/apps/sim/lib/table/rows/writes.integration.ts +++ b/apps/sim/lib/table/rows/writes.integration.ts @@ -2079,14 +2079,24 @@ describe('table row writes against real PostgreSQL', () => { table, 'lockless-batch' ) - // Byte order, as migration 0228 sets on the column: `db:push` leaves the default collation. const orderedNames = async (tableId: string) => ( await control<{ name: string }[]>` SELECT data->>'name' AS name FROM user_table_rows - WHERE table_id = ${tableId} ORDER BY order_key COLLATE "C", id` + WHERE table_id = ${tableId} ORDER BY order_key, id` ).map((row) => row.name) + it('orders rows by order_key in byte order, the order fractional keys are minted in', async () => { + const table = await createTable(textColumns('name')) + await seedRows(table.id, [ + { id: `${table.id}-a`, data: { name: 'a0' }, orderKey: 'a0' }, + { id: `${table.id}-z`, data: { name: 'Zz' }, orderKey: 'Zz' }, + ]) + + // Bytewise `Z` (0x5A) precedes `a` (0x61); a locale collation would put 'a0' first. + expect(await orderedNames(table.id)).toEqual(['Zz', 'a0']) + }) + it('lets every insert path commit while another transaction holds the retired row-order lock', async () => { const table = await createTable([ { id: 'name', name: 'name', type: 'string' }, diff --git a/apps/sim/lib/webhooks/slack-execution-stream.test.ts b/apps/sim/lib/webhooks/slack-execution-stream.test.ts index 765d088719b..bd41a57a64f 100644 --- a/apps/sim/lib/webhooks/slack-execution-stream.test.ts +++ b/apps/sim/lib/webhooks/slack-execution-stream.test.ts @@ -49,6 +49,8 @@ const BASE_CONFIG: SlackStreamResponseConfig = { includeToolCalls: true, taskTitle: 'Running', taskDisplayMode: 'plan', + timelineSources: [], + toolLabels: {}, } function createLoggingSession() { @@ -729,6 +731,213 @@ describe('SlackExecutionStreamController', () => { controller.assertSucceeded() }) + describe('timeline sources', () => { + const TIMELINE_CONFIG: SlackStreamResponseConfig = { + ...BASE_CONFIG, + outputConfigs: [{ blockId: 'reply', path: 'result' }], + timelineSources: [{ workflowId: 'child-workflow', blockId: 'analyst' }], + toolLabels: { lc_cur: 'Reading AWS cost data' }, + } + const TIMELINE_EVENTS: AgentStreamEvent[] = [ + { type: 'tool_call_start', id: 'tool-1', name: 'mcp-6da535c1-lc_cur' }, + { type: 'tool_call_end', id: 'tool-1', name: 'mcp-6da535c1-lc_cur', status: 'success' }, + { type: 'tool_call_start', id: 'tool-2', name: 'mcp-6da535c1-lc_other' }, + { type: 'tool_call_end', id: 'tool-2', name: 'mcp-6da535c1-lc_other', status: 'success' }, + { type: 'text_delta', text: '{"secret":"analyst json"}', turn: 'pending' }, + { type: 'turn_end', turn: 'final' }, + ] + + async function streamTimeline( + controller: SlackExecutionStreamController, + events: AgentStreamEvent[] = TIMELINE_EVENTS + ) { + await controller.callbacks.onStream?.({ + blockId: 'child-workflow.analyst', + childWorkflowInstanceId: 'child-instance-1', + executionOrder: 2, + stream: createByteStream('{"secret":"analyst json"}'), + execution: { success: true, output: {} }, + clientStreamTransformed: false, + subscribe: ({ onEvent }) => { + for (const event of events) void onEvent(event) + return vi.fn() + }, + }) + } + + function allChunks(): SlackStreamChunk[] { + return [ + ...mockStartSlackAgentStream.mock.calls.flatMap((call) => call[2]), + ...mockAppendSlackAgentStream.mock.calls.flatMap((call) => call[3]), + ...mockStopSlackAgentStream.mock.calls.flatMap((call) => call[6] ?? []), + ] + } + + it('streams the source as a block selector so the executor streams it', async () => { + const { controller } = await createController(TIMELINE_CONFIG) + expect(controller.selectedOutputs).toEqual(['reply_result', 'child-workflow.analyst_content']) + }) + + it('shows tool steps without the source text and posts the answer in the same message', async () => { + const { controller } = await createController(TIMELINE_CONFIG) + await streamTimeline(controller) + await controller.callbacks.onBlockComplete?.('reply', 'Reply', 'function', { + output: { result: 'Reviewed answer' }, + executionOrder: 3, + executionTime: 1, + startedAt: '2026-11-24T00:00:00Z', + endedAt: '2026-11-24T00:00:01Z', + }) + await controller.finalize({ success: true, status: 'completed', output: {} }) + + controller.assertSucceeded() + expect(mockStartSlackAgentStream).toHaveBeenCalledTimes(1) + expect(mockStopSlackAgentStream).toHaveBeenCalledTimes(1) + const text = allChunks() + .filter((chunk) => chunk.type === 'markdown_text') + .map((chunk) => (chunk.type === 'markdown_text' ? chunk.text : '')) + .join('') + expect(text).toBe('Reviewed answer') + const toolTitles = allChunks().flatMap((chunk) => + chunk.type === 'task_update' && chunk.id.includes('-tool-') ? [chunk.title] : [] + ) + expect(new Set(toolTitles)).toEqual(new Set(['Reading AWS cost data', 'Lc Other'])) + expect(mockStopSlackAgentStream.mock.calls[0][3]).toBe('processing') + }) + + it('stops a timeline-only message once with an error status when the run fails', async () => { + const { controller } = await createController(TIMELINE_CONFIG) + await streamTimeline(controller, [ + { type: 'tool_call_start', id: 'tool-1', name: 'mcp-6da535c1-lc_cur' }, + ]) + await controller.finalize({ success: false, output: {} }) + + expect(mockStartSlackAgentStream).toHaveBeenCalledTimes(1) + expect(mockStopSlackAgentStream).toHaveBeenCalledTimes(1) + expect(mockStopSlackAgentStream.mock.calls[0][3]).toBe('suspended') + expect(mockStopSlackAgentStream.mock.calls[0][6]).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: 'task_update', title: 'Running', status: 'error' }), + expect.objectContaining({ + type: 'task_update', + id: expect.stringContaining('-tool-tool-1'), + status: 'error', + }), + ]) + ) + }) + + it('never overlaps appends from the timeline and the answer on the shared message', async () => { + let inFlight = 0 + let maxInFlight = 0 + mockAppendSlackAgentStream.mockImplementation(async () => { + inFlight++ + maxInFlight = Math.max(maxInFlight, inFlight) + for (let tick = 0; tick < 20; tick++) await Promise.resolve() + inFlight-- + }) + const { controller } = await createController({ + ...TIMELINE_CONFIG, + outputConfigs: [{ blockId: 'reply', path: 'content' }], + }) + await Promise.all([ + streamTimeline(controller), + controller.callbacks.onStream?.({ + blockId: 'reply', + executionOrder: 3, + stream: createByteStream(), + execution: { success: true, output: {} }, + clientStreamTransformed: false, + subscribe: ({ onEvent }) => { + void onEvent({ type: 'text_delta', text: 'Reviewed answer. ', turn: 'pending' }) + void onEvent({ type: 'turn_end', turn: 'final' }) + return vi.fn() + }, + }), + ]) + + expect(mockStartSlackAgentStream).toHaveBeenCalledTimes(1) + expect(mockAppendSlackAgentStream.mock.calls.length).toBeGreaterThan(1) + expect(maxInFlight).toBe(1) + }) + + it('still rejects a stream from a block in neither list', async () => { + const { controller } = await createController(TIMELINE_CONFIG) + await expect( + controller.callbacks.onStream?.({ + blockId: 'other', + executionOrder: 1, + stream: createByteStream(), + execution: { success: true, output: {} }, + }) + ).rejects.toThrow('unselected block') + }) + }) + + describe('per-invocation outcomes', () => { + const unfinishedTool: AgentStreamEvent[] = [ + { type: 'tool_call_start', id: 'tool-1', name: 'read_file' }, + ] + + function streamEvents( + controller: SlackExecutionStreamController, + executionOrder: number, + events: AgentStreamEvent[] + ) { + return controller.callbacks.onStream?.({ + blockId: 'agent', + executionOrder, + stream: createByteStream(), + execution: { success: true, output: {} }, + clientStreamTransformed: false, + subscribe: ({ onEvent }) => { + for (const event of events) void onEvent(event) + return vi.fn() + }, + }) + } + + it('does not mark an earlier answer failed when a later one fails', async () => { + mockStartSlackAgentStream + .mockResolvedValueOnce({ channel: 'C123', ts: 'first' }) + .mockResolvedValueOnce({ channel: 'C123', ts: 'second' }) + const { controller } = await createController() + await streamEvents(controller, 1, [ + { type: 'text_delta', text: 'First answer', turn: 'pending' }, + { type: 'turn_end', turn: 'final' }, + ]) + await streamEvents(controller, 2, unfinishedTool) + await controller.finalize({ success: true, status: 'completed', output: {} }) + + const statusByTs = Object.fromEntries( + mockStopSlackAgentStream.mock.calls.map((call) => [call[2], call[3]]) + ) + expect(statusByTs).toEqual({ first: 'processing', second: 'suspended' }) + }) + + it('posts no empty reply for a later invocation after an earlier one failed', async () => { + const { controller } = await createController() + await streamEvents(controller, 1, unfinishedTool) + await streamEvents(controller, 2, []) + await controller.finalize({ success: true, status: 'completed', output: {} }) + + expect(mockStartSlackAgentStream).toHaveBeenCalledTimes(1) + expect(mockStopSlackAgentStream).toHaveBeenCalledTimes(1) + }) + + it('titles a tool whose name is an object property', async () => { + const { controller } = await createController({ ...BASE_CONFIG, toolLabels: {} }) + await streamEvents(controller, 1, [ + { type: 'tool_call_start', id: 'tool-1', name: 'toString' }, + { type: 'tool_call_end', id: 'tool-1', name: 'toString', status: 'success' }, + ]) + const toolChunk = mockAppendSlackAgentStream.mock.calls + .flatMap((call) => call[3] as SlackStreamChunk[]) + .find((chunk) => chunk.type === 'task_update' && chunk.id.includes('-tool-')) + expect(toolChunk).toMatchObject({ title: expect.any(String) }) + }) + }) + it('rejects credentials that do not belong to the workflow workspace', async () => { mockGetSlackBotCredential.mockResolvedValue({ botToken: 'xoxb-token', diff --git a/apps/sim/lib/webhooks/slack-execution-stream.ts b/apps/sim/lib/webhooks/slack-execution-stream.ts index d69be842105..2ea742ee0a7 100644 --- a/apps/sim/lib/webhooks/slack-execution-stream.ts +++ b/apps/sim/lib/webhooks/slack-execution-stream.ts @@ -2,6 +2,7 @@ import { createLogger } from '@sim/logger' import { getValueAtPath, isRecordLike } from '@sim/utils/object' import { truncate } from '@sim/utils/string' import type { LoggingSession } from '@/lib/logs/execution/logging-session' +import { parseMcpToolTarget } from '@/lib/mcp/utils' import { getToolDisplayTitle } from '@/lib/mothership/tools/display' import { getSlackBotCredential } from '@/lib/oauth/credential-service' import { @@ -13,9 +14,10 @@ import { stopSlackAgentStream, } from '@/lib/webhooks/slack-agent-api' import { SlackDeliveryError } from '@/lib/webhooks/slack-delivery-error' -import type { - SlackStreamOutputConfig, - SlackStreamResponseConfig, +import { + SLACK_TIMELINE_SOURCE_PATH, + type SlackStreamBlockRef, + type SlackStreamResponseConfig, } from '@/lib/webhooks/slack-stream-config' import { registerSlackStreamSession, @@ -23,6 +25,7 @@ import { unregisterSlackStreamSession, } from '@/lib/webhooks/slack-stream-sessions' import { formatOutputSelector, scopeOutputBlockId } from '@/lib/workflows/streaming/output-selector' +import { isMcpTool } from '@/executor/constants' import type { BlockCompletionCallbackData, ExecutionCallbacks } from '@/executor/execution/types' import type { ExecutionResult, StreamingExecution } from '@/executor/types' import type { AgentStreamEvent } from '@/providers/stream-events' @@ -40,6 +43,8 @@ interface SlackMessageStream { textLength: number textComplete: boolean stopped: boolean + /** Settles after this message's latest append, so writers sharing it append in order. */ + writes: Promise } /** Prefer a nearby paragraph/sentence, then a whole word; only oversized words need hard cuts. */ @@ -126,6 +131,98 @@ export function resolveSlackReplyTarget(triggerInput: Record): } } +/** An MCP tool's label may be keyed by its own name rather than the server-scoped one. */ +function mcpToolName(name: string): string | undefined { + if (!isMcpTool(name)) return undefined + try { + return parseMcpToolTarget(name).toolName + } catch { + return undefined + } +} + +function toolTitle(name: string, labels: Record): string { + const ownName = Object.hasOwn(labels, name) ? name : mcpToolName(name) + const label = ownName !== undefined && Object.hasOwn(labels, ownName) ? labels[ownName] : '' + return truncate(label || getToolDisplayTitle(name), TASK_TEXT_LIMIT) +} + +/** Matches a configured block against the scoped block ID the executor reports. */ +function isBlock(blockId: string): (ref: SlackStreamBlockRef) => boolean { + return (ref) => + (ref.workflowId ? scopeOutputBlockId(ref.workflowId, ref.blockId) : ref.blockId) === blockId +} + +function markdownLength(chunks: SlackStreamChunk[]): number { + return chunks.reduce( + (length, chunk) => length + (chunk.type === 'markdown_text' ? chunk.text.length : 0), + 0 + ) +} + +async function openSlackMessage( + token: string, + target: SlackReplyTarget, + config: SlackStreamResponseConfig, + chunks: SlackStreamChunk[], + taskId: string | undefined, + signal?: AbortSignal +): Promise { + const started = await startSlackAgentStream(token, target, chunks, config.taskDisplayMode, signal) + return { + ...started, + taskId, + textLength: markdownLength(chunks), + textComplete: false, + stopped: false, + writes: Promise.resolve(), + } +} + +/** Stops one message, settling its task. Cleanup has its own deadline, so no abort signal. */ +async function stopMessage( + token: string, + message: SlackMessageStream, + title: string, + failed: boolean, + chunks: SlackStreamChunk[] +): Promise { + await stopSlackAgentStream( + token, + message.channel, + message.ts, + failed ? 'suspended' : 'processing', + undefined, + undefined, + message.taskId + ? [ + ...chunks, + { type: 'task_update', id: message.taskId, title, status: failed ? 'error' : 'complete' }, + ] + : chunks + ) + message.stopped = true +} + +/** + * The first message of an execution, owned and stopped by the controller. Timeline sources write + * their steps into it and the first answer invocation writes its text there too, so steps and + * answer read as one reply. A later answer starts its own message so two answers never interleave. + */ +interface SharedMessage { + message: Promise + hasAnswer: boolean + /** Only these invocations' outcomes decide how the shared message settles. */ + writers: Set +} + +/** Returns the shared message, or undefined when another answer already writes to it. */ +type AcquireSharedMessage = ( + writer: SlackInvocationStream, + forAnswer: boolean, + start: () => Promise +) => Promise | undefined + function formatOutput(value: unknown): string { if (typeof value === 'string') return value const serialized = JSON.stringify(value, null, 2) @@ -134,7 +231,10 @@ function formatOutput(value: unknown): string { } class SlackInvocationStream { + /** Every message this invocation writes to. */ private readonly messages: SlackMessageStream[] = [] + /** The messages this invocation started, and so stops. */ + private readonly ownedMessages = new Set() private answerBuffer = '' private acknowledgedAnswer = '' private thinking = '' @@ -155,8 +255,10 @@ class SlackInvocationStream { private readonly target: SlackReplyTarget, private readonly config: SlackStreamResponseConfig, private readonly taskId: string, - private readonly title: string, private readonly projectLiveText: (text: string) => Promise, + private readonly acquireSharedMessage: AcquireSharedMessage, + /** Shows tool steps and thinking only; the source's text never reaches Slack. */ + private readonly timelineOnly: boolean, private readonly signal?: AbortSignal ) {} @@ -171,40 +273,52 @@ class SlackInvocationStream { private async ensureStarted(): Promise { const current = this.messages.at(-1) if (current) return current - return this.startMessage( - [{ type: 'task_update', id: this.taskId, title: this.title, status: 'in_progress' }], - this.taskId - ) + const start = () => + openSlackMessage( + this.token, + this.target, + this.config, + [ + { + type: 'task_update', + id: this.taskId, + title: this.config.taskTitle, + status: 'in_progress', + }, + ], + this.taskId, + this.signal + ) + const shared = this.acquireSharedMessage(this, !this.timelineOnly, start) + const message = shared ? await shared : await start() + if (!shared) this.ownedMessages.add(message) + this.messages.push(message) + return message } - private async startMessage( - chunks: SlackStreamChunk[], - taskId?: string - ): Promise { - const started = await startSlackAgentStream( + private async startMessage(chunks: SlackStreamChunk[]): Promise { + const message = await openSlackMessage( this.token, this.target, + this.config, chunks, - this.config.taskDisplayMode, + undefined, this.signal ) - const textLength = chunks.reduce( - (length, chunk) => length + (chunk.type === 'markdown_text' ? chunk.text.length : 0), - 0 - ) - const message = { ...started, taskId, textLength, textComplete: false, stopped: false } + this.ownedMessages.add(message) this.messages.push(message) return message } private async append(chunks: SlackStreamChunk[], message?: SlackMessageStream): Promise { const target = message ?? (await this.ensureStarted()) - const textLength = chunks.reduce( - (length, chunk) => length + (chunk.type === 'markdown_text' ? chunk.text.length : 0), - 0 - ) + const textLength = markdownLength(chunks) try { - await appendSlackAgentStream(this.token, target.channel, target.ts, chunks, this.signal) + const write = target.writes.then(() => + appendSlackAgentStream(this.token, target.channel, target.ts, chunks, this.signal) + ) + target.writes = write.catch(() => {}) + await write target.textLength += textLength } catch (error) { logger.warn('Slack stream append failed', { @@ -366,7 +480,7 @@ class SlackInvocationStream { return { type: 'task_update', id: `${this.taskId}-tool-${id}`, - title: truncate(getToolDisplayTitle(tool.name), TASK_TEXT_LIMIT), + title: toolTitle(tool.name, this.config.toolLabels), status: tool.status, } } @@ -399,11 +513,25 @@ class SlackInvocationStream { this.failure ??= formatSlackApiFailure(error) } - finish(success: boolean): Promise { + get failed(): boolean { + return Boolean(this.failure) + } + + /** Error steps for this invocation's tools still running on `message`. */ + unfinishedToolChunks(message: SlackMessageStream): SlackStreamChunk[] { + return [...this.tools].flatMap(([id, tool]) => + tool.message === message && (tool.status === 'pending' || tool.status === 'in_progress') + ? [this.toolChunk(id, { ...tool, status: 'error' })] + : [] + ) + } + + /** Readies this response to stop: a successful empty answer still shows its settled task. */ + settle(success: boolean): Promise { return this.enqueue(async () => { if (this.stopAttempted) return if (this.messages.length === 0) { - if (this.failure || !success) return + if (this.failure || !success || this.timelineOnly) return await this.ensureStarted() } if ( @@ -414,34 +542,23 @@ class SlackInvocationStream { ) { this.failure ??= new Error('Slack delivery ended with unfinished tool calls') } + }) + } + + /** Stops the messages this invocation started; the controller stops the shared one. */ + stop(success: boolean): Promise { + return this.enqueue(async () => { + if (this.stopAttempted) return this.stopAttempted = true - for (const message of this.messages) { - const failed = Boolean(this.failure) || !success - const chunks: SlackStreamChunk[] = [...this.tools].flatMap(([id, tool]) => - tool.message === message && (tool.status === 'pending' || tool.status === 'in_progress') - ? [this.toolChunk(id, { ...tool, status: 'error' })] - : [] - ) - if (message.taskId) { - chunks.push({ - type: 'task_update', - id: message.taskId, - title: this.title, - status: failed ? 'error' : 'complete', - }) - } + for (const message of this.ownedMessages) { try { - /** Cleanup has its own deadline and attempts every part even if an earlier stop failed. */ - await stopSlackAgentStream( + await stopMessage( this.token, - message.channel, - message.ts, - failed ? 'suspended' : 'processing', - undefined, - undefined, - chunks + message, + this.config.taskTitle, + Boolean(this.failure) || !success, + this.unfinishedToolChunks(message) ) - message.stopped = true } catch (error) { this.recordFailure(error) } @@ -451,7 +568,7 @@ class SlackInvocationStream { assertSucceeded(): void { if (this.failure) throw this.failure - if (this.messages.some((message) => !message.stopped)) { + if ([...this.ownedMessages].some((message) => !message.stopped)) { throw new Error('Slack response stream was not stopped') } } @@ -465,6 +582,7 @@ export class SlackExecutionStreamController { private readonly target: SlackReplyTarget private readonly token: string private readonly invocations = new Map() + private sharedMessage?: SharedMessage private finalization?: Promise private finalized = false @@ -475,9 +593,14 @@ export class SlackExecutionStreamController { ) { this.token = token this.target = target - this.selectedOutputs = options.config.outputConfigs.map((output) => - formatOutputSelector(output.blockId, output.path, output.workflowId) - ) + this.selectedOutputs = [ + ...options.config.outputConfigs.map((output) => + formatOutputSelector(output.blockId, output.path, output.workflowId) + ), + ...options.config.timelineSources.map((source) => + formatOutputSelector(source.blockId, SLACK_TIMELINE_SOURCE_PATH, source.workflowId) + ), + ] this.callbacks = { onStream: (stream) => this.onStream(stream), onBlockComplete: (blockId, _blockName, _blockType, data) => @@ -514,13 +637,35 @@ export class SlackExecutionStreamController { return controller } - private selectedForBlock(blockId: string): SlackStreamOutputConfig[] { - return this.options.config.outputConfigs.filter((output) => { - const selectedBlockId = output.workflowId - ? scopeOutputBlockId(output.workflowId, output.blockId) - : output.blockId - return selectedBlockId === blockId - }) + private readonly acquireSharedMessage: AcquireSharedMessage = (writer, forAnswer, start) => { + if (!this.sharedMessage) { + this.sharedMessage = { message: start(), hasAnswer: forAnswer, writers: new Set([writer]) } + return this.sharedMessage.message + } + if (forAnswer) { + if (this.sharedMessage.hasAnswer) return undefined + this.sharedMessage.hasAnswer = true + } + this.sharedMessage.writers.add(writer) + return this.sharedMessage.message + } + + private createInvocation( + executionOrder: number, + childWorkflowInstanceId: string | undefined, + projectLiveText: (text: string) => Promise, + timelineOnly: boolean + ): SlackInvocationStream { + return new SlackInvocationStream( + this.token, + this.target, + this.options.config, + this.taskId(executionOrder, childWorkflowInstanceId), + projectLiveText, + this.acquireSharedMessage, + timelineOnly, + this.options.abortSignal + ) } private invocationKey( @@ -531,8 +676,12 @@ export class SlackExecutionStreamController { return `${blockId}:${childWorkflowInstanceId ?? executionOrder}` } + /** Unique per invocation: blocks of one child workflow instance share the shared message. */ private taskId(executionOrder: number, childWorkflowInstanceId?: string): string { - return `sim-${this.options.executionId}-${childWorkflowInstanceId ?? executionOrder}` + const invocation = childWorkflowInstanceId + ? `${childWorkflowInstanceId}-${executionOrder}` + : executionOrder + return `sim-${this.options.executionId}-${invocation}` } private recordFailure(error: unknown): Error { @@ -558,7 +707,9 @@ export class SlackExecutionStreamController { if (!stream.blockId || stream.executionOrder === undefined) { throw new Error('Slack streaming received a stream without invocation metadata') } - if (this.selectedForBlock(stream.blockId).length === 0) { + const { outputConfigs, timelineSources } = this.options.config + const timelineOnly = !outputConfigs.some(isBlock(stream.blockId)) + if (timelineOnly && !timelineSources.some(isBlock(stream.blockId))) { throw new Error(`Slack streaming received an unselected block: ${stream.blockId}`) } const key = this.invocationKey( @@ -569,18 +720,18 @@ export class SlackExecutionStreamController { if (this.invocations.has(key)) { throw new Error(`Duplicate Slack stream invocation: ${key}`) } - const invocation = new SlackInvocationStream( - this.token, - this.target, - this.options.config, - this.taskId(stream.executionOrder, stream.childWorkflowInstanceId), - this.options.config.taskTitle, + const invocation = this.createInvocation( + stream.executionOrder, + stream.childWorkflowInstanceId, (text) => this.projectLiveText(text, stream.displayResolvedSecretTraceProvenance), - this.options.abortSignal + timelineOnly ) this.invocations.set(key, invocation) - const answerFromEventSink = Boolean(stream.subscribe) && !stream.clientStreamTransformed + // A timeline source's text is drained for the executor but never read into Slack. + const answerFromEventSink = + !timelineOnly && Boolean(stream.subscribe) && !stream.clientStreamTransformed + const answerFromBytes = !timelineOnly && !answerFromEventSink const unsubscribe = stream.subscribe?.({ onEvent: async (event) => { if (!answerFromEventSink && event.type === 'text_delta') return @@ -593,11 +744,11 @@ export class SlackExecutionStreamController { while (true) { const { done, value } = await reader.read() if (done) break - if (!answerFromEventSink) { + if (answerFromBytes) { await invocation.appendProjectedBytes(decoder.decode(value, { stream: true })) } } - if (!answerFromEventSink) { + if (answerFromBytes) { const remainder = decoder.decode() if (remainder) await invocation.appendProjectedBytes(remainder) } @@ -617,7 +768,7 @@ export class SlackExecutionStreamController { private async onBlockComplete(blockId: string, data: BlockCompletionCallbackData): Promise { try { const selectedOutputBlockId = data.outputBlockId ?? blockId - const selected = this.selectedForBlock(selectedOutputBlockId) + const selected = this.options.config.outputConfigs.filter(isBlock(selectedOutputBlockId)) if (selected.length === 0) return const key = this.invocationKey( selectedOutputBlockId, @@ -641,14 +792,11 @@ export class SlackExecutionStreamController { : values.map(({ path, value }) => `*${path}*\n${formatOutput(value)}`).join('\n\n') const invocation = this.invocations.get(key) ?? - new SlackInvocationStream( - this.token, - this.target, - this.options.config, - this.taskId(data.executionOrder, data.childWorkflowInstanceId), - this.options.config.taskTitle, + this.createInvocation( + data.executionOrder, + data.childWorkflowInstanceId, async (value) => value, - this.options.abortSignal + false ) this.invocations.set(key, invocation) await invocation.reconcileSettledOutput(text) @@ -663,13 +811,22 @@ export class SlackExecutionStreamController { } private async finalizeOnce(result: ExecutionResult): Promise { - for (const invocation of this.invocations.values()) { - await invocation.finish( - !this.failure && - result.success && - result.status !== 'cancelled' && - result.status !== 'paused' - ) + const succeeded = () => + !this.failure && result.success && result.status !== 'cancelled' && result.status !== 'paused' + const invocations = [...this.invocations.values()] + // An invocation succeeds only if every one before it did, as when each settled in turn. + const successes = new Map() + let earlierFailed = false + for (const invocation of invocations) { + const success = succeeded() && !earlierFailed + successes.set(invocation, success) + await invocation.settle(success) + earlierFailed ||= invocation.failed + } + // The shared message is the reply's first, so it settles before any continuation. + await this.stopSharedMessage(invocations, successes) + for (const invocation of invocations) { + await invocation.stop(successes.get(invocation) === true) try { invocation.assertSucceeded() } catch (error) { @@ -698,6 +855,27 @@ export class SlackExecutionStreamController { this.finalized = true } + private async stopSharedMessage( + invocations: SlackInvocationStream[], + successes: ReadonlyMap + ): Promise { + if (!this.sharedMessage) return + try { + const message = await this.sharedMessage.message + await stopMessage( + this.token, + message, + this.options.config.taskTitle, + [...this.sharedMessage.writers].some( + (writer) => writer.failed || successes.get(writer) !== true + ), + invocations.flatMap((invocation) => invocation.unfinishedToolChunks(message)) + ) + } catch (error) { + this.recordFailure(error) + } + } + assertSucceeded(): void { if (this.failure) throw this.failure if (!this.finalized) throw new Error('Slack delivery has not been finalized') diff --git a/apps/sim/lib/webhooks/slack-stream-config.test.ts b/apps/sim/lib/webhooks/slack-stream-config.test.ts index 978fb43f8d9..6b1d7987b73 100644 --- a/apps/sim/lib/webhooks/slack-stream-config.test.ts +++ b/apps/sim/lib/webhooks/slack-stream-config.test.ts @@ -33,6 +33,8 @@ describe('Slack stream response config', () => { includeToolCalls: false, taskTitle: 'Working', taskDisplayMode: 'plan', + timelineSources: [], + toolLabels: {}, }) expect(readSlackStreamResponseConfig(providerConfig)).toEqual(normalized) expect(providerConfig.streamResponse).toBeUndefined() @@ -91,4 +93,91 @@ describe('Slack stream response config', () => { ).toThrow('Invalid Slack stream output selector') } ) + + describe('timeline sources', () => { + const blocks = { + 'agent-1': { id: 'agent-1', name: 'Analyst', type: 'agent' }, + 'fn-1': { id: 'fn-1', name: 'Format Answer', type: 'function' }, + } + + it('normalizes block-level sources and tool labels, and reads them back', () => { + const providerConfig: Record = { + eventType: 'message', + streamResponse: true, + streamOutputs: ['formatanswer.result'], + streamTimelineSources: ['analyst.content', `${CHILD_WORKFLOW_ID}.analyst`], + streamToolLabels: [ + { id: 'r1', cells: { Tool: ' lc_cur ', Label: ' Reading AWS cost data ' } }, + { id: 'r2', cells: { Tool: '', Label: 'ignored' } }, + ], + } + const normalized = normalizeSlackStreamResponseConfig(providerConfig, blocks) + replaceSlackStreamAuthoringConfig(providerConfig, normalized) + + expect(normalized?.timelineSources).toEqual([ + { blockId: 'agent-1' }, + { workflowId: CHILD_WORKFLOW_ID, blockId: 'analyst' }, + ]) + expect(normalized?.toolLabels).toEqual({ lc_cur: 'Reading AWS cost data' }) + expect(readSlackStreamResponseConfig(providerConfig)).toEqual(normalized) + expect(providerConfig.streamTimelineSources).toBeUndefined() + expect(providerConfig.streamToolLabels).toBeUndefined() + }) + + it('reads configs deployed before timeline sources existed', () => { + const config = readSlackStreamResponseConfig({ + streamResponseConfig: { + enabled: true, + outputConfigs: [{ blockId: 'block', path: 'content' }], + includeThinking: false, + includeToolCalls: true, + taskDisplayMode: 'timeline', + }, + }) + expect(config?.timelineSources).toEqual([]) + expect(config?.toolLabels).toEqual({}) + }) + + it('rejects a block that is both an answer output and a timeline source', () => { + expect(() => + normalizeSlackStreamResponseConfig( + { + eventType: 'message', + streamResponse: true, + streamOutputs: ['analyst.content'], + streamTimelineSources: ['analyst'], + }, + blocks + ) + ).toThrow('both') + }) + + it('rejects a timeline source that is not an Agent block', () => { + expect(() => + normalizeSlackStreamResponseConfig( + { + eventType: 'message', + streamResponse: true, + streamOutputs: ['analyst.content'], + streamTimelineSources: ['formatanswer'], + }, + blocks + ) + ).toThrow('must be an Agent block') + }) + + it('rejects a timeline source path other than the Agent content', () => { + expect(() => + normalizeSlackStreamResponseConfig( + { + eventType: 'message', + streamResponse: true, + streamOutputs: ['formatanswer.result'], + streamTimelineSources: ['analyst.model'], + }, + blocks + ) + ).toThrow('timeline source') + }) + }) }) diff --git a/apps/sim/lib/webhooks/slack-stream-config.ts b/apps/sim/lib/webhooks/slack-stream-config.ts index 175435902ed..a907646dfd0 100644 --- a/apps/sim/lib/webhooks/slack-stream-config.ts +++ b/apps/sim/lib/webhooks/slack-stream-config.ts @@ -1,4 +1,4 @@ -import { isRecordLike } from '@sim/utils/object' +import { isRecordLike, toRecordOrNull } from '@sim/utils/object' import { formatInternalOutputSelector, parsePublicOutputSelector, @@ -7,9 +7,7 @@ import { import { normalizeName } from '@/executor/constants' import { SLACK_STREAM_RESPONSE_EVENTS } from '@/triggers/slack/shared' -export interface SlackStreamOutputConfig { - workflowId?: string - blockId: string +interface SlackStreamOutputConfig extends SlackStreamBlockRef { path: string } @@ -20,9 +18,24 @@ export interface SlackStreamResponseConfig { includeToolCalls: boolean taskTitle: string taskDisplayMode: 'timeline' | 'plan' + /** Agent blocks whose tool steps (and thinking, when enabled) are shown without their text. */ + timelineSources: SlackStreamBlockRef[] + /** Display titles for tool steps, keyed by tool name (an MCP tool by its own name). */ + toolLabels: Record +} + +/** A block of the triggered workflow, or of a child workflow when `workflowId` is set. */ +export interface SlackStreamBlockRef { + workflowId?: string + blockId: string } +type SlackStreamAuthoringBlocks = Record + const SLACK_TASK_TITLE_LIMIT = 256 +/** A timeline source streams through its Agent's answer output, which is never posted. */ +export const SLACK_TIMELINE_SOURCE_PATH = 'content' +const SLACK_TIMELINE_SOURCE_BLOCK_TYPE = 'agent' function parseSlackOutputSelector( selector: string, @@ -39,10 +52,56 @@ function parseSlackOutputSelector( return { ...parsed, blockId } } +/** Accepts `` or `.`, with or without the `.content` the picker adds. */ +function parseSlackTimelineSource( + selector: string, + blocks: SlackStreamAuthoringBlocks, + currentBlockRefs: ReadonlySet +): SlackStreamBlockRef { + const suffix = `.${SLACK_TIMELINE_SOURCE_PATH}` + const parsed = parsePublicOutputSelector( + selector.endsWith(suffix) ? selector : `${selector}${suffix}`, + { currentBlockRefs } + ) + if (parsed.path !== SLACK_TIMELINE_SOURCE_PATH) { + throw new Error(`Slack timeline source must select an Agent block: ${selector}`) + } + if (parsed.workflowId) return { workflowId: parsed.workflowId, blockId: parsed.blockId } + const blockId = resolveOutputBlockRef(parsed.blockId, blocks) + if (blocks[blockId]?.type !== SLACK_TIMELINE_SOURCE_BLOCK_TYPE) { + throw new Error(`Slack timeline source must be an Agent block: ${selector}`) + } + return { blockId } +} + +function sameBlock(a: SlackStreamBlockRef, b: SlackStreamBlockRef): boolean { + return a.blockId === b.blockId && a.workflowId === b.workflowId +} + +/** Reads the editor's Tool/Label table, skipping incomplete rows. */ +function parseSlackToolLabels(value: unknown): Record { + if (value === undefined || value === null || value === '') return {} + if (!Array.isArray(value)) throw new Error('Slack tool step labels must be a table') + const labels: Record = {} + for (const row of value) { + const cells = isRecordLike(row) ? toRecordOrNull(row.cells) : null + const tool = typeof cells?.Tool === 'string' ? cells.Tool.trim() : '' + const label = typeof cells?.Label === 'string' ? cells.Label.trim() : '' + if (!tool || !label) continue + if (label.length > SLACK_TASK_TITLE_LIMIT) { + throw new Error( + `Slack tool step label for ${tool} must be ${SLACK_TASK_TITLE_LIMIT} characters or fewer` + ) + } + labels[tool] = label + } + return labels +} + /** Converts trigger authoring fields into the durable Slack streaming contract. */ export function normalizeSlackStreamResponseConfig( providerConfig: Record, - blocks: Record + blocks: SlackStreamAuthoringBlocks ): SlackStreamResponseConfig | null { if (providerConfig.streamResponse !== true) return null @@ -83,16 +142,63 @@ export function normalizeSlackStreamResponseConfig( if (block.name) currentBlockRefs.add(normalizeName(block.name)) } + const rawTimelineSources = providerConfig.streamTimelineSources ?? [] + if (!Array.isArray(rawTimelineSources)) { + throw new Error('Slack timeline sources must be a list of Agent blocks') + } + const outputConfigs = selectors.map((selector) => + parseSlackOutputSelector(selector, blocks, currentBlockRefs) + ) + const timelineSources = rawTimelineSources.map((value) => { + if (typeof value !== 'string' || !value) { + throw new Error('Slack timeline sources must be non-empty strings') + } + const source = parseSlackTimelineSource(value, blocks, currentBlockRefs) + if (outputConfigs.some((output) => sameBlock(output, source))) { + throw new Error(`A block cannot be both a streamed output and a timeline source: ${value}`) + } + return source + }) + return { enabled: true, - outputConfigs: selectors.map((selector) => - parseSlackOutputSelector(selector, blocks, currentBlockRefs) - ), + outputConfigs, includeThinking: providerConfig.streamIncludeThinking === true, includeToolCalls: providerConfig.streamIncludeToolCalls !== false, taskTitle, taskDisplayMode, + timelineSources, + toolLabels: parseSlackToolLabels(providerConfig.streamToolLabels), + } +} + +/** Validates a persisted block reference; `kind` names it in errors. */ +function readBlockRef(value: unknown, kind: string): SlackStreamBlockRef { + if (!isRecordLike(value) || typeof value.blockId !== 'string' || !value.blockId) { + throw new Error(`Persisted Slack ${kind} is missing a block ID`) } + if (value.workflowId === undefined) return { blockId: value.blockId } + if (typeof value.workflowId !== 'string' || !value.workflowId) { + throw new Error(`Persisted Slack ${kind} has an invalid workflow ID`) + } + return { workflowId: value.workflowId, blockId: value.blockId } +} + +function readTimelineSources(value: unknown): SlackStreamBlockRef[] { + if (value === undefined) return [] + if (!Array.isArray(value)) throw new Error('Persisted Slack timeline sources are invalid') + return value.map((source) => readBlockRef(source, 'timeline source')) +} + +function readToolLabels(value: unknown): Record { + if (value === undefined) return {} + if (!isRecordLike(value)) throw new Error('Persisted Slack tool step labels are invalid') + return Object.fromEntries( + Object.entries(value).map(([tool, label]) => { + if (typeof label !== 'string') throw new Error('Persisted Slack tool step labels are invalid') + return [tool, label] + }) + ) } /** Reads and validates the normalized config stored on a deployed webhook. */ @@ -108,28 +214,13 @@ export function readSlackStreamResponseConfig( throw new Error('Persisted Slack stream configuration has no outputs') } const outputConfigs = value.outputConfigs.map((output) => { - if (!isRecordLike(output) || typeof output.blockId !== 'string' || !output.blockId) { - throw new Error('Persisted Slack stream output is missing a block ID') - } - if (typeof output.path !== 'string' || !output.path) { + const ref = readBlockRef(output, 'stream output') + const path = isRecordLike(output) ? output.path : undefined + if (typeof path !== 'string' || !path) { throw new Error('Persisted Slack stream output is missing an output path') } - if ( - output.workflowId !== undefined && - (typeof output.workflowId !== 'string' || !output.workflowId) - ) { - throw new Error('Persisted Slack stream output has an invalid workflow ID') - } - formatInternalOutputSelector( - output.blockId, - output.path, - typeof output.workflowId === 'string' ? output.workflowId : undefined - ) - return { - ...(typeof output.workflowId === 'string' ? { workflowId: output.workflowId } : {}), - blockId: output.blockId, - path: output.path, - } + formatInternalOutputSelector(ref.blockId, path, ref.workflowId) + return { ...ref, path } }) if (typeof value.includeThinking !== 'boolean' || typeof value.includeToolCalls !== 'boolean') { throw new Error('Persisted Slack stream visibility settings are invalid') @@ -151,6 +242,8 @@ export function readSlackStreamResponseConfig( includeToolCalls: value.includeToolCalls, taskTitle, taskDisplayMode: value.taskDisplayMode, + timelineSources: readTimelineSources(value.timelineSources), + toolLabels: readToolLabels(value.toolLabels), } } @@ -175,4 +268,6 @@ export function replaceSlackStreamAuthoringConfig( providerConfig.streamIncludeToolCalls = undefined providerConfig.streamTaskTitle = undefined providerConfig.streamTaskDisplayMode = undefined + providerConfig.streamTimelineSources = undefined + providerConfig.streamToolLabels = undefined } diff --git a/apps/sim/lib/workflows/api/index.ts b/apps/sim/lib/workflows/api/index.ts index 45bf083bdb5..0ff72cc9f44 100644 --- a/apps/sim/lib/workflows/api/index.ts +++ b/apps/sim/lib/workflows/api/index.ts @@ -7,6 +7,8 @@ export { v2WorkflowErrorPolicies, WORKFLOW_NOT_FOUND_MESSAGE, } from '@/lib/workflows/api/route-policies' +export { presentV2RunError } from '@/lib/workflows/api/run-error' +export { presentV2RunPause } from '@/lib/workflows/api/run-pause' export { withBoundSourceFindings } from '@/lib/workflows/api/source-findings' export { presentSourceOutcome } from '@/lib/workflows/api/source-presenters' export { applyOrDryRunLane, withSourceSlot } from '@/lib/workflows/api/source-slots' diff --git a/apps/sim/lib/workflows/api/route-policies.ts b/apps/sim/lib/workflows/api/route-policies.ts index 6ba5bbaf78a..8316ff74ea8 100644 --- a/apps/sim/lib/workflows/api/route-policies.ts +++ b/apps/sim/lib/workflows/api/route-policies.ts @@ -4,7 +4,8 @@ import type { SessionPrincipal, WorkspaceApiKeyPrincipal, } from '@sim/auth/principal' -import { boundAnswerFindings } from '@sim/workflow-code/diagnostics' +import { boundAnswerFindings, SOURCE_REFUSAL_CODES } from '@sim/workflow-code/diagnostics' +import type { NextResponse } from 'next/server' import { v2CancelWorkflowRunDataSchema } from '@/lib/api/contracts/v2/workflows' import { createInternalResourceConcealmentPolicy, @@ -62,6 +63,29 @@ function v2CancelRunErrorResponse(error: unknown) { return v2CaughtOrchestrationError(error) } +/** + * The refusals a source apply and a source create share: no slot answers `429` with + * `Retry-After`, refused source answers `400` (`413` for a size limit) with its line-pinned + * diagnostics, and a name taken in the folder answers `409` with `SOURCE_NAME_TAKEN`. + */ +function renderWorkflowSourceRefusal(error: unknown): NextResponse | undefined { + const busy = renderSourceSlotBusy(error) + if (busy) return busy + if (error instanceof WorkflowSourceRejectedError) { + return v2ErrorForOrchestration(error.code, error.message, { + code: SOURCE_REFUSAL_CODES.rejected, + diagnostics: boundAnswerFindings(error.diagnostics), + }) + } + if (error instanceof WorkflowSourceNameTakenError) { + return v2ErrorForOrchestration(error.code, error.message, { + code: SOURCE_REFUSAL_CODES.nameTaken, + name: error.workflowName, + }) + } + return undefined +} + export const v2WorkflowErrorPolicies = { default: v2OrchestrationErrorPolicy, import: { @@ -101,8 +125,8 @@ export const v2WorkflowErrorPolicies = { concealWorkflowGraphAuthorization: createV2ResourceConcealmentPolicy({ notFoundMessage: 'Workflow not found', render(error) { - const busy = renderSourceSlotBusy(error) - if (busy) return busy + const refusal = renderWorkflowSourceRefusal(error) + if (refusal) return refusal if (error instanceof WorkflowOperationsNotAppliedError) { return v2ErrorForOrchestration(error.code, error.message, { code: 'OPERATIONS_NOT_APPLIED', @@ -110,24 +134,12 @@ export const v2WorkflowErrorPolicies = { droppedInputs: error.droppedInputs, }) } - if (error instanceof WorkflowSourceRejectedError) { - return v2ErrorForOrchestration(error.code, error.message, { - code: 'SOURCE_REJECTED', - diagnostics: boundAnswerFindings(error.diagnostics), - }) - } if (error instanceof WorkflowSourceStaleError) { return v2ErrorForOrchestration(error.code, error.message, { - code: 'SOURCE_STALE', + code: SOURCE_REFUSAL_CODES.stale, currentFingerprint: error.currentFingerprint, }) } - if (error instanceof WorkflowSourceNameTakenError) { - return v2ErrorForOrchestration(error.code, error.message, { - code: 'SOURCE_NAME_TAKEN', - name: error.workflowName, - }) - } return v2CaughtOrchestrationError(error) }, }), @@ -141,21 +153,7 @@ export const v2WorkflowErrorPolicies = { concealWorkspaceSourceCreate: createV2ResourceConcealmentPolicy({ notFoundMessage: 'Workspace not found', render(error) { - const busy = renderSourceSlotBusy(error) - if (busy) return busy - if (error instanceof WorkflowSourceRejectedError) { - return v2ErrorForOrchestration(error.code, error.message, { - code: 'SOURCE_REJECTED', - diagnostics: boundAnswerFindings(error.diagnostics), - }) - } - if (error instanceof WorkflowSourceNameTakenError) { - return v2ErrorForOrchestration(error.code, error.message, { - code: 'SOURCE_NAME_TAKEN', - name: error.workflowName, - }) - } - return v2CaughtOrchestrationError(error) + return renderWorkflowSourceRefusal(error) ?? v2CaughtOrchestrationError(error) }, }), concealRunAuthorization: createV2ResourceConcealmentPolicy({ diff --git a/apps/sim/lib/workflows/api/run-error.ts b/apps/sim/lib/workflows/api/run-error.ts new file mode 100644 index 00000000000..e0b1deaa4d4 --- /dev/null +++ b/apps/sim/lib/workflows/api/run-error.ts @@ -0,0 +1,14 @@ +import type { V2ExecutionError } from '@/lib/api/contracts/v2/workflows' +import type { StructuredExecutionError } from '@/executor/utils/errors' + +/** + * The v2 wire shape of a run's failure, shared by the execute result and the run resource: the + * classified error with the block a rerun of it starts from, when the run's reader found one. + */ +export function presentV2RunError( + error: StructuredExecutionError | null, + rerunFromBlockId: string | undefined +): V2ExecutionError | null { + if (!error) return null + return rerunFromBlockId ? { ...error, rerunFromBlockId } : error +} diff --git a/apps/sim/lib/workflows/api/run-pause.ts b/apps/sim/lib/workflows/api/run-pause.ts new file mode 100644 index 00000000000..3856e724b15 --- /dev/null +++ b/apps/sim/lib/workflows/api/run-pause.ts @@ -0,0 +1,20 @@ +import type { V2ExecuteWorkflowData } from '@/lib/api/contracts/v2/workflows' +import type { RunPause } from '@/lib/workflows/executor/run-pause' + +/** + * The v2 wire shape of where a run waits, shared by the execute and resume results; null when it + * is not paused. + */ +export function presentV2RunPause( + pause: RunPause | null | undefined +): V2ExecuteWorkflowData['paused'] { + if (!pause) return null + return { + runId: pause.runId, + points: pause.points.map((point) => ({ + contextId: point.contextId, + kind: point.pauseKind, + status: point.resumeStatus, + })), + } +} diff --git a/apps/sim/lib/workflows/application/apply-workflow-operations-edits.integration.ts b/apps/sim/lib/workflows/application/apply-workflow-operations-edits.integration.ts index ac5b0a3ae4e..83696c90a7f 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-operations-edits.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-operations-edits.integration.ts @@ -1,11 +1,15 @@ /** - * Real PostgreSQL coverage for what an operations batch persists when it renames a block or - * sets a loop or parallel count from a string, read back from the normalized tables. + * Real PostgreSQL coverage for what an operations batch persists when it renames a block, sets a + * loop or parallel count from a string, or moves a connected block into a loop, read back from + * the normalized tables. */ import { db } from '@sim/db' import { auditLog, permissions, user, workflow, workspace } from '@sim/db/schema' import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' -import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' +import { + createDelegatedPrincipal, + createSessionPrincipal, +} from '@sim/testing/factories/principal.factory' import { featureFlagsMock } from '@sim/testing/mocks/feature-flags.mock' import { realtimeNotifyMock } from '@sim/testing/mocks/realtime-notify.mock' import { generateId } from '@sim/utils/id' @@ -38,7 +42,10 @@ function block(id: string, type: string, name: string, code?: string): BlockStat } } -async function seedWorkflow(blocks: BlockState[]): Promise { +async function seedWorkflow( + blocks: BlockState[], + edges: WorkflowState['edges'] = [] +): Promise { const id = generateId() const now = new Date() await db.insert(workflow).values({ @@ -52,7 +59,7 @@ async function seedWorkflow(blocks: BlockState[]): Promise { }) const state: WorkflowState = { blocks: Object.fromEntries(blocks.map((entry) => [entry.id, entry])), - edges: [], + edges, loops: {}, parallels: {}, } @@ -134,6 +141,83 @@ describe('renaming a block through an operations batch', () => { }) }) +describe('moving a connected block into a loop', () => { + it('removes the edges the move leaves crossing the boundary, names them, and applies atomically', async () => { + const start = generateId() + const fetch = generateId() + const notify = generateId() + const loop = generateId() + const edge = (source: string, target: string) => ({ + id: generateId(), + source, + target, + sourceHandle: 'source', + targetHandle: 'target', + }) + const kept = edge(start, fetch) + const workflowId = await seedWorkflow( + [ + block(start, 'starter', 'Start'), + block(fetch, 'function', 'Fetch', 'return 1'), + block(notify, 'function', 'Notify', 'return 2'), + { ...block(loop, 'loop', 'Repeat'), data: { loopType: 'for', count: 2 } }, + ], + [kept, edge(fetch, notify)] + ) + + const result = await apply( + workflowId, + [{ operation_type: 'edit', block_id: notify, params: { parentId: loop } }], + true + ) + + expect(result.skipped).toEqual([]) + expect(result.warnings).toContainEqual( + expect.stringContaining( + 'Removed 1 existing edge(s) this batch left invalid: "Fetch" -> "Notify"' + ) + ) + expect(result.warnings).toContainEqual(expect.stringContaining('wire into its body from')) + const { blocks, edges } = await stored(workflowId) + expect(blocks[notify].data?.parentId).toBe(loop) + expect(edges.map(({ id }) => id)).toEqual([kept.id]) + }) + + it('gives loop and parallel wiring advice only when a removed edge crossed a boundary', async () => { + const fetch = generateId() + const note = generateId() + const workflowId = await seedWorkflow([ + block(fetch, 'function', 'Fetch', 'return 1'), + block(note, 'note', 'Note'), + ]) + const base = await stored(workflowId) + const baseGraph = { + ...base, + edges: [{ id: generateId(), source: fetch, target: note, sourceHandle: 'source' }], + } + + const result = await withPermissionGroupScope(() => + applyWorkflowOperations.execute({ + principal: createDelegatedPrincipal({ + subjectUserId: ownerId, + workspaceId, + audience: 'sim:workflows', + }), + input: { + workflowId, + baseGraph, + operations: [{ operation_type: 'edit', block_id: fetch, params: { name: 'Fetch rows' } }], + }, + }) + ) + + const removed = result.warnings.filter((warning) => warning.startsWith('Removed 1 existing')) + expect(removed).toEqual([expect.stringContaining('"Fetch rows" -> "Note"')]) + expect(removed[0]).not.toContain('loop') + expect((await stored(workflowId)).edges).toEqual([]) + }) +}) + describe('a loop or parallel count given as a string', () => { it('stores a numeric string as its number on add and on edit', async () => { const workflowId = await seedWorkflow([block(generateId(), 'starter', 'Start')]) diff --git a/apps/sim/lib/workflows/application/apply-workflow-operations.test.ts b/apps/sim/lib/workflows/application/apply-workflow-operations.test.ts index 63215ec1ea6..6dfd4f2e358 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-operations.test.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-operations.test.ts @@ -216,6 +216,7 @@ describe('applyWorkflowOperations', () => { validationErrors: [], skippedItems: [], declinedOperationCount: 0, + removedEdges: [], mintedBlockIds: {}, }) mocks.collectReferences.mockResolvedValue([]) @@ -242,6 +243,7 @@ describe('applyWorkflowOperations', () => { validationErrors: [], skippedItems: [], declinedOperationCount: 0, + removedEdges: [], mintedBlockIds: {}, }) mocks.lintGraph.mockReturnValue({ ...EMPTY_GRAPH_LINT, orphanBlocks: [orphan] }) @@ -307,6 +309,7 @@ describe('applyWorkflowOperations', () => { validationErrors: [], skippedItems: [], declinedOperationCount: 0, + removedEdges: [], mintedBlockIds: { triage: 'preview-uuid' }, }) @@ -397,6 +400,7 @@ describe('applyWorkflowOperations', () => { }, ], declinedOperationCount: 1, + removedEdges: [], }) const result = await applyWorkflowOperations.execute({ @@ -422,6 +426,7 @@ describe('applyWorkflowOperations', () => { }, ], declinedOperationCount: 0, + removedEdges: [], }) const result = await applyWorkflowOperations.execute({ @@ -446,6 +451,7 @@ describe('applyWorkflowOperations', () => { }, ], declinedOperationCount: 1, + removedEdges: [], }) const failure = await applyWorkflowOperations @@ -500,6 +506,7 @@ describe('applyWorkflowOperations', () => { validationErrors: [], skippedItems: [], declinedOperationCount: 0, + removedEdges: [], mintedBlockIds: {}, }) @@ -628,6 +635,7 @@ describe('applyWorkflowOperations', () => { validationErrors: [], skippedItems: [], declinedOperationCount: 0, + removedEdges: [], }) mocks.collectReferences.mockResolvedValue([]) mocks.collectToolReferences.mockResolvedValue([]) @@ -649,6 +657,7 @@ describe('applyWorkflowOperations', () => { validationErrors: [], skippedItems: [], declinedOperationCount: 0, + removedEdges: [], }) const result = await applyWorkflowOperations.execute({ @@ -747,6 +756,7 @@ describe('applyWorkflowOperations', () => { validationErrors: [], skippedItems: [], declinedOperationCount: 0, + removedEdges: [], }) const result = await applyWorkflowOperations.execute({ @@ -779,6 +789,7 @@ describe('applyWorkflowOperations', () => { validationErrors: [], skippedItems: [], declinedOperationCount: 0, + removedEdges: [], }) const result = await applyWorkflowOperations.execute({ diff --git a/apps/sim/lib/workflows/application/apply-workflow-operations.ts b/apps/sim/lib/workflows/application/apply-workflow-operations.ts index e155139fa95..bf1fb8a97ac 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-operations.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-operations.ts @@ -42,11 +42,13 @@ import { operationsReferenceSimSandbox } from '@/lib/workflows/editing/sandbox-p import { type EditWorkflowOperation, isDeferredSkippedItem, + type RemovedEdge, type SkippedItem, type SkippedItemType, type ValidationError, } from '@/lib/workflows/editing/types' import { preValidateCredentialInputs } from '@/lib/workflows/editing/validation' +import { quotedBlockLabel } from '@/lib/workflows/labels' import { assertNoWithheldBlockType } from '@/lib/workflows/persistence/block-access-guard' import { prepareWorkflowStateForPersistence } from '@/lib/workflows/persistence/prepare-state' import { @@ -175,6 +177,29 @@ function applyBlockEnabledChanges( return { blocks: current, applied } } +/** + * One warning naming every stored edge the batch removed, by block name (the final name, or the + * stored one for a deleted block): the caller never sent these edges, so their ids mean nothing + * to it. How to wire across a loop's or parallel's boundary is added only when an edge crossed one. + */ +function describeRemovedEdges( + removedEdges: readonly RemovedEdge[], + nameOf: (blockId: string) => string | undefined +): string[] { + if (removedEdges.length === 0) return [] + const label = (blockId: string) => quotedBlockLabel(blockId, nameOf(blockId)) + const edges = removedEdges.map( + (edge) => + `${label(edge.source)} -> ${label(edge.target)} (${edge.sourceHandle}): ${edge.reason}` + ) + const boundaryAdvice = removedEdges.some((edge) => edge.kind === 'scope') + ? " An edge cannot cross a loop's or parallel's boundary: wire into its body from loop-start-source (parallel-start-source) and onward from loop-end-source (parallel-end-source)." + : '' + return [ + `Removed ${removedEdges.length} existing edge(s) this batch left invalid: ${edges.join('; ')}.${boundaryAdvice}`, + ] +} + interface BaseGraph { graph: Record /** Set when the base was read from storage, so the write can prove it is still current. */ @@ -255,6 +280,7 @@ export const applyWorkflowOperations = defineAuthorizedWorkflowUseCase({ validationErrors, skippedItems, declinedOperationCount, + removedEdges, mintedBlockIds, } = await withBlockVisibility(blockVisibility, async () => applyOperationsToWorkflowState( @@ -341,6 +367,11 @@ export const applyWorkflowOperations = defineAuthorizedWorkflowUseCase({ * the findings exist; the findings themselves stay only in `lint`. */ const lintWarnings = hasWorkflowLintIssues(lint) ? [summarizeWorkflowLintIssues(lint)] : [] + const storedBlocks = asGraph(baseGraph).blocks + const removedEdgeWarnings = describeRemovedEdges( + removedEdges, + (blockId) => graph.blocks[blockId]?.name ?? storedBlocks?.[blockId]?.name + ) /** * A dry run still runs the whole engine — operations are applied, refusals @@ -396,6 +427,7 @@ export const applyWorkflowOperations = defineAuthorizedWorkflowUseCase({ warnings: [ ...validation.warnings, ...prepared.warnings, + ...removedEdgeWarnings, ...(Object.keys(mintedBlockIds).length > 0 ? [DRY_RUN_PREVIEW_BLOCK_IDS_WARNING] : []), ...lintWarnings, ], @@ -455,7 +487,12 @@ export const applyWorkflowOperations = defineAuthorizedWorkflowUseCase({ inputValidationErrors: validationErrors, mintedBlockIds, lint, - warnings: [...validation.warnings, ...persisted.warnings, ...lintWarnings], + warnings: [ + ...validation.warnings, + ...persisted.warnings, + ...removedEdgeWarnings, + ...lintWarnings, + ], needsRedeployment: await checkNeedsRedeployment(context.workflowId), dryRun: false, } diff --git a/apps/sim/lib/workflows/application/apply-workflow-source.runtime.integration.ts b/apps/sim/lib/workflows/application/apply-workflow-source.runtime.integration.ts index fcdf008a0fe..7c3bbc9c3b4 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.runtime.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.runtime.integration.ts @@ -3,7 +3,8 @@ * PostgreSQL, while workflow source is applied to the draft. The apply renames the paused block; * the run then resumes from its execution snapshot. Source apply writes the draft only, so the * snapshot and the deployed version must come through it byte-identical, and the renamed block - * must keep its id so the pause point still names a block the draft holds. + * must keep its id so the pause point still names a block the draft holds. The resumed run then + * pauses at a second block under the run it resumed, which the resume names in `paused.runId`. */ import { mkdir, writeFile } from 'node:fs/promises' import { dirname, resolve } from 'node:path' @@ -50,6 +51,7 @@ const workspaceId = generateId() const workflowId = generateId() const startId = generateId() const approvalId = generateId() +const signoffId = generateId() const owner = createSessionPrincipal({ userId: ownerId, sessionId: generateId() }) const ownerKey = createPersonalApiKeyPrincipal({ userId: ownerId, keyId: generateId() }) @@ -168,8 +170,24 @@ beforeAll(async () => { }, }, }), + [signoffId]: createBlock({ + id: signoffId, + type: 'human_in_the_loop', + name: 'Signoff', + position: { x: 600, y: 0 }, + subBlocks: { + inputFormat: { + id: 'inputFormat', + type: 'input-format', + value: [{ id: 'signed', name: 'signed', type: 'boolean', required: true }], + }, + }, + }), }, - edges: [{ id: generateId(), source: startId, target: approvalId }], + edges: [ + { id: generateId(), source: startId, target: approvalId }, + { id: generateId(), source: approvalId, target: signoffId }, + ], loops: {}, parallels: {}, }) @@ -266,7 +284,40 @@ check( }, }) - expect(resumed).toMatchObject({ kind: 'sync', success: true }) - expect(resumed).not.toMatchObject({ status: 'failed' }) + expect(resumed).toMatchObject({ kind: 'sync', success: true, status: 'paused' }) + if (resumed.kind !== 'sync' || !resumed.paused) + throw new Error('Expected the run to pause again') + // The resume attempt runs under its own id, but the pause it reaches is recorded under the run + // it resumed, and that is the run the next resume names. + expect(resumed.executionId).not.toBe(runId) + expect(resumed.paused.runId).toBe(runId) + const [waiting] = resumed.paused.points.filter((point) => point.resumeStatus === 'paused') + if (!waiting) throw new Error('Expected a waiting pause point') + expect(waiting.blockId).toBe(signoffId) + await vi.waitFor( + async () => { + const row = await pausedRow(runId) + const points = Object.values( + (row?.pausePoints ?? {}) as Record + ) + if (!points.some((point) => point.contextId === waiting.contextId)) { + throw new Error('Second pause not yet published') + } + }, + { timeout: 20_000, interval: 250 } + ) + + const signed = await resumeWorkflowRun.execute({ + principal: ownerKey, + input: { + workflowId, + runId: resumed.paused.runId, + contextId: waiting.contextId, + resumeInput: { signed: true }, + surface: 'v2', + }, + }) + + expect(signed).toMatchObject({ kind: 'sync', success: true, status: 'completed', paused: null }) } ) diff --git a/apps/sim/lib/workflows/application/apply-workflow-source.skills.integration.ts b/apps/sim/lib/workflows/application/apply-workflow-source.skills.integration.ts index ca1f0c26c33..ee04254a263 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-source.skills.integration.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-source.skills.integration.ts @@ -297,7 +297,7 @@ check( const written = edit( edit(source.files, 'skills: []', "skills: [skill('listed-only')]"), 'tools: []', - "tools: [customTool('listed-lookup')]" + "tools: [customTool('listed_lookup')]" ) written['workflow.ts'] = written['workflow.ts'].replace( /^import \{ /m, @@ -313,7 +313,7 @@ check( ]) expect(manifest.skills).toContainEqual({ key: 'listed-only', id: skillId, name: 'Listed only' }) expect(manifest.customTools).toContainEqual({ - key: 'listed-lookup', + key: 'listed_lookup', id: toolId, name: 'listed_lookup', }) diff --git a/apps/sim/lib/workflows/application/read-source-resources.integration.ts b/apps/sim/lib/workflows/application/read-source-resources.integration.ts index db6572560e7..1f343161659 100644 --- a/apps/sim/lib/workflows/application/read-source-resources.integration.ts +++ b/apps/sim/lib/workflows/application/read-source-resources.integration.ts @@ -401,7 +401,7 @@ describe('source resources manifest', () => { { key: 'tone', id: ids.laterSkill, name: 'Tone' }, ]) expect(manifest.customTools).toEqual([ - { key: 'lookup-order', id: ids.customTool, name: 'lookup_order' }, + { key: 'lookup_order', id: ids.customTool, name: 'lookup_order' }, ]) }) diff --git a/apps/sim/lib/workflows/application/read-workflow-lint-agent-tools.test.ts b/apps/sim/lib/workflows/application/read-workflow-lint-agent-tools.test.ts index c9662da941b..90f1b5a6374 100644 --- a/apps/sim/lib/workflows/application/read-workflow-lint-agent-tools.test.ts +++ b/apps/sim/lib/workflows/application/read-workflow-lint-agent-tools.test.ts @@ -46,7 +46,7 @@ vi.mock('@/lib/skills/application/use-cases', () => ({ vi.mock('@/lib/mcp/application/use-cases', () => mcpUseCasesMock) vi.mock('@/lib/table/service', () => tableServiceMock) vi.mock('@/lib/secrets/application/use-cases', () => secretsUseCasesMock) -vi.mock('@/blocks/utils', () => ({ getModelOptions: vi.fn(() => []) })) +vi.mock('@/blocks/utils', () => ({ MODEL_OPTION_SOURCES: new Map() })) vi.mock('@/tools/utils', () => toolsUtilsMock) import { OrchestrationError } from '@/lib/core/orchestration/types' diff --git a/apps/sim/lib/workflows/application/read-workflow-lint-refs.test.ts b/apps/sim/lib/workflows/application/read-workflow-lint-refs.test.ts index 65fbb36dd79..f631aaeb248 100644 --- a/apps/sim/lib/workflows/application/read-workflow-lint-refs.test.ts +++ b/apps/sim/lib/workflows/application/read-workflow-lint-refs.test.ts @@ -32,7 +32,7 @@ vi.mock('@/lib/workflows/custom-tools/operations', () => ({ getCustomToolById: v vi.mock('@/lib/workflows/skills/operations', () => ({ getSkillById: vi.fn() })) vi.mock('@/lib/table/service', () => tableServiceMock) vi.mock('@/lib/secrets/application/use-cases', () => secretsUseCasesMock) -vi.mock('@/blocks/utils', () => ({ getModelOptions: vi.fn(() => []) })) +vi.mock('@/blocks/utils', () => ({ MODEL_OPTION_SOURCES: new Map() })) vi.mock('@/tools/utils', () => toolsUtilsMock) vi.mock('@/lib/knowledge/application/documents', () => ({ readKnowledgeDocument: { execute: hoisted.document }, diff --git a/apps/sim/lib/workflows/application/read-workflow-run.ts b/apps/sim/lib/workflows/application/read-workflow-run.ts index d0f1dc53767..2bf37cb2e19 100644 --- a/apps/sim/lib/workflows/application/read-workflow-run.ts +++ b/apps/sim/lib/workflows/application/read-workflow-run.ts @@ -20,12 +20,14 @@ import { projectPausedRunPoints, readPausedRunPoints, } from '@/lib/workflows/executor/execution-status' +import { loadWorkflowFromNormalizedTables } from '@/lib/workflows/persistence/utils' +import { findRerunStartBlockId } from '@/executor/utils/run-from-block' /** * Selectors this resource can never answer, so the caller hears about them. * - * This resource reads a recorded run and deliberately never loads the - * workflow's blocks, so it matches block *ids* only. A selector headed by + * This resource reads a recorded run and never resolves a selector against + * the workflow's blocks, so it matches block *ids* only. A selector headed by * something that is not a block id — a block name, the shape the streaming * execute request accepts — has nothing to resolve against and used to come * back as an empty `blockOutputs` with a `200`, which reads exactly like "that @@ -175,7 +177,25 @@ export const readWorkflowRun = defineAuthorizedWorkflowUseCase({ ) : null - return { ...status, files, pausePoints, failedBlock } + /** + * A rerun runs the saved draft, so where it starts is read from the draft: this resource + * keeps no graph of the run. Read only for a failure a block owns. + */ + const rerunFromBlockId = failedBlock + ? findRerunStartBlockId( + failedBlock.blockId, + (await loadWorkflowFromNormalizedTables(context.workflowId))?.blocks ?? {} + ) + : undefined + + return { + ...status, + files, + pausePoints, + pausedRunId: stateExecutionId, + failedBlock, + rerunFromBlockId, + } } catch (error) { if (error instanceof FunctionalOutputsUnavailableError) { throw new OrchestrationError('conflict', FUNCTIONAL_OUTPUTS_UNAVAILABLE_MESSAGE) diff --git a/apps/sim/lib/workflows/application/read-workflow-source.ts b/apps/sim/lib/workflows/application/read-workflow-source.ts index ee66f0cd412..56fa44f90c6 100644 --- a/apps/sim/lib/workflows/application/read-workflow-source.ts +++ b/apps/sim/lib/workflows/application/read-workflow-source.ts @@ -4,6 +4,7 @@ import { mapWithConcurrency } from '@sim/utils/concurrency' import { compareStrings } from '@sim/utils/string' import { type CanonicalWorkflow, + calledWorkflowKeys, type Diagnostic, type SourceBase, type SourceFingerprint, @@ -36,6 +37,13 @@ import { loadWorkflowGraphs, } from '@/lib/workflows/application/read-workflow-graph' import { recordSourceRead } from '@/lib/workflows/application/source-analytics' +import { + type ChildResultsMemo, + loadChildGraphs, + loadChildResultsFrom, + type StoredGraphs, + storedChildWorkflowIds, +} from '@/lib/workflows/application/source-child-results' import type { WorkflowSourceDiagnostic } from '@/lib/workflows/application/source-error' import { buildSourceCatalog, storedCatalogTypes } from '@/lib/workflows/code/catalog/workspace' import { @@ -230,11 +238,16 @@ interface LoadedSource { gate: CatalogGate sourceMeta: WorkflowSourceMetaV1 | null prefetched: PrefetchedStoredResources + /** The child workflows read for this read, shared by the workflows a batched read prints. */ + childMemo: ChildResultsMemo + /** The graphs of the workflows this one may call ({@link storedChildWorkflowIds}), by id. */ + childGraphs: StoredGraphs } /** * Prints a loaded workflow as source: builds its catalog, canonicalizes the stored graph with its - * resource keys and prints it with its source meta, refusing one over `SOURCE_LIMITS`. + * resource keys and prints it with its source meta and the result fields of the children it calls + * (as an apply of the printed source types them), refusing one over `SOURCE_LIMITS`. */ async function printLoadedSource( loaded: LoadedSource, @@ -252,6 +265,17 @@ async function printLoadedSource( { organizationId: scope.workspaceOrganizationId, gate, prefetched, stored: loaded.stored }, async ({ canonical, resources }, catalog) => { const canonicalHash = storedCanonicalHash(canonical, resources) + const childResults = await loadChildResultsFrom( + { + workspaceId: scope.workspaceId, + workspaceOrganizationId: scope.workspaceOrganizationId, + gate, + memo: loaded.childMemo, + }, + calledWorkflowKeys(canonical.workflow), + loaded.childGraphs, + (key) => resources.toId('workflow', key) + ) const printed = printStoredSource({ state, meta, @@ -260,6 +284,7 @@ async function printLoadedSource( sourceMeta, functionCode, lockless: canonical, + childResults, }) assertFitsSourceLimits(printed, counts) return { @@ -297,8 +322,14 @@ export const readWorkflowSource = defineAuthorizedWorkflowUseCase({ operation: workflowOperations.readSource, resolveContext: resolvePrincipalWorkflowContext, async execute({ principal, input, context }): Promise { - const [stored, gate, sourceMeta, prefetched] = await Promise.all([ - loadStoredSource(context), + const [{ stored, childGraphs }, gate, sourceMeta, prefetched] = await Promise.all([ + loadStoredSource(context).then(async (stored) => ({ + stored, + childGraphs: await loadChildGraphs( + context.workspaceId, + storedChildWorkflowIds(Object.values(stored.state.blocks)) + ), + })), resolveCatalogGate(principal, context, { customBlockInputs: true }), readWorkflowSourceMeta(db, context.workflowId), prefetchStoredResources({ @@ -309,7 +340,7 @@ export const readWorkflowSource = defineAuthorizedWorkflowUseCase({ }), ]) const read = await printLoadedSource( - { scope: context, stored, gate, sourceMeta, prefetched }, + { scope: context, stored, gate, sourceMeta, prefetched, childMemo: new Map(), childGraphs }, input.functionCode ?? 'files' ) if (!input.plan) recordSourceRead(principal, context) @@ -370,6 +401,14 @@ export const readWorkflowSources = defineAuthorizedWorkflowUseCase({ input.workflowIds ), ]) + const childGraphs = await loadChildGraphs( + workspaceId, + [...graphs.values()].flatMap((loaded) => + storedChildWorkflowIds(Object.values(loaded.graph.blocks)) + ), + graphs + ) + const childMemo: ChildResultsMemo = new Map() const printed = await mapWithConcurrency( input.workflowIds, PRINT_CONCURRENCY, @@ -392,6 +431,8 @@ export const readWorkflowSources = defineAuthorizedWorkflowUseCase({ gate, sourceMeta: sourceMetas.get(workflowId) ?? null, prefetched: { ...prefetched, workflowId }, + childMemo, + childGraphs, }, 'files' ) diff --git a/apps/sim/lib/workflows/application/rerun-start.integration.ts b/apps/sim/lib/workflows/application/rerun-start.integration.ts new file mode 100644 index 00000000000..0e89c5c6f30 --- /dev/null +++ b/apps/sim/lib/workflows/application/rerun-start.integration.ts @@ -0,0 +1,184 @@ +/** + * Where a rerun of a failed run starts, against real PostgreSQL: a draft run that fails in a + * block inside a loop names the loop, on the execute result and on the run resource, and a + * run-from-block from that loop is accepted with the failed run as its source, where a start at + * the failed block itself is refused. + */ +import { db } from '@sim/db' +import { + permissions, + user, + userStats, + workflow, + workflowExecutionLogs, + workflowExecutionSnapshots, + workspace, +} from '@sim/db/schema' +import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' +import { + createDelegatedPrincipal, + createSessionPrincipal, +} from '@sim/testing/factories/principal.factory' +import { sleep } from '@sim/utils/helpers' +import { generateId } from '@sim/utils/id' +import { saveWorkflowToNormalizedTables } from '@sim/workflow-persistence/save' +import type { BlockState, WorkflowState } from '@sim/workflow-types/workflow' +import { eq } from 'drizzle-orm' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { closeRedisConnection } from '@/lib/core/config/redis' +import { + executeManualWorkflowFromBlockOperation, + executeManualWorkflowOperation, +} from '@/lib/workflows/application/execute-manual-workflow' +import { readWorkflowRun } from '@/lib/workflows/application/read-workflow-run' +import { getWorkflowExecutionLogStatus } from '@/lib/workflows/executor/execution-state' + +const ownerId = generateId() +const workspaceId = generateId() +const workflowId = generateId() +const principal = createDelegatedPrincipal({ + subjectUserId: ownerId, + workspaceId, + audience: 'sim:workflows', +}) +const reader = createSessionPrincipal({ userId: ownerId }) + +function block(id: string, type: string, extra: Partial = {}): BlockState { + return { + id, + type, + name: id, + position: { x: 0, y: 0 }, + enabled: true, + outputs: {}, + subBlocks: {}, + ...extra, + } +} + +/** Start, then a loop whose one block requests a host that never resolves, so it fails at once. */ +const draft: WorkflowState = { + blocks: { + start: block('start', 'start_trigger'), + loop: block('loop', 'loop', { data: { loopType: 'for', count: 1 } }), + fetch: block('fetch', 'api', { + data: { parentId: 'loop', extent: 'parent' }, + subBlocks: { + url: { id: 'url', type: 'short-input', value: 'http://rerun-start.invalid/' }, + method: { id: 'method', type: 'dropdown', value: 'GET' }, + }, + }), + }, + edges: [ + { id: 'start-loop', source: 'start', target: 'loop' }, + { id: 'loop-fetch', source: 'loop', target: 'fetch', sourceHandle: 'loop-start-source' }, + ], + loops: {}, + parallels: {}, +} + +function runInput() { + return { + workflowId, + requestId: generateId(), + executionId: generateId(), + input: {}, + mode: 'sync' as const, + requestHeaders: new Headers(), + } +} + +/** The settled run, once its log row reads the status the result reported. */ +async function settled(result: R, executionId: string): Promise { + if (!result.ok || !('status' in result)) return result + const deadline = Date.now() + 10_000 + while ((await getWorkflowExecutionLogStatus(executionId, workflowId)) !== result.status) { + if (Date.now() >= deadline) throw new Error('Run did not persist its terminal log') + await sleep(25) + } + return result +} + +beforeAll(async () => { + const now = new Date() + await db.insert(user).values({ + id: ownerId, + name: 'Rerun start fixture', + email: `${ownerId}@rerun-start.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + await db.insert(userStats).values({ id: generateId(), userId: ownerId }) + await insertWorkspaceFixture(db, { + id: workspaceId, + name: 'Rerun start fixture', + ownerId, + billedAccountUserId: ownerId, + }) + await db.insert(permissions).values({ + id: generateId(), + userId: ownerId, + entityType: 'workspace', + entityId: workspaceId, + permissionType: 'admin', + }) + await db.insert(workflow).values({ + id: workflowId, + userId: ownerId, + workspaceId, + name: 'Rerun start fixture', + lastSynced: now, + createdAt: now, + updatedAt: now, + }) + const saved = await saveWorkflowToNormalizedTables(workflowId, draft) + expect(saved.success, saved.error).toBe(true) +}) + +afterAll(async () => { + await db.delete(workflowExecutionLogs).where(eq(workflowExecutionLogs.workflowId, workflowId)) + await db + .delete(workflowExecutionSnapshots) + .where(eq(workflowExecutionSnapshots.workflowId, workflowId)) + await deleteWorkspaceFixture(db, eq(workspace.id, workspaceId)) + await db.delete(user).where(eq(user.id, ownerId)) + await closeRedisConnection() + await db.$client.end() +}) + +describe('a run that failed in a block inside a loop', () => { + it('is rerun from the loop, which run-from-block accepts where it refuses the block', async () => { + const input = { ...runInput(), useMockPayload: false } + const run = await settled( + await executeManualWorkflowOperation.execute({ principal, input }), + input.executionId + ) + expect(run).toMatchObject({ + ok: true, + status: 'failed', + error: { blockId: 'fetch' }, + rerunFromBlockId: 'loop', + }) + + const recorded = await readWorkflowRun.execute({ + principal: reader, + input: { workflowId, runId: input.executionId, includeOutput: false, selectedOutputs: [] }, + }) + expect(recorded).toMatchObject({ failedBlock: { blockId: 'fetch' }, rerunFromBlockId: 'loop' }) + + const fromLoop = { ...runInput(), blockId: 'loop', sourceRunId: input.executionId } + expect( + await executeManualWorkflowFromBlockOperation.execute({ principal, input: fromLoop }) + ).toMatchObject({ ok: true, status: 'failed', error: { blockId: 'fetch' } }) + + const fromBlock = { ...runInput(), blockId: 'fetch', sourceRunId: input.executionId } + const refused = await executeManualWorkflowFromBlockOperation + .execute({ principal, input: fromBlock }) + .then( + (result) => JSON.stringify(result), + (error: unknown) => String(error) + ) + expect(refused).toContain('Cannot run from block inside loop') + }) +}) diff --git a/apps/sim/lib/workflows/application/source-child-results.ts b/apps/sim/lib/workflows/application/source-child-results.ts new file mode 100644 index 00000000000..82ecdfe7cc1 --- /dev/null +++ b/apps/sim/lib/workflows/application/source-child-results.ts @@ -0,0 +1,284 @@ +/** + * How the server types a child workflow call's `>` in a JSON field: by + * the fields the child's Response data holds (`childResultFields`), read from the child's draft + * as stored, or as the workspace source apply that holds the call submits it, each typed in turn + * by the workflows it calls (`resolveChildResults`). Every source compile and print of a workflow + * goes through the same reading, so a get prints a reference in the form the next apply stores + * again, and a workspace directory's check (which reads the children from the directory the same + * way) agrees with both. + */ +import { + type ChildResultFields, + type ChildResultNode, + canonicalize, + canonicalResultNode, + compiledResultNode, + folderCompileInput, + parseWorkflowLock, + type ResourceKeyResolver, + resolveChildResults, +} from '@sim/workflow-code' +import { SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits' +import type { BlockState } from '@sim/workflow-types/workflow' +import { type CatalogGate, withCatalogBlockScope } from '@/lib/catalog/application/context' +import { loadWorkflowGraphs } from '@/lib/workflows/application/read-workflow-graph' +import { buildSourceCatalog, storedCatalogTypes } from '@/lib/workflows/code/catalog/workspace' +import { resolveIds, resolveKeys } from '@/lib/workspaces/resource-keys' + +/** A child's typed result fields, or `null` when it can end without responding or is unreadable. */ +type ChildFields = ChildResultFields | null + +/** + * One request's readings of child workflows by key, each read at most once: a workspace apply + * shares one across every workflow it evaluates. + */ +export type ChildResultsMemo = Map> + +/** A workflow folder as a workspace source apply submits it: its files and `.sim/lock.json`. */ +interface ChildSource { + files: Readonly> + lock: unknown +} + +/** + * The workflow folders a workspace source apply writes with files, by key: a workflow calling + * one is typed by the child's Response data as the folder holds it, as the directory's check + * types it, not as stored. + */ +export type ChildSources = ReadonlyMap + +export interface ChildResultsScope { + workspaceId: string + workspaceOrganizationId: string | null + /** The caller's catalog gate, which the children are compiled or canonicalized under. */ + gate: CatalogGate + memo: ChildResultsMemo + /** The folders the enclosing workspace source apply writes: such a child is read as submitted. */ + submitted?: ChildSources +} + +/** Stored workflow graphs by id, as `loadWorkflowGraphs` reads them. */ +export type StoredGraphs = Awaited> + +/** One stored workflow graph, as `loadWorkflowGraphs` reads it. */ +type StoredGraph = NonNullable> + +/** Graphs a read already loaded, and the workflow each child key resolves to for it. */ +interface LoadedChildren { + graphs: StoredGraphs + toId: (key: string) => string | null +} + +/** + * A submitted folder compiled as the directory's check compiles it ({@link folderCompileInput}): + * continuing the stored workflow its lock binds, so a `stored()` param compiles unread, against + * the catalog the child's own apply compiles it with: the workspace catalog plus the types its + * stored draft holds (`stored`, absent for a workflow the apply creates). + */ +function submittedNode( + source: ChildSource, + stored: StoredGraph | undefined, + scope: ChildResultsScope +): ChildResultNode | null { + const entry = source.files[SOURCE_ENTRY_FILE] + if (entry === undefined) return null + const catalog = buildSourceCatalog({ + gate: scope.gate, + organizationId: scope.workspaceOrganizationId, + storedTypes: storedCatalogTypes(Object.values(stored?.graph.blocks ?? {})), + }) + const lock = source.lock === undefined ? undefined : parseWorkflowLock(source.lock).lock + return compiledResultNode(folderCompileInput(entry, source.files, lock, catalog)) +} + +/** + * A stored workflow canonicalized under its own source catalog, with only the workflows it calls + * lifted to their keys: no Response field's type depends on any other resource's key. + */ +function storedNode( + loaded: StoredGraph, + workflowKeys: ReadonlyMap, + scope: ChildResultsScope +): ChildResultNode { + const { blocks, edges, loops, parallels, variables } = loaded.graph + const catalog = buildSourceCatalog({ + gate: scope.gate, + organizationId: scope.workspaceOrganizationId, + storedTypes: storedCatalogTypes(Object.values(blocks)), + }) + const resources: ResourceKeyResolver = { + toKey: (kind, id) => (kind === 'workflow' ? (workflowKeys.get(id) ?? null) : null), + toId: () => null, + } + const { workflow } = canonicalize( + { blocks, edges, loops, parallels, variables }, + { catalog, meta: { name: loaded.name, description: loaded.description ?? null }, resources } + ) + return canonicalResultNode(workflow, catalog) +} + +/** + * The stored graph of each workflow `keys` name in the workspace, by key (one the workspace does + * not hold, or holds archived, is left out): from `loaded` when it holds the graph a key resolves + * to, else read in one query. + */ +async function keyedGraphs( + keys: readonly string[], + scope: ChildResultsScope, + loaded: LoadedChildren | undefined +): Promise> { + const ids = new Map() + for (const key of keys) { + const id = loaded ? loaded.toId(key) : null + if (id !== null && loaded?.graphs.has(id)) ids.set(key, id) + } + const unloaded = keys.filter((key) => !ids.has(key)) + if (unloaded.length > 0) { + const resolved = + ( + await resolveIds( + scope.workspaceId, + unloaded.map((key) => ({ kind: 'workflow' as const, key })) + ) + ).get('workflow') ?? new Map() + for (const [key, id] of resolved) ids.set(key, id) + } + const graphs = await loadChildGraphs(scope.workspaceId, [...ids.values()], loaded?.graphs) + const byKey = new Map() + for (const [key, id] of ids) { + const graph = graphs.get(id) + if (graph) byKey.set(key, graph) + } + return byKey +} + +/** The node of each stored workflow `graphs` holds, by key ({@link storedNode}). */ +async function storedNodes( + graphs: ReadonlyMap, + scope: ChildResultsScope +): Promise> { + const calledIds = [...graphs.values()].flatMap((graph) => + storedChildWorkflowIds(Object.values(graph.graph.blocks)) + ) + const workflowKeys = + calledIds.length === 0 + ? new Map() + : (( + await resolveKeys( + scope.workspaceId, + calledIds.map((id) => ({ kind: 'workflow' as const, id })), + { allocate: false } + ) + ).get('workflow') ?? new Map()) + const nodes = new Map() + for (const [key, graph] of graphs) nodes.set(key, storedNode(graph, workflowKeys, scope)) + return nodes +} + +/** + * The fields of each workflow `keys` name and every workflow they reach by calls, by key: read + * level by level (a submitted folder as submitted, any other as stored), then resolved callees + * first ({@link resolveChildResults}). + */ +async function readChildResults( + scope: ChildResultsScope, + keys: readonly string[], + loaded: LoadedChildren | undefined +): Promise> { + const nodes = new Map() + let frontier = [...new Set(keys)] + while (frontier.length > 0) { + const graphs = await keyedGraphs(frontier, scope, loaded) + const stored = new Map([...graphs].filter(([key]) => !scope.submitted?.has(key))) + const read = stored.size > 0 ? await storedNodes(stored, scope) : new Map() + for (const key of frontier) { + const source = scope.submitted?.get(key) + nodes.set( + key, + source ? submittedNode(source, graphs.get(key), scope) : (read.get(key) ?? null) + ) + } + const next = new Set(frontier.flatMap((key) => nodes.get(key)?.calls ?? [])) + frontier = [...next].filter((key) => !nodes.has(key)) + } + const present = new Map() + for (const [key, node] of nodes) if (node) present.set(key, node) + const resolved = resolveChildResults(present) + return new Map([...nodes.keys()].map((key) => [key, resolved.get(key) ?? null])) +} + +/** + * The ids of the workflows stored `blocks` may run as children (each `workflowId` value), for a + * read to load their graphs with its own: a superset of the calls its canonical model names. + */ +export function storedChildWorkflowIds(blocks: Iterable): string[] { + const ids = new Set() + for (const block of blocks) { + const value = block.subBlocks?.workflowId?.value + if (typeof value === 'string' && value !== '') ids.add(value) + } + return [...ids] +} + +/** + * Loads the graphs of the workflows `ids` name that `loaded` lacks, in one read, and returns them + * with `loaded`'s ({@link storedChildWorkflowIds}). + */ +export async function loadChildGraphs( + workspaceId: string, + ids: readonly string[], + loaded: StoredGraphs = new Map() +): Promise { + const missing = [...new Set(ids)].filter((id) => !loaded.has(id)) + if (missing.length === 0) return loaded + return new Map([...loaded, ...(await loadWorkflowGraphs(workspaceId, missing))]) +} + +/** + * The typed result fields of each child workflow `keys` name that always responds, by key: a + * child the enclosing apply submits as submitted, any other as its stored draft in the workspace + * (one the workspace does not hold, or holds archived, is left out), each typed by the workflows + * it calls in turn. Each key is read once per `scope.memo`; the workflows a reading reaches + * through calls are kept there too. + */ +export async function loadChildResults( + scope: ChildResultsScope, + keys: readonly string[], + loaded?: LoadedChildren +): Promise> { + const unread = keys.filter((key) => !scope.memo.has(key)) + if (unread.length > 0) { + const reading = withCatalogBlockScope(scope.gate, async () => { + const fields = await readChildResults(scope, unread, loaded) + for (const [key, value] of fields) { + if (!scope.memo.has(key)) scope.memo.set(key, Promise.resolve(value)) + } + return fields + }) + for (const key of unread) { + scope.memo.set( + key, + reading.then((fields) => fields.get(key) ?? null) + ) + } + } + const read = await Promise.all(keys.map(async (key) => [key, await scope.memo.get(key)] as const)) + const results = new Map() + for (const [key, fields] of read) if (fields) results.set(key, fields) + return results +} + +/** + * {@link loadChildResults} for a read of stored workflows that loaded their children's graphs with + * {@link loadChildGraphs} (`toId` names the workflow a key resolves to): a child whose graph is + * there is read from there, any other (a workflow those children call, or a key `toId` does not + * resolve) as {@link loadChildResults} reads it. + */ +export function loadChildResultsFrom( + scope: ChildResultsScope, + keys: readonly string[], + graphs: StoredGraphs, + toId: (key: string) => string | null +): Promise> { + return loadChildResults(scope, keys, { graphs, toId }) +} diff --git a/apps/sim/lib/workflows/application/source-pipeline/evaluate/compile.ts b/apps/sim/lib/workflows/application/source-pipeline/evaluate/compile.ts index 9095c160720..94c1d8a4c44 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/evaluate/compile.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/evaluate/compile.ts @@ -1,6 +1,7 @@ import { type CanonicalizeResult, type CanonicalWorkflowMeta, + calledWorkflowKeys, canonicalizeUnderLock, type Diagnostic, parseWorkflowLock, @@ -33,12 +34,15 @@ export interface CompiledSubmission { /** * Parses the submitted lock and compiles the files against the live catalog and the stored graph - * read under that lock. Refuses a lock that does not parse, or a source that does not compile - * (noting a catalog that moved since the read, which can explain the errors). + * read under that lock, typing child calls' results by the fields of the children the compiled + * source calls (`input.loadChildResults`): a compile names its calls only once it has run, so a + * source calling a child that responds is compiled again with those fields (the lock and the + * stored graph are read once). Refuses a lock that does not parse, or a source that does not + * compile (noting a catalog that moved since the read, which can explain the errors). */ -export function compileSubmission( +export async function compileSubmission( input: SourceEvaluationInput -): { refused: WorkflowSourceDiagnostic[] } | CompiledSubmission { +): Promise<{ refused: WorkflowSourceDiagnostic[] } | CompiledSubmission> { const { catalog, files } = input const parsedLock = parseWorkflowLock(input.lock) @@ -47,9 +51,8 @@ export function compileSubmission( } const lock = parsedLock.lock - const { state } = input.stored const storedCanonical = canonicalizeUnderLock( - state, + input.stored.state, { catalog, meta: input.stored.meta, resources: input.storedCanonical.resources }, input.storedCanonical.canonical, lock @@ -65,6 +68,24 @@ export function compileSubmission( ]), envNames: input.envNames, } + const read = { lock, storedCanonical, compileInput } + + const untyped = compileUnder(input, read) + if ('refused' in untyped || !input.loadChildResults) return untyped + const called = calledWorkflowKeys(untyped.compiledWorkflow) + if (called.length === 0) return untyped + const childResults = await input.loadChildResults(called) + if (childResults.size === 0) return untyped + return compileUnder(input, { ...read, compileInput: { ...compileInput, childResults } }) +} + +/** Compiles the files under the lock and stored graph {@link compileSubmission} read. */ +function compileUnder( + input: SourceEvaluationInput, + read: Pick +): { refused: WorkflowSourceDiagnostic[] } | CompiledSubmission { + const { catalog, files } = input + const { lock, storedCanonical, compileInput } = read const compiled = compileSource({ ...compileInput, stored: storedCanonical.workflow, lock }) const compiledWorkflow = compiled.workflow if (!compiledWorkflow || hasErrors(compiled.diagnostics)) { diff --git a/apps/sim/lib/workflows/application/source-pipeline/evaluate/finalize.ts b/apps/sim/lib/workflows/application/source-pipeline/evaluate/finalize.ts index 179f91d8d64..445414c8dde 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/evaluate/finalize.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/evaluate/finalize.ts @@ -329,6 +329,9 @@ export async function finalizePlan( resources: resolved.resources, references: compiledKeys, envReferences: compiled.envReferences, + ...(submission.compileInput.childResults + ? { childResults: submission.compileInput.childResults } + : {}), }, } } diff --git a/apps/sim/lib/workflows/application/source-pipeline/evaluate/run.ts b/apps/sim/lib/workflows/application/source-pipeline/evaluate/run.ts index a00f70f55cc..25af66bde55 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/evaluate/run.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/evaluate/run.ts @@ -16,7 +16,7 @@ import type { * in the submitted text, or the plan the write stores. */ export async function evaluateSource(input: SourceEvaluationInput): Promise { - const submission = compileSubmission(input) + const submission = await compileSubmission(input) if ('refused' in submission) return { refused: submission.refused } const resolved = await resolveSubmission(input, submission) if ('refused' in resolved) return resolved diff --git a/apps/sim/lib/workflows/application/source-pipeline/evaluate/types.ts b/apps/sim/lib/workflows/application/source-pipeline/evaluate/types.ts index 1471f23dc15..025ef5ccef6 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/evaluate/types.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/evaluate/types.ts @@ -3,6 +3,7 @@ import type { BlockCatalog, CanonicalWorkflow, CanonicalWorkflowMeta, + ChildResultFields, LockIdentity, ResourceKeyResolver, ResourceKind, @@ -43,7 +44,7 @@ export interface SourceEvaluationInput { /** Env names the subject's runs resolve, for `env('…')` checks. */ envNames: ReadonlySet /** Attribution for resource keys a submitted reference allocates. */ - createdBy: string | null + createdBy: string files: Record lock: WorkflowLockV1 /** Where and when the source was read, its fingerprint already matched; absent for a create. */ @@ -62,6 +63,12 @@ export interface SourceEvaluationInput { * created in the same apply resolves instead of failing `E_MAT_UNKNOWN_RESOURCE`. */ pendingResources?: readonly PendingResource[] + /** + * Reads the typed result fields of the child workflows the source calls, by key + * (`loadChildResults`), which type a call's `>`. Absent, those + * references are untyped. + */ + loadChildResults?: (keys: readonly string[]) => Promise> } /** @@ -128,6 +135,8 @@ export interface SourcePlan { references: SourceReference[] /** Every env name the submitted source reads, as the compiler read it. */ envReferences: string[] + /** The child result fields the compile typed with, which every print of the plan types with. */ + childResults?: ReadonlyMap } /** What the submitted source references, as the compiler read it. */ diff --git a/apps/sim/lib/workflows/application/source-pipeline/load.ts b/apps/sim/lib/workflows/application/source-pipeline/load.ts index 7fca7287b2b..a371d092c5d 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/load.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/load.ts @@ -1,8 +1,4 @@ -import { - type Principal, - resolvePrincipalAttribution, - resolvePrincipalSubjectUserId, -} from '@sim/auth/principal' +import { type Principal, requirePrincipalSubjectUserId } from '@sim/auth/principal' import { db } from '@sim/db' import type { BlockCatalog, @@ -19,6 +15,10 @@ import { } from '@/lib/catalog/application/context' import type { ActiveWorkflowApplicationContext } from '@/lib/workflows/application/context' import { loadStoredSource } from '@/lib/workflows/application/read-workflow-source' +import type { + ChildResultsMemo, + ChildSources, +} from '@/lib/workflows/application/source-child-results' import type { SourceScope } from '@/lib/workflows/application/source-pipeline/evaluate' import { buildSourceCatalog, storedCatalogTypes } from '@/lib/workflows/code/catalog/workspace' import { type StoredSource, storedSourceFingerprint } from '@/lib/workflows/code/print-stored' @@ -77,6 +77,10 @@ export type SourceTarget = export interface SourceLoads { catalogGate?: Promise envNames?: Promise + /** The child workflows read to type their callers' results (`loadChildResults`). */ + childResults?: ChildResultsMemo + /** The workflow folders the workspace source apply writes, which its callers are typed by. */ + childSources?: ChildSources } /** Everything a plan reads before it evaluates: the stored draft, its catalog and fingerprint. */ @@ -89,8 +93,6 @@ export interface LoadedTarget { /** The stored draft's fingerprint when loaded; a commit refuses a draft that moved off it. */ storedFingerprint: SourceFingerprint envNames: string[] - /** Attribution for resource keys the write allocates. */ - createdBy: string | null scope: SourceScope } @@ -102,8 +104,8 @@ export function targetIds(target: CommitTarget): { workflowId: string; workspace } /** - * Who and where a write to `target` acts: the human it is attributed to (the workspace's billing - * owner for a workspace key) and the workflow's folder. + * Who and where a write to `target` acts: the human it is attributed to and the workflow's + * folder. */ export function sourceScope(principal: Principal, target: CommitTarget): SourceScope { const context = @@ -114,9 +116,8 @@ export function sourceScope(principal: Principal, target: CommitTarget): SourceS workflowId: context.workflowId, workspaceId: context.workspaceId, workspaceOrganizationId: context.workspaceOrganizationId, - subjectUserId: resolvePrincipalAttribution(principal, { - workspaceBillingOwnerUserId: context.billedAccountUserId, - }).attributedUserId, + // actorless-unsupported: workflows.source.apply, .plan and .create admit only session, personal-key, OAuth or Copilot principals, never an executor or workspace key. + subjectUserId: requirePrincipalSubjectUserId(principal), folderId: target.kind === 'existing' ? target.context.workflow.folderId : target.folderId, } } @@ -134,7 +135,6 @@ export async function loadSourceTarget( options: { loads?: SourceLoads; allocate: boolean } ): Promise { const scope = sourceScope(principal, target) - const createdBy = resolvePrincipalSubjectUserId(principal) ?? null const loads = options.loads ?? {} const context = target.kind === 'existing' @@ -147,7 +147,7 @@ export async function loadSourceTarget( prefetchStoredResources({ workflowId: scope.workflowId, workspaceId: scope.workspaceId, - createdBy, + createdBy: scope.subjectUserId, allocate: options.allocate, }), (loads.envNames ??= loadEnvNames(scope.workspaceId, scope.subjectUserId)), @@ -175,7 +175,6 @@ export async function loadSourceTarget( storedCanonical.resources ), envNames, - createdBy, scope, } }) diff --git a/apps/sim/lib/workflows/application/source-pipeline/outcome.ts b/apps/sim/lib/workflows/application/source-pipeline/outcome.ts index 17396801def..cef70da652a 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/outcome.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/outcome.ts @@ -114,6 +114,7 @@ export function printPlanned( identity: plan.identity, codeFiles, ...(lockless ? { lockless } : {}), + ...(plan.childResults ? { childResults: plan.childResults } : {}), }) } diff --git a/apps/sim/lib/workflows/application/source-pipeline/plan.ts b/apps/sim/lib/workflows/application/source-pipeline/plan.ts index 25ab5d03316..adf25a781f3 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/plan.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/plan.ts @@ -9,6 +9,7 @@ import type { import { diagnostic } from '@sim/workflow-code/diagnostics' import { isEqual } from 'es-toolkit' import { withCatalogBlockScope } from '@/lib/catalog/application/context' +import { loadChildResults } from '@/lib/workflows/application/source-child-results' import { assertCreateNameFree } from '@/lib/workflows/application/source-commit' import { emptyDiffSummary, type SourceDiffSummary } from '@/lib/workflows/application/source-diff' import { @@ -264,6 +265,13 @@ export async function planSource( }) } + const childScope = { + workspaceId: scope.workspaceId, + workspaceOrganizationId: scope.workspaceOrganizationId, + gate: loaded.gate, + memo: options.loads ? (options.loads.childResults ??= new Map()) : new Map(), + ...(options.loads?.childSources ? { submitted: options.loads.childSources } : {}), + } const evaluation = await evaluateSource({ principal, scope, @@ -272,10 +280,11 @@ export async function planSource( storedSourceMeta: loaded.storedSourceMeta, catalog, envNames: new Set(loaded.envNames), - createdBy: loaded.createdBy, + createdBy: loaded.scope.subjectUserId, files: submission.files, lock: submission.lock, ...(submission.pendingResources ? { pendingResources: submission.pendingResources } : {}), + loadChildResults: (keys) => loadChildResults(childScope, keys), ...(target.kind === 'existing' ? { base: target.base, allowDelete: target.allowDelete } : { create: target.create }), diff --git a/apps/sim/lib/workflows/blocks/jev-outputs.ts b/apps/sim/lib/workflows/blocks/jev-outputs.ts index e2545e4bda1..358c6b93651 100644 --- a/apps/sim/lib/workflows/blocks/jev-outputs.ts +++ b/apps/sim/lib/workflows/blocks/jev-outputs.ts @@ -1,6 +1,6 @@ import { isRecordLike } from '@sim/utils/object' +import type { OutputFieldDefinition } from '@sim/workflow-types/blocks' import type { JevAnswer } from '@/providers/typesafe/types' -import type { OutputProperty } from '@/tools/types' const ANSWER_FIELDS = { choice: { @@ -21,16 +21,17 @@ const ANSWER_FIELDS = { type: { type: 'string' }, }, } satisfies { - [Type in JevAnswer['type']]: Record, OutputProperty> + [Type in JevAnswer['type']]: Record< + keyof Extract, + OutputFieldDefinition + > } /** * Describes answers known from the editor's questions without requiring resolved inputs. * Keys containing reference syntax remain accessible through the whole answers object. */ -export function getJevAnswerOutput( - questions: unknown -): (OutputProperty & { type: 'json' }) | undefined { +export function getJevAnswerOutput(questions: unknown): OutputFieldDefinition | undefined { if (typeof questions === 'string') { try { questions = JSON.parse(questions) @@ -40,7 +41,7 @@ export function getJevAnswerOutput( } if (!isRecordLike(questions)) return undefined - const entries: Array<[string, OutputProperty]> = [] + const entries: Array<[string, OutputFieldDefinition]> = [] for (const [id, question] of Object.entries(questions)) { if (!/^[\w-]+$/.test(id) || !isRecordLike(question)) continue const { type } = question diff --git a/apps/sim/lib/workflows/blocks/outputs.ts b/apps/sim/lib/workflows/blocks/outputs.ts index 7ae11bace4a..423d86a3366 100644 --- a/apps/sim/lib/workflows/blocks/outputs.ts +++ b/apps/sim/lib/workflows/blocks/outputs.ts @@ -156,7 +156,7 @@ const CHAT_OUTPUTS: OutputDefinition = { files: { type: 'file[]', description: 'Uploaded files' }, } -const START_RUN_METADATA_OUTPUT = { +const START_RUN_METADATA_OUTPUT: OutputFieldDefinition = { type: 'json', description: 'Trusted run metadata (server-injected)', properties: { @@ -201,7 +201,7 @@ const START_RUN_METADATA_OUTPUT = { executionMode: { type: 'string', description: 'Execution mode: sync, stream, or async' }, startTime: { type: 'string', description: 'ISO timestamp when the execution started' }, }, -} as OutputFieldDefinition +} function applyInputFormatFields( inputFormat: InputFormatField[], diff --git a/apps/sim/lib/workflows/code/catalog/project.ts b/apps/sim/lib/workflows/code/catalog/project.ts index 99e52c9f4b7..c06602c8f7b 100644 --- a/apps/sim/lib/workflows/code/catalog/project.ts +++ b/apps/sim/lib/workflows/code/catalog/project.ts @@ -2,7 +2,6 @@ import { type CatalogBlock, type CatalogBlockGraph, type CatalogCondition, - type CatalogLegacyId, type CatalogOption, type CatalogOutput, type CatalogSubBlock, @@ -20,10 +19,6 @@ import { UNIFIED_START_OUTPUTS } from '@/lib/workflows/blocks/start-outputs' import { probeThunk, readsOnly } from '@/lib/workflows/code/catalog/probe' import { operationOptions } from '@/lib/workflows/code/catalog/sdk-names' import { deriveValueShape } from '@/lib/workflows/code/catalog/value-kind' -import { - CANONICAL_ID_MIGRATIONS, - SUBBLOCK_ID_MIGRATIONS, -} from '@/lib/workflows/migrations/subblock-migrations' import { TRIGGER_TYPES } from '@/lib/workflows/triggers/types' import type { BlockConfig, SubBlockConfig } from '@/blocks/types' import { @@ -31,6 +26,7 @@ import { isMetadataOnlyBlockType, isSentinelBlockType, } from '@/executor/constants' +import { getToolMetadata } from '@/tools/metadata' import { getToolOutputsMetadata } from '@/tools/metadata-outputs' import { getSubBlockValueShape } from '@/tools/param-shape' import type { TriggerConfig } from '@/triggers/types' @@ -404,6 +400,7 @@ const OUTPUT_META_KEYS = new Set([ 'description', 'condition', 'hiddenFromDisplay', + 'mayBeText', 'nullable', 'properties', 'items', @@ -447,6 +444,7 @@ function projectOutput(definition: unknown): CatalogOutput | undefined { output.condition = copyOutputCondition(record.condition as OutputCondition) } if (typed && record.hiddenFromDisplay === true) output.hiddenFromDisplay = true + if (typed && record.mayBeText === true) output.mayBeText = true const nested: Record = {} if (record.properties && typeof record.properties === 'object') { @@ -466,22 +464,43 @@ function projectOutput(definition: unknown): CatalogOutput | undefined { } /** - * Per operation, the block outputs its tool declares and which of them it may return as `null`, - * when the operation picks the tool (`tools.selector: 'operation'`). Kept only where that differs - * from every block output, non-null. + * Each operation's tool id, when the operation alone picks a tool in `tools.access` for every + * operation (`tools.selector: 'operation'`); `null` otherwise. */ -function projectOperationOutputs( +function resolveOperationTools( block: BlockConfig, - operations: readonly string[], - outputNames: readonly string[] -): CatalogBlock['operationOutputs'] { + operations: readonly string[] +): Map | null { const selectTool = block.tools.config?.tool - if (!selectTool) return undefined - const projected: NonNullable = {} + if (!selectTool || operations.length === 0) return null + const access = new Set(block.tools.access) + const operationTools = new Map() for (const operation of operations) { const probe = probeThunk(selectTool, { operation }) - if (!probe.ok || typeof probe.result !== 'string') continue - const toolOutputs = getToolOutputsMetadata(probe.result) + if ( + !probe.ok || + !readsOnly(probe.reads, OPERATION_ONLY) || + typeof probe.result !== 'string' || + !access.has(probe.result) + ) { + return null + } + operationTools.set(operation, probe.result) + } + return operationTools +} + +/** + * Per operation, the block outputs its tool declares and which of them it may return as `null`. + * Kept only where that differs from every block output, non-null. + */ +function projectOperationOutputs( + operationTools: ReadonlyMap, + outputNames: readonly string[] +): CatalogBlock['operationOutputs'] { + const projected: NonNullable = {} + for (const [operation, toolId] of operationTools) { + const toolOutputs = getToolOutputsMetadata(toolId) if (!toolOutputs) continue const names = outputNames.filter((name) => Object.hasOwn(toolOutputs, name)) const nullable = names.filter((name) => toolOutputs[name]?.nullable === true) @@ -491,23 +510,39 @@ function projectOperationOutputs( return Object.keys(projected).length > 0 ? projected : undefined } -function projectTools(block: BlockConfig, operations: readonly string[]): CatalogBlock['tools'] { +/** + * The block's effect from its tools' declared effects, and, when the operation picks the tool, each + * operation whose tool differs from it. An id that is not a registered tool (the model providers an + * Agent, Router, or Evaluator calls) counts as `write`. An opaque selector cannot be probed, so its + * operations inherit the block effect. + */ +function projectEffects( + block: BlockConfig, + operationTools: ReadonlyMap | null +): Pick { + if (block.tools.access.length === 0) return {} + const accessEffects = new Map( + block.tools.access.map( + (toolId) => [toolId, getToolMetadata(toolId)?.effect ?? 'write'] as const + ) + ) + const effect = [...accessEffects.values()].every((entry) => entry === 'read') ? 'read' : 'write' + if (effect === 'read' || !operationTools) return { effect } + const operationEffects: NonNullable = {} + for (const [operation, toolId] of operationTools) { + const operationEffect = accessEffects.get(toolId) ?? 'write' + if (operationEffect !== effect) operationEffects[operation] = operationEffect + } + return Object.keys(operationEffects).length > 0 ? { effect, operationEffects } : { effect } +} + +function projectTools( + block: BlockConfig, + operationTools: ReadonlyMap | null +): CatalogBlock['tools'] { const access = [...block.tools.access] - const selectTool = block.tools.config?.tool - if (!selectTool) return { access, selector: 'single' } - const accessSet = new Set(access) - const perOperation = - operations.length > 0 && - operations.every((operation) => { - const probe = probeThunk(selectTool, { operation }) - return ( - probe.ok && - readsOnly(probe.reads, OPERATION_ONLY) && - typeof probe.result === 'string' && - accessSet.has(probe.result) - ) - }) - return { access, selector: perOperation ? 'operation' : 'opaque' } + if (!block.tools.config?.tool) return { access, selector: 'single' } + return { access, selector: operationTools ? 'operation' : 'opaque' } } function projectGraph(block: BlockConfig): CatalogBlockGraph { @@ -561,20 +596,6 @@ function projectDynamicOutputs(block: BlockConfig): CatalogBlock['dynamicOutputs : { source: 'inputFormat', param: inputFormat.id } } -function projectLegacyIds(type: string): CatalogLegacyId[] | undefined { - const migrations = SUBBLOCK_ID_MIGRATIONS[type] - if (!migrations?.length) return undefined - return migrations.map((migration) => { - const legacy: CatalogLegacyId = { - from: migration.from, - to: migration.to.startsWith('_removed_') ? null : migration.to, - } - if (migration.whenOperation) legacy.whenOperation = [...migration.whenOperation] - if (migration.whenValue) legacy.conditional = true - return legacy - }) -} - /** A block's literal `model` options and static dropdown values, for model-condition probes. */ function conditionChoices(block: BlockConfig): Pick { let models: string[] = [] @@ -604,6 +625,7 @@ function builtInOutputs(block: BlockConfig): BlockConfig['outputs'] { /** Projects one registry block (built-in or custom) into the core-shard shape. */ export function projectBlock(block: BlockConfig): CatalogBlock { const operations = operationOptions(block).map((operation) => operation.id) + const operationTools = resolveOperationTools(block, operations) const tagSurface = block.subBlocks.some((subBlock) => subBlockSurface(subBlock) === 'trigger') const ctx: SubBlockContext = { operations, @@ -616,7 +638,7 @@ export function projectBlock(block: BlockConfig): CatalogBlock { name: block.name, category: block.category, subBlocks: block.subBlocks.map((subBlock) => projectSubBlock(subBlock, ctx)), - tools: projectTools(block, operations), + tools: projectTools(block, operationTools), outputs: projectOutputRecord(builtInOutputs(block)), graph: projectGraph(block), } @@ -629,14 +651,11 @@ export function projectBlock(block: BlockConfig): CatalogBlock { ? { status: block.sunset.status, replacedBy: block.sunset.replacedBy } : { status: block.sunset.status } } - if (projected.tools.selector === 'operation') { - const operationOutputs = projectOperationOutputs( - block, - operations, - Object.keys(projected.outputs) - ) + if (operationTools) { + const operationOutputs = projectOperationOutputs(operationTools, Object.keys(projected.outputs)) if (operationOutputs) projected.operationOutputs = operationOutputs } + Object.assign(projected, projectEffects(block, operationTools)) if (Object.keys(lifecycle).length > 0) projected.lifecycle = lifecycle if (block.hideFromToolbar) projected.addable = false assign(projected, 'triggerAllowed', block.triggerAllowed) @@ -649,12 +668,7 @@ export function projectBlock(block: BlockConfig): CatalogBlock { assign(projected, 'singleInstance', block.singleInstance) const dynamicOutputs = projectDynamicOutputs(block) if (dynamicOutputs) projected.dynamicOutputs = dynamicOutputs - const legacyIds = projectLegacyIds(block.type) - if (legacyIds) projected.legacyIds = legacyIds - const legacyCanonicalIds = CANONICAL_ID_MIGRATIONS[block.type] - if (legacyCanonicalIds?.length) { - projected.legacyCanonicalIds = legacyCanonicalIds.map(({ from, to }) => ({ from, to })) - } + if (block.errorOutputs) projected.errorOutputs = Object.keys(block.errorOutputs) if (block.sourceWorkflowId !== undefined) { projected.custom = { sourceWorkflowId: block.sourceWorkflowId } } diff --git a/apps/sim/lib/workflows/code/json-field-refs.test.ts b/apps/sim/lib/workflows/code/json-field-refs.test.ts index 2e591b2d8e4..4f03e80640d 100644 --- a/apps/sim/lib/workflows/code/json-field-refs.test.ts +++ b/apps/sim/lib/workflows/code/json-field-refs.test.ts @@ -109,3 +109,38 @@ describe('JSON field literals against the real resolver', () => { }) }) }) + +describe('JSON field references to an output that may be text', () => { + /** The `W_JSON_REF_UNTYPED` tokens of a row whose JSON `data` holds `fields` bare. */ + function untypedTokens(fields: string): string[] { + const compiled = compileWorkflow({ + entry: { + path: 'workflow.ts', + text: `// @sim-sdk 1 +import { api, table, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('Text outputs', {}, () => { + const start = trigger.start('Start') + const fetchTicket = api('Fetch ticket', { url: 'https://example.com', method: 'GET' }) + const logTicket = table.insertRow('Log ticket', { tableId: table('tickets'), data: { ${fields} } }) + start.to(fetchTicket).to(logTicket) +}) +`, + }, + files: new Map(), + catalog, + sdkMajor: catalog.sdkMajor, + }) + return compiled.diagnostics + .filter((diagnostic) => diagnostic.code === 'W_JSON_REF_UNTYPED') + .map((diagnostic) => diagnostic.message.match(/<[^>]+>/)?.[0] ?? diagnostic.message) + } + + it('flags a bare HTTP body, which a text response splices in unquoted', () => { + expect(untypedTokens('body: fetchTicket.data')).toEqual(['']) + }) + + it('stores a bare JSON output that is never text without a warning', () => { + expect(untypedTokens('headers: fetchTicket.headers, status: fetchTicket.status')).toEqual([]) + }) +}) diff --git a/apps/sim/lib/workflows/code/print-stored.ts b/apps/sim/lib/workflows/code/print-stored.ts index 4aea2e05319..69bd73dc263 100644 --- a/apps/sim/lib/workflows/code/print-stored.ts +++ b/apps/sim/lib/workflows/code/print-stored.ts @@ -2,6 +2,7 @@ import { type BlockCatalog, type CanonicalizeResult, type CanonicalWorkflowMeta, + type ChildResultFields, canonicalDigests, canonicalHash, canonicalize, @@ -44,6 +45,11 @@ interface PrintStoredSourceInput extends StoredSource { * with the author's file names instead of deriving new ones from the idents. */ codeFiles?: Record + /** + * The typed result fields of the child workflows the state calls, by key: what the apply of the + * printed source types a call's `>` by (`loadChildResults`). + */ + childResults?: ReadonlyMap } /** A stored workflow printed as source, with the lock and freshness token that go with it. */ @@ -142,6 +148,7 @@ export function printStoredSource(input: PrintStoredSourceInput): PrintedSource catalog, hints: metaInputs.hints, options: { functionCode: input.functionCode }, + ...(input.childResults ? { childResults: input.childResults } : {}), }) return { files: Object.fromEntries(printed.files.map((file) => [file.path, file.text])), diff --git a/apps/sim/lib/workflows/code/real-catalog.test.ts b/apps/sim/lib/workflows/code/real-catalog.test.ts index 984778f7bb6..ad282d53449 100644 --- a/apps/sim/lib/workflows/code/real-catalog.test.ts +++ b/apps/sim/lib/workflows/code/real-catalog.test.ts @@ -18,10 +18,12 @@ import { printWorkflow, type ResourceKeyResolver, } from '@sim/workflow-code' +import { SDK_SPECIAL_BUILDERS } from '@sim/workflow-code/sdk' import { + builderSnippet, COOKBOOK_EXAMPLES, + describeBuilder, generateWorkspaceTypes, - SPECIAL_BUILDER_KEYS, WORKSPACE_COOKBOOK, type WorkspaceManifest, } from '@sim/workflow-sdk/codegen' @@ -104,7 +106,9 @@ describe('canonicalize and codegen over the real block catalog', () => { it('maps every builder core.d.ts declares to the block type its signature is written for', () => { expect( - Object.fromEntries(SPECIAL_BUILDER_KEYS.map((key) => [key, catalogBuilder(catalog, key)])) + Object.fromEntries( + Object.keys(SDK_SPECIAL_BUILDERS).map((key) => [key, catalogBuilder(catalog, key)]) + ) ).toEqual({ condition: { type: 'condition' }, router: { type: 'router_v2' }, @@ -117,6 +121,11 @@ describe('canonicalize and codegen over the real block catalog', () => { }) }) + it("fills an MCP server param of a builder's example call with mcp('')", () => { + const reference = describeBuilder(catalog, 'mcpBlock.runOperation') + expect(reference && builderSnippet(reference)).toContain("mcp('')") + }) + it('projects a registry multiSelect dropdown or combobox as a multiple subBlock', () => { const missing: string[] = [] let multiSelects = 0 diff --git a/apps/sim/lib/workflows/code/source-mistakes.test.ts b/apps/sim/lib/workflows/code/source-mistakes.test.ts index 888b859f153..5ffc02b12c7 100644 --- a/apps/sim/lib/workflows/code/source-mistakes.test.ts +++ b/apps/sim/lib/workflows/code/source-mistakes.test.ts @@ -146,4 +146,18 @@ export default workflow('Sync', {}, () => { "Save the token as a workspace credential and write credential: credential(''), so the token never sits in the workflow." ) }) + + it("names a table row's members when a cell is read off the row instead of its data", () => { + const result = compile( + probe('text: t`Answer: ${ask.content}`', 'text: t`Tier: ${save.row.tier}`') + ) + expect(findings(result)).toEqual(['W_UNKNOWN_OUTPUT_PATH 21: Save has no output row.tier.']) + expect(only(result, 'W_UNKNOWN_OUTPUT_PATH')?.hint).toBe( + 'row holds: id, data, position, orderKey, executions, createdAt, updatedAt.' + ) + const cell = compile( + probe('text: t`Answer: ${ask.content}`', 'text: t`Tier: ${save.row.data.tier}`') + ) + expect(findings(cell)).toEqual([]) + }) }) diff --git a/apps/sim/lib/workflows/editing/dangling-refs.test.ts b/apps/sim/lib/workflows/editing/dangling-refs.test.ts index 9d20e9346e2..30a1afe7aec 100644 --- a/apps/sim/lib/workflows/editing/dangling-refs.test.ts +++ b/apps/sim/lib/workflows/editing/dangling-refs.test.ts @@ -2,6 +2,7 @@ import type { Mock } from 'vitest' import { describe, expect, it, vi } from 'vitest' import { createMcpToolOutputSnapshot } from '@/lib/mcp/output-schema' import { collectDanglingBlockOutputReferences } from '@/lib/workflows/editing/lint' +import { FunctionBlock } from '@/blocks/blocks/function' import { McpBlock } from '@/blocks/blocks/mcp' import { getAllBlocks, getBlock, getBlockByToolName, getBlockRegistry } from '@/blocks/registry' @@ -9,7 +10,8 @@ const mockGetBlock = getBlock as Mock const mockGetAllBlocks = getAllBlocks as Mock const mockGetBlockRegistry = getBlockRegistry as Mock const mockGetBlockByToolName = getBlockByToolName as Mock -mockGetBlock.mockImplementation((type: string) => (type === 'mcp' ? McpBlock : MOCK_BLOCKS[type])) +const REAL_BLOCKS: Record = { mcp: McpBlock, function: FunctionBlock } +mockGetBlock.mockImplementation((type: string) => REAL_BLOCKS[type] ?? MOCK_BLOCKS[type]) mockGetAllBlocks.mockImplementation(() => Object.values(MOCK_BLOCKS)) mockGetBlockRegistry.mockImplementation(() => MOCK_BLOCKS) mockGetBlockByToolName.mockImplementation(() => undefined) @@ -246,6 +248,23 @@ describe('collectDanglingBlockOutputReferences', () => { expect(findings).toHaveLength(0) }) + it("accepts a block's declared error outputs as it accepts error, and flags them elsewhere", () => { + const findings = collectDanglingBlockOutputReferences( + graph({ + b1: { type: 'function', name: 'Guard' }, + b2: { type: 'api', name: 'Call' }, + b3: { + type: 'function', + name: 'Collector', + subBlocks: { + code: { value: 'return [, , ]' }, + }, + }, + }) + ) + expect(findings.map((finding) => finding.value)).toEqual([['']]) + }) + it('flags a base output on an agent whose responseFormat replaces its outputs', () => { const responseFormat = JSON.stringify({ type: 'object', diff --git a/apps/sim/lib/workflows/editing/engine.ts b/apps/sim/lib/workflows/editing/engine.ts index 7d59c4c7bcc..e0f7a4adab8 100644 --- a/apps/sim/lib/workflows/editing/engine.ts +++ b/apps/sim/lib/workflows/editing/engine.ts @@ -30,6 +30,7 @@ import type { ApplyOperationsResult, EditWorkflowOperation, OperationContext, + RemovedEdge, ValidationError, } from './types' import { isDeferredSkippedItem, logSkippedItem, type SkippedItem } from './types' @@ -298,9 +299,14 @@ export function applyOperationsToWorkflowState( // and deferred connections are applied so that every block has its final // parentId. Running it per-operation would incorrectly drop edges between // blocks that are both being moved into the same subflow in one batch. A dropped - // edge this batch created declines the operation that asked for it; an existing + // edge this batch created declines the operation that asked for it; a stored // edge a move left crossing scopes is the move's documented effect, not a refusal. - for (const edgeId of removeInvalidScopeEdges(modifiedState, skippedItems)) { + const { refusedEdgeIds, removedEdges } = removeInvalidScopeEdges( + modifiedState, + toArray<{ id: string }>(workflowState.edges), + skippedItems + ) + for (const edgeId of refusedEdgeIds) { const origin = edgeOrigins.get(edgeId) if (origin !== undefined) declinedOperations.add(origin) } @@ -350,6 +356,7 @@ export function applyOperationsToWorkflowState( validationErrors, skippedItems, declinedOperationCount: declinedOperations.size, + removedEdges, mintedBlockIds: Object.fromEntries(idMapping), } } @@ -475,33 +482,59 @@ function resolvePendingConnections( * - Container→child: source is the parent container of the target (start handles) * - Child→container: target is the parent container of the source (end handles) * - * Returns the ids of the dropped edges. + * An invalid edge this batch created is a refusal, recorded as a skipped item. + * An invalid edge the workflow already stored is removed and returned instead: + * moving a block into or out of a loop or parallel is what leaves one crossing + * the boundary, and refusing it would make an atomic batch unable to move a + * connected block at all. */ -function removeInvalidScopeEdges(modifiedState: any, skippedItems: SkippedItem[]): string[] { +function removeInvalidScopeEdges( + modifiedState: any, + storedEdges: readonly { id: string }[], + skippedItems: SkippedItem[] +): { refusedEdgeIds: string[]; removedEdges: RemovedEdge[] } { const { valid, dropped } = validateEdges(modifiedState.edges || [], modifiedState.blocks || {}) modifiedState.edges = valid - - if (dropped.length > 0) { - for (const { edge, reason } of dropped) { - logSkippedItem(skippedItems, { - type: 'invalid_edge_scope', - operationType: 'add_edge', - blockId: edge.source, - reason: `Edge from "${edge.source}" to "${edge.target}" skipped - ${reason}`, - details: { - edgeId: edge.id, - sourceHandle: edge.sourceHandle, - targetHandle: edge.targetHandle, - targetId: edge.target, - }, + if (dropped.length === 0) return { refusedEdgeIds: [], removedEdges: [] } + + const storedEdgeIds = new Set(storedEdges.map((edge) => edge.id)) + + const refusedEdgeIds: string[] = [] + const removedEdges: RemovedEdge[] = [] + for (const { edge, kind, reason } of dropped) { + if (storedEdgeIds.has(edge.id)) { + removedEdges.push({ + id: edge.id, + source: edge.source, + target: edge.target, + sourceHandle: edge.sourceHandle ?? 'source', + kind, + reason, }) + continue } + refusedEdgeIds.push(edge.id) + logSkippedItem(skippedItems, { + type: 'invalid_edge_scope', + operationType: 'add_edge', + blockId: edge.source, + reason: `Edge from "${edge.source}" to "${edge.target}" skipped - ${reason}`, + details: { + edgeId: edge.id, + sourceHandle: edge.sourceHandle, + targetHandle: edge.targetHandle, + targetId: edge.target, + }, + }) + } + if (dropped.length > 0) { logger.info('Removed invalid workflow edges', { - removed: dropped.length, + refused: refusedEdgeIds.length, + removed: removedEdges.length, reasons: dropped.map(({ reason }) => reason), }) } - return dropped.map(({ edge }) => edge.id) + return { refusedEdgeIds, removedEdges } } diff --git a/apps/sim/lib/workflows/editing/lint.ts b/apps/sim/lib/workflows/editing/lint.ts index d97835dfe58..2857b407042 100644 --- a/apps/sim/lib/workflows/editing/lint.ts +++ b/apps/sim/lib/workflows/editing/lint.ts @@ -729,6 +729,16 @@ const DYNAMIC_OUTPUT_BLOCK_TYPES = new Set(['loop', 'parallel', 'table', 'table_ */ const IMPLICIT_ERROR_OUTPUT = 'error' +/** + * Whether `key` is an output the executor writes only on a failure: the implicit + * `error`, or one of the block's declared `errorOutputs` (a Function's `errorMessage`). + */ +function isErrorOutputKey(block: BlockState, key: string): boolean { + if (key === IMPLICIT_ERROR_OUTPUT) return true + const errorOutputs = block.type ? getBlock(block.type)?.errorOutputs : undefined + return errorOutputs !== undefined && Object.hasOwn(errorOutputs, key) +} + /** Trailing `[n]` index suffixes, so `items[0]` compares as the key `items`. */ const INDEX_SUFFIX = /(?:\[\d+\])+$/ @@ -966,7 +976,7 @@ export function collectDanglingBlockOutputReferences( if (nested) undeclaredNested.set(`<${token}>`, { targetId, ...nested }) continue } - if (!keys || !segment || segment === IMPLICIT_ERROR_OUTPUT) continue + if (!keys || !segment || isErrorOutputKey(blocks[targetId], segment)) continue const group = unknownByTarget.get(targetId) ?? { target: blocks[targetId], keys, diff --git a/apps/sim/lib/workflows/editing/operations.test.ts b/apps/sim/lib/workflows/editing/operations.test.ts index 329ade91be5..58e96a9f6a2 100644 --- a/apps/sim/lib/workflows/editing/operations.test.ts +++ b/apps/sim/lib/workflows/editing/operations.test.ts @@ -1771,20 +1771,22 @@ describe('connection shape validation', () => { expect(declinedOperationCount).toBe(1) }) - it('does not charge a move for the existing edges it leaves crossing scopes', () => { - const { skippedItems, declinedOperationCount } = applyOperationsToWorkflowState( - makeLoopWorkflow(), - [ + it('removes the stored edges a move leaves crossing scopes, without skipping anything', () => { + const { state, skippedItems, declinedOperationCount, removedEdges } = + applyOperationsToWorkflowState(makeLoopWorkflow(), [ { operation_type: 'extract_from_subflow', block_id: 'agent-1', params: { subflowId: 'loop-1' }, }, - ] - ) + ]) - expect(skippedItems.filter((item) => item.type === 'invalid_edge_scope')).toHaveLength(1) + expect(skippedItems).toEqual([]) expect(declinedOperationCount).toBe(0) + expect(removedEdges).toEqual([ + expect.objectContaining({ id: 'edge-2', source: 'condition-1', target: 'agent-1' }), + ]) + expect(state.edges.some((edge: { id: string }) => edge.id === 'edge-2')).toBe(false) }) }) diff --git a/apps/sim/lib/workflows/editing/types.ts b/apps/sim/lib/workflows/editing/types.ts index 96c26781271..00977a7c448 100644 --- a/apps/sim/lib/workflows/editing/types.ts +++ b/apps/sim/lib/workflows/editing/types.ts @@ -1,5 +1,6 @@ import { createLogger } from '@sim/logger' import type { PermissionGroupConfig } from '@/lib/permission-groups/fields' +import type { DroppedEdgeKind } from '@/stores/workflows/workflow/edge-validation' /** Selector subblock types that can be validated */ export const SELECTOR_TYPES = new Set([ @@ -153,6 +154,16 @@ export interface EdgeHandleValidationResult { normalizedHandle?: string } +/** A stored edge the batch's moves left invalid, which the apply removed rather than refused. */ +export interface RemovedEdge { + id: string + source: string + target: string + sourceHandle: string + kind: DroppedEdgeKind + reason: string +} + /** * Result of applying operations to workflow state */ @@ -166,6 +177,8 @@ export interface ApplyOperationsResult { * operation, so `operations - skippedItems` would go negative. */ declinedOperationCount: number + /** Stored edges the batch left crossing a loop or parallel boundary (or otherwise invalid), removed. */ + removedEdges: RemovedEdge[] /** * Requested `block_id` -> the id the block was actually given, for every * `add`/`insert_into_subflow` whose requested id was not already a UUID. diff --git a/apps/sim/lib/workflows/editing/validation-models.test.ts b/apps/sim/lib/workflows/editing/validation-models.test.ts new file mode 100644 index 00000000000..7617cc560b7 --- /dev/null +++ b/apps/sim/lib/workflows/editing/validation-models.test.ts @@ -0,0 +1,205 @@ +import { setEnv } from '@sim/testing/mocks/env.mock' +import { envFlagsMockFns, resetEnvFlagsMock, setEnvFlags } from '@sim/testing/mocks/env-flags.mock' +import type { Mock } from 'vitest' +import { afterAll, afterEach, beforeEach, describe, expect, it } from 'vitest' +import { validateInputsForBlock } from '@/lib/workflows/editing/validation' +import { AgentBlock } from '@/blocks/blocks/agent' +import { EvaluatorBlock } from '@/blocks/blocks/evaluator' +import { GuardrailsBlock } from '@/blocks/blocks/guardrails' +import { RouterV2Block } from '@/blocks/blocks/router' +import { TranslateBlock } from '@/blocks/blocks/translate' +import { getBlock } from '@/blocks/registry' + +/** + * The model field of the real model blocks through the real validator: which values each + * block's option source lets an edit write. The registry is mocked globally (vitest.setup), + * so it is pointed at the real block configs here. + */ +const BLOCKS: Record = { + agent: AgentBlock, + router_v2: RouterV2Block, + evaluator: EvaluatorBlock, + translate: TranslateBlock, + guardrails: GuardrailsBlock, +} + +function validateModel(blockType: string, model: string) { + const result = validateInputsForBlock(blockType, { model }, `${blockType}-1`) + return { errors: result.errors, model: result.validInputs.model } +} + +afterAll(resetEnvFlagsMock) + +beforeEach(() => { + ;(getBlock as Mock).mockImplementation((type: string) => BLOCKS[type]) +}) + +afterEach(() => { + setEnvFlags({ isHosted: false }) + setEnv({ OLLAMA_URL: undefined }) + envFlagsMockFns.getBlacklistedProvidersFromEnv.mockReset().mockImplementation(() => []) +}) + +describe('agent model field', () => { + it.each(['', '{{MODEL_ID}}', 'llama3.1:8b', 'sim-auto', 'ft:gpt-4o:org::abc'])( + 'passes %s through unchanged, as it always has', + (model) => { + setEnvFlags({ isHosted: true }) + expect(validateModel('agent', model)).toEqual({ errors: [], model }) + } + ) +}) + +describe('router and evaluator model fields', () => { + it.each(['router_v2', 'evaluator'])('accepts a reference on %s', (blockType) => { + expect(validateModel(blockType, '')).toEqual({ + errors: [], + model: '', + }) + expect(validateModel(blockType, '{{MODEL_ID}}')).toEqual({ errors: [], model: '{{MODEL_ID}}' }) + }) + + it.each(['router_v2', 'evaluator'])( + 'accepts sim-auto on %s on hosted Sim, where the model router resolves it', + (blockType) => { + setEnvFlags({ isHosted: true }) + expect(validateModel(blockType, ' Sim-Auto ')).toEqual({ errors: [], model: 'sim-auto' }) + } + ) + + it('rejects sim-auto on self-hosted Sim, where Auto is never offered', () => { + const { errors, model } = validateModel('router_v2', 'sim-auto') + expect(model).toBeUndefined() + expect(errors[0]?.error).toContain('Unknown model id') + }) +}) + +describe('translate and guardrails model fields', () => { + it.each(['translate', 'guardrails'])( + 'rejects sim-auto on %s, which sends its model straight to the provider', + (blockType) => { + setEnvFlags({ isHosted: true }) + const { errors, model } = validateModel(blockType, 'sim-auto') + expect(model).toBeUndefined() + expect(errors[0]?.error).toContain('Unknown model id') + } + ) +}) + +describe('model ids no provider declares', () => { + const CATALOG_BLOCKS = ['router_v2', 'evaluator', 'translate', 'guardrails'] + + it.each(CATALOG_BLOCKS)( + 'accepts an installed Ollama model on %s where Ollama is reachable', + (blockType) => { + expect(validateModel(blockType, 'llama3.1:8b')).toEqual({ errors: [], model: 'llama3.1:8b' }) + setEnvFlags({ isHosted: true }) + setEnv({ OLLAMA_URL: 'http://ollama.internal:11434' }) + expect(validateModel(blockType, 'qwen3:latest')).toEqual({ + errors: [], + model: 'qwen3:latest', + }) + } + ) + + it.each(CATALOG_BLOCKS)('rejects it on %s on hosted Sim with no Ollama', (blockType) => { + setEnvFlags({ isHosted: true }) + const { errors, model } = validateModel(blockType, 'llama3.1:8b') + expect(model).toBeUndefined() + expect(errors[0]?.error).toContain('Unknown model id') + }) + + it.each(['gpt-oss:20b', 'mistral:latest'])( + 'accepts %s, an installed Ollama model sharing a cloud prefix, where it runs on Ollama', + (model) => { + expect(validateModel('router_v2', model)).toEqual({ errors: [], model }) + setEnvFlags({ isHosted: true }) + expect(validateModel('router_v2', model).errors[0]?.error).toContain('Unknown model id') + } + ) + + it.each(['hhao/qwen2.5-coder-tools', 'hf.co/bartowski/Llama-3.2-1B-Instruct-GGUF:Q4_K_M'])( + 'accepts a namespaced Ollama library name such as %s', + (model) => { + expect(validateModel('router_v2', model)).toEqual({ errors: [], model }) + } + ) + + it.each(['best available model', 'llama3.1:8b:extra', 'model/'])( + 'still rejects %s, which is not an Ollama model name', + (model) => { + const { errors } = validateModel('router_v2', model) + expect(errors[0]?.error).toContain('Unknown model id') + } + ) + + it.each(['claude-sonnet-4.6', 'groq/'])( + 'still rejects %s, which a provider claims, so it never reaches Ollama', + (model) => { + const { errors } = validateModel('router_v2', model) + expect(errors[0]?.error).toContain('Unknown model id') + } + ) + + it('rejects it when the Ollama provider is blacklisted', () => { + envFlagsMockFns.getBlacklistedProvidersFromEnv.mockReturnValue(['ollama']) + const { errors } = validateModel('router_v2', 'llama3.1:8b') + expect(errors[0]?.error).toContain('Unknown model id') + }) + + it('offers an ollama/ namespace example only where Ollama can serve it', () => { + expect(validateModel('router_v2', 'best available model').errors[0]?.error).toContain( + '"ollama/llama3.1:8b"' + ) + + setEnvFlags({ isHosted: true }) + expect(validateModel('router_v2', 'best available model').errors[0]?.error).not.toContain( + 'ollama/' + ) + + setEnvFlags({ isHosted: false }) + envFlagsMockFns.getBlacklistedProvidersFromEnv.mockReturnValue(['ollama']) + expect(validateModel('router_v2', 'best available model').errors[0]?.error).not.toContain( + 'ollama/' + ) + }) +}) + +describe('fallback model rows', () => { + function validateFallback(blockType: string, model: string) { + const result = validateInputsForBlock( + blockType, + { fallbackModels: [{ id: 'row-1', model }] }, + `${blockType}-1` + ) + return { errors: result.errors, rows: result.validInputs.fallbackModels } + } + + it.each(['agent', 'router_v2', 'evaluator'])( + 'accepts an installed Ollama model on %s where Ollama is reachable, as the model field does', + (blockType) => { + const { errors, rows } = validateFallback(blockType, 'mistral:latest') + expect(errors).toEqual([]) + expect(rows).toEqual([expect.objectContaining({ model: 'mistral:latest' })]) + } + ) + + it('rejects it on hosted Sim with no Ollama', () => { + setEnvFlags({ isHosted: true }) + const { errors } = validateFallback('agent', 'mistral:latest') + expect(errors[0]?.error).toContain('unknown model id "mistral:latest"') + }) + + it('rejects it when the Ollama provider is blacklisted', () => { + envFlagsMockFns.getBlacklistedProvidersFromEnv.mockReturnValue(['ollama']) + const { errors } = validateFallback('agent', 'mistral:latest') + expect(errors[0]?.error).toContain('unknown model id "mistral:latest"') + }) + + it('still rejects sim-auto and free text', () => { + expect(validateFallback('agent', 'sim-auto').errors[0]?.error).toContain('sim-auto') + expect(validateFallback('agent', 'best available model').errors[0]?.error).toContain( + 'unknown model id' + ) + }) +}) diff --git a/apps/sim/lib/workflows/editing/validation.test.ts b/apps/sim/lib/workflows/editing/validation.test.ts index c505a92b2e7..3620f9b5cc9 100644 --- a/apps/sim/lib/workflows/editing/validation.test.ts +++ b/apps/sim/lib/workflows/editing/validation.test.ts @@ -269,6 +269,7 @@ const blockConfigsByType: Record = { vi.mock('@/blocks/utils', () => ({ getModelOptions: mockGetModelOptions, + MODEL_OPTION_SOURCES: new Map([[mockGetModelOptions, { auto: false }]]), })) vi.mock('@/tools/utils', () => toolsUtilsMock) @@ -504,7 +505,13 @@ describe('validateInputsForBlock', () => { it('refuses sim-auto, evaluation models, unknown models, missing models, and non-arrays', () => { expect(validate([{ model: 'sim-auto' }]).valid).toBe(false) expect(validate([{ model: 'jev-latest' }]).valid).toBe(false) - expect(validate([{ model: 'definitely-not-a-model-9000' }]).valid).toBe(false) + // An unclaimed Ollama-shaped name is a possible local model wherever Ollama is reachable. + setEnvFlags({ isHosted: true }) + try { + expect(validate([{ model: 'definitely-not-a-model-9000' }]).valid).toBe(false) + } finally { + setEnvFlags({ isHosted: false }) + } expect(validate([{ apiKey: '{{KEY}}' }]).valid).toBe(false) expect(validate({ model: 'claude-sonnet-5' }).valid).toBe(false) }) @@ -722,7 +729,6 @@ describe('validateInputsForBlock', () => { 'nvidia/', 'ollama/', 'ollama-cloud/', - 'unknown/model', ])('rejects incomplete or unsupported cloud namespaces: %s', (model) => { const result = validateInputsForBlock('agent', { model }, 'agent-1') expect(result.validInputs.model).toBeUndefined() diff --git a/apps/sim/lib/workflows/editing/validation.ts b/apps/sim/lib/workflows/editing/validation.ts index f2aeeb01c6c..95022b6f386 100644 --- a/apps/sim/lib/workflows/editing/validation.ts +++ b/apps/sim/lib/workflows/editing/validation.ts @@ -9,6 +9,7 @@ import { resolveCanonicalMode, } from '@sim/workflow-code/catalog/canonical-index' import { isHosted as isHostedDeployment } from '@/lib/core/config/env-flags' +import { isOllamaAvailable } from '@/lib/core/utils/urls' import { isIntegrationDeploymentAvailableForVisibility } from '@/lib/integrations/availability.server' import { mcpOperationPolicySchema } from '@/lib/mcp/operation-policy' import { MCP_SERVER_ADVANCED_TOOL_TYPE } from '@/lib/mcp/shared' @@ -40,15 +41,17 @@ import { import { validateToolBindingAuthoring } from '@/lib/workflows/tool-input/authoring' import { getBlock } from '@/blocks/registry' import type { SubBlockConfig } from '@/blocks/types' -import { getModelOptions } from '@/blocks/utils' +import { MODEL_OPTION_SOURCES } from '@/blocks/utils' import { overlayVisibility } from '@/blocks/visibility/context' import { BlockType, EDGE, normalizeName } from '@/executor/constants' import { + findProviderFromModel, getHostedModels, isAutoModel, isCustomModelId, isEvaluationModel, isKnownModelId, + OLLAMA_MODEL_NAME, suggestModelIdsForUnknownModel, } from '@/providers/models' import { isPiByokOnlyMode } from '@/providers/pi-providers' @@ -557,7 +560,7 @@ function validateFallbackModelEntry(item: any, index: number): string | null { if (isEvaluationModel(model)) { return `${where}: ${model} is an evaluation model and cannot serve as a chat fallback` } - if (!isKnownModelId(model) && !isCustomModelId(model)) { + if (!isRunnableModelId(model)) { const suggestions = suggestModelIdsForUnknownModel(model) const suggestionText = suggestions.length > 0 ? ` Valid options include: ${suggestions.join(', ')}.` : '' @@ -582,6 +585,23 @@ function validateFallbackModelEntry(item: any, index: number): string | null { return null } +/** + * Whether Sim can run `model`: a catalogued or namespaced id, or a local Ollama name. An id no + * provider claims runs on Ollama (`getProviderFromModel`'s default), so wherever an Ollama server + * is reachable an Ollama-shaped name may be a locally installed model. The server cannot list + * what is installed, so a mistyped name of that shape fails at execution instead. sim-auto is + * never one: it never reaches a provider as itself. + */ +function isRunnableModelId(model: string): boolean { + if (isKnownModelId(model) || isCustomModelId(model)) return true + return ( + !isAutoModel(model) && + OLLAMA_MODEL_NAME.test(model) && + findProviderFromModel(model) === null && + isOllamaAvailable() + ) +} + /** A file object as the file-upload editor stores it: at least its name and serve path. */ function isStoredFile(value: unknown): boolean { return isPlainRecord(value) && Boolean(value.name) && Boolean(value.path) @@ -986,22 +1006,34 @@ export function validateValueForSubBlockType( case 'short-input': case 'long-input': case 'combobox': { - const usesProviderCatalog = - fieldName === 'model' && subBlockConfig.options === getModelOptions + const modelSource = + fieldName === 'model' ? MODEL_OPTION_SOURCES.get(subBlockConfig.options) : undefined - if (usesProviderCatalog) { + if (modelSource) { const stringValue = typeof value === 'string' ? value : String(value) const trimmed = stringValue.trim() - // sim-auto is a valid model value on hosted Sim only (mirrors the - // options array the agent reads: it is absent from self-hosted - // snapshots, so writes of it there are rejected as unknown). - if (trimmed !== '' && isAutoModel(trimmed) && isHostedDeployment) { + // A reference or {{ENV_VAR}} names its model only at execution time. + if (containsReference(trimmed)) { + return { valid: true, value: trimmed } + } + // sim-auto is valid only where the source offers Auto, which it does on hosted Sim + // only; writes of it anywhere else are rejected as unknown. + if (isAutoModel(trimmed) && modelSource.auto && isHostedDeployment) { return { valid: true, value: trimmed.toLowerCase() } } - if (trimmed !== '' && !isKnownModelId(trimmed) && !isCustomModelId(trimmed)) { + if (trimmed !== '' && !isRunnableModelId(trimmed)) { const suggestions = suggestModelIdsForUnknownModel(trimmed) const suggestionText = suggestions.length > 0 ? ` Valid options include: ${suggestions.join(', ')}.` : '' + const namespaceExamples = [ + 'azure/my-deployment', + 'azure-anthropic/my-deployment', + 'bedrock/my-inference-profile', + 'vertex/my-model', + ...(isOllamaAvailable() ? ['ollama/llama3.1:8b'] : []), + ] + .map((example) => `"${example}"`) + .join(', ') return { valid: false, error: { @@ -1009,7 +1041,7 @@ export function validateValueForSubBlockType( blockType, field: fieldName, value, - error: `Unknown model id "${trimmed}" for block "${blockType}". Read components/blocks/${blockType}.json (the model.options array) for valid ids; prefer entries with recommended: true and avoid deprecated: true. For user-configured models, use a supported provider namespace, e.g. "azure/my-deployment", "azure-anthropic/my-deployment", "bedrock/my-inference-profile", "vertex/my-model", "ollama/llama3.1:8b", or "openrouter/provider/model".${suggestionText}`, + error: `Unknown model id "${trimmed}" for block "${blockType}". Read components/blocks/${blockType}.json (the model.options array) for valid ids; prefer entries with recommended: true and avoid deprecated: true. For user-configured models, use a supported provider namespace, e.g. ${namespaceExamples}, or "openrouter/provider/model".${suggestionText}`, }, } } diff --git a/apps/sim/lib/workflows/executor/execute-service.ts b/apps/sim/lib/workflows/executor/execute-service.ts index d79453a28a1..aadcba4b1f2 100644 --- a/apps/sim/lib/workflows/executor/execute-service.ts +++ b/apps/sim/lib/workflows/executor/execute-service.ts @@ -32,6 +32,7 @@ import { releaseExecutionIdClaim, } from '@/lib/workflows/executor/execution-id-claim' import { handlePostExecutionPauseState } from '@/lib/workflows/executor/pause-persistence' +import { type RunPause, runPauseOf } from '@/lib/workflows/executor/run-pause' import { loadDeployedWorkflowState, loadWorkflowDeploymentVersionState, @@ -59,6 +60,7 @@ import { type StructuredExecutionError, } from '@/executor/utils/errors' import type { ResolvedSecretTraceProvenanceV1 } from '@/executor/utils/resolved-secret-trace-registry' +import { findRerunStartBlockId } from '@/executor/utils/run-from-block' import type { CoreTriggerType } from '@/stores/logs/filters/types' const logger = createLogger('WorkflowExecuteService') @@ -173,6 +175,8 @@ export interface ExecuteWorkflowServiceRun { aborted: 'client' | 'timeout' | null output: NormalizedBlockOutput | undefined error: StructuredExecutionError | null + /** Where a run-from-block rerun of the failure starts in the graph the run executed; see {@link findRerunStartBlockId}. */ + rerunFromBlockId?: string /** Outputs of the blocks named by `selectedOutputs`, keyed by the caller's selector strings. */ blockOutputs?: Record | null /** Trusted execution-local catalog used by internal callers to project model-visible output. */ @@ -183,6 +187,8 @@ export interface ExecuteWorkflowServiceRun { durationMs?: number /** The execution timeout applied to the run in milliseconds; `0` means untimed. */ executionTimeoutMs: number + /** Where a `paused` run waits; absent otherwise. */ + paused?: RunPause | null } /** A run's result before the applied timeout is stamped onto it. */ @@ -240,6 +246,14 @@ export type ExecuteWorkflowServiceImmediateResult = Exclude< ExecuteWorkflowServicePendingRun > +/** Where a rerun of the block `error` attributes starts in the run's `blocks`, when it names one. */ +function rerunStartOf( + error: StructuredExecutionError | null, + blocks: Record +): string | undefined { + return error?.blockId ? findRerunStartBlockId(error.blockId, blocks) : undefined +} + function failure(f: ExecuteWorkflowServiceFailure): ExecuteWorkflowServiceFailureResult { return { ok: false, failure: f } } @@ -843,6 +857,10 @@ export async function executeWorkflowService( : result.success ? 'completed' : 'failed' + const runError = + status === 'failed' || (status === 'cancelled' && result.error) + ? classifyExecutionError(result.error ? new Error(result.error) : undefined, result) + : null return { ok: true, @@ -855,15 +873,14 @@ export async function executeWorkflowService( await pickRunBlockOutputs(selectedOutputs, workflowBlocks, result.logs), compactionContext ), - error: - status === 'failed' || (status === 'cancelled' && result.error) - ? classifyExecutionError(result.error ? new Error(result.error) : undefined, result) - : null, + error: runError, + rerunFromBlockId: rerunStartOf(runError, workflowBlocks), resolvedSecretTraceProvenance: result.executionState?.resolvedSecretTraceProvenance, hasResponseBlock: workflowHasResponseBlock(result), startedAt: result.metadata?.startTime, endedAt: result.metadata?.endTime, durationMs: result.metadata?.duration, + paused: runPauseOf(result, executionId), } } catch (error: unknown) { const errorMessage = getErrorMessage(error, 'Unknown error') @@ -931,6 +948,7 @@ export async function executeWorkflowService( } } + const thrownError = classifyExecutionError(error, executionResult) return { ok: true, executionId, @@ -939,7 +957,8 @@ export async function executeWorkflowService( aborted: null, output: compactErrorOutput, blockOutputs: compactErrorBlockOutputs, - error: classifyExecutionError(error, executionResult), + error: thrownError, + rerunFromBlockId: rerunStartOf(thrownError, workflowBlocks), resolvedSecretTraceProvenance: executionResult?.executionState?.resolvedSecretTraceProvenance, hasResponseBlock: false, diff --git a/apps/sim/lib/workflows/executor/execution-state.ts b/apps/sim/lib/workflows/executor/execution-state.ts index 91547af2bc7..1b66b7cbf4d 100644 --- a/apps/sim/lib/workflows/executor/execution-state.ts +++ b/apps/sim/lib/workflows/executor/execution-state.ts @@ -4,6 +4,7 @@ import { filterUndefined, isRecordLike } from '@sim/utils/object' import { and, desc, eq, or, sql } from 'drizzle-orm' import { getBaseUrl } from '@/lib/core/utils/urls' import { materializeExecutionData, TRACE_STORE_REF_KEY } from '@/lib/logs/execution/trace-store' +import { forceFailedMessage } from '@/lib/workflows/executor/failure-message' import { buildResumeUiUrl } from '@/executor/constants' import type { SerializableExecutionState } from '@/executor/execution/types' import type { PausePoint } from '@/executor/types' @@ -233,16 +234,15 @@ export async function getHumanPauseResumeUrl( } /** - * The message an error finalization (`force_failed`) stored as the run's `finalOutput.error`. - * Any other run's `finalOutput.error` is the workflow's own data, not a failure message. + * A terminal run's failure message: its own `error`, else {@link forceFailedMessage}. Unlike + * `runFailureMessage` it skips `completionFailure`: it reads completed and cancelled runs too, and + * a completion that fell back to a cost-only log records why there (`Failed to store trace + * spans: …`, `Run was cancelled`), which is a logging note, not the run's error. A failed run's + * error is already its own `error` or its forced finalization's message. */ function readFailureMessage(executionData: Record): string | undefined { if (typeof executionData.error === 'string') return executionData.error - if (executionData.finalizationPath !== 'force_failed') return undefined - const { finalOutput } = executionData - return isRecordLike(finalOutput) && typeof finalOutput.error === 'string' - ? finalOutput.error - : undefined + return forceFailedMessage(executionData) } /** Loads a terminal workflow result only when its server-persisted Copilot binding matches. */ diff --git a/apps/sim/lib/workflows/executor/execution-status.test.ts b/apps/sim/lib/workflows/executor/execution-status.test.ts index 6fe2d592dc0..cfe3eb0a21c 100644 --- a/apps/sim/lib/workflows/executor/execution-status.test.ts +++ b/apps/sim/lib/workflows/executor/execution-status.test.ts @@ -778,6 +778,33 @@ describe('getWorkflowExecutionStatus once a pause has settled', () => { }, }) }) + + it.each([ + [ + 'the message an error finalization recorded', + { + finalizationPath: 'force_failed', + completionFailure: 'Lookup: upstream returned 500', + finalOutput: { error: 'Lookup: upstream returned 500' }, + }, + 'Lookup: upstream returned 500', + ], + [ + "no error from a workflow output's own error field", + { finalizationPath: 'completed', finalOutput: { error: 'no matching customer' } }, + null, + ], + ])('reports as a failed run its error %s', async (_, recorded, error) => { + queueFailedRunWithOpenPause({ 'wait-five': FAILED_TIME_POINT }) + mockMaterializeForDisplayWithBlockOutputs.mockResolvedValue({ + executionData: { ...recorded, traceSpans: [] }, + blockOutputs: new Map(), + }) + + const projected = await getProjectedWorkflowExecutionStatus(input) + + expect(projected?.status).toMatchObject({ status: 'failed', error }) + }) }) describe('readPausedRunPoints cap', () => { diff --git a/apps/sim/lib/workflows/executor/execution-status.ts b/apps/sim/lib/workflows/executor/execution-status.ts index 9461c9e98ac..51bcbf9ca8a 100644 --- a/apps/sim/lib/workflows/executor/execution-status.ts +++ b/apps/sim/lib/workflows/executor/execution-status.ts @@ -25,6 +25,7 @@ import { WORKFLOW_EXECUTION_JOB_ID_PREFIX, } from '@/lib/workflows/executor/execution-job-ids' import { normalizePausePoints } from '@/lib/workflows/executor/execution-state' +import { runFailureMessage } from '@/lib/workflows/executor/failure-message' import { PauseResumeManager } from '@/lib/workflows/executor/human-in-the-loop-manager' import { namePausePoints, pauseBaseBlockId } from '@/lib/workflows/executor/pause-block-names' import { getAutomaticResumeWaitingMetadata } from '@/lib/workflows/executor/paused-execution-metadata' @@ -42,9 +43,7 @@ import type { PauseInputField, PausePoint, ResumeStatus } from '@/executor/types type LogStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' interface ExecutionDataShape { - finalOutput?: { error?: string } & Record - error?: { message?: string } | string - completionFailure?: string + finalOutput?: unknown traceSpans?: unknown } @@ -88,18 +87,6 @@ function isSettledPausePoint(point: PausePoint): boolean { return point.resumeStatus === 'resumed' || point.resumeStatus === 'failed' } -function extractError(executionData: unknown): string | null { - if (!executionData || typeof executionData !== 'object') return null - const data = executionData as ExecutionDataShape - if (typeof data.error === 'string') return data.error - if (data.error && typeof data.error === 'object' && typeof data.error.message === 'string') { - return data.error.message - } - if (typeof data.finalOutput?.error === 'string') return data.finalOutput.error - if (typeof data.completionFailure === 'string') return data.completionFailure - return null -} - function extractJobFinalOutput(output: unknown): unknown | null { if (!output || typeof output !== 'object' || !('output' in output)) return null return (output as Record).output ?? null @@ -603,7 +590,7 @@ async function readWorkflowExecutionStatus( ) const executionData = materialized.executionData as ExecutionDataShape - const error = status === 'failed' ? extractError(executionData) : null + const error = status === 'failed' ? (runFailureMessage(executionData) ?? null) : null const finalOutput = includeOutput && status === 'completed' && executionData diff --git a/apps/sim/lib/workflows/executor/failure-message.ts b/apps/sim/lib/workflows/executor/failure-message.ts new file mode 100644 index 00000000000..ed77ee185e7 --- /dev/null +++ b/apps/sim/lib/workflows/executor/failure-message.ts @@ -0,0 +1,31 @@ +import { isRecordLike } from '@sim/utils/object' + +/** + * The message an error finalization (`force_failed`) stored as the run's `finalOutput.error`. + * Any other run's `finalOutput.error` is the workflow's own data, not a failure message. + */ +export function forceFailedMessage(executionData: Record): string | undefined { + if (executionData.finalizationPath !== 'force_failed') return undefined + const { finalOutput } = executionData + return isRecordLike(finalOutput) && typeof finalOutput.error === 'string' + ? finalOutput.error + : undefined +} + +/** + * The error a failed run recorded for itself, as the run log and status reads report it: its own + * `error` (a string, or an object with a `message`), the failure its completion recorded + * (`completionFailure`), else {@link forceFailedMessage}. Undefined when it recorded none, as a + * run whose status comes from a block's error alone does. + */ +export function runFailureMessage(executionData: unknown): string | undefined { + if (!isRecordLike(executionData)) return undefined + const { error, completionFailure } = executionData + const candidates = [ + error, + isRecordLike(error) ? error.message : undefined, + completionFailure, + forceFailedMessage(executionData), + ] + return candidates.find((value): value is string => typeof value === 'string' && value !== '') +} diff --git a/apps/sim/lib/workflows/executor/human-in-the-loop-manager.ts b/apps/sim/lib/workflows/executor/human-in-the-loop-manager.ts index 77c30588b6b..d0e124aaa75 100644 --- a/apps/sim/lib/workflows/executor/human-in-the-loop-manager.ts +++ b/apps/sim/lib/workflows/executor/human-in-the-loop-manager.ts @@ -59,6 +59,7 @@ import { normalizeAutomaticResumeWaitingReason, resolveAutomaticResumeAdmissionFailure, } from '@/lib/workflows/executor/resume-policy' +import { pausedRunIdOf } from '@/lib/workflows/executor/run-pause' import { forwardAgentStreamToExecutionEvents, shouldForwardAnswerTextFromSink, @@ -997,7 +998,7 @@ export class PauseResumeManager { * reason, then throw so the attempt settles as failed below. The thrown * message stays stable; the underlying error rides on `cause`. */ - const effectiveExecutionId = result.metadata?.executionId ?? resumeExecutionId + const effectiveExecutionId = pausedRunIdOf(result, resumeExecutionId) const failPause = async (reason: string, cause?: unknown): Promise => { logger.error( reason, diff --git a/apps/sim/lib/workflows/executor/resume-execution.ts b/apps/sim/lib/workflows/executor/resume-execution.ts index 2ba5d6e4d06..9d1b16b9f0d 100644 --- a/apps/sim/lib/workflows/executor/resume-execution.ts +++ b/apps/sim/lib/workflows/executor/resume-execution.ts @@ -15,6 +15,7 @@ import { generateRequestId } from '@/lib/core/utils/request' import { preprocessExecution } from '@/lib/execution/preprocessing' import { RESUME_EXECUTION_JOB_ID_PREFIX } from '@/lib/workflows/executor/enqueue-execution' import { PauseResumeManager } from '@/lib/workflows/executor/human-in-the-loop-manager' +import { type RunPause, runPauseOf } from '@/lib/workflows/executor/run-pause' import { createStreamingResponse } from '@/lib/workflows/streaming/streaming' import { executeResumeJob, type ResumeExecutionPayload } from '@/background/resume-execution' import { ExecutionSnapshot } from '@/executor/execution/snapshot' @@ -87,6 +88,8 @@ export type ResumeWorkflowExecutionResult = startTime?: string endTime?: string } + /** Where a run that paused again waits. */ + paused: RunPause | null } | { kind: 'async' @@ -353,6 +356,8 @@ export async function executeResumeWorkflow({ endTime: result.metadata.endTime, } : undefined, + paused: + runFailure === undefined ? runPauseOf(result, enqueueResult.resumeExecutionId) : null, } } diff --git a/apps/sim/lib/workflows/executor/run-pause.ts b/apps/sim/lib/workflows/executor/run-pause.ts new file mode 100644 index 00000000000..a4caecbd5ab --- /dev/null +++ b/apps/sim/lib/workflows/executor/run-pause.ts @@ -0,0 +1,22 @@ +import type { ExecutionResult, PausePoint } from '@/executor/types' + +/** Where a paused run waits: the run its pause is recorded under, and each pause point. */ +export interface RunPause { + runId: string + points: PausePoint[] +} + +/** + * The run a pause is recorded under, which Resume workflow run names: the execution the engine ran + * as, else `runId`, the id the run was started or resumed with. A resumed run that pauses again + * records the pause under the run it resumed, not the resume attempt's own id. + */ +export function pausedRunIdOf(result: ExecutionResult, runId: string): string { + return result.metadata?.executionId ?? runId +} + +/** Where `result` waits when it paused, else null. */ +export function runPauseOf(result: ExecutionResult, runId: string): RunPause | null { + if (result.status !== 'paused') return null + return { runId: pausedRunIdOf(result, runId), points: result.pausePoints ?? [] } +} diff --git a/apps/sim/lib/workflows/migrations/subblock-migrations.ts b/apps/sim/lib/workflows/migrations/subblock-migrations.ts index 1830bffaf06..76436a44757 100644 --- a/apps/sim/lib/workflows/migrations/subblock-migrations.ts +++ b/apps/sim/lib/workflows/migrations/subblock-migrations.ts @@ -644,7 +644,7 @@ export function migrateSubblockIds(blocks: Record): { * typed a reference has both — and `resolveCanonicalMode` prefers basic, which * would silently swap which value the run uses. */ -export interface CanonicalIdMigration { +interface CanonicalIdMigration { /** The canonical id a legacy saved state stores the mode under. */ from: string /** The canonical id the block definition declares now. */ @@ -652,7 +652,7 @@ export interface CanonicalIdMigration { } /** Canonical-id renames per block type. */ -export const CANONICAL_ID_MIGRATIONS: Record = { +const CANONICAL_ID_MIGRATIONS: Record = { /** * The tool parameter is `file`, and `check-block-registry.ts` requires the * canonical id to match it once the parameter is `user-only` — which it diff --git a/apps/sim/lib/workflows/schedules/claim.integration.ts b/apps/sim/lib/workflows/schedules/claim.integration.ts new file mode 100644 index 00000000000..925e0449886 --- /dev/null +++ b/apps/sim/lib/workflows/schedules/claim.integration.ts @@ -0,0 +1,180 @@ +import { mkdir, writeFile } from 'node:fs/promises' +import { dirname, resolve } from 'node:path' +import { db } from '@sim/db' +import { + user, + workflow, + workflowDeploymentVersion, + workflowSchedule, + workspace, +} from '@sim/db/schema' +import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' +import { getErrorMessage } from '@sim/utils/errors' +import { generateId } from '@sim/utils/id' +import { eq, inArray } from 'drizzle-orm' +import { afterAll, beforeAll, expect, it } from 'vitest' +import { claimDueWorkflowSchedules } from '@/lib/workflows/schedules/claim' + +const ownerId = generateId() +const workspaceId = generateId() +const workflowId = generateId() +const liveVersionId = generateId() + +/** Far in the past, so no other suite's schedule is due at this instant. */ +const occurrence = new Date('2001-01-01T00:00:00.000Z') +const queuedAt = new Date('2001-01-01T01:00:00.000Z') +const minutesBefore = (instant: Date, minutes: number) => + new Date(instant.getTime() - minutes * 60_000) + +/** One schedule per claim state the tick has to tell apart. */ +const scheduleIds = { + unclaimed: generateId(), + claimedForEarlierOccurrence: generateId(), + claimHeldPastRecheck: generateId(), + claimInFlight: generateId(), + claimRecheckedRecently: generateId(), + notYetDue: generateId(), +} + +const checks: { name: string; status: string; durationMs: number; error?: string }[] = [] + +function check(name: string, run: () => Promise) { + it(name, async () => { + const started = performance.now() + try { + await run() + checks.push({ name, status: 'passed', durationMs: performance.now() - started }) + } catch (error) { + checks.push({ + name, + status: 'failed', + durationMs: performance.now() - started, + error: getErrorMessage(error), + }) + throw error + } + }) +} + +beforeAll(async () => { + const now = new Date() + await db.insert(user).values({ + id: ownerId, + name: 'Schedule claim fixture', + email: `${ownerId}@schedule-claim.invalid`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + await insertWorkspaceFixture(db, { + id: workspaceId, + ownerId, + billedAccountUserId: ownerId, + name: 'Schedule claim', + }) + await db.insert(workflow).values({ + id: workflowId, + workspaceId, + userId: ownerId, + name: 'Schedule claim fixture', + isDeployed: true, + lastSynced: now, + createdAt: now, + updatedAt: now, + }) + await db.insert(workflowDeploymentVersion).values({ + id: liveVersionId, + workflowId, + version: 1, + isActive: true, + state: { blocks: {}, edges: [], loops: {}, parallels: {} }, + }) + + const schedule = ( + id: string, + nextRunAt: Date, + lastQueuedAt: Date | null, + updatedAt = minutesBefore(queuedAt, 2) + ) => ({ + id, + workflowId, + deploymentVersionId: liveVersionId, + blockId: id, + triggerType: 'schedule', + cronExpression: '*/5 * * * *', + timezone: 'UTC', + status: 'active', + failedCount: 0, + nextRunAt, + lastQueuedAt, + createdAt: occurrence, + updatedAt, + }) + await db + .insert(workflowSchedule) + .values([ + schedule(scheduleIds.unclaimed, occurrence, null), + schedule(scheduleIds.claimedForEarlierOccurrence, occurrence, minutesBefore(occurrence, 5)), + schedule( + scheduleIds.claimHeldPastRecheck, + occurrence, + minutesBefore(queuedAt, 11), + minutesBefore(queuedAt, 11) + ), + schedule(scheduleIds.claimInFlight, occurrence, minutesBefore(queuedAt, 2)), + schedule(scheduleIds.claimRecheckedRecently, occurrence, minutesBefore(queuedAt, 30)), + schedule(scheduleIds.notYetDue, minutesBefore(queuedAt, -1), null), + ]) +}) + +afterAll(async () => { + const reportPath = + process.env.SCHEDULE_CLAIM_REPORT_PATH ?? resolve('test-results/schedule-claim.json') + await mkdir(dirname(reportPath), { recursive: true }) + await writeFile(reportPath, JSON.stringify({ checks }, null, 2)) + await deleteWorkspaceFixture(db, eq(workspace.id, workspaceId)) + await db.delete(user).where(eq(user.id, ownerId)) +}) + +check( + 'claims due schedules and re-examines a stale current-occurrence claim without replacing it', + async () => { + const claimed = await claimDueWorkflowSchedules(queuedAt, 100) + const claimById = new Map( + claimed.filter((row) => row.workflowId === workflowId).map((row) => [row.id, row]) + ) + + expect([...claimById.keys()].sort()).toEqual( + [ + scheduleIds.unclaimed, + scheduleIds.claimedForEarlierOccurrence, + scheduleIds.claimHeldPastRecheck, + ].sort() + ) + expect(claimById.get(scheduleIds.unclaimed)?.lastQueuedAt).toEqual(queuedAt) + expect(claimById.get(scheduleIds.claimedForEarlierOccurrence)?.lastQueuedAt).toEqual(queuedAt) + expect(claimById.get(scheduleIds.claimHeldPastRecheck)?.lastQueuedAt).toEqual( + minutesBefore(queuedAt, 11) + ) + + const rows = await db + .select({ + id: workflowSchedule.id, + lastQueuedAt: workflowSchedule.lastQueuedAt, + updatedAt: workflowSchedule.updatedAt, + }) + .from(workflowSchedule) + .where(inArray(workflowSchedule.id, Object.values(scheduleIds))) + const stored = new Map(rows.map((row) => [row.id, row])) + + expect(stored.get(scheduleIds.claimHeldPastRecheck)?.updatedAt).toEqual(queuedAt) + expect(stored.get(scheduleIds.claimInFlight)).toMatchObject({ + lastQueuedAt: minutesBefore(queuedAt, 2), + updatedAt: minutesBefore(queuedAt, 2), + }) + expect(stored.get(scheduleIds.claimRecheckedRecently)).toMatchObject({ + lastQueuedAt: minutesBefore(queuedAt, 30), + updatedAt: minutesBefore(queuedAt, 2), + }) + } +) diff --git a/apps/sim/lib/workflows/schedules/claim.ts b/apps/sim/lib/workflows/schedules/claim.ts new file mode 100644 index 00000000000..b70ff14c112 --- /dev/null +++ b/apps/sim/lib/workflows/schedules/claim.ts @@ -0,0 +1,101 @@ +import { db, workflow, workflowDeploymentVersion, workflowSchedule } from '@sim/db' +import { and, eq, inArray, isNull, lt, lte, or, sql } from 'drizzle-orm' + +/** + * How long a schedule may hold the claim on its current occurrence before a tick re-examines it. + * It has to outlast one tick's handoff; re-examining is safe because the tick resolves the + * occurrence through its carrier's deterministic job id rather than dispatching it again blindly. + */ +const SCHEDULE_CLAIM_RECHECK_MS = 10 * 60 * 1000 + +/** + * A claim held on the current occurrence (`lastQueuedAt >= nextRunAt`) is the run's identity: the + * worker's claim-guarded writes match it exactly, so a re-examination keeps it and moves only + * `updatedAt`, which serves as the re-check clock. + */ +const holdsCurrentOccurrenceClaim = sql`${workflowSchedule.lastQueuedAt} >= ${workflowSchedule.nextRunAt}` + +const dueFilter = (queuedAt: Date) => + and( + isNull(workflowSchedule.archivedAt), + lte(workflowSchedule.nextRunAt, queuedAt), + sql`${workflowSchedule.status} NOT IN ('disabled', 'completed')`, + or( + isNull(workflowSchedule.lastQueuedAt), + lt(workflowSchedule.lastQueuedAt, workflowSchedule.nextRunAt), + lt(workflowSchedule.updatedAt, new Date(queuedAt.getTime() - SCHEDULE_CLAIM_RECHECK_MS)) + ) + ) + +const activeWorkflowDeploymentFilter = () => + sql`${workflowSchedule.deploymentVersionId} = (select ${workflowDeploymentVersion.id} from ${workflowDeploymentVersion} where ${workflowDeploymentVersion.workflowId} = ${workflowSchedule.workflowId} and ${workflowDeploymentVersion.isActive} = true)` + +const workflowScheduleFilter = (queuedAt: Date) => + and( + dueFilter(queuedAt), + sql`(${workflowSchedule.sourceType} = 'workflow' OR ${workflowSchedule.sourceType} IS NULL)`, + activeWorkflowDeploymentFilter() + ) + +/** + * Claims up to `limit` due workflow schedules on their live deployment, including any whose claim + * on the current occurrence has gone {@link SCHEDULE_CLAIM_RECHECK_MS} without a re-examination. + * Concurrent ticks skip each other's locked rows. + */ +export async function claimDueWorkflowSchedules(queuedAt: Date, limit: number) { + if (limit <= 0) return [] + + return db.transaction(async (tx) => { + const rows = await tx + .select({ + id: workflowSchedule.id, + workspaceId: workflow.workspaceId, + }) + .from(workflowSchedule) + .innerJoin(workflow, eq(workflowSchedule.workflowId, workflow.id)) + .where(workflowScheduleFilter(queuedAt)) + .for('update', { skipLocked: true }) + .limit(limit) + + if (rows.length === 0) return [] + const workspaceIdsByScheduleId = new Map(rows.map((row) => [row.id, row.workspaceId])) + + const claimedRows = await tx + .update(workflowSchedule) + .set({ + lastQueuedAt: sql`CASE WHEN ${holdsCurrentOccurrenceClaim} THEN ${workflowSchedule.lastQueuedAt} ELSE ${sql.param(queuedAt, workflowSchedule.lastQueuedAt)} END`, + updatedAt: queuedAt, + }) + .where( + and( + workflowScheduleFilter(queuedAt), + inArray( + workflowSchedule.id, + rows.map((row) => row.id) + ) + ) + ) + .returning({ + id: workflowSchedule.id, + workflowId: workflowSchedule.workflowId, + blockId: workflowSchedule.blockId, + cronExpression: workflowSchedule.cronExpression, + lastRanAt: workflowSchedule.lastRanAt, + failedCount: workflowSchedule.failedCount, + infraRetryCount: workflowSchedule.infraRetryCount, + nextRunAt: workflowSchedule.nextRunAt, + lastQueuedAt: workflowSchedule.lastQueuedAt, + timezone: workflowSchedule.timezone, + deploymentVersionId: workflowSchedule.deploymentVersionId, + deploymentOperationId: workflowSchedule.deploymentOperationId, + sourceType: workflowSchedule.sourceType, + }) + + return claimedRows.map((row) => ({ + ...row, + workspaceId: workspaceIdsByScheduleId.get(row.id) ?? null, + })) + }) +} + +export type ClaimedWorkflowSchedule = Awaited>[number] diff --git a/apps/sim/lib/workflows/schedules/disable-reasons.ts b/apps/sim/lib/workflows/schedules/disable-reasons.ts index d6d20e67591..13849ff86fc 100644 --- a/apps/sim/lib/workflows/schedules/disable-reasons.ts +++ b/apps/sim/lib/workflows/schedules/disable-reasons.ts @@ -8,6 +8,7 @@ export type ScheduleDisableReason = | 'authorization_error' | 'workflow_not_found' | 'invalid_schedule' + | 'paid_plan_required' /** * User-facing sentence for each reason. Fixed copy rather than the underlying @@ -20,4 +21,6 @@ export const SCHEDULE_DISABLE_REASON_COPY: Record authorization_error: 'The run was not authorized.', workflow_not_found: 'The workflow could not be found.', invalid_schedule: 'The schedule is no longer valid.', + paid_plan_required: + "It uses Sim's hosted models or tools, which need a paid plan. Add your own API key under Settings > BYOK or upgrade, then turn the schedule back on.", } diff --git a/apps/sim/lib/workflows/streaming/nested-output-options.test.ts b/apps/sim/lib/workflows/streaming/nested-output-options.test.ts index 8010fc1547f..f8d571f4e5f 100644 --- a/apps/sim/lib/workflows/streaming/nested-output-options.test.ts +++ b/apps/sim/lib/workflows/streaming/nested-output-options.test.ts @@ -17,6 +17,7 @@ import { buildWorkflowOutputOptions, collectReferencedWorkflowIds, getWorkflowInvocationTarget, + selectBlockPathOptions, } from '@/lib/workflows/streaming/nested-output-options' function block(id: string, type: string, name: string, subBlocks = {}, data = {}) { @@ -105,4 +106,38 @@ describe('nested workflow output options', () => { }, ]) }) + + it('offers an Agent whose response format replaces its content output', () => { + const option = (blockId: string, blockType: string, path: string, workflowId?: string) => ({ + id: `${blockId}_${path}`, + label: `${blockId}.${path}`, + workflowId, + blockId, + blockName: blockId === 'a1' ? 'Analyst' : 'Formatter', + blockType, + groupKey: workflowId ? `invoke/${blockId}` : blockId, + groupLabel: blockId, + path, + menuPath: [], + }) + const options = [ + option('a1', 'agent', 'verdict', 'child-workflow'), + option('a1', 'agent', 'reasons', 'child-workflow'), + option('f1', 'function', 'result'), + ] + + expect( + selectBlockPathOptions(options, 'agent', 'content').map(({ id, label, path }) => ({ + id, + label, + path, + })) + ).toEqual([ + { + id: 'child-workflow.a1_content', + label: 'child-workflow.analyst.content', + path: 'content', + }, + ]) + }) }) diff --git a/apps/sim/lib/workflows/streaming/nested-output-options.ts b/apps/sim/lib/workflows/streaming/nested-output-options.ts index 1ec3ef71908..0ea7e086f71 100644 --- a/apps/sim/lib/workflows/streaming/nested-output-options.ts +++ b/apps/sim/lib/workflows/streaming/nested-output-options.ts @@ -184,3 +184,27 @@ export function buildWorkflowOutputMenu( return roots } + +/** + * One option per block of `blockType`, selecting `path` even when the block does not list it. + * An Agent with a response format lists its schema fields instead of `content`, yet still streams + * through `content`. + */ +export function selectBlockPathOptions( + options: readonly WorkflowOutputOption[], + blockType: string, + path: string +): WorkflowOutputOption[] { + const byBlock = new Map() + for (const option of options) { + if (option.blockType !== blockType || byBlock.has(option.groupKey)) continue + const blockName = normalizeName(option.blockName || `block-${option.blockId}`) + byBlock.set(option.groupKey, { + ...option, + id: formatInternalOutputSelector(option.blockId, path, option.workflowId), + label: formatPublicOutputSelector(blockName, path, option.workflowId), + path, + }) + } + return [...byBlock.values()] +} diff --git a/apps/sim/lib/workspace-source/api/route-policies.ts b/apps/sim/lib/workspace-source/api/route-policies.ts index 2efea163b55..10125471b52 100644 --- a/apps/sim/lib/workspace-source/api/route-policies.ts +++ b/apps/sim/lib/workspace-source/api/route-policies.ts @@ -1,5 +1,5 @@ import { utf8ByteLength } from '@sim/utils/paste' -import { boundAnswerFindings } from '@sim/workflow-code/diagnostics' +import { boundAnswerFindings, SOURCE_REFUSAL_CODES } from '@sim/workflow-code/diagnostics' import { type BlobEntry, budgetOfPath, WORKSPACE_ANSWER_BOUND } from '@sim/workspace-code' import { KIND_LAYOUTS } from '@sim/workspace-code/kinds/registry' import { workflowCodec, workflowFolder } from '@sim/workspace-code/kinds/workflow' @@ -29,15 +29,17 @@ export const v2WorkspaceSourceErrorPolicy = createV2ResourceConcealmentPolicy({ if (busy) return busy if (error instanceof WorkspaceSourceRejectedError) { return v2ErrorForOrchestration(error.code, error.message, { - code: error.stale ? 'SOURCE_STALE' : 'SOURCE_REJECTED', + code: error.stale ? SOURCE_REFUSAL_CODES.stale : SOURCE_REFUSAL_CODES.rejected, diagnostics: boundAnswerFindings(error.diagnostics, WORKSPACE_ANSWER_BOUND), }) } if (error instanceof WorkspaceSourceBusyError) { - return v2ErrorForOrchestration(error.code, error.message, { code: 'SOURCE_BUSY' }) + return v2ErrorForOrchestration(error.code, error.message, { code: SOURCE_REFUSAL_CODES.busy }) } if (error instanceof SourceStagingFullError) { - return v2ErrorForOrchestration(error.code, error.message, { code: 'SOURCE_STAGING_FULL' }) + return v2ErrorForOrchestration(error.code, error.message, { + code: SOURCE_REFUSAL_CODES.stagingFull, + }) } return v2CaughtOrchestrationError(error) }, diff --git a/apps/sim/lib/workspace-source/application/cross-kind.integration.ts b/apps/sim/lib/workspace-source/application/cross-kind.integration.ts index af5c89493ab..fe10721c8bb 100644 --- a/apps/sim/lib/workspace-source/application/cross-kind.integration.ts +++ b/apps/sim/lib/workspace-source/application/cross-kind.integration.ts @@ -33,6 +33,7 @@ import { } from '@sim/testing/mocks/uploads-setup.mock' import { generateId } from '@sim/utils/id' import { compareStrings } from '@sim/utils/string' +import { saveWorkflowToNormalizedTables } from '@sim/workflow-persistence/save' import { WORKSPACE_COOKBOOK } from '@sim/workflow-sdk/codegen' import type { WorkspaceBaseV1, WorkspaceKind } from '@sim/workspace-code' import { WORKSPACE_SOURCE_LIMITS } from '@sim/workspace-code/limits' @@ -74,8 +75,10 @@ import { setSecretUseCase } from '@/lib/secrets/application/use-cases' import { createSkillUseCase } from '@/lib/skills/application/use-cases' import { createTableUseCase, deleteTableUseCase } from '@/lib/table/application/tables' import { uploadWorkspaceFile } from '@/lib/uploads/contexts/workspace/file-manager' +import { applyWorkflowSource } from '@/lib/workflows/application/apply-workflow-source' import { deleteWorkflow } from '@/lib/workflows/application/delete-workflow' import { duplicateWorkflow } from '@/lib/workflows/application/duplicate-workflow' +import { readWorkflowSource } from '@/lib/workflows/application/read-workflow-source' import { loadWorkflowFromNormalizedTables } from '@/lib/workflows/persistence/utils' import { deleteWorkspaceFileOperation } from '@/lib/workspace-files/application/delete-workspace-file' import { withBoundWorkspaceFindings } from '@/lib/workspace-source/api/route-policies' @@ -1428,6 +1431,207 @@ export default workflow('Secret', {}, () => { expect(read.files['workflows/ping/workflow.ts']).toContain("childWorkflow('pong')") }) + check( + "types a call's result.data fields by the child's Response data, as submitted or as stored", + async () => { + const workspaceId = await newWorkspace() + const files = { + 'workflows/parent/workflow.ts': PHONE_PARENT, + 'workflows/normalize/workflow.ts': PHONE_CHILD, + } + + const dryRun = await apply(workspaceId, { files, blobs: {} }, { dryRun: true }) + expect(codes(dryRun.diagnostics, 'warning')).not.toContain('W_JSON_REF_UNTYPED') + const created = await apply(workspaceId, { files, blobs: {} }) + expect(created.failed).toBeUndefined() + const parentId = created.base.resources['workflow:parent']?.id + if (!parentId) throw new Error('The parent was not created') + expect(await responseData(parentId)).toEqual({ + mobile: '""', + digits: '', + }) + + const read = await get(workspaceId) + const printed = read.files['workflows/parent/workflow.ts'] + expect(printed).toContain( + 'body: { mobile: t`${run.result.data.mobile}`, digits: run.result.data.digits }' + ) + const single = await withPermissionGroupScope(() => + readWorkflowSource.execute({ principal: owner, input: { workflowId: parentId } }) + ) + expect(single.files['workflow.ts']).toBe(printed) + + // A single-workflow apply types the call by the child as stored. + const edited = await withPermissionGroupScope(() => + applyWorkflowSource.execute({ + principal: owner, + input: { + workflowId: parentId, + files: { + ...single.files, + 'workflow.ts': printed.replace( + 'digits: run.result.data.digits', + 'digits: run.result.data.digits, again: run.result.data.mobile' + ), + }, + lock: single.lock, + base: single.base, + }, + }) + ) + expect(codes(edited.diagnostics, 'warning')).not.toContain('W_JSON_REF_UNTYPED') + expect(await responseData(parentId)).toEqual({ + mobile: '""', + digits: '', + again: '""', + }) + expect(edited.files['workflow.ts']).toContain('again: t`${run.result.data.mobile}`,') + } + ) + + check( + 'types a call by a field its child forwards from a grandchild, on apply, get and reapply alike', + async () => { + const workspaceId = await newWorkspace() + const files = { + 'workflows/a/workflow.ts': forwarder('A', 'b'), + 'workflows/b/workflow.ts': forwarder('B', 'c'), + 'workflows/c/workflow.ts': TEXT_CHILD, + } + const typed = { text: '""', n: '' } + + const dryRun = await apply(workspaceId, { files, blobs: {} }, { dryRun: true }) + expect(codes(dryRun.diagnostics, 'warning')).not.toContain('W_JSON_REF_UNTYPED') + const created = await apply(workspaceId, { files, blobs: {} }) + expect(created.failed).toBeUndefined() + const id = (key: string) => { + const entry = created.base.resources[`workflow:${key}`] + if (!entry) throw new Error(`${key} was not created`) + return entry.id + } + expect(await responseData(id('a'))).toEqual(typed) + expect(await responseData(id('b'))).toEqual(typed) + + const read = await get(workspaceId) + const printed = read.files['workflows/a/workflow.ts'] + expect(printed).toContain( + 'body: { text: t`${call.result.data.text}`, n: call.result.data.n }' + ) + const single = await withPermissionGroupScope(() => + readWorkflowSource.execute({ principal: owner, input: { workflowId: id('a') } }) + ) + expect(single.files['workflow.ts']).toBe(printed) + + // Every folder sent with its files, so each child is typed as submitted, through the chain. + const reapplied = await apply( + workspaceId, + { files: read.files, blobs: {} }, + { base: read.base } + ) + expect(reapplied.failed).toBeUndefined() + expect(codes(reapplied.diagnostics, 'warning')).not.toContain('W_JSON_REF_UNTYPED') + expect(await responseData(id('a'))).toEqual(typed) + } + ) + + check( + 'types a call by a child sent with a stored() secret, as the directory check types it', + async () => { + const workspaceId = await newWorkspace() + const files = { + 'workflows/parent/workflow.ts': PHONE_PARENT, + 'workflows/normalize/workflow.ts': SECRET_PHONE_CHILD, + } + const created = await apply(workspaceId, { files, blobs: {} }) + expect(created.failed).toBeUndefined() + const parentId = created.base.resources['workflow:parent']?.id + if (!parentId) throw new Error('The parent was not created') + const typed = { mobile: '""', digits: '' } + expect(await responseData(parentId)).toEqual(typed) + + const read = await get(workspaceId) + expect(read.files['workflows/normalize/workflow.ts']).toContain('apiKey: stored()') + const reapplied = await apply( + workspaceId, + { files: read.files, blobs: {} }, + { base: read.base } + ) + expect(reapplied.failed).toBeUndefined() + expect(codes(reapplied.diagnostics, 'warning')).not.toContain('W_JSON_REF_UNTYPED') + expect(await responseData(parentId)).toEqual(typed) + } + ) + + check( + 'types a call by a child sent holding a block type the workspace catalog no longer offers', + async () => { + const workspaceId = await newWorkspace() + const files = { + 'workflows/a/workflow.ts': forwarder('A', 'c'), + 'workflows/c/workflow.ts': TEXT_CHILD, + } + const created = await apply(workspaceId, { files, blobs: {} }) + expect(created.failed).toBeUndefined() + const parentId = created.base.resources['workflow:a']?.id + const childId = created.base.resources['workflow:c']?.id + if (!parentId || !childId) throw new Error('The workflows were not created') + + // `thinking` is hidden from the toolbar, so only the child's own catalog declares it. + const child = await loadWorkflowFromNormalizedTables(childId) + const blockOf = (type: string) => + Object.values(child?.blocks ?? {}).find((block) => block.type === type)?.id + const startId = blockOf('start_trigger') + const replyId = blockOf('response') + if (!child || !startId || !replyId) throw new Error('The child was not stored') + const thinkingId = generateId() + const saved = await saveWorkflowToNormalizedTables(childId, { + ...child, + edges: [ + ...child.edges, + { id: generateId(), source: startId, target: thinkingId }, + { id: generateId(), source: thinkingId, target: replyId }, + ], + blocks: { + ...child.blocks, + [thinkingId]: { + id: thinkingId, + type: 'thinking', + name: 'Ponder', + position: { x: 0, y: 200 }, + subBlocks: { thought: { id: 'thought', type: 'long-input', value: 'Think first' } }, + outputs: {}, + enabled: true, + }, + }, + }) + if (!saved.success) throw new Error(`Seeding the child failed: ${saved.error}`) + + const read = await get(workspaceId) + expect(read.files['workflows/c/workflow.ts']).toContain('Ponder') + const reapplied = await apply( + workspaceId, + { + files: { + ...read.files, + 'workflows/a/workflow.ts': read.files['workflows/a/workflow.ts'].replace( + 'n: call.result.data.n', + 'n: call.result.data.n, again: call.result.data.text' + ), + }, + blobs: {}, + }, + { base: read.base } + ) + expect(reapplied.failed).toBeUndefined() + expect(codes(reapplied.diagnostics, 'warning')).not.toContain('W_JSON_REF_UNTYPED') + expect(await responseData(parentId)).toEqual({ + text: '""', + n: '', + again: '""', + }) + } + ) + check( 'renaming the key of a table or a tool is reported as a key rename, not a taken name', async () => { @@ -1485,6 +1689,93 @@ export default workflow('Child', {}, () => { 'workflows/keep/workflow.ts': TEXT['workflows/keep/workflow.ts'], } +/** A child that always responds with a text `mobile` and a number `digits`. */ +const PHONE_CHILD = `// @sim-sdk 1 +import { response, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('Normalize', {}, () => { + const start = trigger.start('Start', { inputFormat: { phone: 'string', n: 'number' } }) + const reply = response('Reply', { body: { mobile: start.phone, digits: start.n } }) + start.to(reply) +}) +` + +/** A parent that responds with the fields of what `normalize` responds with. */ +const PHONE_PARENT = `// @sim-sdk 1 +import { childWorkflow, response, runWorkflow, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('Parent', {}, () => { + const start = trigger.start('Start', { inputFormat: { phone: 'string' } }) + const run = runWorkflow('Run', { + workflowId: childWorkflow('normalize'), + inputMapping: { phone: start.phone }, + }) + const reply = response('Reply', { + body: { mobile: run.result.data.mobile, digits: run.result.data.digits }, + }) + start.to(run) + run.to(reply) +}) +` + +/** A child that always responds with a text `text` and a number `n`. */ +const TEXT_CHILD = `// @sim-sdk 1 +import { response, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('C', {}, () => { + const start = trigger.start('Start', { inputFormat: { phone: 'string', n: 'number' } }) + const reply = response('Reply', { body: { text: start.phone, n: start.n } }) + start.to(reply) +}) +` + +/** A workflow that responds with the `text` and `n` the workflow under `child` responds with. */ +function forwarder(name: string, child: string): string { + return `// @sim-sdk 1 +import { childWorkflow, response, runWorkflow, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('${name}', {}, () => { + const start = trigger.start('Start', { inputFormat: { phone: 'string' } }) + const call = runWorkflow('Call', { + workflowId: childWorkflow('${child}'), + inputMapping: { phone: start.phone }, + }) + const reply = response('Reply', { + body: { text: call.result.data.text, n: call.result.data.n }, + }) + start.to(call) + call.to(reply) +}) +` +} + +/** {@link PHONE_CHILD} with an Agent on the way to its Response, holding a literal secret. */ +const SECRET_PHONE_CHILD = `// @sim-sdk 1 +import { agent, response, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('Normalize', {}, () => { + const start = trigger.start('Start', { inputFormat: { phone: 'string', n: 'number' } }) + const answer = agent('Answer', { model: 'gpt-4o', messages: [], apiKey: 'placeholder-not-a-real-key' }) + const reply = response('Reply', { body: { mobile: start.phone, digits: start.n } }) + start.to(answer) + answer.to(reply) +}) +` + +/** + * The Response data workflow `workflowId` stores, each field's raw JSON text by key: a quoted + * reference keeps its quotes, a bare one is the reference alone. + */ +async function responseData(workflowId: string): Promise> { + const loaded = await loadWorkflowFromNormalizedTables(workflowId) + const reply = Object.values(loaded?.blocks ?? {}).find((block) => block.type === 'response') + const data = reply?.subBlocks.data?.value + if (typeof data !== 'string') throw new Error('The Response block stores no data') + return Object.fromEntries( + [...data.matchAll(/"(\w+)": ("?<[^>]+>"?)/g)].map(([, key, value]) => [key, value]) + ) +} + /** The workflow ids the Run Workflow blocks of workflow `workflowId` store. */ async function runsWorkflow(workflowId: string): Promise { const loaded = await loadWorkflowFromNormalizedTables(workflowId) diff --git a/apps/sim/lib/workspace-source/application/files.integration.ts b/apps/sim/lib/workspace-source/application/files.integration.ts index abc65f62d1f..7c6dc1da5f7 100644 --- a/apps/sim/lib/workspace-source/application/files.integration.ts +++ b/apps/sim/lib/workspace-source/application/files.integration.ts @@ -642,6 +642,8 @@ describe('workspace source files', () => { const refused = await refusal(apply(workspaceId, dropped, { base: read.base })) expect(codes(refused.diagnostics)).toEqual(['E_APPLY_DELETE_NOT_ALLOWED']) + expect(refused.diagnostics[0].message).toContain('missing from the directory is a delete') + expect(refused.diagnostics[0].message).toContain('--allow-delete') expect((await storedFiles(workspaceId)).map((file) => file.id)).toContain(id) const deleted = await apply(workspaceId, dropped, { base: read.base, allowDelete: true }) diff --git a/apps/sim/lib/workspace-source/application/findings.ts b/apps/sim/lib/workspace-source/application/findings.ts index 8b967624682..20fb7fd5b40 100644 --- a/apps/sim/lib/workspace-source/application/findings.ts +++ b/apps/sim/lib/workspace-source/application/findings.ts @@ -463,12 +463,12 @@ export function planUndeclared( kind, key, 'E_APPLY_DELETE_NOT_ALLOWED', - `${where(kind, key)} is no longer declared; deleting "${resource.name}" needs --allow-delete.`, + `${where(kind, key)} is no longer declared: a resource missing from the directory is a delete, and deleting "${resource.name}" needs --allow-delete.`, { hint: kind === 'deployment' ? 'Pass --allow-delete to delete it, or restore its file to keep it.' - : 'Pass --allow-delete to delete it, or restore its file to keep it. Run with --allow-delete --dry-run to see which workflows use it.', + : 'Pass --allow-delete to delete it, or restore its file or folder to keep it. Run with --allow-delete --dry-run to see which workflows use it.', } ) : kindFinding( diff --git a/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts index cdb4422df52..d4511b3e614 100644 --- a/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts @@ -726,6 +726,13 @@ export const workflowAdapter: KindAdapter<'workflow', StoredWorkflowState> = { : [] ) const pending = [...ctx.pending, ...creates.map(({ created }) => created)] + ctx.loads.childSources = new Map( + [...desired].flatMap(([key, decl]) => + Object.keys(decl.files).length > 0 + ? [[key, { files: decl.files, lock: decl.lock }] as const] + : [] + ) + ) const names = new Map() const evaluatedCreates = new Map() await mapWithConcurrency(creates, PLAN_CONCURRENCY, async ({ step, created }) => { diff --git a/apps/sim/lib/workspaces/__integration__/members.integration.ts b/apps/sim/lib/workspaces/__integration__/members.integration.ts index 7b213711503..f9b0aa13ac5 100644 --- a/apps/sim/lib/workspaces/__integration__/members.integration.ts +++ b/apps/sim/lib/workspaces/__integration__/members.integration.ts @@ -9,6 +9,8 @@ import { organization, permissions, scimConnection, + scimGroupMapping, + scimProjectionGrant, scimUser, session, user, @@ -28,8 +30,10 @@ import { PATCH as updateMember, } from '@/app/api/v2/workspaces/[workspaceId]/members/[userId]/route' import { GET as listMembers } from '@/app/api/v2/workspaces/[workspaceId]/members/route' +import { addGroupMember, insertScimGroup } from '@/ee/scim/lib/repository/groups' /** Directory provisioning on a self-hosted deployment, so a locked SCIM member is refused. */ + vi.mock('@/lib/core/config/env-flags', () => ({ ...envFlagsMock, isScimEnabled: true })) const USER_NAMES = [ @@ -430,7 +434,29 @@ describe('v2 workspace member management against PostgreSQL', () => { expect(await roleOf(f.users.reader)).toBe('read') }) - it('keeps the SCIM_MANAGED_MEMBERSHIP code for a directory-managed member', async () => { + it('changes a provisioned member’s role on a workspace no directory group is mapped to', async () => { + const response = await call(key('admin'), 'PATCH', f.users.managed, { body: { role: 'read' } }) + expect(response.status).toBe(200) + expect(await roleOf(f.users.managed)).toBe('read') + }) + + it('keeps the SCIM_MANAGED_MEMBERSHIP code on a workspace the member’s directory group is mapped to', async () => { + const group = await insertScimGroup(db, { + connectionId: f.scimConnectionId, + displayName: 'Mapped group', + }) + await db.insert(scimGroupMapping).values({ + id: generateId(), + groupId: group.id, + targetKind: 'workspace', + workspaceId: f.workspaceId, + permissionType: 'write', + }) + const [managed] = await db + .select({ id: scimUser.id }) + .from(scimUser) + .where(eq(scimUser.userId, f.users.managed)) + await addGroupMember(db, { groupId: group.id, scimUserId: managed.id }) const response = await call(key('admin'), 'PATCH', f.users.managed, { body: { role: 'read' } }) expect(response).toMatchObject({ status: 403, @@ -439,6 +465,27 @@ describe('v2 workspace member management against PostgreSQL', () => { expect(await roleOf(f.users.managed)).toBe('write') }) + it('refuses a role change while a removed mapping’s grant awaits withdrawal', async () => { + const [managed] = await db + .select({ id: scimUser.id }) + .from(scimUser) + .where(eq(scimUser.userId, f.users.managed)) + await db.insert(scimProjectionGrant).values({ + id: generateId(), + connectionId: f.scimConnectionId, + scimUserId: managed.id, + targetKind: 'workspace', + targetId: f.workspaceId, + permissionType: 'write', + }) + const response = await call(key('admin'), 'PATCH', f.users.managed, { body: { role: 'admin' } }) + expect(response).toMatchObject({ + status: 403, + body: { error: { code: 'FORBIDDEN', details: { code: 'SCIM_MANAGED_MEMBERSHIP' } } }, + }) + expect(await roleOf(f.users.managed)).toBe('write') + }) + it('answers a role change held up by a competing writer with a retryable 503', async () => { let lockTaken!: () => void let release!: () => void diff --git a/apps/sim/lib/workspaces/admin-move.test.ts b/apps/sim/lib/workspaces/admin-move.test.ts index 2303e79592c..fd27c185d61 100644 --- a/apps/sim/lib/workspaces/admin-move.test.ts +++ b/apps/sim/lib/workspaces/admin-move.test.ts @@ -50,7 +50,7 @@ const { cleanupSourceOrganizationArtifactsTx, acquireInvitationMutationLocks, countPendingSeatInvitations, - resolveSeatCapacity, + resolveSeatCap, collectWorkspaceCredentialSummary, getSourceOrganization, } = vi.hoisted(() => ({ @@ -69,7 +69,9 @@ const { ), acquireInvitationMutationLocks: vi.fn(), countPendingSeatInvitations: vi.fn(() => Promise.resolve(0)), - resolveSeatCapacity: vi.fn(() => Promise.resolve(10)), + resolveSeatCap: vi.fn((subscription: { plan: string }) => + Promise.resolve({ seats: 10, kind: subscription.plan === 'enterprise' ? 'fixed' : 'on-demand' }) + ), collectWorkspaceCredentialSummary: vi.fn(), getSourceOrganization: vi.fn(), })) @@ -119,8 +121,7 @@ vi.mock('@/lib/billing/organizations/membership', () => organizationMembershipMo vi.mock('@/lib/billing/storage/payer-transfer', () => billingPayerTransferMock) vi.mock('@/lib/billing/validation/seat-management', () => ({ countPendingSeatInvitations, - planHasFixedSeatCap: vi.fn((plan: string) => plan === 'enterprise'), - resolveSeatCapacity, + resolveSeatCap, })) vi.mock('@/lib/core/outbox/service', () => outboxServiceMock) vi.mock('@/lib/invitations/core', () => invitationsCoreMock) @@ -483,7 +484,7 @@ describe('moveWorkspaceToOrganization retries', () => { }, ]) queueTableRows(invitationWorkspaceGrant, [{ invitationId: 'invitation-1', value: 1 }]) - resolveSeatCapacity.mockResolvedValueOnce(1) + resolveSeatCap.mockResolvedValueOnce({ seats: 1, kind: 'fixed' }) await expect( moveWorkspaceToOrganization({ diff --git a/apps/sim/lib/workspaces/admin-move.ts b/apps/sim/lib/workspaces/admin-move.ts index 29d603f9770..494833ed9df 100644 --- a/apps/sim/lib/workspaces/admin-move.ts +++ b/apps/sim/lib/workspaces/admin-move.ts @@ -27,8 +27,7 @@ import { } from '@/lib/billing/subscriptions/utils' import { countPendingSeatInvitations, - planHasFixedSeatCap, - resolveSeatCapacity, + resolveSeatCap, } from '@/lib/billing/validation/seat-management' import { addOutboxEventSourceOperationId, @@ -690,12 +689,11 @@ export async function getWorkspaceMovePreflight( ]) const organizationSubscription = subscriptionRows[0] - const seatCapacity = - organizationSubscription && - hasPaidSubscriptionStatus(organizationSubscription.status) && - planHasFixedSeatCap(organizationSubscription.plan) - ? await resolveSeatCapacity(organizationSubscription) + const seatCap = + organizationSubscription && hasPaidSubscriptionStatus(organizationSubscription.status) + ? await resolveSeatCap(organizationSubscription) : null + const seatCapacity = seatCap?.kind === 'fixed' ? seatCap.seats : null const currentMembers = memberCountRows[0]?.value ?? 0 const projectedPendingInternalSeats = seatCapacity === null @@ -1189,8 +1187,8 @@ export async function moveWorkspaceToOrganization(params: { ) .limit(1) if (enterpriseSubscription && hasPaidSubscriptionStatus(enterpriseSubscription.status)) { - const [capacity, memberRows, movedWorkspaceInvitations] = await Promise.all([ - resolveSeatCapacity(enterpriseSubscription, tx), + const [seatCap, memberRows, movedWorkspaceInvitations] = await Promise.all([ + resolveSeatCap(enterpriseSubscription, tx), tx .select({ value: count() }) .from(member) @@ -1203,9 +1201,9 @@ export async function moveWorkspaceToOrganization(params: { executor: tx, }) const currentMembers = memberRows[0]?.value ?? 0 - if (currentMembers + projectedPendingSeats > capacity) { + if (seatCap.kind === 'fixed' && currentMembers + projectedPendingSeats > seatCap.seats) { throw new WorkspaceMoveError( - `Moving this workspace would require ${currentMembers + projectedPendingSeats} occupied or reserved seats, above the ${capacity}-seat Enterprise capacity`, + `Moving this workspace would require ${currentMembers + projectedPendingSeats} occupied or reserved seats, above the ${seatCap.seats}-seat Enterprise capacity`, 'seat-capacity-exceeded' ) } diff --git a/apps/sim/lib/workspaces/host-context.ts b/apps/sim/lib/workspaces/host-context.ts index a91ba7c8edf..b22d70255c3 100644 --- a/apps/sim/lib/workspaces/host-context.ts +++ b/apps/sim/lib/workspaces/host-context.ts @@ -49,7 +49,7 @@ async function resolveWorkspaceHostContextForViewer( billingEntity: ownerBilling.organizationId ? { type: 'organization', id: ownerBilling.organizationId } : { type: 'user', id: access.workspace.billedAccountUserId }, - payerSubscription: { plan: ownerBilling.plan }, + payerSubscription: { plan: ownerBilling.plan, status: ownerBilling.status }, }), ]) diff --git a/apps/sim/lib/workspaces/permissions/management-store.ts b/apps/sim/lib/workspaces/permissions/management-store.ts index ee2b035d86b..3db25913153 100644 --- a/apps/sim/lib/workspaces/permissions/management-store.ts +++ b/apps/sim/lib/workspaces/permissions/management-store.ts @@ -18,7 +18,7 @@ import { getEffectiveWorkspacePermission, getWorkspaceWithOwner, } from '@/lib/workspaces/permissions/utils' -import { assertMembershipNotScimManaged } from '@/ee/scim/lib/managed-membership' +import { assertWorkspaceAccessNotScimManaged } from '@/ee/scim/lib/managed-membership' const logger = createLogger('WorkspacesPermissionsAPI') @@ -309,13 +309,17 @@ export async function updateWorkspacePermissionRecords( lockedMembers.filter((row) => isOrgAdminRole(row.role)).map((row) => row.userId) ) /** - * A directory that owns membership also owns the workspace role it set, - * so the change is refused here for the same reason an invitation is: - * the next sync would revert it. Checked under the member lock so a - * connection enabled mid-request cannot slip a change past it. + * A role the directory sets through one of the member's mapped groups is + * refused here for the same reason an invitation is: the next sync would + * revert it. */ for (const userId of targetUserIds) { - await assertMembershipNotScimManaged({ organizationId, userId, executor: tx }) + await assertWorkspaceAccessNotScimManaged({ + organizationId, + userId, + workspaceIds: [workspaceId], + executor: tx, + }) } } diff --git a/apps/sim/lib/workspaces/policy.ts b/apps/sim/lib/workspaces/policy.ts index 74c3fe02727..a2b64bbd791 100644 --- a/apps/sim/lib/workspaces/policy.ts +++ b/apps/sim/lib/workspaces/policy.ts @@ -12,7 +12,10 @@ import { } from '@/lib/billing/organizations/membership' import type { PlanCategory } from '@/lib/billing/plan-helpers' import { getPlanType, isEnterprise, isMaxTier, isPro, isTeam } from '@/lib/billing/plan-helpers' -import { hasUsableSubscriptionStatus } from '@/lib/billing/subscriptions/utils' +import { + hasUsableSubscriptionStatus, + isTrialingSubscription, +} from '@/lib/billing/subscriptions/utils' import { isBillingEnabled } from '@/lib/core/config/env-flags' import type { DbOrTx, DbTransaction } from '@/lib/db/types' import { @@ -459,7 +462,10 @@ export async function getInvitePlanCategoryForUser( ): Promise { try { const sub = await getHighestPrioritySubscription(userId, { executor }) - if (!sub || !hasUsableSubscriptionStatus(sub.status)) return 'free' + // A trial cannot take on seats until it converts, so it invites like a free account. + if (!sub || !hasUsableSubscriptionStatus(sub.status) || isTrialingSubscription(sub)) { + return 'free' + } return getPlanType(sub.plan) } catch (error) { logger.error('Failed to resolve subscription for invite policy', { userId, error }) diff --git a/apps/sim/lib/workspaces/resource-keys.integration.ts b/apps/sim/lib/workspaces/resource-keys.integration.ts index 9a95fc5604a..eafedf63025 100644 --- a/apps/sim/lib/workspaces/resource-keys.integration.ts +++ b/apps/sim/lib/workspaces/resource-keys.integration.ts @@ -67,9 +67,12 @@ async function keyRows(wsId: string, kind: ResourceKind, resourceId: string) { /** * Holds a transaction open with one uncommitted key row, so a concurrent writer that collides on - * a unique index blocks on it. Resolves `committed` once the row is committed. + * a unique index blocks on it. Resolves `inserted` once the row is written (start the competing + * write only then, or it can commit first; it rejects as `committed` does when the write fails) + * and `committed` once the row is committed. */ function holdUncommittedKey(row: { key: string; resourceId: string }): { + inserted: Promise committed: Promise commit: () => void } { @@ -77,6 +80,10 @@ function holdUncommittedKey(row: { key: string; resourceId: string }): { const released = new Promise((resolve) => { commit = resolve }) + let markInserted = () => {} + const inserted = new Promise((resolve) => { + markInserted = resolve + }) const committed = db.transaction(async (tx) => { const now = new Date() await tx.insert(workspaceResourceKey).values({ @@ -90,9 +97,10 @@ function holdUncommittedKey(row: { key: string; resourceId: string }): { createdAt: now, updatedAt: now, }) + markInserted() await released }) - return { committed, commit } + return { inserted: Promise.race([inserted, committed]), committed, commit } } /** Waits until some backend is blocked on a lock while writing `workspace_resource_key`. */ @@ -181,6 +189,35 @@ describe('workspace resource keys against PostgreSQL', () => { expect(new Set(keys)).toEqual(new Set(['invoices', 'invoices-2', 'invoices-3'])) }) + it('keys a name with underscores by its own spelling, apart from the hyphenated one', async () => { + const underscored = generateId() + const hyphenated = generateId() + await insertTable(underscored, workspaceId, 'daily_totals', at(40)) + await insertTable(hyphenated, workspaceId, 'daily-totals', at(41)) + + expect(await keyOf('table', hyphenated)).toBe('daily-totals') + expect(await keyOf('table', underscored)).toBe('daily_totals') + expect(await idOf('table', 'daily_totals')).toBe(underscored) + }) + + it('suffixes an underscored name whose key is taken, and leaves a persisted hyphen key alone', async () => { + const legacy = generateId() + const first = generateId() + const second = generateId() + await insertTable(legacy, workspaceId, 'weekly-totals', at(42)) + expect(await keyOf('table', legacy)).toBe('weekly-totals') + await db + .update(userTableDefinitions) + .set({ name: 'weekly_totals' }) + .where(eq(userTableDefinitions.id, legacy)) + await insertTable(first, workspaceId, 'monthly_totals', at(43)) + await insertTable(second, workspaceId, 'Monthly_Totals!', at(44)) + + expect(await keyOf('table', legacy)).toBe('weekly-totals') + expect(await keyOf('table', first)).toBe('monthly_totals') + expect(await keyOf('table', second)).toBe('monthly_totals-2') + }) + it('keeps every kind’s key through a rename', async () => { const ids = { table: generateId(), @@ -394,6 +431,7 @@ describe('workspace resource keys against PostgreSQL', () => { await insertTable(holder, workspaceId, 'Race Holder', at(50)) await insertTable(claimant, workspaceId, 'Race Claimant', at(51)) const held = holdUncommittedKey({ key: 'race-leads', resourceId: holder }) + await held.inserted const claim = claimResourceKey({ workspaceId, @@ -422,6 +460,7 @@ describe('workspace resource keys against PostgreSQL', () => { const id = generateId() await insertTable(id, workspaceId, 'Race Allocated', at(52)) const held = holdUncommittedKey({ key: 'race-allocated', resourceId: id }) + await held.inserted const claim = claimResourceKey({ workspaceId, diff --git a/apps/sim/lib/workspaces/resource-keys.test.ts b/apps/sim/lib/workspaces/resource-keys.test.ts index 0624a987a1b..b14bcc64e29 100644 --- a/apps/sim/lib/workspaces/resource-keys.test.ts +++ b/apps/sim/lib/workspaces/resource-keys.test.ts @@ -8,6 +8,12 @@ describe('resourceKeyBase', () => { expect(resourceKeyBase('table', 'Leads (EU)!')).toBe('leads-eu') }) + it('keeps the underscores of a name, the spelling its author types', () => { + expect(resourceKeyBase('table', 'daily_totals')).toBe('daily_totals') + expect(resourceKeyBase('table', 'Daily_Totals (v2)')).toBe('daily_totals-v2') + expect(resourceKeyBase('table', '_scratch_')).toBe('scratch') + }) + it('keys a name with no slug characters by its kind', () => { expect(resourceKeyBase('knowledge-base', '***')).toBe('knowledge-base') expect(resourceKeyBase('credential', '')).toBe('credential') diff --git a/apps/sim/lib/workspaces/resource-keys.ts b/apps/sim/lib/workspaces/resource-keys.ts index c2a4ce40495..160c1c0a5c6 100644 --- a/apps/sim/lib/workspaces/resource-keys.ts +++ b/apps/sim/lib/workspaces/resource-keys.ts @@ -13,7 +13,7 @@ import { } from '@sim/db/schema' import { createLogger } from '@sim/logger' import { generateId } from '@sim/utils/id' -import { compareStrings, slugify } from '@sim/utils/string' +import { compareStrings, escapeLikePattern } from '@sim/utils/string' import type { ResourceKind } from '@sim/workflow-code' import { and, asc, eq, inArray, isNull, like, or } from 'drizzle-orm' import { OrchestrationError } from '@/lib/core/orchestration/types' @@ -203,12 +203,24 @@ function trimKey(value: string, maxLength: number): string { } /** - * The key a resource is first offered: its name's slug, or the kind when the name has no slug - * characters; prefixed with the kind when the slug starts with a digit, and cut to the key - * length. Always matches the stored key format `^[a-z][a-z0-9_-]{0,63}$`. + * A name's key characters: lowercased, with every run of other characters one hyphen and no + * leading or trailing separator. Underscores stay, so a table named `daily_totals` is keyed + * `daily_totals`, the spelling its author will type. + */ +function keySlug(name: string): string { + return name + .toLowerCase() + .replace(/[^a-z0-9_]+/g, '-') + .replace(/^[-_]+|[-_]+$/g, '') +} + +/** + * The key a resource is first offered: its name's slug (underscores kept), or the kind when the + * name has no slug characters; prefixed with the kind when the slug starts with a digit, and cut + * to the key length. Always matches the stored key format `^[a-z][a-z0-9_-]{0,63}$`. */ export function resourceKeyBase(kind: ResourceKind, name: string): string { - const slug = slugify(name) + const slug = keySlug(name) const base = slug === '' ? kind : /^[a-z]/.test(slug) ? slug : `${kind}-${slug}` return trimKey(base, MAX_KEY_LENGTH) } @@ -309,7 +321,11 @@ async function readTakenKeys( and( eq(workspaceResourceKey.workspaceId, workspaceId), eq(workspaceResourceKey.kind, kind), - or(...prefixes.map((prefix) => like(workspaceResourceKey.key, `${prefix}%`))) + or( + ...prefixes.map((prefix) => + like(workspaceResourceKey.key, `${escapeLikePattern(prefix)}%`) + ) + ) ) ) return new Set(rows.map((row) => row.key)) diff --git a/apps/sim/next.config.ts b/apps/sim/next.config.ts index c36729f6a63..9d4af5df479 100644 --- a/apps/sim/next.config.ts +++ b/apps/sim/next.config.ts @@ -684,12 +684,6 @@ const nextConfig: NextConfig = { source: '/favicon.ico', destination: '/icon.svg', }, - /** - * Serves Stop from browser tabs still on v0.9.64 or earlier, which call the old abort - * path. Remove in any release after the first one that ships the move (the release - * after v0.9.64). - */ - { source: '/api/copilot/chat/abort', destination: '/api/mothership/chat/abort' }, ], /** * Fallback rewrites run only after every page and dynamic route has failed to match, so diff --git a/apps/sim/providers/default-model.ts b/apps/sim/providers/default-model.ts new file mode 100644 index 00000000000..56643bab2bd --- /dev/null +++ b/apps/sim/providers/default-model.ts @@ -0,0 +1,6 @@ +/** + * The model the agent, router and evaluator blocks run when none is set, and the one sim-auto + * resolves to when the model router cannot pick a pool model. Kept dependency-free so the + * executor's constants can read it without loading the provider registry. + */ +export const DEFAULT_BLOCK_MODEL = 'claude-sonnet-5-5' diff --git a/apps/sim/providers/models.test.ts b/apps/sim/providers/models.test.ts index 07bfa2118aa..2752fb7593a 100644 --- a/apps/sim/providers/models.test.ts +++ b/apps/sim/providers/models.test.ts @@ -3,7 +3,9 @@ import { findProviderFromModel, getBaseModelProviders, getHostedModels, + getModelCapabilities, getModelPricing, + getProviderFromModel, getProviderModels, getStaticProviderModels, isCustomModelId, @@ -98,6 +100,28 @@ describe('custom cloud model routing', () => { }) }) +describe('tagged Ollama model names that share a cloud prefix', () => { + it.each(['gpt-oss:20b', 'mistral:latest', 'GPT-OSS:120B', 'claude-local:7b'])( + 'leaves %s unclaimed, so it runs on Ollama with no cloud capabilities', + (model) => { + expect(findProviderFromModel(model)).toBeNull() + expect(getProviderFromModel(model)).toBe('ollama') + expect(getModelCapabilities(model)).toBeNull() + } + ) + + it('still resolves untagged cloud ids, namespaced tags, and catalog ids by their provider', () => { + expect(findProviderFromModel('gpt-oss-custom')).toBe('openai') + expect(findProviderFromModel('mistral-large-latest')).toBe('mistral') + expect(findProviderFromModel('ollama/gpt-oss:20b')).toBe('ollama') + expect(findProviderFromModel('openrouter/org/model:free')).toBe('openrouter') + expect(findProviderFromModel('bedrock/amazon.nova-lite-v1:0')).toBe('bedrock') + expect(getModelCapabilities('ollama/gpt-oss:20b')).toEqual( + PROVIDER_DEFINITIONS.ollama.capabilities + ) + }) +}) + describe('catalog featured model metadata', () => { it('defines at most one active featured model per provider', () => { for (const provider of Object.values(PROVIDER_DEFINITIONS)) { diff --git a/apps/sim/providers/models.ts b/apps/sim/providers/models.ts index 68848787242..ebeae0e515c 100644 --- a/apps/sim/providers/models.ts +++ b/apps/sim/providers/models.ts @@ -6915,6 +6915,9 @@ export function getBaseModelProviders(): Record { ) } +/** An Ollama model name, `[host/][namespace/]name[:tag]`: `llama3.1:8b`, `hf.co/org/model:Q4_K_M`. */ +export const OLLAMA_MODEL_NAME = /^[\w.-]+(\/[\w.-]+)*(:[\w.-]+)?$/ + /** * The provider that declares `model`, or `null` when none does. Resolves catalog entries and * provider patterns without guessing a fallback provider. @@ -6945,6 +6948,14 @@ export function findProviderFromModel(model: string): ProviderId | null { } } + /** + * Provider patterns are cloud model-name prefixes, and no cloud model id carries an Ollama + * `:tag`. Ollama lists every installed model with its tag (`gpt-oss:20b`, `mistral:latest`), + * so a tagged name a pattern would claim is a local model that only shares a prefix with a + * cloud family. The server never holds the installed list, so the name itself has to say so. + */ + if (normalizedModel.includes(':') && OLLAMA_MODEL_NAME.test(normalizedModel)) return null + for (const [providerId, provider] of Object.entries(PROVIDER_DEFINITIONS)) { if (provider.modelPatterns?.some((pattern) => pattern.test(normalizedModel))) { return providerId as ProviderId @@ -6995,17 +7006,8 @@ export function getModelCapabilities(modelId: string): ModelCapabilities | null } } - for (const provider of Object.values(PROVIDER_DEFINITIONS)) { - if (provider.modelPatterns) { - for (const pattern of provider.modelPatterns) { - if (pattern.test(modelId.toLowerCase())) { - return provider.capabilities || null - } - } - } - } - - return null + const providerId = findProviderFromModel(modelId) + return providerId ? PROVIDER_DEFINITIONS[providerId]?.capabilities || null : null } export function getProvidersWithToolUsageControl(): string[] { @@ -7067,40 +7069,22 @@ export function supportsForcedToolUse(modelId: string): boolean { return capabilities?.forcedToolUse ?? capabilities?.toolUsageControl ?? false } +/** Discovered model ids as unpriced, capability-less catalog entries. */ +function toUnpricedModels(models: string[]): ModelDefinition[] { + const updatedAt = new Date().toISOString().split('T')[0] + return models.map((id) => ({ id, pricing: { input: 0, output: 0, updatedAt }, capabilities: {} })) +} + export function updateOllamaModels(models: string[]): void { - PROVIDER_DEFINITIONS.ollama.models = models.map((modelId) => ({ - id: modelId, - pricing: { - input: 0, - output: 0, - updatedAt: new Date().toISOString().split('T')[0], - }, - capabilities: {}, - })) + PROVIDER_DEFINITIONS.ollama.models = toUnpricedModels(models) } export function updateVLLMModels(models: string[]): void { - PROVIDER_DEFINITIONS.vllm.models = models.map((modelId) => ({ - id: modelId, - pricing: { - input: 0, - output: 0, - updatedAt: new Date().toISOString().split('T')[0], - }, - capabilities: {}, - })) + PROVIDER_DEFINITIONS.vllm.models = toUnpricedModels(models) } export function updateLiteLLMModels(models: string[]): void { - PROVIDER_DEFINITIONS.litellm.models = models.map((modelId) => ({ - id: modelId, - pricing: { - input: 0, - output: 0, - updatedAt: new Date().toISOString().split('T')[0], - }, - capabilities: {}, - })) + PROVIDER_DEFINITIONS.litellm.models = toUnpricedModels(models) } /** @@ -7116,66 +7100,24 @@ export function updateFireworksModels(models: string[]): void { const staticIds = new Set(STATIC_FIREWORKS_MODELS.map((model) => model.id.toLowerCase())) PROVIDER_DEFINITIONS.fireworks.models = [ ...STATIC_FIREWORKS_MODELS, - ...models - .filter((modelId) => !staticIds.has(modelId.toLowerCase())) - .map((modelId) => ({ - id: modelId, - pricing: { - input: 0, - output: 0, - updatedAt: new Date().toISOString().split('T')[0], - }, - capabilities: {}, - })), + ...toUnpricedModels(models.filter((modelId) => !staticIds.has(modelId.toLowerCase()))), ] } export function updateTogetherModels(models: string[]): void { - PROVIDER_DEFINITIONS.together.models = models.map((modelId) => ({ - id: modelId, - pricing: { - input: 0, - output: 0, - updatedAt: new Date().toISOString().split('T')[0], - }, - capabilities: {}, - })) + PROVIDER_DEFINITIONS.together.models = toUnpricedModels(models) } export function updateBasetenModels(models: string[]): void { - PROVIDER_DEFINITIONS.baseten.models = models.map((modelId) => ({ - id: modelId, - pricing: { - input: 0, - output: 0, - updatedAt: new Date().toISOString().split('T')[0], - }, - capabilities: {}, - })) + PROVIDER_DEFINITIONS.baseten.models = toUnpricedModels(models) } export function updateOllamaCloudModels(models: string[]): void { - PROVIDER_DEFINITIONS['ollama-cloud'].models = models.map((modelId) => ({ - id: modelId, - pricing: { - input: 0, - output: 0, - updatedAt: new Date().toISOString().split('T')[0], - }, - capabilities: {}, - })) + PROVIDER_DEFINITIONS['ollama-cloud'].models = toUnpricedModels(models) } export function updateOpenRouterModels(models: string[]): void { - PROVIDER_DEFINITIONS.openrouter.models = models.map((modelId) => ({ - id: modelId, - pricing: { - input: 0, - output: 0, - updatedAt: new Date().toISOString().split('T')[0], - }, - capabilities: {}, - })) + PROVIDER_DEFINITIONS.openrouter.models = toUnpricedModels(models) } export const EMBEDDING_MODEL_PRICING: Record = { diff --git a/apps/sim/providers/run-usage-limit.ts b/apps/sim/providers/run-usage-limit.ts index cb8434e886d..e1fe3cb66d2 100644 --- a/apps/sim/providers/run-usage-limit.ts +++ b/apps/sim/providers/run-usage-limit.ts @@ -1,6 +1,6 @@ import { readMidRunUsageVerdict } from '@/lib/billing/core/mid-run-usage' import { NEAR_LIMIT_USAGE_GATE_TTL_MS } from '@/lib/billing/core/usage-gate-cache' -import { isPaid } from '@/lib/billing/plan-helpers' +import { billsOverage } from '@/lib/billing/subscriptions/utils' import { resolveUsageUpgradePayload } from '@/lib/billing/usage-upgrade' import { markFailureKind } from '@/lib/core/errors/failure-log' import { NonRetryableExecutionError } from '@/lib/execution/non-retryable-error' @@ -61,11 +61,12 @@ export function recordModelStepCost( } /** - * Stops a free-plan workflow run before its next model call once the payer's recorded usage plus - * the run's own unrecorded model spend reaches its limit. A run's cost reaches the ledger only - * with its log, so admission alone would let one run keep calling models long past the limit, - * and a free plan's spend past its limit is never billed. A paid payer's overshoot is billed as - * overage, so its runs are left to admission and never read here. + * Stops a capped workflow run (free plan or trial) before its next model call once the payer's + * recorded usage plus the run's own unrecorded model spend reaches its limit. A run's cost reaches + * the ledger only with its log, so admission alone would let one run keep calling models long past + * the limit, and a capped payer's spend past its limit is never billed. A paid payer's overshoot + * is billed as overage ({@link billsOverage}), so its runs are left to admission and never read + * here. * * Reads nothing until the run has spent, then the payer's ledger. A gate that cannot * answer stops the run as if the limit were spent. A blocked account lets the run continue and @@ -85,7 +86,7 @@ export async function assertRunWithinUsageLimit( !attribution || !unrecorded || unrecorded.total <= 0 || - isPaid(attribution.payerSubscription?.plan) || + billsOverage(attribution.payerSubscription) || executionContext.abortSignal?.aborted || Date.now() < (unrecorded.readDeferredUntil ?? 0) ) { @@ -93,7 +94,7 @@ export async function assertRunWithinUsageLimit( } const verdict = await readMidRunUsageVerdict(attribution, unrecorded.total, { - uncachedForFreePayer: true, + uncachedForCappedPayer: true, }) // A run cancelled during the read keeps its cancellation; the provider call then aborts. if (verdict.status === 'within' || executionContext.abortSignal?.aborted) return diff --git a/apps/sim/providers/utils.test.ts b/apps/sim/providers/utils.test.ts index 9bea9fc9dcc..9c66386a402 100644 --- a/apps/sim/providers/utils.test.ts +++ b/apps/sim/providers/utils.test.ts @@ -1527,6 +1527,13 @@ describe('Provider Management', () => { expect(getProviderFromModel('unknown-model')).toBe('ollama') }) + it('refuses sim-auto rather than defaulting it to ollama, since only the router resolves it', () => { + expect(() => getProviderFromModel('sim-auto')).toThrow( + 'sim-auto has no provider until the model router resolves it' + ) + expect(() => getProviderFromModel(' Sim-Auto ')).toThrow('has no provider') + }) + it('should resolve gateway models that getBaseModelProviders deliberately omits', () => { // getBaseModelProviders() filters these providers out entirely, so a model // block that looked models up there rejected valid ids like these. diff --git a/apps/sim/providers/utils.ts b/apps/sim/providers/utils.ts index 0d210d5b064..3faeeb5ff7b 100644 --- a/apps/sim/providers/utils.ts +++ b/apps/sim/providers/utils.ts @@ -39,9 +39,13 @@ import { getModelsWithVerbosity, getProviderDefaultModel as getProviderDefaultModelFromDefinitions, getProviderModels, + isAutoModel, isKnownModelLevelValue, PROVIDER_DEFINITIONS, - updateOllamaModels as updateOllamaModelsInDefinitions, + SIM_AUTO_MODEL_ID, + updateLiteLLMModels, + updateOllamaModels, + updateVLLMModels, } from '@/providers/models' import { getModelPricing as getRegisteredModelPricing, @@ -171,18 +175,16 @@ export const providers: Record = { } export function updateOllamaProviderModels(models: string[]): void { - updateOllamaModelsInDefinitions(models) + updateOllamaModels(models) providers.ollama.models = getProviderModels('ollama') } export function updateVLLMProviderModels(models: string[]): void { - const { updateVLLMModels } = require('@/providers/models') updateVLLMModels(models) providers.vllm.models = getProviderModels('vllm') } export function updateLiteLLMProviderModels(models: string[]): void { - const { updateLiteLLMModels } = require('@/providers/models') updateLiteLLMModels(models) providers.litellm.models = getProviderModels('litellm') } @@ -258,7 +260,19 @@ function filterBlacklistedModelsFromProviderMap( return filtered } +/** + * The provider that serves `model`, defaulting an unrecognised id to Ollama. + * + * Throws for a blacklisted provider or model, and for sim-auto: the pseudo-model has no + * provider of its own until the model router (`lib/model-router`) swaps in a concrete one at + * execution time, so answering Ollama for it would send `sim-auto` to a server that has + * never heard of it. + */ export function getProviderFromModel(model: string): ProviderId { + if (isAutoModel(model)) { + throw new Error(`${SIM_AUTO_MODEL_ID} has no provider until the model router resolves it`) + } + const normalizedModel = model.toLowerCase() let providerId = findProviderFromModel(model) diff --git a/apps/sim/public/library/agentforce-pricing/cover.jpg b/apps/sim/public/library/agentforce-pricing/cover.jpg new file mode 100644 index 00000000000..925c250b4cf Binary files /dev/null and b/apps/sim/public/library/agentforce-pricing/cover.jpg differ diff --git a/apps/sim/public/library/atlassian-service-accounts-ai-agents-jira-confluence/cover.jpg b/apps/sim/public/library/atlassian-service-accounts-ai-agents-jira-confluence/cover.jpg new file mode 100644 index 00000000000..0bfb44dece5 Binary files /dev/null and b/apps/sim/public/library/atlassian-service-accounts-ai-agents-jira-confluence/cover.jpg differ diff --git a/apps/sim/public/library/best-glean-alternatives-pricing-2026/cover.jpg b/apps/sim/public/library/best-glean-alternatives-pricing-2026/cover.jpg new file mode 100644 index 00000000000..1db1a04bd45 Binary files /dev/null and b/apps/sim/public/library/best-glean-alternatives-pricing-2026/cover.jpg differ diff --git a/apps/sim/public/library/cheapest-ai-agent-builders-for-startups-2026/cover.jpg b/apps/sim/public/library/cheapest-ai-agent-builders-for-startups-2026/cover.jpg new file mode 100644 index 00000000000..20e8f693740 Binary files /dev/null and b/apps/sim/public/library/cheapest-ai-agent-builders-for-startups-2026/cover.jpg differ diff --git a/apps/sim/public/library/greenhouse-ai-agent-recruiting-operations/cover.jpg b/apps/sim/public/library/greenhouse-ai-agent-recruiting-operations/cover.jpg new file mode 100644 index 00000000000..21bf134c549 Binary files /dev/null and b/apps/sim/public/library/greenhouse-ai-agent-recruiting-operations/cover.jpg differ diff --git a/apps/sim/public/library/iso-42001-nist-ai-rmf-ai-agent-governance-controls/cover.jpg b/apps/sim/public/library/iso-42001-nist-ai-rmf-ai-agent-governance-controls/cover.jpg new file mode 100644 index 00000000000..b7ed9ce901f Binary files /dev/null and b/apps/sim/public/library/iso-42001-nist-ai-rmf-ai-agent-governance-controls/cover.jpg differ diff --git a/apps/sim/public/library/n8n-pricing-cloud-self-hosted-enterprise/cover.jpg b/apps/sim/public/library/n8n-pricing-cloud-self-hosted-enterprise/cover.jpg new file mode 100644 index 00000000000..edccd610d12 Binary files /dev/null and b/apps/sim/public/library/n8n-pricing-cloud-self-hosted-enterprise/cover.jpg differ diff --git a/apps/sim/public/library/servicenow-ai-agent-it-service-requests/cover.jpg b/apps/sim/public/library/servicenow-ai-agent-it-service-requests/cover.jpg new file mode 100644 index 00000000000..eabe46453c7 Binary files /dev/null and b/apps/sim/public/library/servicenow-ai-agent-it-service-requests/cover.jpg differ diff --git a/apps/sim/public/library/workato-pricing-ai-agents-cost/cover.jpg b/apps/sim/public/library/workato-pricing-ai-agents-cost/cover.jpg new file mode 100644 index 00000000000..3846e9000b9 Binary files /dev/null and b/apps/sim/public/library/workato-pricing-ai-agents-cost/cover.jpg differ diff --git a/apps/sim/scripts/saved-credential-contract.test.ts b/apps/sim/scripts/saved-credential-contract.test.ts index 17c755c9128..266c3339619 100644 --- a/apps/sim/scripts/saved-credential-contract.test.ts +++ b/apps/sim/scripts/saved-credential-contract.test.ts @@ -20,6 +20,7 @@ function requestTool( name: 'Probe fixture', description: 'Fixture for the host-steering probe', version: '1.0.0', + effect: 'write', params: Object.fromEntries( Object.entries(params).map(([name, param]) => [ name, diff --git a/apps/sim/scripts/test-landing-seo-e2e.ts b/apps/sim/scripts/test-landing-seo-e2e.ts index 39ccab3f8fb..880cad48114 100644 --- a/apps/sim/scripts/test-landing-seo-e2e.ts +++ b/apps/sim/scripts/test-landing-seo-e2e.ts @@ -27,6 +27,7 @@ import { vellumProfile, } from '@/lib/compare/data' import { ContentFrontmatterSchema } from '@/lib/content/schema' +import { HOME_FAQS } from '@/app/(landing)/components/home-faq/faqs' import { INTEGRATION_SEO } from '@/app/(landing)/integrations/data/seo-content' /** @@ -455,6 +456,32 @@ async function run() { } ) + await check('home FAQPage pairs each visible question with its answer', async () => { + const { body } = await get(HOME_PATH) + const faqPage = jsonLdNodes(body).find((node) => node['@type'] === 'FAQPage') + const entries = (faqPage?.mainEntity ?? []) as { + name?: string + acceptedAnswer?: { text?: string } + }[] + const expected = HOME_FAQS.map(({ question, answer }) => ({ question, answer })) + assert.deepEqual( + entries.map((entry) => ({ question: entry.name, answer: entry.acceptedAnswer?.text })), + expected, + 'Home FAQPage does not match the home FAQ' + ) + const $ = load(body) + assert.deepEqual( + $('#faq details') + .toArray() + .map((el) => ({ + question: $(el).find('summary h3').text().trim(), + answer: $(el).children('p').text().trim(), + })), + expected, + 'Rendered home FAQ does not match the FAQPage' + ) + }) + await check('pricing declares its offers on the canonical product node', async () => { const { body } = await get('/pricing') const product = jsonLdNodes(body).find((node) => Array.isArray(node.offers)) diff --git a/apps/sim/scripts/test-markdown-viewer-e2e.ts b/apps/sim/scripts/test-markdown-viewer-e2e.ts index 516ee6dcd41..9db21ed0d2e 100644 --- a/apps/sim/scripts/test-markdown-viewer-e2e.ts +++ b/apps/sim/scripts/test-markdown-viewer-e2e.ts @@ -187,6 +187,25 @@ async function check(name: string, run: () => Promise, page?: Page) { } } +const CANCELLED_FETCH = / due to access control checks\.$/ + +/** + * WebKit rejects a fetch the page cancels by navigating away, such as a Next.js RSC prefetch, with + * " due to access control checks.", and the router leaves that rejection unhandled. For a + * same-origin RSC request that is a cancellation, never an access failure. + */ +function isCancelledRscFetch(message: string): boolean { + if (!CANCELLED_FETCH.test(message)) return false + // WebKit names the request as `/host:port/path?query`, without its scheme. + const target = message.replace(CANCELLED_FETCH, '').split(' ').pop() ?? '' + try { + const url = new URL(target.startsWith('/') ? `${base.protocol}/${target}` : target) + return url.origin === base.origin && url.searchParams.has('_rsc') + } catch { + return false + } +} + async function wideTableProof(page: Page) { const table = page.locator('.rich-markdown-prose table').filter({ hasText: 'Option Alpha' }) await expect(table).toBeVisible({ timeout: 120_000 }) @@ -349,6 +368,24 @@ async function proveToolbar(page: Page, toolbar: Locator) { ) } +const FOCUS_SETTLED = 'markdownViewerFocusSettled' + +/** + * ProseMirror writes its own selection back to the DOM 20 ms after the editor gains focus + * (prosemirror-view's focus handler). In WebKit that timer can run after a key's native selection + * change but before the `selectionchange` event that reports it, so the keystroke is reverted. + * Timers with equal delays fire in the order they were set, so one set by a later focus listener, + * or now when the editor already has focus, sets {@link FOCUS_SETTLED} after ProseMirror's has run. + */ +async function armFocusSettled(editor: Locator) { + await editor.evaluate((element, flag) => { + Reflect.set(window, flag, false) + const settle = () => setTimeout(() => Reflect.set(window, flag, true), 20) + if (document.activeElement === element) settle() + else element.addEventListener('focus', settle, { once: true }) + }, FOCUS_SETTLED) +} + async function editLastCell(page: Page, marker: string) { await wideTableProof(page) const last = page @@ -385,18 +422,36 @@ async function editLastCell(page: Page, marker: string) { timeout: 120_000, }) await page.bringToFront() + const editor = page.locator('.rich-markdown-prose[contenteditable="true"]') + await armFocusSettled(editor) await page .locator('.rich-markdown-prose strong') .filter({ hasText: /^bold$/ }) .click() - await expect(page.locator('.rich-markdown-prose[contenteditable="true"]')).toBeFocused() + await expect(editor).toBeFocused() + await expect + .poll(() => page.evaluate((flag) => Reflect.get(window, flag), FOCUS_SETTLED)) + .toBe(true) await page.keyboard.press('ArrowLeft') await page.keyboard.press('Shift+ArrowRight') - await expect - .poll(() => page.evaluate(() => getSelection()?.toString().trim() ?? ''), { - message: 'Keyboard selection did not select text', + try { + await expect + .poll(() => page.evaluate(() => getSelection()?.toString().trim() ?? '')) + .not.toBe('') + } catch { + // Name where the caret and focus ended up. + const state = await page.evaluate(() => { + const selection = getSelection() + return { + anchorText: selection?.anchorNode?.textContent?.slice(0, 40) ?? null, + anchorOffset: selection?.anchorOffset ?? null, + focusOffset: selection?.focusOffset ?? null, + rangeCount: selection?.rangeCount ?? 0, + activeElement: document.activeElement?.className ?? null, + } }) - .not.toBe('') + throw new Error(`Keyboard selection did not select text: ${JSON.stringify(state)}`) + } await proveToolbar(page, page.getByRole('toolbar', { name: 'Text formatting' })) await page.keyboard.press('ArrowRight') } @@ -419,6 +474,7 @@ async function provePastePersistence(page: Page, browserName: string) { const pastedShareToken = generateShortId() const readPasteSource = async () => (await request(`/api/files/public/${pastedShareToken}/content`)).text() + let proved = false try { await sql`insert into public_share (id, resource_type, resource_id, entity_type, entity_id, workspace_id, created_by, token) values (${pastedShareId}, 'file', ${pastedFileId}, 'workspace', ${workspaceId}, ${workspaceId}, ${userId}, ${pastedShareToken})` await page.goto(new URL(`/workspace/${workspaceId}/files/${pastedFileId}`, base).href, { @@ -563,8 +619,12 @@ async function provePastePersistence(page: Page, browserName: string) { afterLocalEdit.includes(`${marker} measure
    `), 'External update lost the pasted table' ) + proved = true } finally { try { + // Leave the file before deleting it, or the open editor refetches it and the next check on + // this page records that 404 as its own. A failed proof keeps the page for its screenshot. + if (proved) await page.goto('about:blank') await request(`/api/workspaces/${workspaceId}/files/${pastedFileId}`, undefined, 'DELETE') } finally { await sql`delete from public_share where id=${pastedShareId}` @@ -972,7 +1032,10 @@ try { { name: 'better-auth.session_token', value: cookie, url: base.origin }, ]) const page = await context.newPage() - page.on('pageerror', (error) => errors.push(`${browserName}: ${error.message}`)) + page.on('pageerror', (error) => { + if (browserName === 'webkit' && isCancelledRscFetch(error.message)) return + errors.push(`${browserName}: ${error.message}`) + }) for (const width of widths) { await page.setViewportSize({ width, height: 1000 }) await page.goto(new URL(`/f/${shareToken}`, base).href, { diff --git a/apps/sim/scripts/test-project-files-e2e.ts b/apps/sim/scripts/test-project-files-e2e.ts index a262c47e316..98a3ad6757c 100644 --- a/apps/sim/scripts/test-project-files-e2e.ts +++ b/apps/sim/scripts/test-project-files-e2e.ts @@ -95,7 +95,6 @@ const environment: NodeJS.ProcessEnv = { ALLOWED_ORIGINS: base.origin, NEXT_PUBLIC_FORCE_HOSTED: 'true', BILLING_ENABLED: 'true', - NEXT_PUBLIC_BILLING_ENABLED: 'true', ENTERPRISE_ENABLED: 'true', ACCESS_CONTROL_ENABLED: 'true', ORGANIZATIONS_ENABLED: 'true', diff --git a/apps/sim/scripts/test-scim-e2e.ts b/apps/sim/scripts/test-scim-e2e.ts index f21fb3174a5..b93f2ab3ae4 100644 --- a/apps/sim/scripts/test-scim-e2e.ts +++ b/apps/sim/scripts/test-scim-e2e.ts @@ -1580,7 +1580,7 @@ async function run() { ) await check( - 'Managed membership locks block invitations and permission edits while allowing unmanaged members', + 'Managed membership locks block edits only on workspaces the member’s groups map, and never unmanaged members', async () => { const manualUserId = generateId() const manualEmail = `manual@${primary.domain}` @@ -1589,42 +1589,61 @@ async function run() { await sql`insert into user_stats (id, user_id) values (${generateId()}, ${manualUserId})` await sql`insert into member (id, user_id, organization_id, role) values (${generateId()}, ${manualUserId}, ${primary.orgId}, 'member')` + const editAlice = (permissions: string, expected?: number) => + request(`/api/workspaces/${primary.workspaceId}/permissions`, { + fixture: primary, + method: 'PATCH', + ...(expected ? { expected } : {}), + contentType: 'application/json', + body: { updates: [{ userId: aliceUserId, permissions }] }, + }) await admin(primary, '', { method: 'PUT', body: { settings: { lockManualMembership: true } }, }) + let lockedGroupId = '' try { - const invitationBody = { - workspaceIds: [primary.workspaceId], - permission: 'read', - membership: 'member', - } - const managedInvite = ( - await request('/api/workspaces/invitations/batch', { - fixture: primary, - method: 'POST', - contentType: 'application/json', - body: { ...invitationBody, emails: [aliceEmail] }, - }) - ).body - assert.equal(managedInvite.success, false) - assert(Array.isArray(managedInvite.failed)) - assert.match(string(record(managedInvite.failed[0]).error), /identity provider/) - assert(!JSON.stringify(managedInvite).includes('select ')) - await request(`/api/workspaces/${primary.workspaceId}/permissions`, { - fixture: primary, - method: 'PATCH', - expected: 403, - contentType: 'application/json', - body: { updates: [{ userId: aliceUserId, permissions: 'write' }] }, + await editAlice('write') + assert.equal(await permission(aliceUserId, primary.workspaceId), 'write') + await editAlice('read') + assert.equal(await permission(aliceUserId, primary.workspaceId), 'read') + + const created = await scim(token, '/Groups', { + method: 'POST', + expected: 201, + body: { + schemas: [GROUP_SCHEMA], + displayName: 'SCIM E2E managed workspace', + members: [{ value: aliceId }], + }, }) + lockedGroupId = string(created.body.id) + await admin(primary, '/mappings', { + method: 'POST', + expected: 201, + body: { + groupId: lockedGroupId, + targetKind: 'workspace', + workspaceId: primary.workspaceId, + permissionType: 'read', + }, + }) + const refused = await editAlice('write', 403) + assert.match(JSON.stringify(refused.body), /identity provider/) + assert(!JSON.stringify(refused.body).includes('select ')) assert.equal(await permission(aliceUserId, primary.workspaceId), 'read') + const manualInvite = ( await request('/api/workspaces/invitations/batch', { fixture: primary, method: 'POST', contentType: 'application/json', - body: { ...invitationBody, emails: [manualEmail] }, + body: { + workspaceIds: [primary.workspaceId], + permission: 'read', + membership: 'member', + emails: [manualEmail], + }, }) ).body assert.equal(manualInvite.success, true) @@ -1637,11 +1656,15 @@ async function run() { }) assert.equal(await permission(manualUserId, primary.workspaceId), 'write') } finally { + /** Unlocked first, so removing the mapping restores Alice's manual access instead of withdrawing it. */ await admin(primary, '', { method: 'PUT', body: { settings: { lockManualMembership: false } }, }) + if (lockedGroupId) + await scim(token, `/Groups/${lockedGroupId}`, { method: 'DELETE', expected: 204 }) } + assert.equal(await permission(aliceUserId, primary.workspaceId), 'read') } ) diff --git a/apps/sim/stores/workflows/workflow/edge-validation.ts b/apps/sim/stores/workflows/workflow/edge-validation.ts index 12f6868e67c..32c2450d4b6 100644 --- a/apps/sim/stores/workflows/workflow/edge-validation.ts +++ b/apps/sim/stores/workflows/workflow/edge-validation.ts @@ -6,8 +6,12 @@ import type { Edge } from '@xyflow/react' import { TriggerUtils } from '@/lib/workflows/triggers/triggers' import type { BlockState } from '@/stores/workflows/workflow/types' +/** Why an edge was dropped; `scope` is an edge crossing a loop's or parallel's boundary. */ +export type DroppedEdgeKind = 'missing_block' | 'annotation_only' | 'trigger_target' | 'scope' + interface DroppedEdge { edge: Edge + kind: DroppedEdgeKind reason: string } @@ -28,7 +32,7 @@ export function validateEdges( const targetBlock = blocks[edge.target] if (!sourceBlock || !targetBlock) { - dropped.push({ edge, reason: 'edge references a missing block' }) + dropped.push({ edge, kind: 'missing_block', reason: 'edge references a missing block' }) continue } @@ -36,18 +40,26 @@ export function validateEdges( isWorkflowAnnotationOnlyBlockType(sourceBlock.type) || isWorkflowAnnotationOnlyBlockType(targetBlock.type) ) { - dropped.push({ edge, reason: 'edge references an annotation-only block' }) + dropped.push({ + edge, + kind: 'annotation_only', + reason: 'edge references an annotation-only block', + }) continue } if (TriggerUtils.isTriggerBlock(targetBlock)) { - dropped.push({ edge, reason: 'trigger blocks cannot be edge targets' }) + dropped.push({ + edge, + kind: 'trigger_target', + reason: 'trigger blocks cannot be edge targets', + }) continue } const scopeDropReason = getWorkflowEdgeScopeDropReason(edge, blocks) if (scopeDropReason) { - dropped.push({ edge, reason: scopeDropReason }) + dropped.push({ edge, kind: 'scope', reason: scopeDropReason }) continue } diff --git a/apps/sim/tools/a2a/cancel_task.ts b/apps/sim/tools/a2a/cancel_task.ts index 42c171e1032..b29619b653f 100644 --- a/apps/sim/tools/a2a/cancel_task.ts +++ b/apps/sim/tools/a2a/cancel_task.ts @@ -6,6 +6,7 @@ export const a2aCancelTaskTool: InternalToolConfig = name: 'Get Draft', description: 'Get details of a specific email draft in AgentMail', version: '1.0.0', + effect: 'read', oauth: AGENTMAIL_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/agentmail/get_inbox.ts b/apps/sim/tools/agentmail/get_inbox.ts index 5416958403d..3760029130c 100644 --- a/apps/sim/tools/agentmail/get_inbox.ts +++ b/apps/sim/tools/agentmail/get_inbox.ts @@ -8,6 +8,7 @@ export const agentmailGetInboxTool: ToolConfig = name: 'Get Inbox', description: 'Get details of a specific email inbox in AgentMail', version: '1.0.0', + effect: 'read', oauth: AGENTMAIL_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/agentmail/get_message.ts b/apps/sim/tools/agentmail/get_message.ts index 0e077df2f3b..6047f8ce988 100644 --- a/apps/sim/tools/agentmail/get_message.ts +++ b/apps/sim/tools/agentmail/get_message.ts @@ -8,6 +8,7 @@ export const agentmailGetMessageTool: ToolConfig description: "Get the anchor text distribution for a target domain or URL's backlinks, showing how many links and referring domains use each anchor text.", version: '1.0.0', + effect: 'read', oauth: AHREFS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/ahrefs/backlinks.ts b/apps/sim/tools/ahrefs/backlinks.ts index fcb139f6f60..b30feaaff70 100644 --- a/apps/sim/tools/ahrefs/backlinks.ts +++ b/apps/sim/tools/ahrefs/backlinks.ts @@ -11,6 +11,7 @@ export const backlinksTool: ToolConfig description: 'Get a one-call organic and paid search overview for a target domain or URL: organic traffic, organic keywords, paid traffic, paid keywords, and estimated traffic cost.', version: '1.0.0', + effect: 'read', oauth: AHREFS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/ahrefs/metrics_history.ts b/apps/sim/tools/ahrefs/metrics_history.ts index 7c59410d1e8..1c4e1912faf 100644 --- a/apps/sim/tools/ahrefs/metrics_history.ts +++ b/apps/sim/tools/ahrefs/metrics_history.ts @@ -13,6 +13,7 @@ export const metricsHistoryTool: ToolConfig< description: 'Get the historical organic and paid traffic trend for a target domain or URL over a date range: organic traffic/cost and paid traffic/cost at each point in time.', version: '1.0.0', + effect: 'read', oauth: AHREFS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/ahrefs/organic_competitors.ts b/apps/sim/tools/ahrefs/organic_competitors.ts index 3997a69aa00..53f1a120e5f 100644 --- a/apps/sim/tools/ahrefs/organic_competitors.ts +++ b/apps/sim/tools/ahrefs/organic_competitors.ts @@ -17,6 +17,7 @@ export const organicCompetitorsTool: ToolConfig< description: 'Get domains that compete with a target domain or URL for the same organic keywords, ranked by keyword overlap.', version: '1.0.0', + effect: 'read', oauth: AHREFS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/ahrefs/organic_keywords.ts b/apps/sim/tools/ahrefs/organic_keywords.ts index 76893629f34..e78e11ce209 100644 --- a/apps/sim/tools/ahrefs/organic_keywords.ts +++ b/apps/sim/tools/ahrefs/organic_keywords.ts @@ -17,6 +17,7 @@ export const organicKeywordsTool: ToolConfig< description: 'Get organic keywords that a target domain or URL ranks for in Google search results. Returns keyword details including search volume, ranking position, and estimated traffic.', version: '1.0.0', + effect: 'read', oauth: AHREFS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/ahrefs/paid_pages.ts b/apps/sim/tools/ahrefs/paid_pages.ts index 1145e3fed4e..9cd3523d6e3 100644 --- a/apps/sim/tools/ahrefs/paid_pages.ts +++ b/apps/sim/tools/ahrefs/paid_pages.ts @@ -10,6 +10,7 @@ export const paidPagesTool: ToolConfig name: 'Algolia Search', description: 'Search an Algolia index', version: '1.0', + effect: 'read', oauth: ALGOLIA_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/algolia/update_settings.ts b/apps/sim/tools/algolia/update_settings.ts index f91b02583ba..2f1e0f459e1 100644 --- a/apps/sim/tools/algolia/update_settings.ts +++ b/apps/sim/tools/algolia/update_settings.ts @@ -13,6 +13,7 @@ export const updateSettingsTool: ToolConfig< name: 'Algolia Update Settings', description: 'Update the settings of an Algolia index', version: '1.0', + effect: 'write', oauth: ALGOLIA_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/amplitude/event_segmentation.ts b/apps/sim/tools/amplitude/event_segmentation.ts index b71b0ee2b4d..e35cf5e07c7 100644 --- a/apps/sim/tools/amplitude/event_segmentation.ts +++ b/apps/sim/tools/amplitude/event_segmentation.ts @@ -15,6 +15,7 @@ export const eventSegmentationTool: ToolConfig< description: 'Query event analytics data with segmentation. Get event counts, uniques, averages, and more.', version: '1.0.0', + effect: 'read', oauth: AMPLITUDE_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/amplitude/funnels.ts b/apps/sim/tools/amplitude/funnels.ts index bc47e8ddad6..ad4b051531a 100644 --- a/apps/sim/tools/amplitude/funnels.ts +++ b/apps/sim/tools/amplitude/funnels.ts @@ -9,6 +9,7 @@ export const funnelsTool: ToolConfig = { name: 'APIFY Get Run', description: 'Get the status and details of an APIFY actor run', version: '1.0.0', + effect: 'read', oauth: APIFY_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apify/run_actor_async.ts b/apps/sim/tools/apify/run_actor_async.ts index 7039ecd5f73..154b13565d9 100644 --- a/apps/sim/tools/apify/run_actor_async.ts +++ b/apps/sim/tools/apify/run_actor_async.ts @@ -135,6 +135,7 @@ export const apifyRunActorAsyncTool: ToolConfig description: 'Start an APIFY Actor run and poll it within the same workflow step until completion or the polling deadline', version: '1.0.0', + effect: 'write', oauth: APIFY_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apify/run_actor_sync.ts b/apps/sim/tools/apify/run_actor_sync.ts index df0322e7d6d..280a4abc58e 100644 --- a/apps/sim/tools/apify/run_actor_sync.ts +++ b/apps/sim/tools/apify/run_actor_sync.ts @@ -7,6 +7,7 @@ export const apifyRunActorSyncTool: ToolConfig = name: 'APIFY Run Actor (Sync)', description: 'Run an APIFY actor synchronously and get results (max 5 minutes)', version: '1.0.0', + effect: 'write', oauth: APIFY_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apify/run_task.ts b/apps/sim/tools/apify/run_task.ts index 5d7b60564c5..3e9bff643a2 100644 --- a/apps/sim/tools/apify/run_task.ts +++ b/apps/sim/tools/apify/run_task.ts @@ -7,6 +7,7 @@ export const apifyRunTaskTool: ToolConfig = { name: 'APIFY Run Task', description: 'Run a saved APIFY actor task synchronously and get dataset items (max 5 minutes)', version: '1.0.0', + effect: 'write', oauth: APIFY_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/account_bulk_create.ts b/apps/sim/tools/apollo/account_bulk_create.ts index f331d39aee1..37549d14db9 100644 --- a/apps/sim/tools/apollo/account_bulk_create.ts +++ b/apps/sim/tools/apollo/account_bulk_create.ts @@ -15,6 +15,7 @@ export const apolloAccountBulkCreateTool: ToolConfig< description: 'Create up to 100 accounts at once in your Apollo database. Set run_dedupe=true to deduplicate by domain, organization_id, and name. Master key required.', version: '1.0.0', + effect: 'write', oauth: APOLLO_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/account_bulk_update.ts b/apps/sim/tools/apollo/account_bulk_update.ts index 098167beb3e..532749149bf 100644 --- a/apps/sim/tools/apollo/account_bulk_update.ts +++ b/apps/sim/tools/apollo/account_bulk_update.ts @@ -15,6 +15,7 @@ export const apolloAccountBulkUpdateTool: ToolConfig< description: 'Update up to 1000 existing accounts at once in your Apollo database (higher limit than contacts!). Each account must include an id field. Master key required.', version: '1.0.0', + effect: 'write', oauth: APOLLO_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/account_create.ts b/apps/sim/tools/apollo/account_create.ts index ec60693f8e0..39f522705dc 100644 --- a/apps/sim/tools/apollo/account_create.ts +++ b/apps/sim/tools/apollo/account_create.ts @@ -11,6 +11,7 @@ export const apolloAccountCreateTool: ToolConfig< name: 'Apollo Create Account', description: 'Create a new account (company) in your Apollo database', version: '1.0.0', + effect: 'write', oauth: APOLLO_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/account_search.ts b/apps/sim/tools/apollo/account_search.ts index 49d2c235de3..91b47328328 100644 --- a/apps/sim/tools/apollo/account_search.ts +++ b/apps/sim/tools/apollo/account_search.ts @@ -12,6 +12,7 @@ export const apolloAccountSearchTool: ToolConfig< description: "Search your team's accounts in Apollo. Display limit: 50,000 records (100 records per page, 500 pages max). Use filters to narrow results. Master key required.", version: '1.0.0', + effect: 'read', oauth: APOLLO_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/account_update.ts b/apps/sim/tools/apollo/account_update.ts index 600293e4b77..db9ea464e33 100644 --- a/apps/sim/tools/apollo/account_update.ts +++ b/apps/sim/tools/apollo/account_update.ts @@ -11,6 +11,7 @@ export const apolloAccountUpdateTool: ToolConfig< name: 'Apollo Update Account', description: 'Update an existing account in your Apollo database', version: '1.0.0', + effect: 'write', oauth: APOLLO_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/contact_bulk_create.ts b/apps/sim/tools/apollo/contact_bulk_create.ts index 035bb6336b4..c4f839d2525 100644 --- a/apps/sim/tools/apollo/contact_bulk_create.ts +++ b/apps/sim/tools/apollo/contact_bulk_create.ts @@ -15,6 +15,7 @@ export const apolloContactBulkCreateTool: ToolConfig< description: 'Create up to 100 contacts at once in your Apollo database. Supports deduplication to prevent creating duplicate contacts. Master key required.', version: '1.0.0', + effect: 'write', oauth: APOLLO_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/contact_bulk_update.ts b/apps/sim/tools/apollo/contact_bulk_update.ts index 1a61bfce940..4726ca3702a 100644 --- a/apps/sim/tools/apollo/contact_bulk_update.ts +++ b/apps/sim/tools/apollo/contact_bulk_update.ts @@ -15,6 +15,7 @@ export const apolloContactBulkUpdateTool: ToolConfig< description: 'Update up to 100 existing contacts at once in your Apollo database. Each contact must include an id field. Master key required.', version: '1.0.0', + effect: 'write', oauth: APOLLO_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/contact_create.ts b/apps/sim/tools/apollo/contact_create.ts index 5cee7a4e839..a47ee1e3387 100644 --- a/apps/sim/tools/apollo/contact_create.ts +++ b/apps/sim/tools/apollo/contact_create.ts @@ -11,6 +11,7 @@ export const apolloContactCreateTool: ToolConfig< name: 'Apollo Create Contact', description: 'Create a new contact in your Apollo database', version: '1.0.0', + effect: 'write', oauth: APOLLO_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/contact_search.ts b/apps/sim/tools/apollo/contact_search.ts index 1f3af7a3865..af9cf6a365e 100644 --- a/apps/sim/tools/apollo/contact_search.ts +++ b/apps/sim/tools/apollo/contact_search.ts @@ -11,6 +11,7 @@ export const apolloContactSearchTool: ToolConfig< name: 'Apollo Search Contacts', description: "Search your team's contacts in Apollo", version: '1.0.0', + effect: 'read', oauth: APOLLO_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/contact_update.ts b/apps/sim/tools/apollo/contact_update.ts index f6ab4557f72..6910f1f3320 100644 --- a/apps/sim/tools/apollo/contact_update.ts +++ b/apps/sim/tools/apollo/contact_update.ts @@ -11,6 +11,7 @@ export const apolloContactUpdateTool: ToolConfig< name: 'Apollo Update Contact', description: 'Update an existing contact in your Apollo database', version: '1.0.0', + effect: 'write', oauth: APOLLO_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/email_accounts.ts b/apps/sim/tools/apollo/email_accounts.ts index e2d28c36a57..a3da7b5be73 100644 --- a/apps/sim/tools/apollo/email_accounts.ts +++ b/apps/sim/tools/apollo/email_accounts.ts @@ -11,6 +11,7 @@ export const apolloEmailAccountsTool: ToolConfig< name: 'Apollo Get Email Accounts', description: "Get list of team's linked email accounts in Apollo", version: '1.0.0', + effect: 'read', oauth: APOLLO_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/opportunity_create.ts b/apps/sim/tools/apollo/opportunity_create.ts index 6a68b575dcd..13eb70ab2f3 100644 --- a/apps/sim/tools/apollo/opportunity_create.ts +++ b/apps/sim/tools/apollo/opportunity_create.ts @@ -14,6 +14,7 @@ export const apolloOpportunityCreateTool: ToolConfig< name: 'Apollo Create Opportunity', description: 'Create a new deal for an account in your Apollo database (master key required)', version: '1.0.0', + effect: 'write', oauth: APOLLO_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/opportunity_get.ts b/apps/sim/tools/apollo/opportunity_get.ts index 4bcb3e8de41..dcc970b25da 100644 --- a/apps/sim/tools/apollo/opportunity_get.ts +++ b/apps/sim/tools/apollo/opportunity_get.ts @@ -11,6 +11,7 @@ export const apolloOpportunityGetTool: ToolConfig< name: 'Apollo Get Opportunity', description: 'Retrieve complete details of a specific deal/opportunity by ID', version: '1.0.0', + effect: 'read', oauth: APOLLO_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/opportunity_search.ts b/apps/sim/tools/apollo/opportunity_search.ts index 3059a415879..e830ccb3e92 100644 --- a/apps/sim/tools/apollo/opportunity_search.ts +++ b/apps/sim/tools/apollo/opportunity_search.ts @@ -14,6 +14,7 @@ export const apolloOpportunitySearchTool: ToolConfig< name: 'Apollo Search Opportunities', description: "Search and list all deals/opportunities in your team's Apollo account", version: '1.0.0', + effect: 'read', oauth: APOLLO_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/opportunity_update.ts b/apps/sim/tools/apollo/opportunity_update.ts index d48489a85b2..22cb51fa3a4 100644 --- a/apps/sim/tools/apollo/opportunity_update.ts +++ b/apps/sim/tools/apollo/opportunity_update.ts @@ -14,6 +14,7 @@ export const apolloOpportunityUpdateTool: ToolConfig< name: 'Apollo Update Opportunity', description: 'Update an existing deal/opportunity in your Apollo database', version: '1.0.0', + effect: 'write', oauth: APOLLO_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/organization_bulk_enrich.ts b/apps/sim/tools/apollo/organization_bulk_enrich.ts index c2b0bfeb8ab..5b563374f32 100644 --- a/apps/sim/tools/apollo/organization_bulk_enrich.ts +++ b/apps/sim/tools/apollo/organization_bulk_enrich.ts @@ -14,6 +14,7 @@ export const apolloOrganizationBulkEnrichTool: ToolConfig< name: 'Apollo Bulk Organization Enrichment', description: 'Enrich data for up to 10 organizations at once using Apollo', version: '1.0.0', + effect: 'read', oauth: APOLLO_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/organization_enrich.ts b/apps/sim/tools/apollo/organization_enrich.ts index f52ea1fbcb1..5d65f447665 100644 --- a/apps/sim/tools/apollo/organization_enrich.ts +++ b/apps/sim/tools/apollo/organization_enrich.ts @@ -14,6 +14,7 @@ export const apolloOrganizationEnrichTool: ToolConfig< name: 'Apollo Organization Enrichment', description: 'Enrich data for a single organization using Apollo', version: '1.0.0', + effect: 'read', oauth: APOLLO_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/organization_search.ts b/apps/sim/tools/apollo/organization_search.ts index c47c292e763..1452bd4e442 100644 --- a/apps/sim/tools/apollo/organization_search.ts +++ b/apps/sim/tools/apollo/organization_search.ts @@ -14,6 +14,7 @@ export const apolloOrganizationSearchTool: ToolConfig< name: 'Apollo Organization Search', description: "Search Apollo's database for companies using filters", version: '1.0.0', + effect: 'read', oauth: APOLLO_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/people_bulk_enrich.ts b/apps/sim/tools/apollo/people_bulk_enrich.ts index 3c9bfa0ac00..75bcab6f286 100644 --- a/apps/sim/tools/apollo/people_bulk_enrich.ts +++ b/apps/sim/tools/apollo/people_bulk_enrich.ts @@ -14,6 +14,7 @@ export const apolloPeopleBulkEnrichTool: ToolConfig< name: 'Apollo Bulk People Enrichment', description: 'Enrich data for up to 10 people at once using Apollo', version: '1.0.0', + effect: 'write', oauth: APOLLO_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/people_enrich.ts b/apps/sim/tools/apollo/people_enrich.ts index 4691b453a6c..eb5056b7609 100644 --- a/apps/sim/tools/apollo/people_enrich.ts +++ b/apps/sim/tools/apollo/people_enrich.ts @@ -11,6 +11,7 @@ export const apolloPeopleEnrichTool: ToolConfig< name: 'Apollo People Enrichment', description: 'Enrich data for a single person using Apollo', version: '1.0.0', + effect: 'write', oauth: APOLLO_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/people_search.ts b/apps/sim/tools/apollo/people_search.ts index 0bba604b0f4..3861e9eff49 100644 --- a/apps/sim/tools/apollo/people_search.ts +++ b/apps/sim/tools/apollo/people_search.ts @@ -22,6 +22,7 @@ export const apolloPeopleSearchTool: ToolConfig< name: 'Apollo People Search', description: "Search Apollo's database for people using demographic filters", version: '1.0.0', + effect: 'read', oauth: APOLLO_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/sequence_add_contacts.ts b/apps/sim/tools/apollo/sequence_add_contacts.ts index 0d06d20b202..f61886c6574 100644 --- a/apps/sim/tools/apollo/sequence_add_contacts.ts +++ b/apps/sim/tools/apollo/sequence_add_contacts.ts @@ -14,6 +14,7 @@ export const apolloSequenceAddContactsTool: ToolConfig< name: 'Apollo Add Contacts to Sequence', description: 'Add contacts to an Apollo sequence', version: '1.0.0', + effect: 'write', oauth: APOLLO_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/sequence_search.ts b/apps/sim/tools/apollo/sequence_search.ts index d90921028d7..425af5c5cde 100644 --- a/apps/sim/tools/apollo/sequence_search.ts +++ b/apps/sim/tools/apollo/sequence_search.ts @@ -11,6 +11,7 @@ export const apolloSequenceSearchTool: ToolConfig< name: 'Apollo Search Sequences', description: "Search for sequences/campaigns in your team's Apollo account (master key required)", version: '1.0.0', + effect: 'read', oauth: APOLLO_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/apollo/task_create.ts b/apps/sim/tools/apollo/task_create.ts index afcc6cb21e8..45a33186e3c 100644 --- a/apps/sim/tools/apollo/task_create.ts +++ b/apps/sim/tools/apollo/task_create.ts @@ -8,6 +8,7 @@ export const apolloTaskCreateTool: ToolConfig = { name: 'ArXiv Search', description: 'Search for academic papers on ArXiv by keywords, authors, titles, or other fields.', version: '1.0.0', + effect: 'read', params: { searchQuery: { diff --git a/apps/sim/tools/asana/add_comment.ts b/apps/sim/tools/asana/add_comment.ts index 5330c067d8a..1b5dee1f9f3 100644 --- a/apps/sim/tools/asana/add_comment.ts +++ b/apps/sim/tools/asana/add_comment.ts @@ -9,6 +9,7 @@ export const asanaAddCommentTool: InternalToolConfig< name: 'Asana Add Comment', description: 'Add a comment (story) to an Asana task', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/asana/add_followers.ts b/apps/sim/tools/asana/add_followers.ts index 67f427d073b..6c05f1d9197 100644 --- a/apps/sim/tools/asana/add_followers.ts +++ b/apps/sim/tools/asana/add_followers.ts @@ -9,6 +9,7 @@ export const asanaAddFollowersTool: InternalToolConfig< name: 'Asana Add Followers', description: 'Add one or more followers to an Asana task', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/asana/create_project.ts b/apps/sim/tools/asana/create_project.ts index 485d8aa8319..36963a5b032 100644 --- a/apps/sim/tools/asana/create_project.ts +++ b/apps/sim/tools/asana/create_project.ts @@ -9,6 +9,7 @@ export const asanaCreateProjectTool: InternalToolConfig< name: 'Asana Create Project', description: 'Create a new project in an Asana workspace', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/asana/create_section.ts b/apps/sim/tools/asana/create_section.ts index 2473aa77c43..c0d717c4226 100644 --- a/apps/sim/tools/asana/create_section.ts +++ b/apps/sim/tools/asana/create_section.ts @@ -9,6 +9,7 @@ export const asanaCreateSectionTool: InternalToolConfig< name: 'Asana Create Section', description: 'Create a new section in an Asana project', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/asana/create_subtask.ts b/apps/sim/tools/asana/create_subtask.ts index 43e4fa6c388..c4d2d2a89f4 100644 --- a/apps/sim/tools/asana/create_subtask.ts +++ b/apps/sim/tools/asana/create_subtask.ts @@ -9,6 +9,7 @@ export const asanaCreateSubtaskTool: InternalToolConfig< name: 'Asana Create Subtask', description: 'Create a subtask under an existing Asana task', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/asana/create_task.ts b/apps/sim/tools/asana/create_task.ts index d5ddf943a8c..a49c92bb24c 100644 --- a/apps/sim/tools/asana/create_task.ts +++ b/apps/sim/tools/asana/create_task.ts @@ -9,6 +9,7 @@ export const asanaCreateTaskTool: InternalToolConfig< name: 'Asana Create Task', description: 'Create a new task in Asana', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/asana/delete_task.ts b/apps/sim/tools/asana/delete_task.ts index 764903ea716..91ffca1af92 100644 --- a/apps/sim/tools/asana/delete_task.ts +++ b/apps/sim/tools/asana/delete_task.ts @@ -9,6 +9,7 @@ export const asanaDeleteTaskTool: InternalToolConfig< name: 'Asana Delete Task', description: 'Delete an Asana task by its GID (moves it to the trash)', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/asana/get_project.ts b/apps/sim/tools/asana/get_project.ts index 4569f952c11..6b7f21e80d4 100644 --- a/apps/sim/tools/asana/get_project.ts +++ b/apps/sim/tools/asana/get_project.ts @@ -9,6 +9,7 @@ export const asanaGetProjectTool: InternalToolConfig< name: 'Asana Get Project', description: 'Retrieve a single Asana project by its GID', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/asana/get_projects.ts b/apps/sim/tools/asana/get_projects.ts index c32ce3af9c0..3e2c441cbf5 100644 --- a/apps/sim/tools/asana/get_projects.ts +++ b/apps/sim/tools/asana/get_projects.ts @@ -9,6 +9,7 @@ export const asanaGetProjectsTool: InternalToolConfig< name: 'Asana Get Projects', description: 'Retrieve all projects from an Asana workspace', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/asana/get_task.ts b/apps/sim/tools/asana/get_task.ts index 82da9992f19..62974a8fa8d 100644 --- a/apps/sim/tools/asana/get_task.ts +++ b/apps/sim/tools/asana/get_task.ts @@ -6,6 +6,7 @@ export const asanaGetTaskTool: InternalToolConfig = { name: 'Ashby Get Job', description: 'Retrieves full details about a single job by its ID.', version: '1.0.0', + effect: 'read', oauth: ASHBY_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/ashby/get_job_posting.ts b/apps/sim/tools/ashby/get_job_posting.ts index c66b420d2ce..e42e5ecf38d 100644 --- a/apps/sim/tools/ashby/get_job_posting.ts +++ b/apps/sim/tools/ashby/get_job_posting.ts @@ -89,6 +89,7 @@ export const getJobPostingTool: ToolConfig = { name: 'Ashby Get Opening', description: 'Retrieves one Ashby headcount opening by UUID.', version: '1.0.0', + effect: 'read', oauth: ASHBY_CREDENTIAL_OAUTH, params: { apiKey: { diff --git a/apps/sim/tools/ashby/list_application_feedback.ts b/apps/sim/tools/ashby/list_application_feedback.ts index 9a6e1bfa56d..846249d2e2b 100644 --- a/apps/sim/tools/ashby/list_application_feedback.ts +++ b/apps/sim/tools/ashby/list_application_feedback.ts @@ -30,6 +30,7 @@ export const listApplicationFeedbackTool: ToolConfig = { description: 'Lists submitted interview feedback, optionally for one application, with pagination and incremental sync.', version: '1.0.0', + effect: 'read', oauth: ASHBY_CREDENTIAL_OAUTH, params: { apiKey: { diff --git a/apps/sim/tools/ashby/list_application_history.ts b/apps/sim/tools/ashby/list_application_history.ts index 4349a666592..18028dc8756 100644 --- a/apps/sim/tools/ashby/list_application_history.ts +++ b/apps/sim/tools/ashby/list_application_history.ts @@ -17,6 +17,7 @@ export const listApplicationHistoryTool: ToolConfig = { name: 'Ashby List Application History', description: 'Lists the full stage history and allowed actions for an application.', version: '1.0.0', + effect: 'read', oauth: ASHBY_CREDENTIAL_OAUTH, params: { apiKey: { diff --git a/apps/sim/tools/ashby/list_applications.ts b/apps/sim/tools/ashby/list_applications.ts index 23b3424b0b7..42c870afde8 100644 --- a/apps/sim/tools/ashby/list_applications.ts +++ b/apps/sim/tools/ashby/list_applications.ts @@ -22,6 +22,7 @@ export const listApplicationsTool: ToolConfig< description: 'Lists all applications in an Ashby organization with pagination and optional filters for status, job, and creation date.', version: '1.0.0', + effect: 'read', oauth: ASHBY_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/ashby/list_archive_reasons.ts b/apps/sim/tools/ashby/list_archive_reasons.ts index 9734896a790..a533b2b2ce8 100644 --- a/apps/sim/tools/ashby/list_archive_reasons.ts +++ b/apps/sim/tools/ashby/list_archive_reasons.ts @@ -28,6 +28,7 @@ export const listArchiveReasonsTool: ToolConfig< name: 'Ashby List Archive Reasons', description: 'Lists all archive reasons configured in Ashby.', version: '1.0.0', + effect: 'read', oauth: ASHBY_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/ashby/list_candidate_tags.ts b/apps/sim/tools/ashby/list_candidate_tags.ts index 174a2c1db25..4c454f4b78c 100644 --- a/apps/sim/tools/ashby/list_candidate_tags.ts +++ b/apps/sim/tools/ashby/list_candidate_tags.ts @@ -33,6 +33,7 @@ export const listCandidateTagsTool: ToolConfig< name: 'Ashby List Candidate Tags', description: 'Lists all candidate tags configured in Ashby.', version: '1.0.0', + effect: 'read', oauth: ASHBY_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/ashby/list_candidates.ts b/apps/sim/tools/ashby/list_candidates.ts index a9d213f19c2..f9591fb4cab 100644 --- a/apps/sim/tools/ashby/list_candidates.ts +++ b/apps/sim/tools/ashby/list_candidates.ts @@ -18,6 +18,7 @@ export const listCandidatesTool: ToolConfig< name: 'Ashby List Candidates', description: 'Lists all candidates in an Ashby organization with cursor-based pagination.', version: '1.0.0', + effect: 'read', oauth: ASHBY_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/ashby/list_custom_fields.ts b/apps/sim/tools/ashby/list_custom_fields.ts index bf5bb84df1a..5d4f42aa8e3 100644 --- a/apps/sim/tools/ashby/list_custom_fields.ts +++ b/apps/sim/tools/ashby/list_custom_fields.ts @@ -42,6 +42,7 @@ export const listCustomFieldsTool: ToolConfig< name: 'Ashby List Custom Fields', description: 'Lists all custom field definitions configured in Ashby.', version: '1.0.0', + effect: 'read', oauth: ASHBY_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/ashby/list_departments.ts b/apps/sim/tools/ashby/list_departments.ts index eeeba817b00..60c66a6c8f3 100644 --- a/apps/sim/tools/ashby/list_departments.ts +++ b/apps/sim/tools/ashby/list_departments.ts @@ -38,6 +38,7 @@ export const listDepartmentsTool: ToolConfig< name: 'Ashby List Departments', description: 'Lists all departments in Ashby.', version: '1.0.0', + effect: 'read', oauth: ASHBY_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/ashby/list_interview_plans.ts b/apps/sim/tools/ashby/list_interview_plans.ts index 689472558b9..65943bf29ab 100644 --- a/apps/sim/tools/ashby/list_interview_plans.ts +++ b/apps/sim/tools/ashby/list_interview_plans.ts @@ -30,6 +30,7 @@ export const listInterviewPlansTool: ToolConfig = { description: 'Lists Ashby interview plans, including optional archived plans and incremental changes.', version: '1.0.0', + effect: 'read', oauth: ASHBY_CREDENTIAL_OAUTH, params: { apiKey: { diff --git a/apps/sim/tools/ashby/list_interview_stages.ts b/apps/sim/tools/ashby/list_interview_stages.ts index 4d39357c93d..e9c7dc59166 100644 --- a/apps/sim/tools/ashby/list_interview_stages.ts +++ b/apps/sim/tools/ashby/list_interview_stages.ts @@ -24,6 +24,7 @@ export const listInterviewStagesTool: ToolConfig = { name: 'Ashby List Interview Stages', description: 'Lists the ordered stages in an Ashby interview plan.', version: '1.0.0', + effect: 'read', oauth: ASHBY_CREDENTIAL_OAUTH, params: { apiKey: { diff --git a/apps/sim/tools/ashby/list_interviews.ts b/apps/sim/tools/ashby/list_interviews.ts index 8284bfe2d5a..11756dc325c 100644 --- a/apps/sim/tools/ashby/list_interviews.ts +++ b/apps/sim/tools/ashby/list_interviews.ts @@ -105,6 +105,7 @@ export const listInterviewsTool: ToolConfig< description: 'Lists interview schedules in Ashby, optionally filtered by application or interview stage.', version: '1.0.0', + effect: 'read', oauth: ASHBY_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/ashby/list_job_postings.ts b/apps/sim/tools/ashby/list_job_postings.ts index 5f96e28a3c1..d42fcb69ca0 100644 --- a/apps/sim/tools/ashby/list_job_postings.ts +++ b/apps/sim/tools/ashby/list_job_postings.ts @@ -49,6 +49,7 @@ export const listJobPostingsTool: ToolConfig< name: 'Ashby List Job Postings', description: 'Lists all job postings in Ashby.', version: '1.0.0', + effect: 'read', oauth: ASHBY_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/ashby/list_jobs.ts b/apps/sim/tools/ashby/list_jobs.ts index c3dc77937c5..ada85dc7433 100644 --- a/apps/sim/tools/ashby/list_jobs.ts +++ b/apps/sim/tools/ashby/list_jobs.ts @@ -39,6 +39,7 @@ export const listJobsTool: ToolConfig = { description: 'Searches Ashby jobs by title and/or requisition ID. Provide at least one of these filters.', version: '1.0.0', + effect: 'read', oauth: ASHBY_CREDENTIAL_OAUTH, params: { apiKey: { diff --git a/apps/sim/tools/ashby/search_openings.ts b/apps/sim/tools/ashby/search_openings.ts index ce179d0d4ce..ff2b25432f2 100644 --- a/apps/sim/tools/ashby/search_openings.ts +++ b/apps/sim/tools/ashby/search_openings.ts @@ -20,6 +20,7 @@ export const searchOpeningsTool: ToolConfig = { name: 'Ashby Search Openings', description: 'Searches Ashby headcount openings by human-readable identifier.', version: '1.0.0', + effect: 'read', oauth: ASHBY_CREDENTIAL_OAUTH, params: { apiKey: { diff --git a/apps/sim/tools/ashby/search_users.ts b/apps/sim/tools/ashby/search_users.ts index 611b32d5397..6a2c5c5cefd 100644 --- a/apps/sim/tools/ashby/search_users.ts +++ b/apps/sim/tools/ashby/search_users.ts @@ -20,6 +20,7 @@ export const searchUsersTool: ToolConfig = { name: 'Ashby Search Users', description: 'Searches Ashby users by exact email address.', version: '1.0.0', + effect: 'read', oauth: ASHBY_CREDENTIAL_OAUTH, params: { apiKey: { diff --git a/apps/sim/tools/ashby/set_custom_field_value.ts b/apps/sim/tools/ashby/set_custom_field_value.ts index da0c28c83dc..367be46affe 100644 --- a/apps/sim/tools/ashby/set_custom_field_value.ts +++ b/apps/sim/tools/ashby/set_custom_field_value.ts @@ -34,6 +34,7 @@ export const setCustomFieldValueTool: ToolConfig< description: 'Sets the value of a single custom field on an Ashby Application, Candidate, Job, or Opening. Custom fields are the only way to annotate a job or req, since Ashby has no job notes and no job tags. Requires the candidatesWrite permission.', version: '1.0.0', + effect: 'write', oauth: ASHBY_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/ashby/set_custom_field_values.ts b/apps/sim/tools/ashby/set_custom_field_values.ts index 66841e38fb7..42769199bd8 100644 --- a/apps/sim/tools/ashby/set_custom_field_values.ts +++ b/apps/sim/tools/ashby/set_custom_field_values.ts @@ -33,6 +33,7 @@ export const setCustomFieldValuesTool: ToolConfig< description: 'Sets several custom field values on one Ashby Application, Candidate, Job, or Opening in a single call. Prefer this over repeated single-field writes to the same object - Ashby recommends it because concurrent single-field calls can race and overwrite each other. Requires the candidatesWrite permission.', version: '1.0.0', + effect: 'write', oauth: ASHBY_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/ashby/transfer_application.ts b/apps/sim/tools/ashby/transfer_application.ts index 7189efa785d..654b7dbbcb1 100644 --- a/apps/sim/tools/ashby/transfer_application.ts +++ b/apps/sim/tools/ashby/transfer_application.ts @@ -25,6 +25,7 @@ export const transferApplicationTool: ToolConfig = { name: 'Ashby Transfer Application', description: 'Transfers an application to another job, interview plan, and stage.', version: '1.0.0', + effect: 'write', oauth: ASHBY_CREDENTIAL_OAUTH, params: { apiKey: { diff --git a/apps/sim/tools/ashby/update_candidate.ts b/apps/sim/tools/ashby/update_candidate.ts index fbe2bf954ff..630b187ff2d 100644 --- a/apps/sim/tools/ashby/update_candidate.ts +++ b/apps/sim/tools/ashby/update_candidate.ts @@ -39,6 +39,7 @@ export const updateCandidateTool: ToolConfig< name: 'Ashby Update Candidate', description: 'Updates an existing candidate record in Ashby. Only provided fields are changed.', version: '1.0.0', + effect: 'write', oauth: ASHBY_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/ashby/upload_candidate_file.ts b/apps/sim/tools/ashby/upload_candidate_file.ts index 8fe853c048d..b7b3ad00d9a 100644 --- a/apps/sim/tools/ashby/upload_candidate_file.ts +++ b/apps/sim/tools/ashby/upload_candidate_file.ts @@ -15,6 +15,7 @@ export const uploadCandidateFileTool: InternalToolConfig ({ getTool: vi.fn(), resolveToken: vi.fn(), @@ -71,7 +70,8 @@ function tool(id: string): InternalToolConfig { name: id, description: 'Personal integration fixture', version: '1.0.0', - assistant: { effect: 'read', version: 1 }, + effect: 'read', + assistant: { version: 1 }, oauth: { required: true, provider: 'google-drive' }, params: { accessToken: { type: 'string', visibility: 'hidden' } }, operation: { input: (params) => params }, @@ -214,6 +214,36 @@ describe('Assistant integration execution boundary', () => { expect(operation).not.toHaveBeenCalled() }) + it.each([ + ['read', 2], + ['write', 1], + ] as const)( + 'replays a %s operation after a rejected credential only when replay cannot repeat a write', + async (effect, calls) => { + const selected = tool('google_drive_get_file') + selected.effect = effect + selected.oauth = { required: true, provider: 'google-drive', retryOnUnauthorized: true } + getTool.mockReturnValue(selected) + getToolMetadata.mockReturnValue(selected) + operation.mockImplementationOnce(async () => new Response(null, { status: 401 })) + const operationContext = { ...assistantContext, organizationId: 'org' } + + await withAssistantActionExecution( + { + userId: 'caller', + organizationId: 'org', + toolCallId: 'assistant-call', + toolId: selected.id, + args: { credentialId: 'mine' }, + binding: { credentialId: 'mine', operationVersion: 1, effect }, + }, + () => executeTool(selected.id, { credentialId: 'mine' }, { operationContext }) + ) + + expect(operation).toHaveBeenCalledTimes(calls) + } + ) + it('binds the personal token and host through the authorized operation', async () => { const gitlab = tool('gitlab_list_projects') gitlab.oauth = undefined diff --git a/apps/sim/tools/athena/batch_get_named_query.ts b/apps/sim/tools/athena/batch_get_named_query.ts index 94e54a4159f..d80fc4dfd32 100644 --- a/apps/sim/tools/athena/batch_get_named_query.ts +++ b/apps/sim/tools/athena/batch_get_named_query.ts @@ -13,6 +13,7 @@ export const batchGetNamedQueryTool: InternalToolConfig< name: 'Athena Batch Get Named Queries', description: 'Get the details of up to 50 Athena named queries by ID in a single call', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/athena/batch_get_prepared_statement.ts b/apps/sim/tools/athena/batch_get_prepared_statement.ts index b34fe78edf4..ec576d8e6eb 100644 --- a/apps/sim/tools/athena/batch_get_prepared_statement.ts +++ b/apps/sim/tools/athena/batch_get_prepared_statement.ts @@ -14,6 +14,7 @@ export const batchGetPreparedStatementTool: InternalToolConfig< description: 'Get the details of up to 256 prepared statements in an Athena workgroup by name in a single call', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/athena/batch_get_query_execution.ts b/apps/sim/tools/athena/batch_get_query_execution.ts index df95c795adb..c0579f0a3e5 100644 --- a/apps/sim/tools/athena/batch_get_query_execution.ts +++ b/apps/sim/tools/athena/batch_get_query_execution.ts @@ -13,6 +13,7 @@ export const batchGetQueryExecutionTool: InternalToolConfig< name: 'Athena Batch Get Query Executions', description: 'Get the status and details of up to 50 Athena query executions in one call', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/athena/create_named_query.ts b/apps/sim/tools/athena/create_named_query.ts index 5ca926fddda..4c2300b7112 100644 --- a/apps/sim/tools/athena/create_named_query.ts +++ b/apps/sim/tools/athena/create_named_query.ts @@ -13,6 +13,7 @@ export const createNamedQueryTool: InternalToolConfig< name: 'Athena Create Named Query', description: 'Create a saved/named query in AWS Athena', version: '1.0.0', + effect: 'write', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/athena/create_prepared_statement.ts b/apps/sim/tools/athena/create_prepared_statement.ts index 14ddf13d188..041381ab994 100644 --- a/apps/sim/tools/athena/create_prepared_statement.ts +++ b/apps/sim/tools/athena/create_prepared_statement.ts @@ -14,6 +14,7 @@ export const createPreparedStatementTool: InternalToolConfig< description: 'Create a parameterized prepared statement in an Athena workgroup for use with EXECUTE or execution parameters', version: '1.0.0', + effect: 'write', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/athena/delete_named_query.ts b/apps/sim/tools/athena/delete_named_query.ts index e8849cc19db..d229a6a8c99 100644 --- a/apps/sim/tools/athena/delete_named_query.ts +++ b/apps/sim/tools/athena/delete_named_query.ts @@ -13,6 +13,7 @@ export const deleteNamedQueryTool: InternalToolConfig< name: 'Athena Delete Named Query', description: 'Delete a saved/named query in AWS Athena', version: '1.0.0', + effect: 'write', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/athena/delete_prepared_statement.ts b/apps/sim/tools/athena/delete_prepared_statement.ts index ec6a33d7228..063ecaecdef 100644 --- a/apps/sim/tools/athena/delete_prepared_statement.ts +++ b/apps/sim/tools/athena/delete_prepared_statement.ts @@ -13,6 +13,7 @@ export const deletePreparedStatementTool: InternalToolConfig< name: 'Athena Delete Prepared Statement', description: 'Delete a prepared statement from an Athena workgroup', version: '1.0.0', + effect: 'write', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/athena/get_data_catalog.ts b/apps/sim/tools/athena/get_data_catalog.ts index 54f7eb37016..cf61e4a18eb 100644 --- a/apps/sim/tools/athena/get_data_catalog.ts +++ b/apps/sim/tools/athena/get_data_catalog.ts @@ -10,6 +10,7 @@ export const getDataCatalogTool: InternalToolConfig< name: 'Athena Get Data Catalog', description: 'Get the type, status, and connection parameters of an Athena data catalog', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/athena/get_database.ts b/apps/sim/tools/athena/get_database.ts index ee30fbbf2fe..3a27cd4616b 100644 --- a/apps/sim/tools/athena/get_database.ts +++ b/apps/sim/tools/athena/get_database.ts @@ -11,6 +11,7 @@ export const getDatabaseTool: InternalToolConfig< description: 'Get a single database (name, description, and parameters) from an Athena data catalog', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/athena/get_named_query.ts b/apps/sim/tools/athena/get_named_query.ts index d4f9dfc63d8..ffb08b8d07d 100644 --- a/apps/sim/tools/athena/get_named_query.ts +++ b/apps/sim/tools/athena/get_named_query.ts @@ -10,6 +10,7 @@ export const getNamedQueryTool: InternalToolConfig< name: 'Athena Get Named Query', description: 'Get details of a saved/named query in AWS Athena', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/athena/get_prepared_statement.ts b/apps/sim/tools/athena/get_prepared_statement.ts index 1109e73234e..c58d323f606 100644 --- a/apps/sim/tools/athena/get_prepared_statement.ts +++ b/apps/sim/tools/athena/get_prepared_statement.ts @@ -13,6 +13,7 @@ export const getPreparedStatementTool: InternalToolConfig< name: 'Athena Get Prepared Statement', description: 'Get the SQL and metadata of a prepared statement in an Athena workgroup', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/athena/get_query_execution.ts b/apps/sim/tools/athena/get_query_execution.ts index 0f77b63cc49..bc8890b8f72 100644 --- a/apps/sim/tools/athena/get_query_execution.ts +++ b/apps/sim/tools/athena/get_query_execution.ts @@ -13,6 +13,7 @@ export const getQueryExecutionTool: InternalToolConfig< name: 'Athena Get Query Execution', description: 'Get the status and details of an Athena query execution', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/athena/get_query_results.ts b/apps/sim/tools/athena/get_query_results.ts index e6dd1d41954..2a9ab515b2b 100644 --- a/apps/sim/tools/athena/get_query_results.ts +++ b/apps/sim/tools/athena/get_query_results.ts @@ -13,6 +13,7 @@ export const getQueryResultsTool: InternalToolConfig< name: 'Athena Get Query Results', description: 'Retrieve the results of a completed Athena query execution', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/athena/get_query_runtime_statistics.ts b/apps/sim/tools/athena/get_query_runtime_statistics.ts index 8330c1ecaca..c5c45067b98 100644 --- a/apps/sim/tools/athena/get_query_runtime_statistics.ts +++ b/apps/sim/tools/athena/get_query_runtime_statistics.ts @@ -14,6 +14,7 @@ export const getQueryRuntimeStatisticsTool: InternalToolConfig< description: 'Get runtime statistics (timeline, row counts, and output stage) for a completed Athena query execution', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/athena/get_table_metadata.ts b/apps/sim/tools/athena/get_table_metadata.ts index 69d1f185583..fa59e4952f8 100644 --- a/apps/sim/tools/athena/get_table_metadata.ts +++ b/apps/sim/tools/athena/get_table_metadata.ts @@ -14,6 +14,7 @@ export const getTableMetadataTool: InternalToolConfig< description: 'Get the columns, partition keys, and properties of a single table in an Athena data catalog database', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/athena/get_work_group.ts b/apps/sim/tools/athena/get_work_group.ts index ac8a7da0f64..2e7012614ce 100644 --- a/apps/sim/tools/athena/get_work_group.ts +++ b/apps/sim/tools/athena/get_work_group.ts @@ -11,6 +11,7 @@ export const getWorkGroupTool: InternalToolConfig< description: 'Get the configuration of an Athena workgroup, including its result location, encryption, and limits', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/athena/list_data_catalogs.ts b/apps/sim/tools/athena/list_data_catalogs.ts index 64697f17f36..29bd3eb89be 100644 --- a/apps/sim/tools/athena/list_data_catalogs.ts +++ b/apps/sim/tools/athena/list_data_catalogs.ts @@ -13,6 +13,7 @@ export const listDataCatalogsTool: InternalToolConfig< name: 'Athena List Data Catalogs', description: 'List the data catalogs (data sources) registered in the AWS account', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/athena/list_databases.ts b/apps/sim/tools/athena/list_databases.ts index e961fd516d0..7e09cc46ce9 100644 --- a/apps/sim/tools/athena/list_databases.ts +++ b/apps/sim/tools/athena/list_databases.ts @@ -10,6 +10,7 @@ export const listDatabasesTool: InternalToolConfig< name: 'Athena List Databases', description: 'List the databases available in an Athena data catalog', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/athena/list_named_queries.ts b/apps/sim/tools/athena/list_named_queries.ts index 2d650a8e3bd..82d70a7aea4 100644 --- a/apps/sim/tools/athena/list_named_queries.ts +++ b/apps/sim/tools/athena/list_named_queries.ts @@ -13,6 +13,7 @@ export const listNamedQueriesTool: InternalToolConfig< name: 'Athena List Named Queries', description: 'List saved/named query IDs in AWS Athena', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/athena/list_prepared_statements.ts b/apps/sim/tools/athena/list_prepared_statements.ts index 1d608c223f7..e0ab42a0662 100644 --- a/apps/sim/tools/athena/list_prepared_statements.ts +++ b/apps/sim/tools/athena/list_prepared_statements.ts @@ -13,6 +13,7 @@ export const listPreparedStatementsTool: InternalToolConfig< name: 'Athena List Prepared Statements', description: 'List the prepared statements saved in an Athena workgroup', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/athena/list_query_executions.ts b/apps/sim/tools/athena/list_query_executions.ts index 7cb75c61814..02abf27dd21 100644 --- a/apps/sim/tools/athena/list_query_executions.ts +++ b/apps/sim/tools/athena/list_query_executions.ts @@ -13,6 +13,7 @@ export const listQueryExecutionsTool: InternalToolConfig< name: 'Athena List Query Executions', description: 'List recent Athena query execution IDs', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/athena/list_table_metadata.ts b/apps/sim/tools/athena/list_table_metadata.ts index 9864838ae65..eac6bc081c9 100644 --- a/apps/sim/tools/athena/list_table_metadata.ts +++ b/apps/sim/tools/athena/list_table_metadata.ts @@ -13,6 +13,7 @@ export const listTableMetadataTool: InternalToolConfig< name: 'Athena List Table Metadata', description: 'List tables and their column/partition metadata for an Athena database', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/athena/list_work_groups.ts b/apps/sim/tools/athena/list_work_groups.ts index 985073c03d1..0e52704a3e3 100644 --- a/apps/sim/tools/athena/list_work_groups.ts +++ b/apps/sim/tools/athena/list_work_groups.ts @@ -10,6 +10,7 @@ export const listWorkGroupsTool: InternalToolConfig< name: 'Athena List Workgroups', description: 'List the Athena workgroups available in the AWS account', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/athena/start_query.ts b/apps/sim/tools/athena/start_query.ts index 7f76779e5f1..382f8a5da82 100644 --- a/apps/sim/tools/athena/start_query.ts +++ b/apps/sim/tools/athena/start_query.ts @@ -38,6 +38,7 @@ export const startQueryTool: InternalToolConfig = name: 'Azure DevOps Add Comment', description: 'Add a comment to a work item in Azure DevOps.', version: '1.0.0', + effect: 'write', oauth: AZURE_DEVOPS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/azure_devops/create_work_item.ts b/apps/sim/tools/azure_devops/create_work_item.ts index 113c64fcf1c..2ee3097b957 100644 --- a/apps/sim/tools/azure_devops/create_work_item.ts +++ b/apps/sim/tools/azure_devops/create_work_item.ts @@ -22,6 +22,7 @@ export const createWorkItemTool: ToolConfig description: 'Fetch the text content of a specific build log in Azure DevOps. Use List Build Logs first to get the log ID. Optionally retrieve only a line range with startLine/endLine.', version: '1.0.0', + effect: 'read', oauth: AZURE_DEVOPS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/azure_devops/get_build_timeline.ts b/apps/sim/tools/azure_devops/get_build_timeline.ts index 71d128e5e11..05c88c1f4ba 100644 --- a/apps/sim/tools/azure_devops/get_build_timeline.ts +++ b/apps/sim/tools/azure_devops/get_build_timeline.ts @@ -13,6 +13,7 @@ export const getBuildTimelineTool: ToolConfig name: 'Azure DevOps Get Comments', description: 'List comments for an Azure DevOps work item.', version: '1.0.0', + effect: 'read', oauth: AZURE_DEVOPS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/azure_devops/get_pipeline.ts b/apps/sim/tools/azure_devops/get_pipeline.ts index cebac855fbc..1ee111f28d8 100644 --- a/apps/sim/tools/azure_devops/get_pipeline.ts +++ b/apps/sim/tools/azure_devops/get_pipeline.ts @@ -10,6 +10,7 @@ export const getPipelineTool: ToolConfig description: 'Get details for a specific pipeline in an Azure DevOps project, including configuration and repository info.', version: '1.0.0', + effect: 'read', oauth: AZURE_DEVOPS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/azure_devops/get_pipeline_run.ts b/apps/sim/tools/azure_devops/get_pipeline_run.ts index dc33965825b..226b9cd3c5f 100644 --- a/apps/sim/tools/azure_devops/get_pipeline_run.ts +++ b/apps/sim/tools/azure_devops/get_pipeline_run.ts @@ -10,6 +10,7 @@ export const getPipelineRunTool: ToolConfig description: 'Fetch full details of a single work item by ID from Azure DevOps, including title, state, type, assignee, and area path.', version: '1.0.0', + effect: 'read', oauth: AZURE_DEVOPS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/azure_devops/get_work_items_batch.ts b/apps/sim/tools/azure_devops/get_work_items_batch.ts index 07e8ff1f74b..e89a38e6311 100644 --- a/apps/sim/tools/azure_devops/get_work_items_batch.ts +++ b/apps/sim/tools/azure_devops/get_work_items_batch.ts @@ -21,6 +21,7 @@ export const getWorkItemsBatchTool: ToolConfig = description: 'List builds in an Azure DevOps project. Optionally filter by pipeline definition, status, result, reason, requester, branch, or time range, and page with a continuation token.', version: '1.0.0', + effect: 'read', oauth: AZURE_DEVOPS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/azure_devops/list_pipeline_runs.ts b/apps/sim/tools/azure_devops/list_pipeline_runs.ts index c177c52eb63..a5d6629698a 100644 --- a/apps/sim/tools/azure_devops/list_pipeline_runs.ts +++ b/apps/sim/tools/azure_devops/list_pipeline_runs.ts @@ -10,6 +10,7 @@ export const listPipelineRunsTool: ToolConfig = name: 'Box Delete File', description: 'Delete a file from Box', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/box/delete_folder.ts b/apps/sim/tools/box/delete_folder.ts index 1319bf65e09..a862870af16 100644 --- a/apps/sim/tools/box/delete_folder.ts +++ b/apps/sim/tools/box/delete_folder.ts @@ -7,6 +7,7 @@ export const boxDeleteFolderTool: ToolConfig = { name: 'Box Search', description: 'Search for files and folders in Box', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/box/update_file.ts b/apps/sim/tools/box/update_file.ts index 027afb62563..264489dbab7 100644 --- a/apps/sim/tools/box/update_file.ts +++ b/apps/sim/tools/box/update_file.ts @@ -8,6 +8,7 @@ export const boxUpdateFileTool: ToolConfig name: 'Brex Get User', description: 'Get a Brex user by their ID', version: '1.0.0', + effect: 'read', oauth: BREX_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/brex/get_vendor.ts b/apps/sim/tools/brex/get_vendor.ts index ebde7d5efbc..7ac2534ae35 100644 --- a/apps/sim/tools/brex/get_vendor.ts +++ b/apps/sim/tools/brex/get_vendor.ts @@ -8,6 +8,7 @@ export const brexGetVendorTool: ToolConfig name: 'Checkr Get Geo', description: 'Retrieve a geo by ID.', version: '1.0.0', + effect: 'read', oauth: CHECKR_CREDENTIAL_OAUTH, errorExtractor: CHECKR_ERROR_EXTRACTOR, diff --git a/apps/sim/tools/checkr/get_invitation.ts b/apps/sim/tools/checkr/get_invitation.ts index 7c038f094c1..6aee9a2bc87 100644 --- a/apps/sim/tools/checkr/get_invitation.ts +++ b/apps/sim/tools/checkr/get_invitation.ts @@ -22,6 +22,7 @@ export const checkrGetInvitationTool: ToolConfig< name: 'Checkr Get Invitation', description: 'Retrieve an invitation by ID, including its status and invitation URL.', version: '1.0.0', + effect: 'read', oauth: CHECKR_CREDENTIAL_OAUTH, errorExtractor: CHECKR_ERROR_EXTRACTOR, diff --git a/apps/sim/tools/checkr/get_node.ts b/apps/sim/tools/checkr/get_node.ts index 13174f901f7..473579461e4 100644 --- a/apps/sim/tools/checkr/get_node.ts +++ b/apps/sim/tools/checkr/get_node.ts @@ -19,6 +19,7 @@ export const checkrGetNodeTool: ToolConfig = { name: 'Coda Delete Doc', description: 'Delete a Coda doc', version: '1.0.0', + effect: 'write', oauth: codaOAuth, errorExtractor: ErrorExtractorId.CODA_ERRORS, diff --git a/apps/sim/tools/coda/delete_folder.ts b/apps/sim/tools/coda/delete_folder.ts index 20eb2bc6e20..86f6e710367 100644 --- a/apps/sim/tools/coda/delete_folder.ts +++ b/apps/sim/tools/coda/delete_folder.ts @@ -16,6 +16,7 @@ export const codaDeleteFolderTool: ToolConfig = { description: 'Get metadata for a Coda doc, including its owner, workspace, folder, size, and publishing settings', version: '1.0.0', + effect: 'read', oauth: codaOAuth, errorExtractor: ErrorExtractorId.CODA_ERRORS, diff --git a/apps/sim/tools/coda/get_doc_analytics_summary.ts b/apps/sim/tools/coda/get_doc_analytics_summary.ts index 82543342c68..1ed3dbfe8cf 100644 --- a/apps/sim/tools/coda/get_doc_analytics_summary.ts +++ b/apps/sim/tools/coda/get_doc_analytics_summary.ts @@ -21,6 +21,7 @@ export const codaGetDocAnalyticsSummaryTool: ToolConfig< name: 'Coda Get Doc Analytics Summary', description: 'Get the total number of sessions across the Coda docs the user can access', version: '1.0.0', + effect: 'read', oauth: codaOAuth, errorExtractor: ErrorExtractorId.CODA_ERRORS, diff --git a/apps/sim/tools/coda/get_folder.ts b/apps/sim/tools/coda/get_folder.ts index 7a3db5aace6..55d98f8c37b 100644 --- a/apps/sim/tools/coda/get_folder.ts +++ b/apps/sim/tools/coda/get_folder.ts @@ -19,6 +19,7 @@ export const codaGetFolderTool: ToolConfig name: 'Coda Get Folder', description: 'Get details about a Coda folder', version: '1.0.0', + effect: 'read', oauth: codaOAuth, errorExtractor: ErrorExtractorId.CODA_ERRORS, diff --git a/apps/sim/tools/coda/get_formula.ts b/apps/sim/tools/coda/get_formula.ts index 3f66c9fc83c..0993f37b8dd 100644 --- a/apps/sim/tools/coda/get_formula.ts +++ b/apps/sim/tools/coda/get_formula.ts @@ -19,6 +19,7 @@ export const codaGetFormulaTool: ToolConfig = { name: 'Coda Get Page', description: 'Get metadata for a page in a Coda doc', version: '1.0.0', + effect: 'read', oauth: codaOAuth, errorExtractor: ErrorExtractorId.CODA_ERRORS, diff --git a/apps/sim/tools/coda/get_page_content.ts b/apps/sim/tools/coda/get_page_content.ts index 686fe4cf034..24820b014b2 100644 --- a/apps/sim/tools/coda/get_page_content.ts +++ b/apps/sim/tools/coda/get_page_content.ts @@ -34,6 +34,7 @@ export const codaGetPageContentTool: ToolConfig< description: 'Read the content of a Coda canvas page as plain-text lines with their styles (headings, paragraphs, lists, quotes, code) and element IDs', version: '1.0.0', + effect: 'read', oauth: codaOAuth, errorExtractor: ErrorExtractorId.CODA_ERRORS, diff --git a/apps/sim/tools/coda/get_page_export_status.ts b/apps/sim/tools/coda/get_page_export_status.ts index c218548e512..55cbede30ca 100644 --- a/apps/sim/tools/coda/get_page_export_status.ts +++ b/apps/sim/tools/coda/get_page_export_status.ts @@ -24,6 +24,7 @@ export const codaGetPageExportStatusTool: ToolConfig< description: 'Check a Coda page export and get its download link once complete. Download links expire shortly after they are issued.', version: '1.0.0', + effect: 'read', oauth: codaOAuth, errorExtractor: ErrorExtractorId.CODA_ERRORS, diff --git a/apps/sim/tools/coda/get_row.ts b/apps/sim/tools/coda/get_row.ts index 750230327e0..c9fd477ba58 100644 --- a/apps/sim/tools/coda/get_row.ts +++ b/apps/sim/tools/coda/get_row.ts @@ -21,6 +21,7 @@ export const codaGetRowTool: ToolConfig = { name: 'Coda Get Row', description: 'Get a single row from a Coda table, including all of its cell values', version: '1.0.0', + effect: 'read', oauth: codaOAuth, errorExtractor: ErrorExtractorId.CODA_ERRORS, diff --git a/apps/sim/tools/coda/get_sharing_metadata.ts b/apps/sim/tools/coda/get_sharing_metadata.ts index f4722b22cf3..c91b1e0726b 100644 --- a/apps/sim/tools/coda/get_sharing_metadata.ts +++ b/apps/sim/tools/coda/get_sharing_metadata.ts @@ -17,6 +17,7 @@ export const codaGetSharingMetadataTool: ToolConfig description: 'Get details about a table or view in a Coda doc, including its row count, sorts, layout, and filter', version: '1.0.0', + effect: 'read', oauth: codaOAuth, errorExtractor: ErrorExtractorId.CODA_ERRORS, diff --git a/apps/sim/tools/coda/list_categories.ts b/apps/sim/tools/coda/list_categories.ts index 21d1cd8e960..e926ba72d54 100644 --- a/apps/sim/tools/coda/list_categories.ts +++ b/apps/sim/tools/coda/list_categories.ts @@ -14,6 +14,7 @@ export const codaListCategoriesTool: ToolConfig = { id: 'coda_list_columns', - assistant: { effect: 'read', version: 1 }, + assistant: { version: 1 }, name: 'Coda List Columns', description: 'List the columns of a Coda table with their IDs, formats, and formulas. Use column IDs when reading and writing rows.', version: '1.0.0', + effect: 'read', oauth: codaOAuth, errorExtractor: ErrorExtractorId.CODA_ERRORS, diff --git a/apps/sim/tools/coda/list_controls.ts b/apps/sim/tools/coda/list_controls.ts index 7daa3d63410..246bfa78d5e 100644 --- a/apps/sim/tools/coda/list_controls.ts +++ b/apps/sim/tools/coda/list_controls.ts @@ -25,6 +25,7 @@ export const codaListControlsTool: ToolConfig = { id: 'coda_list_pages', - assistant: { effect: 'read', version: 1 }, + assistant: { version: 1 }, name: 'Coda List Pages', description: 'List the pages in a Coda doc, including their hierarchy', version: '1.0.0', + effect: 'read', oauth: codaOAuth, errorExtractor: ErrorExtractorId.CODA_ERRORS, diff --git a/apps/sim/tools/coda/list_permissions.ts b/apps/sim/tools/coda/list_permissions.ts index 8329573c7b3..54fabcd4af8 100644 --- a/apps/sim/tools/coda/list_permissions.ts +++ b/apps/sim/tools/coda/list_permissions.ts @@ -26,6 +26,7 @@ export const codaListPermissionsTool: ToolConfig< name: 'Coda List Permissions', description: 'List who a Coda doc is shared with and their access levels', version: '1.0.0', + effect: 'read', oauth: codaOAuth, errorExtractor: ErrorExtractorId.CODA_ERRORS, diff --git a/apps/sim/tools/coda/list_rows.ts b/apps/sim/tools/coda/list_rows.ts index d86f849ebba..41fca4a73d2 100644 --- a/apps/sim/tools/coda/list_rows.ts +++ b/apps/sim/tools/coda/list_rows.ts @@ -21,11 +21,12 @@ import type { ToolConfig } from '@/tools/types' export const codaListRowsTool: ToolConfig = { id: 'coda_list_rows', - assistant: { effect: 'read', version: 1 }, + assistant: { version: 1 }, name: 'Coda List Rows', description: 'List rows in a Coda table or view, optionally filtered by a column value, sorted, or limited to rows changed since a sync token', version: '1.0.0', + effect: 'read', oauth: codaOAuth, errorExtractor: ErrorExtractorId.CODA_ERRORS, diff --git a/apps/sim/tools/coda/list_tables.ts b/apps/sim/tools/coda/list_tables.ts index f8204137e18..6735e8bcdee 100644 --- a/apps/sim/tools/coda/list_tables.ts +++ b/apps/sim/tools/coda/list_tables.ts @@ -22,10 +22,11 @@ import type { ToolConfig } from '@/tools/types' export const codaListTablesTool: ToolConfig = { id: 'coda_list_tables', - assistant: { effect: 'read', version: 1 }, + assistant: { version: 1 }, name: 'Coda List Tables', description: 'List the tables and views in a Coda doc', version: '1.0.0', + effect: 'read', oauth: codaOAuth, errorExtractor: ErrorExtractorId.CODA_ERRORS, diff --git a/apps/sim/tools/coda/list_workspace_members.ts b/apps/sim/tools/coda/list_workspace_members.ts index 8b7d8eb9468..2218c6a6327 100644 --- a/apps/sim/tools/coda/list_workspace_members.ts +++ b/apps/sim/tools/coda/list_workspace_members.ts @@ -35,6 +35,7 @@ export const codaListWorkspaceMembersTool: ToolConfig< description: 'List the members of a Coda workspace with their roles and doc activity, requesting user first. The workspace must belong to an organization.', version: '1.0.0', + effect: 'read', oauth: codaOAuth, errorExtractor: ErrorExtractorId.CODA_ERRORS, diff --git a/apps/sim/tools/coda/list_workspace_roles.ts b/apps/sim/tools/coda/list_workspace_roles.ts index e0e3a5ec204..e4097edecfc 100644 --- a/apps/sim/tools/coda/list_workspace_roles.ts +++ b/apps/sim/tools/coda/list_workspace_roles.ts @@ -24,6 +24,7 @@ export const codaListWorkspaceRolesTool: ToolConfig< description: 'Get monthly counts of active and inactive Admins, Doc Makers, and Editors in a workspace. The workspace must belong to an organization.', version: '1.0.0', + effect: 'read', oauth: codaOAuth, errorExtractor: ErrorExtractorId.CODA_ERRORS, diff --git a/apps/sim/tools/coda/publish_doc.ts b/apps/sim/tools/coda/publish_doc.ts index 07ac562099a..d78ba5c63d4 100644 --- a/apps/sim/tools/coda/publish_doc.ts +++ b/apps/sim/tools/coda/publish_doc.ts @@ -20,6 +20,7 @@ export const codaPublishDocTool: ToolConfig = { id: 'coda_resolve_browser_link', - assistant: { effect: 'read', version: 1 }, + assistant: { version: 1 }, name: 'Coda Resolve Browser Link', description: 'Resolve a Coda browser URL (doc, page, table, row, etc.) into its resource type and ID for use in other Coda operations', version: '1.0.0', + effect: 'read', oauth: codaOAuth, errorExtractor: ErrorExtractorId.CODA_ERRORS, diff --git a/apps/sim/tools/coda/search_principals.ts b/apps/sim/tools/coda/search_principals.ts index ec1153eb59e..7abcd255712 100644 --- a/apps/sim/tools/coda/search_principals.ts +++ b/apps/sim/tools/coda/search_principals.ts @@ -26,6 +26,7 @@ export const codaSearchPrincipalsTool: ToolConfig< description: 'Search for users and groups a Coda doc can be shared with (up to 20 of each). Returns nothing without a query.', version: '1.0.0', + effect: 'read', oauth: codaOAuth, errorExtractor: ErrorExtractorId.CODA_ERRORS, diff --git a/apps/sim/tools/coda/trigger_automation.ts b/apps/sim/tools/coda/trigger_automation.ts index 664d0713d66..b503a59d5fc 100644 --- a/apps/sim/tools/coda/trigger_automation.ts +++ b/apps/sim/tools/coda/trigger_automation.ts @@ -22,6 +22,7 @@ export const codaTriggerAutomationTool: ToolConfig< description: 'Trigger a webhook-invoked automation in a Coda doc, optionally passing a JSON payload the automation can read', version: '1.0.0', + effect: 'write', oauth: codaOAuth, errorExtractor: ErrorExtractorId.CODA_ERRORS, diff --git a/apps/sim/tools/coda/unpublish_doc.ts b/apps/sim/tools/coda/unpublish_doc.ts index 6527b3bc374..001b880defe 100644 --- a/apps/sim/tools/coda/unpublish_doc.ts +++ b/apps/sim/tools/coda/unpublish_doc.ts @@ -16,6 +16,7 @@ export const codaUnpublishDocTool: ToolConfig name: 'Coda Unpublish Doc', description: 'Unpublish a Coda doc', version: '1.0.0', + effect: 'write', oauth: codaOAuth, errorExtractor: ErrorExtractorId.CODA_ERRORS, diff --git a/apps/sim/tools/coda/update_acl_settings.ts b/apps/sim/tools/coda/update_acl_settings.ts index 17bb1a782e7..25c61488a98 100644 --- a/apps/sim/tools/coda/update_acl_settings.ts +++ b/apps/sim/tools/coda/update_acl_settings.ts @@ -25,6 +25,7 @@ export const codaUpdateAclSettingsTool: ToolConfig = { name: 'Coda Get Current User', description: 'Get the user and default workspace behind the connected Coda API token', version: '1.0.0', + effect: 'read', oauth: codaOAuth, errorExtractor: ErrorExtractorId.CODA_ERRORS, diff --git a/apps/sim/tools/codepipeline/disable_stage_transition.ts b/apps/sim/tools/codepipeline/disable_stage_transition.ts index c00b26232b9..718bcab7cff 100644 --- a/apps/sim/tools/codepipeline/disable_stage_transition.ts +++ b/apps/sim/tools/codepipeline/disable_stage_transition.ts @@ -14,6 +14,7 @@ export const disableStageTransitionTool: InternalToolConfig< description: 'Prevent artifacts from transitioning into or out of a CodePipeline stage, freezing the pipeline at that point', version: '1.0.0', + effect: 'write', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/codepipeline/enable_stage_transition.ts b/apps/sim/tools/codepipeline/enable_stage_transition.ts index c62aa1f1ecc..afb565883b5 100644 --- a/apps/sim/tools/codepipeline/enable_stage_transition.ts +++ b/apps/sim/tools/codepipeline/enable_stage_transition.ts @@ -14,6 +14,7 @@ export const enableStageTransitionTool: InternalToolConfig< description: 'Re-enable artifacts transitioning into or out of a CodePipeline stage after it was disabled', version: '1.0.0', + effect: 'write', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/codepipeline/get_pipeline.ts b/apps/sim/tools/codepipeline/get_pipeline.ts index cf019684cc0..6f624d13ff5 100644 --- a/apps/sim/tools/codepipeline/get_pipeline.ts +++ b/apps/sim/tools/codepipeline/get_pipeline.ts @@ -14,6 +14,7 @@ export const getPipelineTool: InternalToolConfig< description: 'Get the structure of a CodePipeline pipeline, including its stages, actions, and variables', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/codepipeline/get_pipeline_execution.ts b/apps/sim/tools/codepipeline/get_pipeline_execution.ts index 2b5d6d94ac1..40ea0d5fa53 100644 --- a/apps/sim/tools/codepipeline/get_pipeline_execution.ts +++ b/apps/sim/tools/codepipeline/get_pipeline_execution.ts @@ -14,6 +14,7 @@ export const getPipelineExecutionTool: InternalToolConfig< description: 'Get details of a CodePipeline execution, including status, trigger, source revisions, and resolved variables', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/codepipeline/get_pipeline_state.ts b/apps/sim/tools/codepipeline/get_pipeline_state.ts index 38b37198c78..58355a265d0 100644 --- a/apps/sim/tools/codepipeline/get_pipeline_state.ts +++ b/apps/sim/tools/codepipeline/get_pipeline_state.ts @@ -14,6 +14,7 @@ export const getPipelineStateTool: InternalToolConfig< description: 'Get the current state of a CodePipeline pipeline, including stage and action status and pending approval tokens', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/codepipeline/list_action_executions.ts b/apps/sim/tools/codepipeline/list_action_executions.ts index e7deca406f5..75a1fe266f2 100644 --- a/apps/sim/tools/codepipeline/list_action_executions.ts +++ b/apps/sim/tools/codepipeline/list_action_executions.ts @@ -14,6 +14,7 @@ export const listActionExecutionsTool: InternalToolConfig< description: 'List action-level execution history for a CodePipeline pipeline, including per-action status, timing, and error details', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/codepipeline/list_pipeline_executions.ts b/apps/sim/tools/codepipeline/list_pipeline_executions.ts index ac5630cd91d..c103de36043 100644 --- a/apps/sim/tools/codepipeline/list_pipeline_executions.ts +++ b/apps/sim/tools/codepipeline/list_pipeline_executions.ts @@ -13,6 +13,7 @@ export const listPipelineExecutionsTool: InternalToolConfig< name: 'CodePipeline List Pipeline Executions', description: 'List recent executions of a CodePipeline pipeline with status and source revisions', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/codepipeline/list_pipelines.ts b/apps/sim/tools/codepipeline/list_pipelines.ts index 5cb2336679e..6badc0e5e68 100644 --- a/apps/sim/tools/codepipeline/list_pipelines.ts +++ b/apps/sim/tools/codepipeline/list_pipelines.ts @@ -13,6 +13,7 @@ export const listPipelinesTool: InternalToolConfig< name: 'CodePipeline List Pipelines', description: 'List all CodePipeline pipelines in an AWS account and region', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/codepipeline/put_approval_result.ts b/apps/sim/tools/codepipeline/put_approval_result.ts index e7a39539c94..5c921141eb7 100644 --- a/apps/sim/tools/codepipeline/put_approval_result.ts +++ b/apps/sim/tools/codepipeline/put_approval_result.ts @@ -14,6 +14,7 @@ export const putApprovalResultTool: InternalToolConfig< description: 'Approve or reject a pending CodePipeline manual approval action. The approval token is available from Get Pipeline State on the pending approval action', version: '1.0.0', + effect: 'write', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/codepipeline/retry_stage_execution.ts b/apps/sim/tools/codepipeline/retry_stage_execution.ts index afdf1cf5cdc..bf3767e4d5e 100644 --- a/apps/sim/tools/codepipeline/retry_stage_execution.ts +++ b/apps/sim/tools/codepipeline/retry_stage_execution.ts @@ -13,6 +13,7 @@ export const retryStageExecutionTool: InternalToolConfig< name: 'CodePipeline Retry Stage Execution', description: 'Retry the failed actions (or all actions) of a failed CodePipeline stage', version: '1.0.0', + effect: 'write', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/codepipeline/start_execution.ts b/apps/sim/tools/codepipeline/start_execution.ts index 69f9a6db29c..a7931219a82 100644 --- a/apps/sim/tools/codepipeline/start_execution.ts +++ b/apps/sim/tools/codepipeline/start_execution.ts @@ -13,6 +13,7 @@ export const startExecutionTool: InternalToolConfig< name: 'CodePipeline Start Execution', description: 'Start a CodePipeline pipeline execution, optionally overriding pipeline variables', version: '1.0.0', + effect: 'write', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/codepipeline/stop_execution.ts b/apps/sim/tools/codepipeline/stop_execution.ts index 9aa65154886..d14bec64a68 100644 --- a/apps/sim/tools/codepipeline/stop_execution.ts +++ b/apps/sim/tools/codepipeline/stop_execution.ts @@ -14,6 +14,7 @@ export const stopExecutionTool: InternalToolConfig< description: 'Stop a CodePipeline pipeline execution, either finishing in-progress actions or abandoning them', version: '1.0.0', + effect: 'write', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/confluence/add_label.ts b/apps/sim/tools/confluence/add_label.ts index c50177860ce..a77cd8c3690 100644 --- a/apps/sim/tools/confluence/add_label.ts +++ b/apps/sim/tools/confluence/add_label.ts @@ -28,6 +28,7 @@ export const confluenceAddLabelTool: InternalToolConfig< name: 'Confluence Add Label', description: 'Add a label to a Confluence page for organization and categorization.', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/confluence/create_blogpost.ts b/apps/sim/tools/confluence/create_blogpost.ts index e1912d7d975..ef53e6c975f 100644 --- a/apps/sim/tools/confluence/create_blogpost.ts +++ b/apps/sim/tools/confluence/create_blogpost.ts @@ -38,6 +38,7 @@ export const confluenceCreateBlogPostTool: InternalToolConfig< name: 'Confluence Create Blog Post', description: 'Create a new blog post in a Confluence space.', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/confluence/create_comment.ts b/apps/sim/tools/confluence/create_comment.ts index 1232f6c045f..64b88c1de26 100644 --- a/apps/sim/tools/confluence/create_comment.ts +++ b/apps/sim/tools/confluence/create_comment.ts @@ -31,6 +31,7 @@ export const confluenceCreateCommentTool: InternalToolConfig< name: 'Confluence Create Comment', description: 'Add a comment to a Confluence page.', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/confluence/create_page.ts b/apps/sim/tools/confluence/create_page.ts index a4c68c090cf..a67b4cc95c0 100644 --- a/apps/sim/tools/confluence/create_page.ts +++ b/apps/sim/tools/confluence/create_page.ts @@ -34,6 +34,7 @@ export const confluenceCreatePageTool: InternalToolConfig< name: 'Confluence Create Page', description: 'Create a new page in a Confluence space.', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/confluence/create_page_property.ts b/apps/sim/tools/confluence/create_page_property.ts index e26e8e22452..ad1e25c741f 100644 --- a/apps/sim/tools/confluence/create_page_property.ts +++ b/apps/sim/tools/confluence/create_page_property.ts @@ -32,6 +32,7 @@ export const confluenceCreatePagePropertyTool: InternalToolConfig< name: 'Confluence Create Page Property', description: 'Create a new custom property (metadata) on a Confluence page.', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/confluence/create_space.ts b/apps/sim/tools/confluence/create_space.ts index 2c5fd0a6a79..125222b68c3 100644 --- a/apps/sim/tools/confluence/create_space.ts +++ b/apps/sim/tools/confluence/create_space.ts @@ -33,6 +33,7 @@ export const confluenceCreateSpaceTool: InternalToolConfig< name: 'Confluence Create Space', description: 'Create a new Confluence space.', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/confluence/create_space_property.ts b/apps/sim/tools/confluence/create_space_property.ts index 0898519effc..006ae396c2a 100644 --- a/apps/sim/tools/confluence/create_space_property.ts +++ b/apps/sim/tools/confluence/create_space_property.ts @@ -29,6 +29,7 @@ export const confluenceCreateSpacePropertyTool: InternalToolConfig< name: 'Confluence Create Space Property', description: 'Create a property on a Confluence space.', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/confluence/delete_attachment.ts b/apps/sim/tools/confluence/delete_attachment.ts index 849216c3d8e..f0fe624c7e8 100644 --- a/apps/sim/tools/confluence/delete_attachment.ts +++ b/apps/sim/tools/confluence/delete_attachment.ts @@ -24,6 +24,7 @@ export const confluenceDeleteAttachmentTool: InternalToolConfig< name: 'Confluence Delete Attachment', description: 'Delete an attachment from a Confluence page (moves to trash).', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/confluence/delete_blogpost.ts b/apps/sim/tools/confluence/delete_blogpost.ts index a0afa10476e..9557752c033 100644 --- a/apps/sim/tools/confluence/delete_blogpost.ts +++ b/apps/sim/tools/confluence/delete_blogpost.ts @@ -25,6 +25,7 @@ export const confluenceDeleteBlogPostTool: InternalToolConfig< name: 'Confluence Delete Blog Post', description: 'Delete a Confluence blog post.', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/confluence/delete_comment.ts b/apps/sim/tools/confluence/delete_comment.ts index e2ade8a2ce8..a0d95e6d0d9 100644 --- a/apps/sim/tools/confluence/delete_comment.ts +++ b/apps/sim/tools/confluence/delete_comment.ts @@ -24,6 +24,7 @@ export const confluenceDeleteCommentTool: InternalToolConfig< name: 'Confluence Delete Comment', description: 'Delete a comment from a Confluence page.', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/confluence/delete_label.ts b/apps/sim/tools/confluence/delete_label.ts index eb344886890..4256f416bf8 100644 --- a/apps/sim/tools/confluence/delete_label.ts +++ b/apps/sim/tools/confluence/delete_label.ts @@ -27,6 +27,7 @@ export const confluenceDeleteLabelTool: InternalToolConfig< name: 'Confluence Delete Label', description: 'Remove a label from a Confluence page.', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/confluence/delete_page.ts b/apps/sim/tools/confluence/delete_page.ts index c8440a3553a..3e2418e9c03 100644 --- a/apps/sim/tools/confluence/delete_page.ts +++ b/apps/sim/tools/confluence/delete_page.ts @@ -26,6 +26,7 @@ export const confluenceDeletePageTool: InternalToolConfig< description: 'Delete a Confluence page. By default moves to trash; use purge=true to permanently delete.', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/confluence/delete_page_property.ts b/apps/sim/tools/confluence/delete_page_property.ts index f50c61ee08d..a9e0826a572 100644 --- a/apps/sim/tools/confluence/delete_page_property.ts +++ b/apps/sim/tools/confluence/delete_page_property.ts @@ -27,6 +27,7 @@ export const confluenceDeletePagePropertyTool: InternalToolConfig< name: 'Confluence Delete Page Property', description: 'Delete a content property from a Confluence page by its property ID.', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/confluence/delete_space.ts b/apps/sim/tools/confluence/delete_space.ts index 999880e621f..06162b0ae93 100644 --- a/apps/sim/tools/confluence/delete_space.ts +++ b/apps/sim/tools/confluence/delete_space.ts @@ -27,6 +27,7 @@ export const confluenceDeleteSpaceTool: InternalToolConfig< name: 'Confluence Delete Space', description: 'Delete a Confluence space.', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/confluence/delete_space_property.ts b/apps/sim/tools/confluence/delete_space_property.ts index cc5e59a880b..13de355bd1a 100644 --- a/apps/sim/tools/confluence/delete_space_property.ts +++ b/apps/sim/tools/confluence/delete_space_property.ts @@ -27,6 +27,7 @@ export const confluenceDeleteSpacePropertyTool: InternalToolConfig< name: 'Confluence Delete Space Property', description: 'Delete a property from a Confluence space.', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/confluence/get_blogpost.ts b/apps/sim/tools/confluence/get_blogpost.ts index e9bd90984a0..dfa9426db1e 100644 --- a/apps/sim/tools/confluence/get_blogpost.ts +++ b/apps/sim/tools/confluence/get_blogpost.ts @@ -45,6 +45,7 @@ export const confluenceGetBlogPostTool: InternalToolConfig< name: 'Confluence Get Blog Post', description: 'Get a specific Confluence blog post by ID, including its content.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/get_page_ancestors.ts b/apps/sim/tools/confluence/get_page_ancestors.ts index 17419caa353..ec6727f0454 100644 --- a/apps/sim/tools/confluence/get_page_ancestors.ts +++ b/apps/sim/tools/confluence/get_page_ancestors.ts @@ -29,11 +29,12 @@ export const confluenceGetPageAncestorsTool: InternalToolConfig< ConfluenceGetPageAncestorsResponse > = { id: 'confluence_get_page_ancestors', - assistant: { effect: 'read', version: 1 }, + assistant: { version: 1 }, name: 'Confluence Get Page Ancestors', description: 'Get the ancestor (parent) pages of a specific Confluence page. Returns the full hierarchy from the page up to the root.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/get_page_children.ts b/apps/sim/tools/confluence/get_page_children.ts index a3b7007f00e..3bc55f3a49f 100644 --- a/apps/sim/tools/confluence/get_page_children.ts +++ b/apps/sim/tools/confluence/get_page_children.ts @@ -32,11 +32,12 @@ export const confluenceGetPageChildrenTool: InternalToolConfig< ConfluenceGetPageChildrenResponse > = { id: 'confluence_get_page_children', - assistant: { effect: 'read', version: 1 }, + assistant: { version: 1 }, name: 'Confluence Get Page Children', description: 'Get all child pages of a specific Confluence page. Useful for navigating page hierarchies.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/get_page_descendants.ts b/apps/sim/tools/confluence/get_page_descendants.ts index 86f8754cd04..3509353966f 100644 --- a/apps/sim/tools/confluence/get_page_descendants.ts +++ b/apps/sim/tools/confluence/get_page_descendants.ts @@ -37,6 +37,7 @@ export const confluenceGetPageDescendantsTool: InternalToolConfig< name: 'Confluence Get Page Descendants', description: 'Get all descendants of a Confluence page recursively.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/get_page_version.ts b/apps/sim/tools/confluence/get_page_version.ts index ec8c505d825..cd165bee8fc 100644 --- a/apps/sim/tools/confluence/get_page_version.ts +++ b/apps/sim/tools/confluence/get_page_version.ts @@ -48,6 +48,7 @@ export const confluenceGetPageVersionTool: InternalToolConfig< name: 'Confluence Get Page Version', description: 'Get details about a specific version of a Confluence page.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/get_pages_by_label.ts b/apps/sim/tools/confluence/get_pages_by_label.ts index e6206938364..e5d2e7f171a 100644 --- a/apps/sim/tools/confluence/get_pages_by_label.ts +++ b/apps/sim/tools/confluence/get_pages_by_label.ts @@ -41,6 +41,7 @@ export const confluenceGetPagesByLabelTool: InternalToolConfig< name: 'Confluence Get Pages by Label', description: 'Retrieve all pages that have a specific label applied.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/get_space.ts b/apps/sim/tools/confluence/get_space.ts index 651c29e52ee..18000927c72 100644 --- a/apps/sim/tools/confluence/get_space.ts +++ b/apps/sim/tools/confluence/get_space.ts @@ -37,6 +37,7 @@ export const confluenceGetSpaceTool: InternalToolConfig< name: 'Confluence Get Space', description: 'Get details about a specific Confluence space.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/get_task.ts b/apps/sim/tools/confluence/get_task.ts index 376743cdd7d..7f9afe3f19b 100644 --- a/apps/sim/tools/confluence/get_task.ts +++ b/apps/sim/tools/confluence/get_task.ts @@ -37,6 +37,7 @@ export const confluenceGetTaskTool: InternalToolConfig< name: 'Confluence Get Task', description: 'Get a specific Confluence inline task by ID.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/get_user.ts b/apps/sim/tools/confluence/get_user.ts index 66d55e11e02..b017e8b88c2 100644 --- a/apps/sim/tools/confluence/get_user.ts +++ b/apps/sim/tools/confluence/get_user.ts @@ -26,10 +26,11 @@ export const confluenceGetUserTool: InternalToolConfig< ConfluenceGetUserResponse > = { id: 'confluence_get_user', - assistant: { effect: 'read', version: 1 }, + assistant: { version: 1 }, name: 'Confluence Get User', description: 'Get display name and profile info for a Confluence user by account ID.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/list_attachments.ts b/apps/sim/tools/confluence/list_attachments.ts index 83b4e6e0446..3d00101fb26 100644 --- a/apps/sim/tools/confluence/list_attachments.ts +++ b/apps/sim/tools/confluence/list_attachments.ts @@ -33,6 +33,7 @@ export const confluenceListAttachmentsTool: InternalToolConfig< name: 'Confluence List Attachments', description: 'List all attachments on a Confluence page.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/list_blogposts.ts b/apps/sim/tools/confluence/list_blogposts.ts index 9fe92ab4e65..8c77d0259a8 100644 --- a/apps/sim/tools/confluence/list_blogposts.ts +++ b/apps/sim/tools/confluence/list_blogposts.ts @@ -41,6 +41,7 @@ export const confluenceListBlogPostsTool: InternalToolConfig< name: 'Confluence List Blog Posts', description: 'List all blog posts across all accessible Confluence spaces.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/list_blogposts_in_space.ts b/apps/sim/tools/confluence/list_blogposts_in_space.ts index 4b6d1fc73e0..e496c0f1653 100644 --- a/apps/sim/tools/confluence/list_blogposts_in_space.ts +++ b/apps/sim/tools/confluence/list_blogposts_in_space.ts @@ -49,6 +49,7 @@ export const confluenceListBlogPostsInSpaceTool: InternalToolConfig< name: 'Confluence List Blog Posts in Space', description: 'List all blog posts within a specific Confluence space.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/list_comments.ts b/apps/sim/tools/confluence/list_comments.ts index ef818be4127..51f1474c8bc 100644 --- a/apps/sim/tools/confluence/list_comments.ts +++ b/apps/sim/tools/confluence/list_comments.ts @@ -31,10 +31,11 @@ export const confluenceListCommentsTool: InternalToolConfig< ConfluenceListCommentsResponse > = { id: 'confluence_list_comments', - assistant: { effect: 'read', version: 1 }, + assistant: { version: 1 }, name: 'Confluence List Comments', description: 'List all comments on a Confluence page.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/list_labels.ts b/apps/sim/tools/confluence/list_labels.ts index 99a94dae98a..6beddcb5d1c 100644 --- a/apps/sim/tools/confluence/list_labels.ts +++ b/apps/sim/tools/confluence/list_labels.ts @@ -31,6 +31,7 @@ export const confluenceListLabelsTool: InternalToolConfig< name: 'Confluence List Labels', description: 'List all labels on a Confluence page.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/list_page_properties.ts b/apps/sim/tools/confluence/list_page_properties.ts index 52c5e40b99e..eabd52127af 100644 --- a/apps/sim/tools/confluence/list_page_properties.ts +++ b/apps/sim/tools/confluence/list_page_properties.ts @@ -37,6 +37,7 @@ export const confluenceListPagePropertiesTool: InternalToolConfig< name: 'Confluence List Page Properties', description: 'List all custom properties (metadata) attached to a Confluence page.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/list_page_versions.ts b/apps/sim/tools/confluence/list_page_versions.ts index 49e49461d17..aef8cb956be 100644 --- a/apps/sim/tools/confluence/list_page_versions.ts +++ b/apps/sim/tools/confluence/list_page_versions.ts @@ -34,6 +34,7 @@ export const confluenceListPageVersionsTool: InternalToolConfig< name: 'Confluence List Page Versions', description: 'List all versions (revision history) of a Confluence page.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/list_pages_in_space.ts b/apps/sim/tools/confluence/list_pages_in_space.ts index d480cc1dd1e..5b5b996e9ef 100644 --- a/apps/sim/tools/confluence/list_pages_in_space.ts +++ b/apps/sim/tools/confluence/list_pages_in_space.ts @@ -51,6 +51,7 @@ export const confluenceListPagesInSpaceTool: InternalToolConfig< description: 'List all pages within a specific Confluence space. Supports pagination and filtering by status.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/list_space_labels.ts b/apps/sim/tools/confluence/list_space_labels.ts index bb896ff19e3..267b878615c 100644 --- a/apps/sim/tools/confluence/list_space_labels.ts +++ b/apps/sim/tools/confluence/list_space_labels.ts @@ -32,6 +32,7 @@ export const confluenceListSpaceLabelsTool: InternalToolConfig< name: 'Confluence List Space Labels', description: 'List all labels associated with a Confluence space.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/list_space_permissions.ts b/apps/sim/tools/confluence/list_space_permissions.ts index 50111acb16c..8616e56d8f9 100644 --- a/apps/sim/tools/confluence/list_space_permissions.ts +++ b/apps/sim/tools/confluence/list_space_permissions.ts @@ -36,6 +36,7 @@ export const confluenceListSpacePermissionsTool: InternalToolConfig< name: 'Confluence List Space Permissions', description: 'List permissions for a Confluence space.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/list_space_properties.ts b/apps/sim/tools/confluence/list_space_properties.ts index 44a45cbf53d..bcf65112ce2 100644 --- a/apps/sim/tools/confluence/list_space_properties.ts +++ b/apps/sim/tools/confluence/list_space_properties.ts @@ -32,6 +32,7 @@ export const confluenceListSpacePropertiesTool: InternalToolConfig< name: 'Confluence List Space Properties', description: 'List properties on a Confluence space.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/list_spaces.ts b/apps/sim/tools/confluence/list_spaces.ts index 1713db7c67a..e42a09e6752 100644 --- a/apps/sim/tools/confluence/list_spaces.ts +++ b/apps/sim/tools/confluence/list_spaces.ts @@ -29,10 +29,11 @@ export const confluenceListSpacesTool: InternalToolConfig< ConfluenceListSpacesResponse > = { id: 'confluence_list_spaces', - assistant: { effect: 'read', version: 1 }, + assistant: { version: 1 }, name: 'Confluence List Spaces', description: 'List all Confluence spaces accessible to the user.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/list_tasks.ts b/apps/sim/tools/confluence/list_tasks.ts index 1449a587a53..89e923342b4 100644 --- a/apps/sim/tools/confluence/list_tasks.ts +++ b/apps/sim/tools/confluence/list_tasks.ts @@ -46,6 +46,7 @@ export const confluenceListTasksTool: InternalToolConfig< description: 'List inline tasks from Confluence. Optionally filter by page, space, assignee, or status.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/retrieve.ts b/apps/sim/tools/confluence/retrieve.ts index b0f510a1cd0..b61eb621ee2 100644 --- a/apps/sim/tools/confluence/retrieve.ts +++ b/apps/sim/tools/confluence/retrieve.ts @@ -16,6 +16,7 @@ export const confluenceRetrieveTool: InternalToolConfig< name: 'Confluence Retrieve', description: 'Retrieve content from Confluence pages using the Confluence API.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/search.ts b/apps/sim/tools/confluence/search.ts index 2589cd5d849..51330fcb958 100644 --- a/apps/sim/tools/confluence/search.ts +++ b/apps/sim/tools/confluence/search.ts @@ -35,6 +35,7 @@ export const confluenceSearchTool: InternalToolConfig< name: 'Confluence Search', description: 'Search for content across Confluence pages, blog posts, and other content.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/search_in_space.ts b/apps/sim/tools/confluence/search_in_space.ts index 1a1646f1229..25cea4290ec 100644 --- a/apps/sim/tools/confluence/search_in_space.ts +++ b/apps/sim/tools/confluence/search_in_space.ts @@ -40,6 +40,7 @@ export const confluenceSearchInSpaceTool: InternalToolConfig< description: 'Search for content within a specific Confluence space. Optionally filter by text query and content type.', version: '1.0.0', + effect: 'read', oauth: { required: true, diff --git a/apps/sim/tools/confluence/update.ts b/apps/sim/tools/confluence/update.ts index 7cdde1264f5..af07ffb3b5b 100644 --- a/apps/sim/tools/confluence/update.ts +++ b/apps/sim/tools/confluence/update.ts @@ -10,6 +10,7 @@ export const confluenceUpdateTool: InternalToolConfig< name: 'Confluence Update', description: 'Update a Confluence page using the Confluence API.', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/confluence/update_blogpost.ts b/apps/sim/tools/confluence/update_blogpost.ts index a75ee089512..3e6133e621b 100644 --- a/apps/sim/tools/confluence/update_blogpost.ts +++ b/apps/sim/tools/confluence/update_blogpost.ts @@ -31,6 +31,7 @@ export const confluenceUpdateBlogPostTool: InternalToolConfig< name: 'Confluence Update Blog Post', description: 'Update an existing Confluence blog post title and/or content.', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/confluence/update_comment.ts b/apps/sim/tools/confluence/update_comment.ts index d673e8f00f9..8f987e8e793 100644 --- a/apps/sim/tools/confluence/update_comment.ts +++ b/apps/sim/tools/confluence/update_comment.ts @@ -25,6 +25,7 @@ export const confluenceUpdateCommentTool: InternalToolConfig< name: 'Confluence Update Comment', description: 'Update an existing comment on a Confluence page.', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/confluence/update_space.ts b/apps/sim/tools/confluence/update_space.ts index c4264396cad..e8fb1e01385 100644 --- a/apps/sim/tools/confluence/update_space.ts +++ b/apps/sim/tools/confluence/update_space.ts @@ -32,6 +32,7 @@ export const confluenceUpdateSpaceTool: InternalToolConfig< name: 'Confluence Update Space', description: 'Update a Confluence space name or description.', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/confluence/update_task.ts b/apps/sim/tools/confluence/update_task.ts index 7d695d6a621..abda67a609c 100644 --- a/apps/sim/tools/confluence/update_task.ts +++ b/apps/sim/tools/confluence/update_task.ts @@ -38,6 +38,7 @@ export const confluenceUpdateTaskTool: InternalToolConfig< name: 'Confluence Update Task', description: 'Update the status of a Confluence inline task (complete or incomplete).', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/confluence/upload_attachment.ts b/apps/sim/tools/confluence/upload_attachment.ts index 0d9b222a197..8fecded50c5 100644 --- a/apps/sim/tools/confluence/upload_attachment.ts +++ b/apps/sim/tools/confluence/upload_attachment.ts @@ -31,6 +31,7 @@ export const confluenceUploadAttachmentTool: InternalToolConfig< name: 'Confluence Upload Attachment', description: 'Upload a file as an attachment to a Confluence page.', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/context_dev/classify_naics.ts b/apps/sim/tools/context_dev/classify_naics.ts index 9d3039edec6..c700b6e1f9d 100644 --- a/apps/sim/tools/context_dev/classify_naics.ts +++ b/apps/sim/tools/context_dev/classify_naics.ts @@ -22,6 +22,7 @@ export const contextDevClassifyNaicsTool: ToolConfig< name: 'Context.dev Classify NAICS', description: 'Classify a brand into NAICS industry codes from its domain or company name.', version: '1.0.0', + effect: 'read', hosting: contextDevHosting(), diff --git a/apps/sim/tools/context_dev/classify_sic.ts b/apps/sim/tools/context_dev/classify_sic.ts index 9827d729e1a..80fff2739ed 100644 --- a/apps/sim/tools/context_dev/classify_sic.ts +++ b/apps/sim/tools/context_dev/classify_sic.ts @@ -22,6 +22,7 @@ export const contextDevClassifySicTool: ToolConfig< name: 'Context.dev Classify SIC', description: 'Classify a brand into SIC industry codes from its domain or company name.', version: '1.0.0', + effect: 'read', hosting: contextDevHosting(), diff --git a/apps/sim/tools/context_dev/crawl.ts b/apps/sim/tools/context_dev/crawl.ts index 1244e35e136..c53dbf69405 100644 --- a/apps/sim/tools/context_dev/crawl.ts +++ b/apps/sim/tools/context_dev/crawl.ts @@ -16,6 +16,7 @@ export const contextDevCrawlTool: ToolConfig(), diff --git a/apps/sim/tools/context_dev/extract.ts b/apps/sim/tools/context_dev/extract.ts index 2352d284ee0..e12f44298eb 100644 --- a/apps/sim/tools/context_dev/extract.ts +++ b/apps/sim/tools/context_dev/extract.ts @@ -16,6 +16,7 @@ export const contextDevExtractTool: ToolConfig(), diff --git a/apps/sim/tools/context_dev/extract_product.ts b/apps/sim/tools/context_dev/extract_product.ts index 2c2efd49dff..afa71dc0fe3 100644 --- a/apps/sim/tools/context_dev/extract_product.ts +++ b/apps/sim/tools/context_dev/extract_product.ts @@ -22,6 +22,7 @@ export const contextDevExtractProductTool: ToolConfig< name: 'Context.dev Extract Product', description: 'Detect and extract structured product details from a single product page URL.', version: '1.0.0', + effect: 'read', hosting: contextDevHosting(), diff --git a/apps/sim/tools/context_dev/extract_products.ts b/apps/sim/tools/context_dev/extract_products.ts index f58356b9d82..c777874c23a 100644 --- a/apps/sim/tools/context_dev/extract_products.ts +++ b/apps/sim/tools/context_dev/extract_products.ts @@ -22,6 +22,7 @@ export const contextDevExtractProductsTool: ToolConfig< name: 'Context.dev Extract Products', description: "Extract the product catalog from a brand's website by domain (beta).", version: '1.0.0', + effect: 'read', hosting: contextDevHosting(), diff --git a/apps/sim/tools/context_dev/get_brand.ts b/apps/sim/tools/context_dev/get_brand.ts index 9bfb1c40a0a..2e089f104e9 100644 --- a/apps/sim/tools/context_dev/get_brand.ts +++ b/apps/sim/tools/context_dev/get_brand.ts @@ -18,6 +18,7 @@ export const contextDevGetBrandTool: ToolConfig(), diff --git a/apps/sim/tools/context_dev/get_brand_by_email.ts b/apps/sim/tools/context_dev/get_brand_by_email.ts index 4ee9d565e86..15cb09dface 100644 --- a/apps/sim/tools/context_dev/get_brand_by_email.ts +++ b/apps/sim/tools/context_dev/get_brand_by_email.ts @@ -23,6 +23,7 @@ export const contextDevGetBrandByEmailTool: ToolConfig< description: 'Retrieve brand data from a work email address. Free/disposable emails are rejected (422).', version: '1.0.0', + effect: 'read', hosting: contextDevHosting(), diff --git a/apps/sim/tools/context_dev/get_brand_by_name.ts b/apps/sim/tools/context_dev/get_brand_by_name.ts index 239ff2187dd..a4b6d51cc6a 100644 --- a/apps/sim/tools/context_dev/get_brand_by_name.ts +++ b/apps/sim/tools/context_dev/get_brand_by_name.ts @@ -23,6 +23,7 @@ export const contextDevGetBrandByNameTool: ToolConfig< description: 'Retrieve brand data by company name: logos, colors, socials, address, and industry.', version: '1.0.0', + effect: 'read', hosting: contextDevHosting(), diff --git a/apps/sim/tools/context_dev/get_brand_by_ticker.ts b/apps/sim/tools/context_dev/get_brand_by_ticker.ts index 432426274e1..8bea34d7992 100644 --- a/apps/sim/tools/context_dev/get_brand_by_ticker.ts +++ b/apps/sim/tools/context_dev/get_brand_by_ticker.ts @@ -22,6 +22,7 @@ export const contextDevGetBrandByTickerTool: ToolConfig< name: 'Context.dev Get Brand by Ticker', description: 'Retrieve brand data for a public company by its stock ticker symbol.', version: '1.0.0', + effect: 'read', hosting: contextDevHosting(), diff --git a/apps/sim/tools/context_dev/identify_transaction.ts b/apps/sim/tools/context_dev/identify_transaction.ts index c75b2fd156c..3719250b41a 100644 --- a/apps/sim/tools/context_dev/identify_transaction.ts +++ b/apps/sim/tools/context_dev/identify_transaction.ts @@ -23,6 +23,7 @@ export const contextDevIdentifyTransactionTool: ToolConfig< description: 'Identify the brand behind a raw bank/card transaction descriptor and return its brand data.', version: '1.0.0', + effect: 'read', hosting: contextDevHosting(), diff --git a/apps/sim/tools/context_dev/map.ts b/apps/sim/tools/context_dev/map.ts index d1c0feaa1a1..a93bf7fa436 100644 --- a/apps/sim/tools/context_dev/map.ts +++ b/apps/sim/tools/context_dev/map.ts @@ -15,6 +15,7 @@ export const contextDevMapTool: ToolConfig(), diff --git a/apps/sim/tools/context_dev/scrape_fonts.ts b/apps/sim/tools/context_dev/scrape_fonts.ts index 0d859106177..bc31f3cb771 100644 --- a/apps/sim/tools/context_dev/scrape_fonts.ts +++ b/apps/sim/tools/context_dev/scrape_fonts.ts @@ -22,6 +22,7 @@ export const contextDevScrapeFontsTool: ToolConfig< name: 'Context.dev Scrape Fonts', description: 'Extract the font families, usage stats, and font files used by a domain.', version: '1.0.0', + effect: 'read', hosting: contextDevHosting(), diff --git a/apps/sim/tools/context_dev/scrape_html.ts b/apps/sim/tools/context_dev/scrape_html.ts index 8b1291d52db..1d5a824dc1b 100644 --- a/apps/sim/tools/context_dev/scrape_html.ts +++ b/apps/sim/tools/context_dev/scrape_html.ts @@ -21,6 +21,7 @@ export const contextDevScrapeHtmlTool: ToolConfig< name: 'Context.dev Scrape HTML', description: 'Scrape any URL and return the raw HTML content of the page.', version: '1.0.0', + effect: 'read', hosting: contextDevHosting(), diff --git a/apps/sim/tools/context_dev/scrape_images.ts b/apps/sim/tools/context_dev/scrape_images.ts index 46a8cfcbe86..776b3f50242 100644 --- a/apps/sim/tools/context_dev/scrape_images.ts +++ b/apps/sim/tools/context_dev/scrape_images.ts @@ -22,6 +22,7 @@ export const contextDevScrapeImagesTool: ToolConfig< name: 'Context.dev Scrape Images', description: 'Discover every image asset on a page, with optional dimension and type enrichment.', version: '1.0.0', + effect: 'read', hosting: contextDevHosting(), diff --git a/apps/sim/tools/context_dev/scrape_markdown.ts b/apps/sim/tools/context_dev/scrape_markdown.ts index eca3c8881fc..0d509f71c12 100644 --- a/apps/sim/tools/context_dev/scrape_markdown.ts +++ b/apps/sim/tools/context_dev/scrape_markdown.ts @@ -21,6 +21,7 @@ export const contextDevScrapeMarkdownTool: ToolConfig< name: 'Context.dev Scrape Markdown', description: 'Scrape any URL and return clean, LLM-ready markdown content.', version: '1.0.0', + effect: 'read', hosting: contextDevHosting(), diff --git a/apps/sim/tools/context_dev/scrape_styleguide.ts b/apps/sim/tools/context_dev/scrape_styleguide.ts index d5afcd26a39..6feef04654b 100644 --- a/apps/sim/tools/context_dev/scrape_styleguide.ts +++ b/apps/sim/tools/context_dev/scrape_styleguide.ts @@ -22,6 +22,7 @@ export const contextDevScrapeStyleguideTool: ToolConfig< description: "Extract a domain's design system: colors, typography, spacing, shadows, and UI components.", version: '1.0.0', + effect: 'read', hosting: contextDevHosting(), diff --git a/apps/sim/tools/context_dev/screenshot.ts b/apps/sim/tools/context_dev/screenshot.ts index d8c68edf160..47860477f5c 100644 --- a/apps/sim/tools/context_dev/screenshot.ts +++ b/apps/sim/tools/context_dev/screenshot.ts @@ -47,6 +47,7 @@ export const contextDevScreenshotTool: ToolConfig< name: 'Context.dev Screenshot', description: 'Capture a screenshot of any web page and store it as a downloadable image file.', version: '1.0.0', + effect: 'read', hosting: contextDevHosting(), diff --git a/apps/sim/tools/context_dev/search.ts b/apps/sim/tools/context_dev/search.ts index c12ee6bf5ee..34386d2d36a 100644 --- a/apps/sim/tools/context_dev/search.ts +++ b/apps/sim/tools/context_dev/search.ts @@ -16,6 +16,7 @@ export const contextDevSearchTool: ToolConfig(), diff --git a/apps/sim/tools/convex/action.ts b/apps/sim/tools/convex/action.ts index 599ae1de6d5..de7aa1686ac 100644 --- a/apps/sim/tools/convex/action.ts +++ b/apps/sim/tools/convex/action.ts @@ -13,6 +13,7 @@ export const actionTool: ToolConfig name: 'Cursor Add Follow-up', description: 'Add a follow-up instruction to an existing cloud agent.', version: '1.0.0', + effect: 'write', oauth: CURSOR_CREDENTIAL_OAUTH, ...addFollowupBase, @@ -124,6 +125,7 @@ export const addFollowupV2Tool: ToolConfig { const data = await response.json() diff --git a/apps/sim/tools/cursor/delete_agent.ts b/apps/sim/tools/cursor/delete_agent.ts index e1f3dc6e84b..909586f38a3 100644 --- a/apps/sim/tools/cursor/delete_agent.ts +++ b/apps/sim/tools/cursor/delete_agent.ts @@ -33,6 +33,7 @@ export const deleteAgentTool: ToolConfig name: 'Cursor Delete Agent', description: 'Permanently delete a cloud agent. This action cannot be undone.', version: '1.0.0', + effect: 'write', oauth: CURSOR_CREDENTIAL_OAUTH, ...deleteAgentBase, @@ -78,6 +79,7 @@ export const deleteAgentV2Tool: ToolConfig { const data = await response.json() diff --git a/apps/sim/tools/cursor/download_artifact.ts b/apps/sim/tools/cursor/download_artifact.ts index 716bd895987..234dbdbc441 100644 --- a/apps/sim/tools/cursor/download_artifact.ts +++ b/apps/sim/tools/cursor/download_artifact.ts @@ -48,6 +48,7 @@ export const downloadArtifactTool: InternalToolConfig< name: 'Cursor Download Artifact', description: 'Download a generated artifact file from a cloud agent.', version: '1.0.0', + effect: 'read', oauth: CURSOR_CREDENTIAL_OAUTH, ...downloadArtifactBase, @@ -98,6 +99,7 @@ export const downloadArtifactV2Tool: InternalToolConfig< description: 'Download a generated artifact file from a cloud agent. Returns the file for execution storage.', version: '2.0.0', + effect: 'read', oauth: CURSOR_CREDENTIAL_OAUTH, transformResponse: async (response) => { diff --git a/apps/sim/tools/cursor/get_agent.ts b/apps/sim/tools/cursor/get_agent.ts index 302ad617679..7d4de4873ad 100644 --- a/apps/sim/tools/cursor/get_agent.ts +++ b/apps/sim/tools/cursor/get_agent.ts @@ -33,6 +33,7 @@ export const getAgentTool: ToolConfig = { name: 'Cursor Get Agent', description: 'Retrieve the current status and results of a cloud agent.', version: '1.0.0', + effect: 'read', oauth: CURSOR_CREDENTIAL_OAUTH, ...getAgentBase, @@ -87,6 +88,7 @@ export const getAgentV2Tool: ToolConfig = { description: 'Retrieve the current status and results of a cloud agent. Returns API-aligned fields only.', version: '2.0.0', + effect: 'read', oauth: CURSOR_CREDENTIAL_OAUTH, transformResponse: async (response) => { const data = await response.json() diff --git a/apps/sim/tools/cursor/get_api_key_info.ts b/apps/sim/tools/cursor/get_api_key_info.ts index 4dc4216fc5a..28a5fa589d6 100644 --- a/apps/sim/tools/cursor/get_api_key_info.ts +++ b/apps/sim/tools/cursor/get_api_key_info.ts @@ -25,6 +25,7 @@ export const getApiKeyInfoTool: ToolConfig { const data = await response.json() diff --git a/apps/sim/tools/cursor/get_conversation.ts b/apps/sim/tools/cursor/get_conversation.ts index d27ff2363a1..dc2877d680a 100644 --- a/apps/sim/tools/cursor/get_conversation.ts +++ b/apps/sim/tools/cursor/get_conversation.ts @@ -34,6 +34,7 @@ export const getConversationTool: ToolConfig { const data = await response.json() diff --git a/apps/sim/tools/cursor/launch_agent.ts b/apps/sim/tools/cursor/launch_agent.ts index d9e980998f8..45e4c1b9df7 100644 --- a/apps/sim/tools/cursor/launch_agent.ts +++ b/apps/sim/tools/cursor/launch_agent.ts @@ -131,6 +131,7 @@ export const launchAgentTool: ToolConfig description: 'Start a new cloud agent to work on a GitHub repository with the given instructions.', version: '1.0.0', + effect: 'write', oauth: CURSOR_CREDENTIAL_OAUTH, ...launchAgentBase, @@ -179,6 +180,7 @@ export const launchAgentV2Tool: ToolConfig { const data = await response.json() diff --git a/apps/sim/tools/cursor/list_agents.ts b/apps/sim/tools/cursor/list_agents.ts index 5853e83ad57..c80700a45e3 100644 --- a/apps/sim/tools/cursor/list_agents.ts +++ b/apps/sim/tools/cursor/list_agents.ts @@ -49,6 +49,7 @@ export const listAgentsTool: ToolConfig = name: 'Cursor List Agents', description: 'List all cloud agents for the authenticated user with optional pagination.', version: '1.0.0', + effect: 'read', oauth: CURSOR_CREDENTIAL_OAUTH, ...listAgentsBase, @@ -103,6 +104,7 @@ export const listAgentsV2Tool: ToolConfig { const data = await response.json() diff --git a/apps/sim/tools/cursor/list_artifacts.ts b/apps/sim/tools/cursor/list_artifacts.ts index 2042df2b4e9..72d5f1f9c9e 100644 --- a/apps/sim/tools/cursor/list_artifacts.ts +++ b/apps/sim/tools/cursor/list_artifacts.ts @@ -55,6 +55,7 @@ export const listArtifactsTool: ToolConfig { diff --git a/apps/sim/tools/cursor/list_models.ts b/apps/sim/tools/cursor/list_models.ts index 9f2480881f3..1b7004e192d 100644 --- a/apps/sim/tools/cursor/list_models.ts +++ b/apps/sim/tools/cursor/list_models.ts @@ -25,6 +25,7 @@ export const listModelsTool: ToolConfig = name: 'Cursor List Models', description: 'List the models available for launching cloud agents.', version: '1.0.0', + effect: 'read', oauth: CURSOR_CREDENTIAL_OAUTH, ...listModelsBase, @@ -74,6 +75,7 @@ export const listModelsV2Tool: ToolConfig { const data = await response.json() diff --git a/apps/sim/tools/cursor/list_repositories.ts b/apps/sim/tools/cursor/list_repositories.ts index 01cd9067e0a..274707004f0 100644 --- a/apps/sim/tools/cursor/list_repositories.ts +++ b/apps/sim/tools/cursor/list_repositories.ts @@ -25,6 +25,7 @@ export const listRepositoriesTool: ToolConfig { const data = await response.json() diff --git a/apps/sim/tools/cursor/stop_agent.ts b/apps/sim/tools/cursor/stop_agent.ts index adbc14e77ab..abcacafec7c 100644 --- a/apps/sim/tools/cursor/stop_agent.ts +++ b/apps/sim/tools/cursor/stop_agent.ts @@ -33,6 +33,7 @@ export const stopAgentTool: ToolConfig = { name: 'Cursor Stop Agent', description: 'Stop a running cloud agent. This pauses the agent without deleting it.', version: '1.0.0', + effect: 'write', oauth: CURSOR_CREDENTIAL_OAUTH, ...stopAgentBase, @@ -78,6 +79,7 @@ export const stopAgentV2Tool: ToolConfig = name: 'Cursor Stop Agent', description: 'Stop a running cloud agent. Returns API-aligned fields only.', version: '2.0.0', + effect: 'write', oauth: CURSOR_CREDENTIAL_OAUTH, transformResponse: async (response) => { const data = await response.json() diff --git a/apps/sim/tools/dagster/delete_run.ts b/apps/sim/tools/dagster/delete_run.ts index e6975b4c21d..75d10d9e20d 100644 --- a/apps/sim/tools/dagster/delete_run.ts +++ b/apps/sim/tools/dagster/delete_run.ts @@ -38,6 +38,7 @@ export const deleteRunTool: ToolConfig name: 'Dagster Get Run', description: 'Get the status and details of a Dagster run by its ID.', version: '1.0.0', + effect: 'read', params: { host: { diff --git a/apps/sim/tools/dagster/get_run_logs.ts b/apps/sim/tools/dagster/get_run_logs.ts index aef20e14807..dac1de873f6 100644 --- a/apps/sim/tools/dagster/get_run_logs.ts +++ b/apps/sim/tools/dagster/get_run_logs.ts @@ -55,6 +55,7 @@ export const getRunLogsTool: ToolConfig description: 'Post an event to the Datadog event stream. Use for deployment notifications, alerts, or any significant occurrences. Uses the v1 events endpoint, which Datadog has deprecated and serves only to organizations that have used it before.', version: '1.0.0', + effect: 'write', oauth: DATADOG_API_KEY_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/datadog/create_incident.ts b/apps/sim/tools/datadog/create_incident.ts index 50daeaa917f..1c4fbcd1573 100644 --- a/apps/sim/tools/datadog/create_incident.ts +++ b/apps/sim/tools/datadog/create_incident.ts @@ -15,6 +15,7 @@ export const createIncidentTool: ToolConfig = { description: 'Create a service level objective from a metric query, monitors, or a time-slice condition.', version: '1.0.0', + effect: 'write', oauth: DATADOG_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/datadog/delete_dashboard.ts b/apps/sim/tools/datadog/delete_dashboard.ts index 9297589ebb0..b7609c25905 100644 --- a/apps/sim/tools/datadog/delete_dashboard.ts +++ b/apps/sim/tools/datadog/delete_dashboard.ts @@ -13,6 +13,7 @@ export const deleteDashboardTool: ToolConfig = { description: 'Permanently delete a service level objective. Datadog returns a conflict when the SLO is still referenced by a dashboard.', version: '1.0.0', + effect: 'write', oauth: DATADOG_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/datadog/get_browser_synthetics_results.ts b/apps/sim/tools/datadog/get_browser_synthetics_results.ts index 0c32409ae14..7e51e51066b 100644 --- a/apps/sim/tools/datadog/get_browser_synthetics_results.ts +++ b/apps/sim/tools/datadog/get_browser_synthetics_results.ts @@ -21,6 +21,7 @@ export const getBrowserSyntheticsResultsTool: ToolConfig< description: 'Get the latest result summaries (up to the last 150 runs) for a Synthetic browser test, including step counts and errors.', version: '1.0.0', + effect: 'read', oauth: DATADOG_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/datadog/get_dashboard.ts b/apps/sim/tools/datadog/get_dashboard.ts index ca7c0899e37..04f7f8585dc 100644 --- a/apps/sim/tools/datadog/get_dashboard.ts +++ b/apps/sim/tools/datadog/get_dashboard.ts @@ -13,6 +13,7 @@ export const getDashboardTool: ToolConfig description: 'Get the details of a single incident by ID. Requires the Incident Management `incident_read` permission; the Incidents API is in public beta.', version: '1.0.0', + effect: 'read', oauth: DATADOG_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/datadog/get_monitor.ts b/apps/sim/tools/datadog/get_monitor.ts index 1414c4e1330..362925938fa 100644 --- a/apps/sim/tools/datadog/get_monitor.ts +++ b/apps/sim/tools/datadog/get_monitor.ts @@ -8,6 +8,7 @@ export const getMonitorTool: ToolConfig = name: 'Datadog Get Monitor', description: 'Retrieve details of a specific monitor by ID.', version: '1.0.0', + effect: 'read', oauth: DATADOG_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/datadog/get_security_signal.ts b/apps/sim/tools/datadog/get_security_signal.ts index c3acf3d0254..272b14ecede 100644 --- a/apps/sim/tools/datadog/get_security_signal.ts +++ b/apps/sim/tools/datadog/get_security_signal.ts @@ -15,6 +15,7 @@ export const getSecuritySignalTool: ToolConfig = { name: 'Datadog Get SLO', description: 'Get the configuration of a single service level objective by ID.', version: '1.0.0', + effect: 'read', oauth: DATADOG_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/datadog/get_slo_history.ts b/apps/sim/tools/datadog/get_slo_history.ts index a42b62089dc..69812550815 100644 --- a/apps/sim/tools/datadog/get_slo_history.ts +++ b/apps/sim/tools/datadog/get_slo_history.ts @@ -14,6 +14,7 @@ export const getSloHistoryTool: ToolConfig = { description: 'List service level objectives, optionally filtered by IDs, name, tags, or underlying metrics query.', version: '1.0.0', + effect: 'read', oauth: DATADOG_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/datadog/list_synthetics_tests.ts b/apps/sim/tools/datadog/list_synthetics_tests.ts index 4df58a5bb43..0ad297f4aeb 100644 --- a/apps/sim/tools/datadog/list_synthetics_tests.ts +++ b/apps/sim/tools/datadog/list_synthetics_tests.ts @@ -15,6 +15,7 @@ export const listSyntheticsTestsTool: ToolConfig< name: 'Datadog List Synthetic Tests', description: 'List all Synthetic tests (API, browser, and mobile) with their current status.', version: '1.0.0', + effect: 'read', oauth: DATADOG_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/datadog/mute_monitor.ts b/apps/sim/tools/datadog/mute_monitor.ts index 75417da13c1..3f4b8ec3a62 100644 --- a/apps/sim/tools/datadog/mute_monitor.ts +++ b/apps/sim/tools/datadog/mute_monitor.ts @@ -14,6 +14,7 @@ export const muteMonitorTool: ToolConfig description: 'Mute a monitor to temporarily suppress its notifications. Use Unmute Monitor to reverse it, or schedule a downtime instead when you want a planned, auditable maintenance window.', version: '1.0.0', + effect: 'write', oauth: DATADOG_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/datadog/query_logs.ts b/apps/sim/tools/datadog/query_logs.ts index 3a384f6e128..30d0e782fa5 100644 --- a/apps/sim/tools/datadog/query_logs.ts +++ b/apps/sim/tools/datadog/query_logs.ts @@ -14,6 +14,7 @@ export const queryLogsTool: ToolConfig = { description: 'Search and retrieve logs from Datadog. Use for troubleshooting, analysis, or monitoring.', version: '1.0.0', + effect: 'read', oauth: DATADOG_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/datadog/query_timeseries.ts b/apps/sim/tools/datadog/query_timeseries.ts index 5a80464ecfe..33884d14014 100644 --- a/apps/sim/tools/datadog/query_timeseries.ts +++ b/apps/sim/tools/datadog/query_timeseries.ts @@ -13,6 +13,7 @@ export const queryTimeseriesTool: ToolConfig name: 'Datadog Search Spans', description: 'Search indexed APM spans using the span query syntax, with cursor pagination.', version: '1.0.0', + effect: 'read', oauth: DATADOG_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/datadog/send_logs.ts b/apps/sim/tools/datadog/send_logs.ts index b1a0118fa78..a5d76a43451 100644 --- a/apps/sim/tools/datadog/send_logs.ts +++ b/apps/sim/tools/datadog/send_logs.ts @@ -9,6 +9,7 @@ export const sendLogsTool: ToolConfig = { name: 'Datadog Send Logs', description: 'Send log entries to Datadog for centralized logging and analysis.', version: '1.0.0', + effect: 'write', oauth: DATADOG_API_KEY_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/datadog/submit_metrics.ts b/apps/sim/tools/datadog/submit_metrics.ts index ece0410fc19..30a2dcd6591 100644 --- a/apps/sim/tools/datadog/submit_metrics.ts +++ b/apps/sim/tools/datadog/submit_metrics.ts @@ -39,6 +39,7 @@ export const submitMetricsTool: ToolConfig((_params, output) => { const name = output.name as string | null diff --git a/apps/sim/tools/datagma/enrich_person.ts b/apps/sim/tools/datagma/enrich_person.ts index 2f1aaf02870..3aba24a5a0f 100644 --- a/apps/sim/tools/datagma/enrich_person.ts +++ b/apps/sim/tools/datagma/enrich_person.ts @@ -17,6 +17,8 @@ export const enrichPersonTool: ToolConfig((params, output) => { const name = output.name as string | null diff --git a/apps/sim/tools/datagma/find_email.ts b/apps/sim/tools/datagma/find_email.ts index b61e783d13d..0e947621912 100644 --- a/apps/sim/tools/datagma/find_email.ts +++ b/apps/sim/tools/datagma/find_email.ts @@ -16,6 +16,8 @@ export const findEmailTool: ToolConfig((_params, output) => { const email = output.email as string | null diff --git a/apps/sim/tools/datagma/find_phone.ts b/apps/sim/tools/datagma/find_phone.ts index 7d3b019f0e8..3ff0b70b738 100644 --- a/apps/sim/tools/datagma/find_phone.ts +++ b/apps/sim/tools/datagma/find_phone.ts @@ -17,6 +17,8 @@ export const findPhoneTool: ToolConfig((_params, output) => { const phone = output.phone as string | null diff --git a/apps/sim/tools/datagma/get_credits.ts b/apps/sim/tools/datagma/get_credits.ts index fecedc68aac..9b009e5a319 100644 --- a/apps/sim/tools/datagma/get_credits.ts +++ b/apps/sim/tools/datagma/get_credits.ts @@ -14,6 +14,7 @@ export const getCreditsTool: ToolConfig name: 'Dropbox Copy', description: 'Copy a file or folder in Dropbox', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/dropbox/create_folder.ts b/apps/sim/tools/dropbox/create_folder.ts index b57711591e3..11a51a130c3 100644 --- a/apps/sim/tools/dropbox/create_folder.ts +++ b/apps/sim/tools/dropbox/create_folder.ts @@ -9,6 +9,7 @@ export const dropboxCreateFolderTool: ToolConfig< name: 'Dropbox Create Folder', description: 'Create a new folder in Dropbox', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/dropbox/create_shared_link.ts b/apps/sim/tools/dropbox/create_shared_link.ts index f8256c24c15..4dbfcced1ff 100644 --- a/apps/sim/tools/dropbox/create_shared_link.ts +++ b/apps/sim/tools/dropbox/create_shared_link.ts @@ -12,6 +12,7 @@ export const dropboxCreateSharedLinkTool: ToolConfig< name: 'Dropbox Create Shared Link', description: 'Create a shareable link for a file or folder in Dropbox', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/dropbox/delete.ts b/apps/sim/tools/dropbox/delete.ts index 1e700eb4dd3..b0d010a5626 100644 --- a/apps/sim/tools/dropbox/delete.ts +++ b/apps/sim/tools/dropbox/delete.ts @@ -6,6 +6,7 @@ export const dropboxDeleteTool: ToolConfig name: 'Dropbox Move', description: 'Move or rename a file or folder in Dropbox', version: '1.0.0', + effect: 'write', oauth: { required: true, diff --git a/apps/sim/tools/dropbox/restore.ts b/apps/sim/tools/dropbox/restore.ts index 3cbb2259330..c645dc88b78 100644 --- a/apps/sim/tools/dropbox/restore.ts +++ b/apps/sim/tools/dropbox/restore.ts @@ -6,6 +6,7 @@ export const dropboxRestoreTool: ToolConfig((_params, output) => { // 1 credit per contact when a verified email is found. diff --git a/apps/sim/tools/dspy/chain_of_thought.ts b/apps/sim/tools/dspy/chain_of_thought.ts index 8427e4784b8..c93d627d750 100644 --- a/apps/sim/tools/dspy/chain_of_thought.ts +++ b/apps/sim/tools/dspy/chain_of_thought.ts @@ -9,6 +9,7 @@ export const chainOfThoughtTool: ToolConfig = { name: 'DSPy Predict', description: 'Run a prediction using a self-hosted DSPy program endpoint', version: '1.0.0', + effect: 'read', params: { baseUrl: { diff --git a/apps/sim/tools/dspy/react.ts b/apps/sim/tools/dspy/react.ts index 3627983768f..463ba47773e 100644 --- a/apps/sim/tools/dspy/react.ts +++ b/apps/sim/tools/dspy/react.ts @@ -8,6 +8,7 @@ export const reactTool: ToolConfig = { description: 'Run a ReAct agent using a self-hosted DSPy ReAct program endpoint for multi-step reasoning and action', version: '1.0.0', + effect: 'write', params: { baseUrl: { diff --git a/apps/sim/tools/dub/bulk_create_links.ts b/apps/sim/tools/dub/bulk_create_links.ts index d28b7b6c797..3307dfa7bce 100644 --- a/apps/sim/tools/dub/bulk_create_links.ts +++ b/apps/sim/tools/dub/bulk_create_links.ts @@ -9,6 +9,7 @@ export const bulkCreateLinksTool: ToolConfig name: 'Dub Create Tag', description: 'Create a new tag in the workspace for organizing and filtering short links.', version: '1.0.0', + effect: 'write', oauth: DUB_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/dub/delete_link.ts b/apps/sim/tools/dub/delete_link.ts index 54ee6ec9905..f9cc0ea6ab3 100644 --- a/apps/sim/tools/dub/delete_link.ts +++ b/apps/sim/tools/dub/delete_link.ts @@ -7,6 +7,7 @@ export const deleteLinkTool: ToolConfig description: 'Retrieve a paginated stream of individual click, lead, and sale events for links, with filtering by link, time range, and location.', version: '1.0.0', + effect: 'read', oauth: DUB_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/dub/get_link.ts b/apps/sim/tools/dub/get_link.ts index b6544edf085..f1e7bdd32c9 100644 --- a/apps/sim/tools/dub/get_link.ts +++ b/apps/sim/tools/dub/get_link.ts @@ -8,6 +8,7 @@ export const getLinkTool: ToolConfig = { description: 'Retrieve information about a short link by its link ID, external ID, or domain + key combination.', version: '1.0.0', + effect: 'read', oauth: DUB_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/dub/get_links_count.ts b/apps/sim/tools/dub/get_links_count.ts index 096a48cc22d..6c46ff77702 100644 --- a/apps/sim/tools/dub/get_links_count.ts +++ b/apps/sim/tools/dub/get_links_count.ts @@ -8,6 +8,7 @@ export const getLinksCountTool: ToolConfig description: 'Retrieve a paginated list of short links for the authenticated workspace. Supports filtering by domain, search query, tags, and sorting.', version: '1.0.0', + effect: 'read', oauth: DUB_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/dub/list_tags.ts b/apps/sim/tools/dub/list_tags.ts index 46a1964a5ee..0a88ad9176f 100644 --- a/apps/sim/tools/dub/list_tags.ts +++ b/apps/sim/tools/dub/list_tags.ts @@ -8,6 +8,7 @@ export const listTagsTool: ToolConfig = description: 'Retrieve the tags defined in the workspace, so the right tag IDs can be assigned to links.', version: '1.0.0', + effect: 'read', oauth: DUB_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/dub/update_link.ts b/apps/sim/tools/dub/update_link.ts index 678ec10cddf..9b29aa84d4f 100644 --- a/apps/sim/tools/dub/update_link.ts +++ b/apps/sim/tools/dub/update_link.ts @@ -8,6 +8,7 @@ export const updateLinkTool: ToolConfig name: 'DynamoDB Get', description: 'Get an item from a DynamoDB table by primary key', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/dynamodb/introspect.ts b/apps/sim/tools/dynamodb/introspect.ts index 2a73c6b1f36..fa1b9097bb5 100644 --- a/apps/sim/tools/dynamodb/introspect.ts +++ b/apps/sim/tools/dynamodb/introspect.ts @@ -11,6 +11,7 @@ export const introspectTool: InternalToolConfig< description: 'Introspect DynamoDB to list tables or get detailed schema information for a specific table', version: '1.0.0', + effect: 'read', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/dynamodb/put.ts b/apps/sim/tools/dynamodb/put.ts index d916262dbfc..51dfa2f3c3f 100644 --- a/apps/sim/tools/dynamodb/put.ts +++ b/apps/sim/tools/dynamodb/put.ts @@ -7,6 +7,7 @@ export const putTool: InternalToolConfig name: 'DynamoDB Put', description: 'Put an item into a DynamoDB table', version: '1.0.0', + effect: 'write', oauth: AWS_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/dynamodb/query.ts b/apps/sim/tools/dynamodb/query.ts index 2cd11c2f9b2..76aafb4e3c5 100644 --- a/apps/sim/tools/dynamodb/query.ts +++ b/apps/sim/tools/dynamodb/query.ts @@ -7,6 +7,7 @@ export const queryTool: InternalToolConfig((_params, output) => { // 1 credit charged only when a valid email is returned. Compare diff --git a/apps/sim/tools/enrow/verify_email.ts b/apps/sim/tools/enrow/verify_email.ts index 835676327e3..4e7c68bc090 100644 --- a/apps/sim/tools/enrow/verify_email.ts +++ b/apps/sim/tools/enrow/verify_email.ts @@ -42,6 +42,7 @@ export const enrowVerifyEmailTool: ToolConfig((_params, output) => { // 0.25 credits per completed verification. Bill only when the job resolved diff --git a/apps/sim/tools/exa/agent.ts b/apps/sim/tools/exa/agent.ts index 2af163fa392..f076979d7bf 100644 --- a/apps/sim/tools/exa/agent.ts +++ b/apps/sim/tools/exa/agent.ts @@ -20,6 +20,7 @@ export const agentTool: ToolConfig = { description: 'Run a deep research task with Exa Agent. Handles multi-step list building, enrichment, and research, returning a written answer with field-level citations and optional structured output.', version: '1.0.0', + effect: 'write', params: { query: { diff --git a/apps/sim/tools/exa/answer.ts b/apps/sim/tools/exa/answer.ts index 88713a919a0..1d5cc7448d2 100644 --- a/apps/sim/tools/exa/answer.ts +++ b/apps/sim/tools/exa/answer.ts @@ -7,6 +7,7 @@ export const answerTool: ToolConfig = { name: 'Exa Answer', description: 'Get an AI-generated answer to a question with citations from the web using Exa AI.', version: '2.0.0', + effect: 'read', params: { query: { diff --git a/apps/sim/tools/exa/find_similar_links.ts b/apps/sim/tools/exa/find_similar_links.ts index 0f36fa8d7d8..13bcdab1fae 100644 --- a/apps/sim/tools/exa/find_similar_links.ts +++ b/apps/sim/tools/exa/find_similar_links.ts @@ -21,6 +21,7 @@ export const findSimilarLinksTool: ToolConfig< description: 'Find webpages similar to a given URL using Exa AI. Deprecated by Exa in favor of Search — prefer Search for new workflows.', version: '2.0.0', + effect: 'read', params: { url: { diff --git a/apps/sim/tools/exa/get_contents.ts b/apps/sim/tools/exa/get_contents.ts index a3b412ecbff..77e3889292f 100644 --- a/apps/sim/tools/exa/get_contents.ts +++ b/apps/sim/tools/exa/get_contents.ts @@ -8,6 +8,7 @@ export const getContentsTool: ToolConfig = { description: 'Search the web using Exa AI. Returns relevant search results with titles, URLs, and text snippets.', version: '2.0.0', + effect: 'read', params: { query: { diff --git a/apps/sim/tools/extend/parser.ts b/apps/sim/tools/extend/parser.ts index a9c74c96515..f27382f47d5 100644 --- a/apps/sim/tools/extend/parser.ts +++ b/apps/sim/tools/extend/parser.ts @@ -13,6 +13,7 @@ export const extendParserTool: InternalToolConfig description: 'Append content to an existing workspace file. The file must already exist. Content is added to the end of the file.', version: '1.0.0', + effect: 'write', params: { fileName: { diff --git a/apps/sim/tools/file/compress.ts b/apps/sim/tools/file/compress.ts index e4c3a93769d..a20bd84ba50 100644 --- a/apps/sim/tools/file/compress.ts +++ b/apps/sim/tools/file/compress.ts @@ -15,6 +15,7 @@ export const fileCompressTool: InternalToolConfig = { description: 'Apply one precise edit to an existing text file without rewriting it. Use search_replace for verbatim replacement, optionally with replaceAll. Use replace_between, insert_after, or delete_between for complete trimmed-line anchors that stay stable when line numbers move. Folder scope can disambiguate a name or constrain a file ID.', version: '1.0.0', + effect: 'write', params: { fileName: { diff --git a/apps/sim/tools/file/folders.ts b/apps/sim/tools/file/folders.ts index 093778c31b4..222da631b20 100644 --- a/apps/sim/tools/file/folders.ts +++ b/apps/sim/tools/file/folders.ts @@ -71,6 +71,7 @@ export const fileListTool: InternalToolConfig = { description: 'List what is inside a workspace folder: its subfolders and its files together. Lists direct children by default; set Recursive to walk the whole subtree.', version: '1.0.0', + effect: 'read', params: { path: { @@ -143,6 +144,7 @@ export const fileCreateFolderTool: InternalToolConfig = { description: 'Move an existing workspace file into a folder. Moves the file itself; use Move File Folder to relocate a whole folder.', version: '1.0.0', + effect: 'write', params: { fileId: { diff --git a/apps/sim/tools/file/get.ts b/apps/sim/tools/file/get.ts index 87a5c713cf5..e9de346acc4 100644 --- a/apps/sim/tools/file/get.ts +++ b/apps/sim/tools/file/get.ts @@ -23,6 +23,7 @@ const createFileReadTool = (config: { name: config.name, description: config.description, version: '1.0.0', + effect: 'read', params: { fileId: { @@ -84,6 +85,7 @@ export const fileGetTool: InternalToolConfig = { name: 'File Get', description: 'Get a workspace file object from a selected file or canonical workspace file ID.', version: '1.0.0', + effect: 'read', params: { fileId: { @@ -150,6 +152,7 @@ export const fileGetContentTool: InternalToolConfig = description: 'Create a new workspace file, either from text content or from an existing file. If a file with the same name already exists, a numeric suffix is added (e.g., "data (1).csv") unless overwrite is enabled.', version: '1.0.0', + effect: 'write', params: { fileName: { diff --git a/apps/sim/tools/findymail/find_email_from_linkedin.ts b/apps/sim/tools/findymail/find_email_from_linkedin.ts index 5d095cd9cf4..5f8c43d1d96 100644 --- a/apps/sim/tools/findymail/find_email_from_linkedin.ts +++ b/apps/sim/tools/findymail/find_email_from_linkedin.ts @@ -15,6 +15,7 @@ export const findEmailFromLinkedInTool: ToolConfig< description: "Find someone's email from a LinkedIn profile URL or username. Uses one finder credit when a verified email is found.", version: '1.0.0', + effect: 'write', hosting: findymailHosting((_params, output) => { const contact = output.contact as { email?: string } | null diff --git a/apps/sim/tools/findymail/find_email_from_name.ts b/apps/sim/tools/findymail/find_email_from_name.ts index 6a09ed75bd3..f0d24e6e6df 100644 --- a/apps/sim/tools/findymail/find_email_from_name.ts +++ b/apps/sim/tools/findymail/find_email_from_name.ts @@ -15,6 +15,7 @@ export const findEmailFromNameTool: ToolConfig< description: "Find someone's email from their name and a company domain or company name. Uses one finder credit when a verified email is found.", version: '1.0.0', + effect: 'write', hosting: findymailHosting((_params, output) => { const contact = output.contact as { email?: string } | null diff --git a/apps/sim/tools/findymail/find_emails_by_domain.ts b/apps/sim/tools/findymail/find_emails_by_domain.ts index de26fd4f0a3..bcb21b3f62e 100644 --- a/apps/sim/tools/findymail/find_emails_by_domain.ts +++ b/apps/sim/tools/findymail/find_emails_by_domain.ts @@ -15,6 +15,7 @@ export const findEmailsByDomainTool: ToolConfig< description: 'Find verified contacts at a given domain matching one or more target roles (max 3 roles). Limited to 5 concurrent synchronous requests.', version: '1.0.0', + effect: 'write', hosting: findymailHosting((_params, output) => { // No contacts array means no verified contacts returned — no charge. diff --git a/apps/sim/tools/findymail/find_employees.ts b/apps/sim/tools/findymail/find_employees.ts index 9051ad8d75e..23a21cdff21 100644 --- a/apps/sim/tools/findymail/find_employees.ts +++ b/apps/sim/tools/findymail/find_employees.ts @@ -15,6 +15,7 @@ export const findEmployeesTool: ToolConfig< description: 'Find employees at a company by website and target job titles. Uses 1 credit per found contact. Does not return email addresses.', version: '1.0.0', + effect: 'read', hosting: findymailHosting((_params, output) => { // No employees array means no contacts found — no charge. diff --git a/apps/sim/tools/findymail/find_phone.ts b/apps/sim/tools/findymail/find_phone.ts index 8a5c48f1591..26ae03a08cf 100644 --- a/apps/sim/tools/findymail/find_phone.ts +++ b/apps/sim/tools/findymail/find_phone.ts @@ -8,6 +8,7 @@ export const findPhoneTool: ToolConfig((_params, output) => { // Phone lookups consume 10 finder credits, only when a number is found. diff --git a/apps/sim/tools/findymail/get_company.ts b/apps/sim/tools/findymail/get_company.ts index 64c03bcf831..2086291cb1b 100644 --- a/apps/sim/tools/findymail/get_company.ts +++ b/apps/sim/tools/findymail/get_company.ts @@ -11,6 +11,7 @@ export const getCompanyTool: ToolConfig((_params, output) => { // 1 finder credit per successful company match. diff --git a/apps/sim/tools/findymail/get_credits.ts b/apps/sim/tools/findymail/get_credits.ts index 7d36549d0af..56de1a3dddd 100644 --- a/apps/sim/tools/findymail/get_credits.ts +++ b/apps/sim/tools/findymail/get_credits.ts @@ -9,6 +9,7 @@ export const getCreditsTool: ToolConfig((_params, output) => { // 1 finder credit when a technology stack is returned, free otherwise. diff --git a/apps/sim/tools/findymail/reverse_email_lookup.ts b/apps/sim/tools/findymail/reverse_email_lookup.ts index 447d112b696..e5e37ef9083 100644 --- a/apps/sim/tools/findymail/reverse_email_lookup.ts +++ b/apps/sim/tools/findymail/reverse_email_lookup.ts @@ -14,6 +14,7 @@ export const reverseEmailLookupTool: ToolConfig< description: 'Find a business profile from an email address. Uses 1 finder credit if a profile is found, 2 credits if returning full profile data.', version: '1.0.0', + effect: 'read', hosting: findymailHosting((params, output) => { const found = Boolean(output.email || output.linkedin_url || output.fullName) diff --git a/apps/sim/tools/findymail/search_technologies.ts b/apps/sim/tools/findymail/search_technologies.ts index 64d56b785a3..4f47db3bac6 100644 --- a/apps/sim/tools/findymail/search_technologies.ts +++ b/apps/sim/tools/findymail/search_technologies.ts @@ -15,6 +15,7 @@ export const searchTechnologiesTool: ToolConfig< description: 'Search the technology catalog by name. Returns up to 25 technologies. Free endpoint, rate limited to 10 requests per minute.', version: '1.0.0', + effect: 'read', hosting: findymailHosting(() => { // Free catalog search — consumes no Findymail credits. diff --git a/apps/sim/tools/findymail/verify_email.ts b/apps/sim/tools/findymail/verify_email.ts index 30463e1fe6c..761fbb4d1b9 100644 --- a/apps/sim/tools/findymail/verify_email.ts +++ b/apps/sim/tools/findymail/verify_email.ts @@ -11,6 +11,7 @@ export const verifyEmailTool: ToolConfig(() => { // Each verification consumes one verifier credit, billed at the finder-credit rate. diff --git a/apps/sim/tools/firecrawl/agent.ts b/apps/sim/tools/firecrawl/agent.ts index a09d2b3f4a1..3988333ae08 100644 --- a/apps/sim/tools/firecrawl/agent.ts +++ b/apps/sim/tools/firecrawl/agent.ts @@ -17,6 +17,7 @@ export const agentTool: ToolConfig = { description: 'Autonomous web data extraction agent. Searches and gathers information based on natural language prompts without requiring specific URLs.', version: '1.0.0', + effect: 'write', params: { prompt: { diff --git a/apps/sim/tools/firecrawl/batch-scrape-status.ts b/apps/sim/tools/firecrawl/batch-scrape-status.ts index fd45a6dc8ca..969ba4636d2 100644 --- a/apps/sim/tools/firecrawl/batch-scrape-status.ts +++ b/apps/sim/tools/firecrawl/batch-scrape-status.ts @@ -14,6 +14,7 @@ export const batchScrapeStatusTool: ToolConfig< description: 'Check the status and retrieve results of a previously started Firecrawl batch scrape job by its job ID.', version: '1.0.0', + effect: 'read', params: { jobId: { diff --git a/apps/sim/tools/firecrawl/batch-scrape.ts b/apps/sim/tools/firecrawl/batch-scrape.ts index 1ae7f77fffa..c9a127f0f56 100644 --- a/apps/sim/tools/firecrawl/batch-scrape.ts +++ b/apps/sim/tools/firecrawl/batch-scrape.ts @@ -57,6 +57,7 @@ export const batchScrapeTool: ToolConfig name: 'Firecrawl Crawl', description: 'Crawl entire websites and extract structured content from all accessible pages', version: '1.0.0', + effect: 'write', params: { url: { type: 'string', diff --git a/apps/sim/tools/firecrawl/credit-usage.ts b/apps/sim/tools/firecrawl/credit-usage.ts index 540c3f5b95d..3d5aa80ae6e 100644 --- a/apps/sim/tools/firecrawl/credit-usage.ts +++ b/apps/sim/tools/firecrawl/credit-usage.ts @@ -10,6 +10,7 @@ export const creditUsageTool: ToolConfig(), params: { apiKey: { diff --git a/apps/sim/tools/firecrawl/extract-status.ts b/apps/sim/tools/firecrawl/extract-status.ts index 99cfcfadd24..fdec456c775 100644 --- a/apps/sim/tools/firecrawl/extract-status.ts +++ b/apps/sim/tools/firecrawl/extract-status.ts @@ -13,6 +13,7 @@ export const extractStatusTool: ToolConfig< description: 'Check the status and retrieve results of a previously started Firecrawl extract job by its job ID.', version: '1.0.0', + effect: 'read', params: { jobId: { diff --git a/apps/sim/tools/firecrawl/extract.ts b/apps/sim/tools/firecrawl/extract.ts index 62ce5a83651..a29a39f7e86 100644 --- a/apps/sim/tools/firecrawl/extract.ts +++ b/apps/sim/tools/firecrawl/extract.ts @@ -26,6 +26,7 @@ export const extractTool: ToolConfig = { description: 'Extract structured data from web pages using natural language prompts and JSON Schema.', version: '1.0.0', + effect: 'write', params: { urls: { diff --git a/apps/sim/tools/firecrawl/map.ts b/apps/sim/tools/firecrawl/map.ts index c7d52b08d06..930e22487c5 100644 --- a/apps/sim/tools/firecrawl/map.ts +++ b/apps/sim/tools/firecrawl/map.ts @@ -8,6 +8,7 @@ export const mapTool: ToolConfig = { description: 'Get a complete list of URLs from any website quickly and reliably. Useful for discovering all pages on a site without crawling them.', version: '1.0.0', + effect: 'read', params: { url: { diff --git a/apps/sim/tools/firecrawl/parse.ts b/apps/sim/tools/firecrawl/parse.ts index d450a0ff5b0..840f9b76dfe 100644 --- a/apps/sim/tools/firecrawl/parse.ts +++ b/apps/sim/tools/firecrawl/parse.ts @@ -16,6 +16,7 @@ export const parseTool: InternalToolConfig = { description: 'Parse uploaded documents (PDF, DOCX, HTML, etc.) into clean markdown using Firecrawl. Supports .html, .htm, .pdf, .docx, .doc, .odt, .rtf, .xlsx, .xls.', version: '1.0.0', + effect: 'read', params: { file: { diff --git a/apps/sim/tools/firecrawl/scrape.ts b/apps/sim/tools/firecrawl/scrape.ts index 6e569f7f206..06748dd2ec0 100644 --- a/apps/sim/tools/firecrawl/scrape.ts +++ b/apps/sim/tools/firecrawl/scrape.ts @@ -16,6 +16,7 @@ export const scrapeTool: ToolConfig = { description: 'Convert web pages to Markdown or HTML, including SEO metadata, Open Graph tags, and page information.', version: '1.0.0', + effect: 'read', params: { url: { diff --git a/apps/sim/tools/firecrawl/search.ts b/apps/sim/tools/firecrawl/search.ts index 03bcb87e45f..27b0e45c4d7 100644 --- a/apps/sim/tools/firecrawl/search.ts +++ b/apps/sim/tools/firecrawl/search.ts @@ -12,6 +12,7 @@ export const searchTool: ToolConfig = { name: 'Firecrawl Search', description: 'Search for information on the web using Firecrawl', version: '1.0.0', + effect: 'read', params: { query: { diff --git a/apps/sim/tools/fireflies/add_to_live_meeting.ts b/apps/sim/tools/fireflies/add_to_live_meeting.ts index 8a256fde01b..6049859f3f1 100644 --- a/apps/sim/tools/fireflies/add_to_live_meeting.ts +++ b/apps/sim/tools/fireflies/add_to_live_meeting.ts @@ -13,6 +13,7 @@ export const firefliesAddToLiveMeetingTool: ToolConfig< name: 'Fireflies Add to Live Meeting', description: 'Add the Fireflies.ai bot to an ongoing meeting to record and transcribe', version: '1.0.0', + effect: 'write', oauth: FIREFLIES_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/fireflies/create_bite.ts b/apps/sim/tools/fireflies/create_bite.ts index ac58a901c97..c7d7ba75774 100644 --- a/apps/sim/tools/fireflies/create_bite.ts +++ b/apps/sim/tools/fireflies/create_bite.ts @@ -13,6 +13,7 @@ export const firefliesCreateBiteTool: ToolConfig< name: 'Fireflies Create Bite', description: 'Create a soundbite/highlight from a specific time range in a transcript', version: '1.0.0', + effect: 'write', oauth: FIREFLIES_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/fireflies/delete_transcript.ts b/apps/sim/tools/fireflies/delete_transcript.ts index 8164b38efcc..7e6c2aebbf5 100644 --- a/apps/sim/tools/fireflies/delete_transcript.ts +++ b/apps/sim/tools/fireflies/delete_transcript.ts @@ -13,6 +13,7 @@ export const firefliesDeleteTranscriptTool: ToolConfig< name: 'Fireflies Delete Transcript', description: 'Delete a transcript from Fireflies.ai', version: '1.0.0', + effect: 'write', oauth: FIREFLIES_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/fireflies/get_transcript.ts b/apps/sim/tools/fireflies/get_transcript.ts index c50688cc5fb..8bf6a046348 100644 --- a/apps/sim/tools/fireflies/get_transcript.ts +++ b/apps/sim/tools/fireflies/get_transcript.ts @@ -14,6 +14,7 @@ export const firefliesGetTranscriptTool: ToolConfig< description: 'Get a single transcript with full details including summary, action items, and analytics', version: '1.0.0', + effect: 'read', oauth: FIREFLIES_CREDENTIAL_OAUTH, params: { diff --git a/apps/sim/tools/fireflies/get_user.ts b/apps/sim/tools/fireflies/get_user.ts index 101a90f9b74..5ec6a78c7ad 100644 --- a/apps/sim/tools/fireflies/get_user.ts +++ b/apps/sim/tools/fireflies/get_user.ts @@ -7,6 +7,7 @@ export const firefliesGetUserTool: ToolConfig name: 'Flow Add Link', description: 'Add a downstream relationship between Flow entities on the selected branch.', version: '1.0.0', + effect: 'write', oauth: FLOW_OAUTH, params: { ...FLOW_AUTH_PARAMS, diff --git a/apps/sim/tools/flow/create-branch.ts b/apps/sim/tools/flow/create-branch.ts index 7a0c5ac9119..6436bc8500e 100644 --- a/apps/sim/tools/flow/create-branch.ts +++ b/apps/sim/tools/flow/create-branch.ts @@ -16,6 +16,7 @@ export const flowCreateBranchTool: ToolConfig name: 'Gauge Get Tag', description: 'Read a prompt tag and its usage count.', version: '1.0.0', + effect: 'read', oauth: gaugeOAuth, params: { ...gaugeAuthParams, diff --git a/apps/sim/tools/gauge/get_topic.ts b/apps/sim/tools/gauge/get_topic.ts index 1f06b0d6673..986343f3d78 100644 --- a/apps/sim/tools/gauge/get_topic.ts +++ b/apps/sim/tools/gauge/get_topic.ts @@ -9,6 +9,7 @@ export const gaugeGetTopicTool: ToolConfig = description: 'Run a report on AI answers, citations, search queries, or AI bot traffic using metrics from the query catalog.', version: '1.0.0', + effect: 'read', oauth: gaugeOAuth, params: { ...gaugeAuthParams, diff --git a/apps/sim/tools/gauge/remove_tags_from_prompts.ts b/apps/sim/tools/gauge/remove_tags_from_prompts.ts index 6d43b279f73..7fa93ca80cd 100644 --- a/apps/sim/tools/gauge/remove_tags_from_prompts.ts +++ b/apps/sim/tools/gauge/remove_tags_from_prompts.ts @@ -21,6 +21,7 @@ export const gaugeRemoveTagsFromPromptsTool: ToolConfig< name: 'Gauge Remove Tags From Prompts', description: 'Remove a set of tags from the selected tracked prompts.', version: '1.0.0', + effect: 'write', oauth: gaugeOAuth, params: { ...gaugeAuthParams, diff --git a/apps/sim/tools/gauge/rename_topic.ts b/apps/sim/tools/gauge/rename_topic.ts index be80b6d1c26..f21e92779ab 100644 --- a/apps/sim/tools/gauge/rename_topic.ts +++ b/apps/sim/tools/gauge/rename_topic.ts @@ -13,6 +13,7 @@ export const gaugeRenameTopicTool: ToolConfig = JSON.parse( - '{"a2a_cancel_task":{"id":"a2a_cancel_task","name":"A2A Cancel Task","description":"Request cancellation of an in-progress A2A task.","version":"1.0.0","params":{"agentUrl":{"type":"string","required":true,"visibility":"user-only","description":"The A2A agent endpoint URL"},"taskId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The task ID to cancel"},"apiKey":{"type":"string","required":false,"visibility":"user-only","description":"API key for authentication (if required)"}},"hostedApiKey":"none"},"a2a_get_agent_card":{"id":"a2a_get_agent_card","name":"A2A Get Agent Card","description":"Fetch the Agent Card (discovery document) for an external A2A agent.","version":"1.0.0","params":{"agentUrl":{"type":"string","required":true,"visibility":"user-only","description":"The A2A agent endpoint URL"},"apiKey":{"type":"string","required":false,"visibility":"user-only","description":"API key for authentication (if required)"}},"hostedApiKey":"none"},"a2a_get_task":{"id":"a2a_get_task","name":"A2A Get Task","description":"Retrieve the current state and result of an A2A task.","version":"1.0.0","params":{"agentUrl":{"type":"string","required":true,"visibility":"user-only","description":"The A2A agent endpoint URL"},"taskId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The task ID to retrieve"},"historyLength":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of history messages to include"},"apiKey":{"type":"string","required":false,"visibility":"user-only","description":"API key for authentication (if required)"}},"hostedApiKey":"none"},"a2a_send_message":{"id":"a2a_send_message","name":"A2A Send Message","description":"Send a message to an external A2A agent and return its response.","version":"1.0.0","params":{"agentUrl":{"type":"string","required":true,"visibility":"user-only","description":"The A2A agent endpoint URL"},"message":{"type":"string","required":true,"visibility":"user-or-llm","description":"The message text to send"},"data":{"type":"json","required":false,"visibility":"user-or-llm","description":"Optional structured JSON data to attach"},"files":{"type":"json","required":false,"visibility":"user-or-llm","description":"Optional files to attach"},"taskId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Existing task ID to continue"},"contextId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Conversation context ID to continue"},"apiKey":{"type":"string","required":false,"visibility":"user-only","description":"API key for authentication (if required)"}},"hostedApiKey":"none"},"affinity_batch_update_entity_fields":{"id":"affinity_batch_update_entity_fields","name":"Affinity Batch Update Entity Fields","description":"Write up to 100 non-list field values on one company or person in a single request.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which entity to write the fields on: companies or persons"},"entityId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of that company or person"},"updates":{"type":"json","required":true,"visibility":"user-or-llm","description":"Up to 100 field updates as [{\\"id\\":\\"\\",\\"value\\":{\\"type\\":\\"…\\",\\"data\\":…}}], using the same value shapes as a single field update"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_batch_update_list_entry_fields":{"id":"affinity_batch_update_list_entry_fields","name":"Affinity Batch Update List Entry Fields","description":"Write up to 100 field values on one list row in a single request. Requires the \\"Export data from Lists\\" permission.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"listEntryId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list entry ID"},"updates":{"type":"json","required":true,"visibility":"user-or-llm","description":"Up to 100 field updates as [{\\"id\\":\\"\\",\\"value\\":{\\"type\\":\\"…\\",\\"data\\":…}}], using the same value shapes as a single field update"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_create_list":{"id":"affinity_create_list","name":"Affinity Create List","description":"Create a list. Its type fixes which entities it can hold, and the API key holder becomes its creator and owner.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the new list"},"type":{"type":"string","required":true,"visibility":"user-or-llm","description":"Entity kind the list holds: company, opportunity, or person"},"isPublic":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Whether everyone in the organization can see the list"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_create_list_field_dropdown_option":{"id":"affinity_create_list_field_dropdown_option","name":"Affinity Create List Field Dropdown Option","description":"Add a selectable option to a dropdown field on a list. A ranked or status option also needs a rank and a color.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"fieldId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The dropdown field ID on that list"},"type":{"type":"string","required":true,"visibility":"user-or-llm","description":"Kind of option to create, matching the field. dropdown takes only a label; ranked-dropdown also requires rank and color; status-dropdown additionally requires a status category. Sending a field the kind does not accept is rejected"},"text":{"type":"string","required":true,"visibility":"user-or-llm","description":"The option label"},"rank":{"type":"number","required":false,"visibility":"user-or-llm","description":"Sort order. Required on a ranked-dropdown or status-dropdown option"},"color":{"type":"string","required":false,"visibility":"user-or-llm","description":"Option color: white, gray, blue, green, purple, orange, or red. Required on a ranked-dropdown or status-dropdown option"},"statusCategory":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pipeline meaning of the option: open, won, lost, or on-hold. Status-dropdown options only"},"winRate":{"type":"number","required":false,"visibility":"user-or-llm","description":"Expected win rate of the status. Status-dropdown options only"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_create_merge":{"id":"affinity_create_merge","name":"Affinity Create Merge","description":"Fold a duplicate company or person into the record you are keeping. The merge runs asynchronously — poll the returned task to see it finish. Requires the \\"Manage duplicates\\" permission and an admin role.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"What to merge: companies or persons"},"primaryId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the record to keep"},"duplicateId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the duplicate record to fold in"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_create_note":{"id":"affinity_create_note","name":"Affinity Create Note","description":"Write a note — attached to companies, persons, and opportunities, anchored to a meeting, call, or chat message, or posted as a reply to an existing note.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"type":{"type":"string","required":true,"visibility":"user-or-llm","description":"Note shape: entities to attach it to records, interaction to anchor it to a meeting, call, or chat message, or user-reply to reply to a note"},"html":{"type":"string","required":true,"visibility":"user-or-llm","description":"The note body as HTML"},"companyIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Companies to attach the note to, e.g. [1, 2]. Not used on a reply"},"personIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Persons to attach the note to, e.g. [1, 2]. Not used on a reply"},"opportunityIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Opportunities to attach the note to, e.g. [1, 2]. Not used on a reply"},"interactionId":{"type":"string","required":false,"visibility":"user-or-llm","description":"The interaction to anchor the note to. Required for an interaction note"},"interactionType":{"type":"string","required":false,"visibility":"user-or-llm","description":"Kind of the anchoring interaction: meeting, call, or chat-message. Required for an interaction note"},"parentId":{"type":"string","required":false,"visibility":"user-or-llm","description":"The note being replied to. Required for a user-reply note"},"creatorId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Attribute the note to another internal person. Defaults to the API key holder"},"createdAt":{"type":"string","required":false,"visibility":"user-or-llm","description":"Backdate the note to this ISO 8601 timestamp"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_create_reminder":{"id":"affinity_create_reminder","name":"Affinity Create Reminder","description":"Create a reminder on one company, person, or opportunity. A recurring reminder resets whenever the chosen signal happens instead of firing once.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"type":{"type":"string","required":true,"visibility":"user-or-llm","description":"one-time to fire once, or recurring to reset on a signal"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"What the reminder is about: company, person, or opportunity"},"entityId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of that company, person, or opportunity"},"dueDate":{"type":"string","required":false,"visibility":"user-or-llm","description":"When the reminder is due, as an ISO 8601 timestamp. Required for a one-time reminder; on a recurring one Affinity computes it from the period when omitted"},"content":{"type":"string","required":false,"visibility":"user-or-llm","description":"What the reminder says"},"ownerId":{"type":"string","required":true,"visibility":"user-or-llm","description":"User the reminder is assigned to. Must be an internal user. The API key holder is recorded as the creator, which is a separate field"},"resetTrigger":{"type":"string","required":false,"visibility":"user-or-llm","description":"What restarts a recurring reminder: interaction, email, or event. Required when the type is recurring"},"periodDays":{"type":"number","required":false,"visibility":"user-or-llm","description":"Days between firings of a recurring reminder. Required when the type is recurring"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_delete_list_field_dropdown_option":{"id":"affinity_delete_list_field_dropdown_option","name":"Affinity Delete List Field Dropdown Option","description":"Permanently delete a dropdown option on a list field. Every list entry currently set to it is cleared, and those values cannot be recovered.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"fieldId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The dropdown field ID on that list"},"dropdownOptionId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The dropdown option ID to delete"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_delete_note":{"id":"affinity_delete_note","name":"Affinity Delete Note","description":"Delete a note you created. Deleting a root note also deletes its replies; deleting a reply removes only that reply.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"noteId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The note ID to delete"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_company":{"id":"affinity_get_company","name":"Affinity Get Company","description":"Look up one company by ID. Field data is returned only for the Field IDs or Field Types asked for.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"companyId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The company ID"},"fieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs to return values for, e.g. [\\"affinity-data-location\\"]. Mutually exclusive with Field Types"},"fieldTypes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field categories to return values for: enriched, global, or relationship-intelligence. Mutually exclusive with Field IDs"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_current_user":{"id":"affinity_get_current_user","name":"Affinity Get Current User","description":"Verify an Affinity API key and return the tenant, the user behind the key, and the scopes the grant carries.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_entity_field_value":{"id":"affinity_get_entity_field_value","name":"Affinity Get Entity Field Value","description":"Read one non-list field value from a company or person.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which entity to read the field from: companies or persons"},"entityId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of that company or person"},"fieldId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The field ID to read"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_list":{"id":"affinity_get_list","name":"Affinity Get List","description":"Read one list — its name, type, owner, and privacy setting.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_list_entry":{"id":"affinity_get_list_entry","name":"Affinity Get List Entry","description":"Read one row of a list with its entity. Field data is returned only for the Field IDs or Field Types asked for.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"listEntryId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list entry ID"},"fieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs to return values for, e.g. [\\"affinity-data-location\\"]. Mutually exclusive with Field Types"},"fieldTypes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field categories to return values for: enriched, global, list, or relationship-intelligence. Mutually exclusive with Field IDs"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_list_entry_field":{"id":"affinity_get_list_entry_field","name":"Affinity Get List Entry Field","description":"Read one field value on a list row.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"listEntryId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list entry ID"},"fieldId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The field ID to read"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_list_field_dropdown_option":{"id":"affinity_get_list_field_dropdown_option","name":"Affinity Get List Field Dropdown Option","description":"Read one dropdown option on a list field.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"fieldId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The dropdown field ID on that list"},"dropdownOptionId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The dropdown option ID"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_merge":{"id":"affinity_get_merge","name":"Affinity Get Merge","description":"Read the status of one company or person merge, including why it failed if it did.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which merge to read: companies or persons"},"mergeId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The merge ID"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_merge_task":{"id":"affinity_get_merge_task","name":"Affinity Get Merge Task","description":"Read one merge task and how its merges are progressing. Poll this after starting a merge.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which merge task to read: companies or persons"},"taskId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The merge task ID"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_note":{"id":"affinity_get_note","name":"Affinity Get Note","description":"Read one note with its body, author, mentions, and attached records.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"noteId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The note ID"},"includes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Extra properties to return, e.g. [\\"repliesCount\\",\\"personsPreview\\",\\"companiesPreview\\",\\"opportunitiesPreview\\"]. Those four fields are omitted unless requested here"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_opportunity":{"id":"affinity_get_opportunity","name":"Affinity Get Opportunity","description":"Read one opportunity and the list it belongs to. Its field data lives on the list entry.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"opportunityId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The opportunity ID"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_person":{"id":"affinity_get_person","name":"Affinity Get Person","description":"Look up one person by ID. Field data is returned only for the Field IDs or Field Types asked for.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"personId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The person ID"},"fieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs to return values for, e.g. [\\"affinity-data-location\\"]. Mutually exclusive with Field Types"},"fieldTypes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field categories to return values for: enriched, global, or relationship-intelligence. Mutually exclusive with Field IDs"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_saved_view":{"id":"affinity_get_saved_view","name":"Affinity Get Saved View","description":"Read one saved view — its name, kind, and creation date.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"viewId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The saved view ID"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_transcript":{"id":"affinity_get_transcript","name":"Affinity Get Transcript","description":"Read one transcript with its first 100 fragments. Page the fragments endpoint for a longer meeting.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"transcriptId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The transcript ID"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_user":{"id":"affinity_get_user","name":"Affinity Get User","description":"Read one internal user. A user and their person record share the same numeric ID, so a person ID works here.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"userId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The user ID, which is also their person ID"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_calls":{"id":"affinity_list_calls","name":"Affinity List Calls","description":"Page through logged calls and their participants. Only calls the API key holder can see are returned.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression, e.g. \\"createdAt>=2026-01-01\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_chat_messages":{"id":"affinity_list_chat_messages","name":"Affinity List Chat Messages","description":"Page through logged chat messages and their participants. Only messages the API key holder can see are returned.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression, e.g. \\"createdAt>=2026-01-01\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_companies":{"id":"affinity_list_companies","name":"Affinity List Companies","description":"Page through companies. Companies come back without field data unless Field IDs or Field Types asks for it.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"ids":{"type":"json","required":false,"visibility":"user-or-llm","description":"Restrict the page to these company IDs, e.g. [1, 2, 3]"},"fieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs to return values for, e.g. [\\"affinity-data-location\\"]. Mutually exclusive with Field Types"},"fieldTypes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field categories to return values for: enriched, global, or relationship-intelligence. Mutually exclusive with Field IDs"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_coworker_connections":{"id":"affinity_list_coworker_connections","name":"Affinity List Coworker Connections","description":"Find warm paths into a company through shared work history: who in your Affinity data once worked alongside the people you want to reach. Grouped by target, strongest first.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"filter":{"type":"string","required":true,"visibility":"user-or-llm","description":"Required scope. The only supported filter is target.currentCompany.id, e.g. \\"target.currentCompany.id=123\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of targets to return per page, 1-50. Defaults to 20"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_emails":{"id":"affinity_list_emails","name":"Affinity List Emails","description":"Page through email metadata — subject, participants, and timestamps. Affinity never exposes email bodies through the API.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression, e.g. \\"createdAt>=2026-01-01\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_entity_field_values":{"id":"affinity_list_entity_field_values","name":"Affinity List Entity Field Values","description":"Page through a company\'s or person\'s non-list field values. List fields are not returned here — read those through the list entry.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which entity to read field values from: companies or persons"},"entityId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of that company or person"},"ids":{"type":"json","required":false,"visibility":"user-or-llm","description":"Restrict to these field IDs. Mutually exclusive with Field Types"},"types":{"type":"json","required":false,"visibility":"user-or-llm","description":"Restrict to these field categories: enriched, global, relationship-intelligence. Mutually exclusive with Field IDs"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 20"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_entity_list_entries":{"id":"affinity_list_entity_list_entries","name":"Affinity List Entity List Entries","description":"Page through a company\'s or person\'s rows across every list, each carrying that list\'s field values and when the entity was added.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which entity to look up the rows of: companies or persons"},"entityId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of that company or person"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_entity_lists":{"id":"affinity_list_entity_lists","name":"Affinity List Entity Lists","description":"List every list a company or person appears on that the caller can view.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which entity to look up the lists of: companies or persons"},"entityId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of that company or person"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_entity_notes":{"id":"affinity_list_entity_notes","name":"Affinity List Entity Notes","description":"List the notes relevant to one company, person, or opportunity — directly attached notes plus notes reaching it through its people and meetings.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which entity the notes hang off: companies, persons, or opportunities"},"entityId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of that company, person, or opportunity"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression, e.g. \\"createdAt>=2026-01-01\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_entity_relationships":{"id":"affinity_list_entity_relationships","name":"Affinity List Entity Relationships","description":"List who knows a company or person, scored 0.0 to 1.0 by how much the two actually interact. Strongest first by default.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which entity to look up relationships for: companies or persons"},"entityId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of that company or person"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression. This endpoint filters on interactionScore only, e.g. \\"interactionScore>=0.5\\""},"orderBy":{"type":"json","required":false,"visibility":"user-or-llm","description":"Sort order: [\\"interactionScore\\"] for weakest first, [\\"-interactionScore\\"] for strongest first (the default)"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_field_dropdown_options":{"id":"affinity_list_field_dropdown_options","name":"Affinity List Field Dropdown Options","description":"List the selectable options on a dropdown or ranked-dropdown company or person field. Writing such a field needs the option ID, not its text.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which field family the field belongs to: companies or persons"},"fieldId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The dropdown or ranked-dropdown field ID"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_field_metadata":{"id":"affinity_list_field_metadata","name":"Affinity List Field Metadata","description":"List the non-list company or person fields, with the value type, filter operators, and sort support of each. Start here to find the Field IDs the read and write tools take.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which fields to describe: companies or persons"},"includes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Extra properties to return: [\\"filterability\\",\\"sortability\\"]. Both are omitted unless requested here"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression. This endpoint filters on name only, e.g. \\"name=~Status\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_field_value_changes":{"id":"affinity_list_field_value_changes","name":"Affinity List Field Value Changes","description":"Page through field value changes across the whole workspace. Built for delta sync: follow nextCursor to the end of a run, then resume from the last cursor next time.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression over field.id, listEntry.id, changer.id, changedAt, or actionType. Resume a sync with e.g. \\"changedAt>2026-06-01T12:00:00Z\\""},"orderBy":{"type":"json","required":false,"visibility":"user-or-llm","description":"Sort order: [\\"changedAt\\"] for oldest first (the default), [\\"-changedAt\\"] for newest first"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_investor_executive_connections":{"id":"affinity_list_investor_executive_connections","name":"Affinity List Investor Executive Connections","description":"Find warm paths into a company through investment history: which investors in your Affinity data backed a company the people you want to reach once led. Grouped by target, strongest first.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"filter":{"type":"string","required":true,"visibility":"user-or-llm","description":"Required scope. The only supported filter is target.currentCompany.id, e.g. \\"target.currentCompany.id=123\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of targets to return per page, 1-50. Defaults to 20"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_list_entries":{"id":"affinity_list_list_entries","name":"Affinity List List Entries","description":"Page through the rows of a list. Rows come back without field data unless Field IDs or Field Types asks for it.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"fieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs to return values for, e.g. [\\"affinity-data-location\\"]. Mutually exclusive with Field Types"},"fieldTypes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field categories to return values for: enriched, global, list, or relationship-intelligence. Mutually exclusive with Field IDs"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_list_entry_field_value_changes":{"id":"affinity_list_list_entry_field_value_changes","name":"Affinity List List Entry Field Value Changes","description":"Page through the history of one list row — who changed which field, when, and to what.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"listEntryId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list entry ID"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression over field.id, changer.id, changedAt, or actionType, e.g. \\"field.id=field-1234\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_list_entry_fields":{"id":"affinity_list_list_entry_fields","name":"Affinity List List Entry Fields","description":"Page through every field value on one list row, including the list-specific columns. All fields are returned unless narrowed.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"listEntryId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list entry ID"},"ids":{"type":"json","required":false,"visibility":"user-or-llm","description":"Restrict to these field IDs. Mutually exclusive with Field Types"},"types":{"type":"json","required":false,"visibility":"user-or-llm","description":"Restrict to these field categories: enriched, global, list, relationship-intelligence. Mutually exclusive with Field IDs"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 20"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_list_field_dropdown_options":{"id":"affinity_list_list_field_dropdown_options","name":"Affinity List List Field Dropdown Options","description":"List the selectable options on a dropdown, ranked-dropdown, or status-dropdown field of a list.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"fieldId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The dropdown field ID on that list"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_list_fields":{"id":"affinity_list_list_fields","name":"Affinity List List Fields","description":"List the fields available on one list, including its list-specific columns. Use these Field IDs when reading or writing list entries.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"includes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Extra properties to return: [\\"filterability\\",\\"sortability\\"]. Both are omitted unless requested here"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression. This endpoint filters on name only, e.g. \\"name=~Stage\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_lists":{"id":"affinity_list_lists","name":"Affinity List Lists","description":"Page through the lists in the organization that the caller can view.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"term":{"type":"string","required":false,"visibility":"user-or-llm","description":"Case-insensitive substring match on the list name"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_meetings":{"id":"affinity_list_meetings","name":"Affinity List Meetings","description":"Page through past and upcoming meetings with their organizer and attendees.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression, e.g. \\"createdAt>=2026-01-01\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_merge_tasks":{"id":"affinity_list_merge_tasks","name":"Affinity List Merge Tasks","description":"Page through merge tasks, each summarizing how many of its merges are in progress, succeeded, or failed.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which merge tasks to list: companies or persons"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression. This endpoint filters on status only, e.g. \\"status=in-progress\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_merges":{"id":"affinity_list_merges","name":"Affinity List Merges","description":"Page through the company or person merges the organization has run, with the status and the records involved in each.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which merges to list: companies or persons"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression over status or taskId, e.g. \\"status=failed\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_note_attached_companies":{"id":"affinity_list_note_attached_companies","name":"Affinity List Note Attached Companies","description":"List the companies directly attached to one note.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"noteId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The note ID"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_note_attached_opportunities":{"id":"affinity_list_note_attached_opportunities","name":"Affinity List Note Attached Opportunities","description":"List the opportunities directly attached to one note.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"noteId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The note ID"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_note_attached_persons":{"id":"affinity_list_note_attached_persons","name":"Affinity List Note Attached Persons","description":"List the persons directly attached to one note.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"noteId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The note ID"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_note_replies":{"id":"affinity_list_note_replies","name":"Affinity List Note Replies","description":"Page through the replies on one note, including AI Notetaker replies.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"noteId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The note ID whose replies to read"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression, e.g. \\"createdAt>=2026-01-01\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_notes":{"id":"affinity_list_notes","name":"Affinity List Notes","description":"Page through every note the caller can see. Replies are excluded.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"includes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Extra properties to return, e.g. [\\"repliesCount\\",\\"personsPreview\\",\\"companiesPreview\\",\\"opportunitiesPreview\\"]. Those four fields are omitted unless requested here"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression, e.g. \\"createdAt>=2026-01-01\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_opportunities":{"id":"affinity_list_opportunities","name":"Affinity List Opportunities","description":"Page through opportunities. Field data lives on the list entry, not here — read it through the list or saved view the opportunity belongs to.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"ids":{"type":"json","required":false,"visibility":"user-or-llm","description":"Restrict the page to these opportunity IDs, e.g. [1, 2, 3]"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_persons":{"id":"affinity_list_persons","name":"Affinity List Persons","description":"Page through persons. Persons come back without field data unless Field IDs or Field Types asks for it.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"ids":{"type":"json","required":false,"visibility":"user-or-llm","description":"Restrict the page to these person IDs, e.g. [1, 2, 3]"},"fieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs to return values for, e.g. [\\"affinity-data-location\\"]. Mutually exclusive with Field Types"},"fieldTypes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field categories to return values for: enriched, global, or relationship-intelligence. Mutually exclusive with Field IDs"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_reminders":{"id":"affinity_list_reminders","name":"Affinity List Reminders","description":"Page through the reminders the caller can see. Filter by status to surface what is overdue.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression, e.g. \\"createdAt>=2026-01-01\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_saved_view_entries":{"id":"affinity_list_saved_view_entries","name":"Affinity List Saved View Entries","description":"Page through the rows of a saved view. The view\'s own filters and columns decide which rows and which field data come back.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"viewId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The saved view ID"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_saved_views":{"id":"affinity_list_saved_views","name":"Affinity List Saved Views","description":"List the saved views on a list that the caller can view.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_transcript_fragments":{"id":"affinity_list_transcript_fragments","name":"Affinity List Transcript Fragments","description":"Page through everything said in a meeting, segment by segment with the speaker.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"transcriptId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The transcript ID"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_transcripts":{"id":"affinity_list_transcripts","name":"Affinity List Transcripts","description":"Page through meeting transcript metadata. Read one transcript to get what was actually said.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression, e.g. \\"createdAt>=2026-01-01\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_users":{"id":"affinity_list_users","name":"Affinity List Users","description":"Page through the internal users in the organization. Email addresses and roles are returned only to callers with the \\"Manage Users\\" permission.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"term":{"type":"string","required":false,"visibility":"user-or-llm","description":"Case-insensitive match across first name, last name, and primary email"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression over id or status, e.g. \\"status=active\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_search_companies":{"id":"affinity_search_companies","name":"Affinity Search Companies","description":"Search companies by filters, sorts, and a free-text term. Requires the \\"Export All Organizations directory\\" permission.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"filters":{"type":"json","required":false,"visibility":"user-or-llm","description":"Filter group as {operator: \\"and\\"|\\"or\\", filters: [...]}, at most 50 leaves. Each leaf is {valueType, fieldId, operator, value}, and a leaf may itself be a nested group"},"searchTerm":{"type":"string","required":false,"visibility":"user-or-llm","description":"Free-text term matched against the searchable fields. At least 3 characters"},"searchFieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs the search term is matched against. Defaults to the searchable fields"},"sorts":{"type":"json","required":false,"visibility":"user-or-llm","description":"Sort order as [{fieldId, direction: \\"asc\\"|\\"desc\\", attributeId?}], up to 5, applied in order"},"fieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs to return values for, e.g. [\\"affinity-data-location\\"]. Mutually exclusive with Field Types"},"fieldTypes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field categories to return values for: enriched, global, or relationship-intelligence. Mutually exclusive with Field IDs"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_search_files":{"id":"affinity_search_files","name":"Affinity Search Files","description":"Search files by keyword, ordered by relevance. Narrow to specific files or to one company, or leave both unset to search the whole account.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"prompt":{"type":"string","required":true,"visibility":"user-or-llm","description":"What to search for. Between 3 and 500 characters"},"ids":{"type":"json","required":false,"visibility":"user-or-llm","description":"Restrict the search to these file IDs. Cannot be combined with Company ID"},"companyId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Restrict the search to one company\'s files. Cannot be combined with file IDs"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of files to return, 1-100. Defaults to 20"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_search_list_entries":{"id":"affinity_search_list_entries","name":"Affinity Search List Entries","description":"Search the rows of one list by filters, sorts, and a free-text term. Requires the \\"Export data from Lists\\" permission.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID to search"},"filters":{"type":"json","required":false,"visibility":"user-or-llm","description":"Filter group as {operator: \\"and\\"|\\"or\\", filters: [...]}, at most 50 leaves. Each leaf is {valueType, fieldId, operator, value}, and a leaf may itself be a nested group"},"searchTerm":{"type":"string","required":false,"visibility":"user-or-llm","description":"Free-text term matched against the searchable fields. At least 3 characters"},"searchFieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs the search term is matched against. Defaults to the searchable fields"},"sorts":{"type":"json","required":false,"visibility":"user-or-llm","description":"Sort order as [{fieldId, direction: \\"asc\\"|\\"desc\\", attributeId?}], up to 5, applied in order"},"fieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs to return values for, e.g. [\\"affinity-data-location\\"]. Mutually exclusive with Field Types"},"fieldTypes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field categories to return values for: enriched, global, list, or relationship-intelligence. Mutually exclusive with Field IDs"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_search_notes":{"id":"affinity_search_notes","name":"Affinity Search Notes","description":"Search notes by keyword, ordered by relevance. Narrow to specific notes or to one company, or leave both unset to search the whole account.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"prompt":{"type":"string","required":true,"visibility":"user-or-llm","description":"What to search for. Between 3 and 500 characters"},"ids":{"type":"json","required":false,"visibility":"user-or-llm","description":"Restrict the search to these note IDs. Cannot be combined with Company ID"},"companyId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Restrict the search to one company\'s notes. Cannot be combined with note IDs"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of notes to return, 1-100. Defaults to 20"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_search_persons":{"id":"affinity_search_persons","name":"Affinity Search Persons","description":"Search persons by filters, sorts, and a free-text term. Requires the \\"Export All People directory\\" permission.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"filters":{"type":"json","required":false,"visibility":"user-or-llm","description":"Filter group as {operator: \\"and\\"|\\"or\\", filters: [...]}, at most 50 leaves. Each leaf is {valueType, fieldId, operator, value}, and a leaf may itself be a nested group"},"searchTerm":{"type":"string","required":false,"visibility":"user-or-llm","description":"Free-text term matched against the searchable fields. At least 3 characters"},"searchFieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs the search term is matched against. Defaults to the searchable fields"},"sorts":{"type":"json","required":false,"visibility":"user-or-llm","description":"Sort order as [{fieldId, direction: \\"asc\\"|\\"desc\\", attributeId?}], up to 5, applied in order"},"fieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs to return values for, e.g. [\\"affinity-data-location\\"]. Mutually exclusive with Field Types"},"fieldTypes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field categories to return values for: enriched, global, or relationship-intelligence. Mutually exclusive with Field IDs"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_semantic_search":{"id":"affinity_semantic_search","name":"Affinity Semantic Search","description":"Find companies from a description in plain language — industry, technology, stage, or business model. Currently searches companies only.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"prompt":{"type":"string","required":true,"visibility":"user-or-llm","description":"What to look for, in plain language, e.g. \\"climate tech companies in our pipeline\\". Up to 500 characters"},"listIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Restrict the search to companies on these lists, e.g. [1, 2]"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of companies to return, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_update_entity_field_value":{"id":"affinity_update_entity_field_value","name":"Affinity Update Entity Field Value","description":"Write one non-list field value on a company or person. The value type must match how the field is defined.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which entity to write the field on: companies or persons"},"entityId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of that company or person"},"fieldId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The field ID to write"},"value":{"type":"json","required":true,"visibility":"user-or-llm","description":"The new value as {type, data}, where type matches the field\'s value type. Examples: {\\"type\\":\\"text\\",\\"data\\":\\"Series B\\"}, {\\"type\\":\\"number\\",\\"data\\":42}, {\\"type\\":\\"dropdown\\",\\"data\\":{\\"dropdownOptionId\\":7}}, {\\"type\\":\\"person\\",\\"data\\":{\\"id\\":123}}, {\\"type\\":\\"person-multi\\",\\"data\\":[{\\"id\\":123}]}. Pass data as null to clear the field"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_update_list_entry_field":{"id":"affinity_update_list_entry_field","name":"Affinity Update List Entry Field","description":"Write one field value on a list row. Requires the \\"Export data from Lists\\" permission.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"listEntryId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list entry ID"},"fieldId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The field ID to write"},"value":{"type":"json","required":true,"visibility":"user-or-llm","description":"The new value as {type, data}, where type matches the field\'s value type. Examples: {\\"type\\":\\"text\\",\\"data\\":\\"Series B\\"}, {\\"type\\":\\"number\\",\\"data\\":42}, {\\"type\\":\\"dropdown\\",\\"data\\":{\\"dropdownOptionId\\":7}}, {\\"type\\":\\"person\\",\\"data\\":{\\"id\\":123}}, {\\"type\\":\\"person-multi\\",\\"data\\":[{\\"id\\":123}]}. Pass data as null to clear the field"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_update_list_field_dropdown_option":{"id":"affinity_update_list_field_dropdown_option","name":"Affinity Update List Field Dropdown Option","description":"Change a dropdown option on a list field. Every field is optional — supply only what should change, and only fields the option\'s kind actually has.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"fieldId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The dropdown field ID on that list"},"dropdownOptionId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The dropdown option ID to update"},"text":{"type":"string","required":false,"visibility":"user-or-llm","description":"Replacement option label. Supply at least one field to change"},"rank":{"type":"number","required":false,"visibility":"user-or-llm","description":"Sort order. Required on a ranked-dropdown or status-dropdown option"},"color":{"type":"string","required":false,"visibility":"user-or-llm","description":"Option color: white, gray, blue, green, purple, orange, or red. Required on a ranked-dropdown or status-dropdown option"},"statusCategory":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pipeline meaning of the option: open, won, lost, or on-hold. Status-dropdown options only"},"winRate":{"type":"number","required":false,"visibility":"user-or-llm","description":"Expected win rate of the status. Status-dropdown options only"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_update_note":{"id":"affinity_update_note","name":"Affinity Update Note","description":"Rewrite a note\'s body or replace which records it is attached to. Each list of IDs replaces that association wholesale, an empty list clears it, and omitting one leaves it untouched. A note\'s type cannot be changed.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"noteId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The note ID to update"},"html":{"type":"string","required":false,"visibility":"user-or-llm","description":"Replacement note body as HTML"},"companyIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Replacement set of attached companies, e.g. [1, 2]. Send [] to detach every company; omit to leave them unchanged"},"personIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Replacement set of attached persons, e.g. [1, 2]. Send [] to detach every person; omit to leave them unchanged"},"opportunityIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Replacement set of attached opportunities, e.g. [1, 2]. Send [] to detach every opportunity; omit to leave them unchanged"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_create_draft":{"id":"agentmail_create_draft","name":"Create Draft","description":"Create a new email draft in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox to create the draft in"},"to":{"type":"string","required":false,"visibility":"user-or-llm","description":"Recipient email addresses (comma-separated)"},"subject":{"type":"string","required":false,"visibility":"user-or-llm","description":"Draft subject line"},"text":{"type":"string","required":false,"visibility":"user-or-llm","description":"Plain text draft body"},"html":{"type":"string","required":false,"visibility":"user-or-llm","description":"HTML draft body"},"cc":{"type":"string","required":false,"visibility":"user-or-llm","description":"CC recipient email addresses (comma-separated)"},"bcc":{"type":"string","required":false,"visibility":"user-or-llm","description":"BCC recipient email addresses (comma-separated)"},"inReplyTo":{"type":"string","required":false,"visibility":"user-or-llm","description":"ID of message being replied to"},"sendAt":{"type":"string","required":false,"visibility":"user-or-llm","description":"ISO 8601 timestamp to schedule sending"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_create_inbox":{"id":"agentmail_create_inbox","name":"Create Inbox","description":"Create a new email inbox with AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"username":{"type":"string","required":false,"visibility":"user-or-llm","description":"Username for the inbox email address"},"domain":{"type":"string","required":false,"visibility":"user-or-llm","description":"Domain for the inbox email address"},"displayName":{"type":"string","required":false,"visibility":"user-or-llm","description":"Display name for the inbox"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_delete_draft":{"id":"agentmail_delete_draft","name":"Delete Draft","description":"Delete an email draft in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox containing the draft"},"draftId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the draft to delete"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_delete_inbox":{"id":"agentmail_delete_inbox","name":"Delete Inbox","description":"Delete an email inbox in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox to delete"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_delete_thread":{"id":"agentmail_delete_thread","name":"Delete Thread","description":"Delete an email thread in AgentMail (moves to trash, or permanently deletes if already in trash)","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox containing the thread"},"threadId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the thread to delete"},"permanent":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Force permanent deletion instead of moving to trash"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_forward_message":{"id":"agentmail_forward_message","name":"Forward Message","description":"Forward an email message to new recipients in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox containing the message"},"messageId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the message to forward"},"to":{"type":"string","required":true,"visibility":"user-or-llm","description":"Recipient email addresses (comma-separated)"},"subject":{"type":"string","required":false,"visibility":"user-or-llm","description":"Override subject line"},"text":{"type":"string","required":false,"visibility":"user-or-llm","description":"Additional plain text to prepend"},"html":{"type":"string","required":false,"visibility":"user-or-llm","description":"Additional HTML to prepend"},"cc":{"type":"string","required":false,"visibility":"user-or-llm","description":"CC recipient email addresses (comma-separated)"},"bcc":{"type":"string","required":false,"visibility":"user-or-llm","description":"BCC recipient email addresses (comma-separated)"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_get_draft":{"id":"agentmail_get_draft","name":"Get Draft","description":"Get details of a specific email draft in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox the draft belongs to"},"draftId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the draft to retrieve"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_get_inbox":{"id":"agentmail_get_inbox","name":"Get Inbox","description":"Get details of a specific email inbox in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox to retrieve"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_get_message":{"id":"agentmail_get_message","name":"Get Message","description":"Get details of a specific email message in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox containing the message"},"messageId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the message to retrieve"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_get_thread":{"id":"agentmail_get_thread","name":"Get Thread","description":"Get details of a specific email thread including messages in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox containing the thread"},"threadId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the thread to retrieve"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_list_drafts":{"id":"agentmail_list_drafts","name":"List Drafts","description":"List email drafts in an inbox in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox to list drafts from"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of drafts to return"},"pageToken":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination token for next page of results"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_list_inboxes":{"id":"agentmail_list_inboxes","name":"List Inboxes","description":"List all email inboxes in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of inboxes to return"},"pageToken":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination token for next page of results"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_list_messages":{"id":"agentmail_list_messages","name":"List Messages","description":"List messages in an inbox in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox to list messages from"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of messages to return"},"pageToken":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination token for next page of results"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_list_threads":{"id":"agentmail_list_threads","name":"List Threads","description":"List email threads in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox to list threads from"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of threads to return"},"pageToken":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination token for next page of results"},"labels":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated labels to filter threads by"},"before":{"type":"string","required":false,"visibility":"user-or-llm","description":"Filter threads before this ISO 8601 timestamp"},"after":{"type":"string","required":false,"visibility":"user-or-llm","description":"Filter threads after this ISO 8601 timestamp"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_reply_message":{"id":"agentmail_reply_message","name":"Reply to Message","description":"Reply to an existing email message in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox to reply from"},"messageId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the message to reply to"},"text":{"type":"string","required":false,"visibility":"user-or-llm","description":"Plain text reply body"},"html":{"type":"string","required":false,"visibility":"user-or-llm","description":"HTML reply body"},"to":{"type":"string","required":false,"visibility":"user-or-llm","description":"Override recipient email addresses (comma-separated)"},"cc":{"type":"string","required":false,"visibility":"user-or-llm","description":"CC email addresses (comma-separated)"},"bcc":{"type":"string","required":false,"visibility":"user-or-llm","description":"BCC email addresses (comma-separated)"},"replyAll":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Reply to all recipients of the original message"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_send_draft":{"id":"agentmail_send_draft","name":"Send Draft","description":"Send an existing email draft in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox containing the draft"},"draftId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the draft to send"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_send_message":{"id":"agentmail_send_message","name":"Send Message","description":"Send an email message from an AgentMail inbox","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox to send from"},"to":{"type":"string","required":true,"visibility":"user-or-llm","description":"Recipient email address (comma-separated for multiple)"},"subject":{"type":"string","required":true,"visibility":"user-or-llm","description":"Email subject line"},"text":{"type":"string","required":false,"visibility":"user-or-llm","description":"Plain text email body"},"html":{"type":"string","required":false,"visibility":"user-or-llm","description":"HTML email body"},"cc":{"type":"string","required":false,"visibility":"user-or-llm","description":"CC recipient email addresses (comma-separated)"},"bcc":{"type":"string","required":false,"visibility":"user-or-llm","description":"BCC recipient email addresses (comma-separated)"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_update_draft":{"id":"agentmail_update_draft","name":"Update Draft","description":"Update an existing email draft in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox containing the draft"},"draftId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the draft to update"},"to":{"type":"string","required":false,"visibility":"user-or-llm","description":"Recipient email addresses (comma-separated)"},"subject":{"type":"string","required":false,"visibility":"user-or-llm","description":"Draft subject line"},"text":{"type":"string","required":false,"visibility":"user-or-llm","description":"Plain text draft body"},"html":{"type":"string","required":false,"visibility":"user-or-llm","description":"HTML draft body"},"cc":{"type":"string","required":false,"visibility":"user-or-llm","description":"CC recipient email addresses (comma-separated)"},"bcc":{"type":"string","required":false,"visibility":"user-or-llm","description":"BCC recipient email addresses (comma-separated)"},"sendAt":{"type":"string","required":false,"visibility":"user-or-llm","description":"ISO 8601 timestamp to schedule sending"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_update_inbox":{"id":"agentmail_update_inbox","name":"Update Inbox","description":"Update the display name of an email inbox in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox to update"},"displayName":{"type":"string","required":true,"visibility":"user-or-llm","description":"New display name for the inbox"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_update_message":{"id":"agentmail_update_message","name":"Update Message","description":"Add or remove labels on an email message in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox containing the message"},"messageId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the message to update"},"addLabels":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated labels to add to the message"},"removeLabels":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated labels to remove from the message"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_update_thread":{"id":"agentmail_update_thread","name":"Update Thread Labels","description":"Add or remove labels on an email thread in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox containing the thread"},"threadId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the thread to update"},"addLabels":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated labels to add to the thread"},"removeLabels":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated labels to remove from the thread"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_create_call":{"id":"agentphone_create_call","name":"Create Outbound Call","description":"Initiate an outbound voice call from an AgentPhone agent","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"agentId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Agent that will handle the call"},"toNumber":{"type":"string","required":true,"visibility":"user-or-llm","description":"Phone number to call in E.164 format (e.g. +14155551234)"},"fromNumberId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Phone number ID to use as caller ID. Must belong to the agent. If omitted, the agent\'s first assigned number is used."},"initialGreeting":{"type":"string","required":false,"visibility":"user-or-llm","description":"Optional greeting spoken when the recipient answers"},"voice":{"type":"string","required":false,"visibility":"user-or-llm","description":"Voice ID override for this call (defaults to the agent\'s configured voice)"},"systemPrompt":{"type":"string","required":false,"visibility":"user-or-llm","description":"When provided, uses a built-in LLM for the conversation instead of forwarding to your webhook"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_create_contact":{"id":"agentphone_create_contact","name":"Create Contact","description":"Create a new contact in AgentPhone","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"phoneNumber":{"type":"string","required":true,"visibility":"user-or-llm","description":"Phone number in E.164 format (e.g. +14155551234)"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Contact\'s full name"},"email":{"type":"string","required":false,"visibility":"user-or-llm","description":"Contact\'s email address"},"notes":{"type":"string","required":false,"visibility":"user-or-llm","description":"Freeform notes stored on the contact"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_create_number":{"id":"agentphone_create_number","name":"Create Phone Number","description":"Provision a new SMS- and voice-enabled phone number","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Two-letter country code (e.g. US, CA). Defaults to US."},"areaCode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Preferred area code (US/CA only, e.g. \\"415\\"). Best-effort — may be ignored if unavailable."},"agentId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Optionally attach the number to an agent immediately"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_delete_contact":{"id":"agentphone_delete_contact","name":"Delete Contact","description":"Delete a contact by ID","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"contactId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Contact ID"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_get_call":{"id":"agentphone_get_call","name":"Get Call","description":"Fetch a call and its full transcript","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"callId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the call to retrieve"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_get_call_transcript":{"id":"agentphone_get_call_transcript","name":"Get Call Transcript","description":"Get the full ordered transcript for a call","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"callId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the call to retrieve the transcript for"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_get_contact":{"id":"agentphone_get_contact","name":"Get Contact","description":"Fetch a single contact by ID","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"contactId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Contact ID"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_get_conversation":{"id":"agentphone_get_conversation","name":"Get Conversation","description":"Get a conversation along with its recent messages","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"conversationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Conversation ID"},"messageLimit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of recent messages to include (default 50, max 100)"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_get_conversation_messages":{"id":"agentphone_get_conversation_messages","name":"Get Conversation Messages","description":"Get paginated messages for a conversation","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"conversationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Conversation ID"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of messages to return (default 50, max 200)"},"before":{"type":"string","required":false,"visibility":"user-or-llm","description":"Return messages received before this ISO 8601 timestamp"},"after":{"type":"string","required":false,"visibility":"user-or-llm","description":"Return messages received after this ISO 8601 timestamp"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_get_number_messages":{"id":"agentphone_get_number_messages","name":"Get Phone Number Messages","description":"Fetch messages received on a specific phone number","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"numberId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the phone number"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of messages to return (default 50, max 200)"},"before":{"type":"string","required":false,"visibility":"user-or-llm","description":"Return messages received before this ISO 8601 timestamp"},"after":{"type":"string","required":false,"visibility":"user-or-llm","description":"Return messages received after this ISO 8601 timestamp"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_get_usage":{"id":"agentphone_get_usage","name":"Get Usage","description":"Retrieve current usage statistics for the AgentPhone account","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_get_usage_daily":{"id":"agentphone_get_usage_daily","name":"Get Daily Usage","description":"Get a daily breakdown of usage (messages, calls, webhooks) for the last N days","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"days":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of days to return (1-365, default 30)"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_get_usage_monthly":{"id":"agentphone_get_usage_monthly","name":"Get Monthly Usage","description":"Get monthly usage aggregation (messages, calls, webhooks) for the last N months","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"months":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of months to return (1-24, default 6)"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_list_calls":{"id":"agentphone_list_calls","name":"List Calls","description":"List voice calls for this AgentPhone account","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of results to return (default 20, max 100)"},"offset":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of results to skip (min 0)"},"status":{"type":"string","required":false,"visibility":"user-or-llm","description":"Filter by status (completed, in-progress, failed)"},"direction":{"type":"string","required":false,"visibility":"user-or-llm","description":"Filter by direction (inbound, outbound)"},"type":{"type":"string","required":false,"visibility":"user-or-llm","description":"Filter by call type (pstn, web)"},"search":{"type":"string","required":false,"visibility":"user-or-llm","description":"Search by phone number (matches fromNumber or toNumber)"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_list_contacts":{"id":"agentphone_list_contacts","name":"List Contacts","description":"List contacts for this AgentPhone account","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"search":{"type":"string","required":false,"visibility":"user-or-llm","description":"Filter by name or phone number (case-insensitive contains)"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of results to return (default 50, max 200)"},"offset":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of results to skip (min 0)"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_list_conversations":{"id":"agentphone_list_conversations","name":"List Conversations","description":"List conversations (message threads) for this AgentPhone account","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of results to return (default 20, max 100)"},"offset":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of results to skip (min 0)"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_list_numbers":{"id":"agentphone_list_numbers","name":"List Phone Numbers","description":"List all phone numbers provisioned for this AgentPhone account","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of results to return (default 20, max 100)"},"offset":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of results to skip (min 0)"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_react_to_message":{"id":"agentphone_react_to_message","name":"React to Message","description":"Send an iMessage tapback reaction to a message (iMessage only)","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"messageId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the message to react to"},"reaction":{"type":"string","required":true,"visibility":"user-or-llm","description":"Reaction type: love, like, dislike, laugh, emphasize, or question"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_release_number":{"id":"agentphone_release_number","name":"Release Phone Number","description":"Release (delete) a phone number. This action is irreversible.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"numberId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the phone number to release"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_send_message":{"id":"agentphone_send_message","name":"Send Message","description":"Send an outbound SMS or iMessage from an AgentPhone agent","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"agentId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Agent sending the message"},"toNumber":{"type":"string","required":true,"visibility":"user-or-llm","description":"Recipient phone number in E.164 format (e.g. +14155551234)"},"body":{"type":"string","required":true,"visibility":"user-or-llm","description":"Message text to send"},"mediaUrl":{"type":"string","required":false,"visibility":"user-or-llm","description":"Optional URL of an image, video, or file to attach"},"numberId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Phone number ID to send from. If omitted, the agent\'s first assigned number is used."}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_update_contact":{"id":"agentphone_update_contact","name":"Update Contact","description":"Update a contact\'s fields","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"contactId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Contact ID"},"phoneNumber":{"type":"string","required":false,"visibility":"user-or-llm","description":"New phone number in E.164 format"},"name":{"type":"string","required":false,"visibility":"user-or-llm","description":"New contact name"},"email":{"type":"string","required":false,"visibility":"user-or-llm","description":"New email address"},"notes":{"type":"string","required":false,"visibility":"user-or-llm","description":"New freeform notes"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_update_conversation":{"id":"agentphone_update_conversation","name":"Update Conversation","description":"Update conversation metadata (stored state). Pass null to clear existing metadata.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"conversationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Conversation ID"},"metadata":{"type":"json","required":false,"visibility":"user-or-llm","description":"Custom key-value metadata to store on the conversation. Pass null to clear existing metadata."}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agiloft_async_status":{"id":"agiloft_async_status","name":"Agiloft Async Status","description":"Check whether an asynchronous Agiloft call, such as a run action button, has completed.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table the asynchronous call was made against"},"callbackId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Callback ID returned by the asynchronous call, e.g. from Run Action Button"}},"hostedApiKey":"none"},"agiloft_attach_file":{"id":"agiloft_attach_file","name":"Agiloft Attach File","description":"Attach a file to a field in an Agiloft record.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\")"},"recordId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the record to attach the file to"},"fieldName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the attachment field"},"file":{"type":"file","required":true,"visibility":"user-or-llm","description":"File to attach"},"fileName":{"type":"string","required":false,"visibility":"user-or-llm","description":"Name to assign to the file (defaults to original file name)"},"overwrite":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Replace the contents of the field instead of adding another file to it"}},"hostedApiKey":"none"},"agiloft_attachment_info":{"id":"agiloft_attachment_info","name":"Agiloft Attachment Info","description":"Get information about file attachments on a record field.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\")"},"recordId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the record to check attachments on"},"fieldName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the attachment field to inspect"}},"hostedApiKey":"none"},"agiloft_create_record":{"id":"agiloft_create_record","name":"Agiloft Create Record","description":"Create a new record in an Agiloft table.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\", \\"contacts.employees\\")"},"data":{"type":"string","required":true,"visibility":"user-or-llm","description":"Record field values as a JSON object (e.g., {\\"first_name\\": \\"John\\", \\"status\\": \\"Active\\"})"}},"hostedApiKey":"none"},"agiloft_delete_record":{"id":"agiloft_delete_record","name":"Agiloft Delete Record","description":"Delete a record from an Agiloft table.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\", \\"contacts.employees\\")"},"recordId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the record to delete"},"substituteIds":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated IDs of records that adopt the dependants of the deleted record. Read only when the delete rule is REPLACE_WITH_ANOTHER."},"deleteRule":{"type":"string","required":false,"visibility":"user-or-llm","description":"How to treat records that depend on this one: ERROR_IF_DEPENDANTS (default — fails rather than cascading), APPLY_DELETE_WHERE_POSSIBLE, DELETE_WHERE_POSSIBLE_OTHERWISE_UNLINK, APPLY_UNLINK, UNLINK_WHERE_POSSIBLE_OTHERWISE_DELETE, or REPLACE_WITH_ANOTHER"}},"hostedApiKey":"none"},"agiloft_get_choice_line_id":{"id":"agiloft_get_choice_line_id","name":"Agiloft Get Choice Line ID","description":"Resolve the internal numeric ID of a choice-list value, for use in EWSelect WHERE clauses against choice fields.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"case\\", \\"contracts\\")"},"fieldName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Choice field name (e.g., \\"priority\\", \\"status\\")"},"value":{"type":"string","required":true,"visibility":"user-or-llm","description":"Choice display value to resolve (e.g., \\"High\\", \\"Active\\")"}},"hostedApiKey":"none"},"agiloft_list_tables":{"id":"agiloft_list_tables","name":"Agiloft List Tables","description":"List the tables and fields in an Agiloft knowledge base, to discover the logical names other operations need.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":false,"visibility":"user-or-llm","description":"Logical name of a single table to describe (e.g., \\"contacts\\"). Leave empty to list every table in the knowledge base."},"includeLinkedInfo":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the source table and column behind each linked field"},"skipColumnsInfo":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Return table names only, omitting field details, for a much smaller response"}},"hostedApiKey":"none"},"agiloft_lock_record":{"id":"agiloft_lock_record","name":"Agiloft Lock Record","description":"Lock, unlock, or check the lock status of an Agiloft record.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\")"},"recordId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the record to lock, unlock, or check"},"lockAction":{"type":"string","required":true,"visibility":"user-or-llm","description":"Action to perform: \\"lock\\", \\"unlock\\", or \\"check\\""},"force":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Unlock only: release a lock held by another user."}},"hostedApiKey":"none"},"agiloft_nlp_search":{"id":"agiloft_nlp_search","name":"Agiloft Natural Language Search","description":"Search Agiloft records by describing what you want in plain language, such as \\"active NDAs submitted last month\\".","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"nlpQuery":{"type":"string","required":true,"visibility":"user-or-llm","description":"The request in plain language, e.g. \\"Show me open, high-priority contracts\\". Structured field filters are not accepted — use Search Records for those."},"fields":{"type":"string","required":true,"visibility":"user-or-llm","description":"Comma-separated field names to return, e.g. \\"id, contract_title1, company_name\\""},"page":{"type":"string","required":false,"visibility":"user-or-llm","description":"Page number, starting from 0"},"limit":{"type":"string","required":false,"visibility":"user-or-llm","description":"Records per page"}},"hostedApiKey":"none"},"agiloft_read_record":{"id":"agiloft_read_record","name":"Agiloft Read Record","description":"Read a record by ID from an Agiloft table.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\", \\"contacts.employees\\")"},"recordId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the record to read"},"fields":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated list of field names to include in the response"}},"hostedApiKey":"none"},"agiloft_remove_attachment":{"id":"agiloft_remove_attachment","name":"Agiloft Remove Attachment","description":"Remove an attached file from a field in an Agiloft record.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\")"},"recordId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the record containing the attachment"},"fieldName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the attachment field"},"position":{"type":"string","required":true,"visibility":"user-or-llm","description":"Position index of the file to remove (starting from 0)"}},"hostedApiKey":"none"},"agiloft_retrieve_attachment":{"id":"agiloft_retrieve_attachment","name":"Agiloft Retrieve Attachment","description":"Download an attached file from an Agiloft record field.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\")"},"recordId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the record containing the attachment"},"fieldName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the attachment field"},"position":{"type":"string","required":true,"visibility":"user-or-llm","description":"Position index of the file in the field (starting from 0)"}},"hostedApiKey":"none"},"agiloft_run_action_button":{"id":"agiloft_run_action_button","name":"Agiloft Run Action Button","description":"Run an action button on an Agiloft record, such as an approval or send-for-signature step.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\", \\"case\\")"},"recordId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the record to run the action button on"},"actionButtonField":{"type":"string","required":true,"visibility":"user-or-llm","description":"Logical name of the field holding the action button (e.g., \\"ab_field\\")"}},"hostedApiKey":"none"},"agiloft_saved_search":{"id":"agiloft_saved_search","name":"Agiloft Saved Search","description":"List the saved searches defined for an Agiloft table.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Logical table name to list saved searches for (e.g., \\"contract\\")"}},"hostedApiKey":"none"},"agiloft_search_records":{"id":"agiloft_search_records","name":"Agiloft Search Records","description":"Search for records in an Agiloft table using a query.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name to search in (e.g., \\"contracts\\", \\"contacts.employees\\")"},"query":{"type":"string","required":false,"visibility":"user-or-llm","description":"Ad hoc EWSearch query. Combine conditions with && (and) or || (or) and quote every value — e.g. \\"summary~=\'test\'&&priority=\'High\'\\". Required unless a saved search is given."},"search":{"type":"string","required":false,"visibility":"user-or-llm","description":"Label of a saved search defined on the table (e.g., \\"C: Status is Closed\\"). Can be combined with a query to narrow it further."},"fields":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated list of field names to include in the results"},"page":{"type":"string","required":false,"visibility":"user-or-llm","description":"Page number for paginated results (starting from 0)"},"limit":{"type":"string","required":false,"visibility":"user-or-llm","description":"Maximum number of records to return per page. Agiloft treats 0 as \\"all records\\", so leave it unset or use a positive value to keep result sizes bounded."}},"hostedApiKey":"none"},"agiloft_select_records":{"id":"agiloft_select_records","name":"Agiloft Select Records","description":"Select record IDs matching a SQL WHERE clause from an Agiloft table.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\", \\"contacts.employees\\")"},"where":{"type":"string","required":true,"visibility":"user-or-llm","description":"SQL WHERE clause using database column names (e.g., \\"summary like \'%new%\'\\" or \\"assigned_person=\'John Doe\'\\"). EWSelect has no page size and returns every matching ID, so append a database limit such as \\"limit 0,200\\" to bound the result."}},"hostedApiKey":"none"},"agiloft_update_record":{"id":"agiloft_update_record","name":"Agiloft Update Record","description":"Update an existing record in an Agiloft table.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\", \\"contacts.employees\\")"},"recordId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the record to update"},"data":{"type":"string","required":true,"visibility":"user-or-llm","description":"Updated field values as a JSON object (e.g., {\\"status\\": \\"Active\\", \\"priority\\": \\"High\\"})"}},"hostedApiKey":"none"},"agiloft_upsert_record":{"id":"agiloft_upsert_record","name":"Agiloft Upsert Record","description":"Create an Agiloft record, or update it when a record already matches the given fields.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\", \\"contacts.employees\\")"},"match":{"type":"string","required":true,"visibility":"user-or-llm","description":"Field used to find an existing record (e.g., \\"ext_id\\"). Pick something that identifies a record uniquely — if more than one record matches, Agiloft writes nothing and returns a conflict."},"async":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Queue the write instead of waiting for it. Returns a callback ID instead of a record ID; pass that to Async Status to poll the result."},"data":{"type":"string","required":true,"visibility":"user-or-llm","description":"Field values as a JSON object. On create these populate the new record; on update only the supplied fields change."}},"hostedApiKey":"none"},"ahrefs_anchors":{"id":"ahrefs_anchors","name":"Ahrefs Anchors","description":"Get the anchor text distribution for a target domain or URL\'s backlinks, showing how many links and referring domains use each anchor text.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\" or \\"https://example.com/page\\""},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match)"},"history":{"type":"string","required":false,"visibility":"user-or-llm","description":"Historical scope: \\"live\\" (currently live), \\"all_time\\" (default, includes lost backlinks), or \\"since:YYYY-MM-DD\\" (backlinks found since a date)"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_backlinks":{"id":"ahrefs_backlinks","name":"Ahrefs Backlinks","description":"Get a list of backlinks pointing to a target domain or URL. Returns details about each backlink including source URL, anchor text, and domain rating.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\" or \\"https://example.com/page\\""},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match). Example: \\"domain\\""},"history":{"type":"string","required":false,"visibility":"user-or-llm","description":"Historical scope: \\"live\\" (currently live backlinks), \\"all_time\\" (default, includes lost backlinks), or \\"since:YYYY-MM-DD\\" (backlinks found since a date)."},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_backlinks_stats":{"id":"ahrefs_backlinks_stats","name":"Ahrefs Backlinks Stats","description":"Get backlink and referring domain totals for a target domain or URL, both currently live and across all time.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\" or \\"https://example.com/page\\""},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match). Example: \\"domain\\""},"date":{"type":"string","required":false,"visibility":"user-only","description":"Date to report metrics on, in YYYY-MM-DD format (defaults to today)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_batch_analysis":{"id":"ahrefs_batch_analysis","name":"Ahrefs Batch Analysis","description":"Get bulk SEO metrics (Domain Rating, backlinks, referring domains, organic traffic, and more) for multiple domains or URLs in a single request. Useful for comparing many competitors at once.","version":"1.0.0","params":{"targets":{"type":"string","required":true,"visibility":"user-or-llm","description":"Comma-separated list of domains or URLs to analyze. Example: \\"example.com,competitor.com\\""},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode applied to every target: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match)"},"protocol":{"type":"string","required":false,"visibility":"user-or-llm","description":"Protocol applied to every target: \\"both\\" (default), \\"http\\", or \\"https\\""},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Country code for traffic data. Example: \\"us\\", \\"gb\\", \\"de\\" (default: \\"us\\")"},"volumeMode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Search volume calculation: \\"monthly\\" or \\"average\\" (default: \\"monthly\\")"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_broken_backlinks":{"id":"ahrefs_broken_backlinks","name":"Ahrefs Broken Backlinks","description":"Get a list of broken backlinks pointing to a target domain or URL. Useful for identifying link reclamation opportunities.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\" or \\"https://example.com/page\\""},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match). Example: \\"domain\\""},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_domain_rating":{"id":"ahrefs_domain_rating","name":"Ahrefs Domain Rating","description":"Get the Domain Rating (DR) and Ahrefs Rank for a target domain. Domain Rating shows the strength of a website\'s backlink profile on a scale from 0 to 100.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain to analyze (e.g., example.com)"},"date":{"type":"string","required":false,"visibility":"user-only","description":"Date for historical data in YYYY-MM-DD format (defaults to today)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_domain_rating_history":{"id":"ahrefs_domain_rating_history","name":"Ahrefs Domain Rating History","description":"Get the historical Domain Rating (DR) trend for a target domain or URL over a date range, grouped daily, weekly, or monthly.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\""},"dateFrom":{"type":"string","required":true,"visibility":"user-only","description":"Start date of the historical period, in YYYY-MM-DD format"},"dateTo":{"type":"string","required":false,"visibility":"user-only","description":"End date of the historical period, in YYYY-MM-DD format (defaults to today)"},"historyGrouping":{"type":"string","required":false,"visibility":"user-or-llm","description":"Time interval for grouping data points: \\"daily\\", \\"weekly\\", or \\"monthly\\" (default: \\"monthly\\")"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_keyword_overview":{"id":"ahrefs_keyword_overview","name":"Ahrefs Keyword Overview","description":"Get detailed metrics for a keyword including search volume, keyword difficulty, CPC, clicks, and traffic potential.","version":"1.0.0","params":{"keyword":{"type":"string","required":true,"visibility":"user-or-llm","description":"The keyword to analyze"},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Country code for keyword data. Example: \\"us\\", \\"gb\\", \\"de\\" (default: \\"us\\")"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_keywords_history":{"id":"ahrefs_keywords_history","name":"Ahrefs Keywords History","description":"Get the historical organic keyword ranking distribution for a target domain or URL over a date range: how many keywords rank in each position bucket at each point in time.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\""},"dateFrom":{"type":"string","required":true,"visibility":"user-only","description":"Start date of the historical period, in YYYY-MM-DD format"},"dateTo":{"type":"string","required":false,"visibility":"user-only","description":"End date of the historical period, in YYYY-MM-DD format (defaults to today)"},"historyGrouping":{"type":"string","required":false,"visibility":"user-or-llm","description":"Time interval for grouping data points: \\"daily\\", \\"weekly\\", or \\"monthly\\" (default: \\"monthly\\")"},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Country code for search results. Example: \\"us\\", \\"gb\\", \\"de\\" (default: \\"us\\")"},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_metrics":{"id":"ahrefs_metrics","name":"Ahrefs Metrics","description":"Get a one-call organic and paid search overview for a target domain or URL: organic traffic, organic keywords, paid traffic, paid keywords, and estimated traffic cost.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\""},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Country code for traffic data. Example: \\"us\\", \\"gb\\", \\"de\\""},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match). Example: \\"domain\\""},"date":{"type":"string","required":false,"visibility":"user-only","description":"Date to report metrics on, in YYYY-MM-DD format (defaults to today)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_metrics_history":{"id":"ahrefs_metrics_history","name":"Ahrefs Metrics History","description":"Get the historical organic and paid traffic trend for a target domain or URL over a date range: organic traffic/cost and paid traffic/cost at each point in time.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\""},"dateFrom":{"type":"string","required":true,"visibility":"user-only","description":"Start date of the historical period, in YYYY-MM-DD format"},"dateTo":{"type":"string","required":false,"visibility":"user-only","description":"End date of the historical period, in YYYY-MM-DD format (defaults to today)"},"volumeMode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Search volume calculation: \\"monthly\\" or \\"average\\" (default: \\"monthly\\")"},"historyGrouping":{"type":"string","required":false,"visibility":"user-or-llm","description":"Time interval for grouping data points: \\"daily\\", \\"weekly\\", or \\"monthly\\" (default: \\"monthly\\")"},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Country code for traffic data. Example: \\"us\\", \\"gb\\", \\"de\\" (default: \\"us\\")"},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_organic_competitors":{"id":"ahrefs_organic_competitors","name":"Ahrefs Organic Competitors","description":"Get domains that compete with a target domain or URL for the same organic keywords, ranked by keyword overlap.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\""},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Country code for search results. Example: \\"us\\", \\"gb\\", \\"de\\" (default: \\"us\\")"},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match). Example: \\"domain\\""},"date":{"type":"string","required":false,"visibility":"user-only","description":"Date to report metrics on, in YYYY-MM-DD format (defaults to today)"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_organic_keywords":{"id":"ahrefs_organic_keywords","name":"Ahrefs Organic Keywords","description":"Get organic keywords that a target domain or URL ranks for in Google search results. Returns keyword details including search volume, ranking position, and estimated traffic.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\" or \\"https://example.com/page\\""},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Country code for search results. Example: \\"us\\", \\"gb\\", \\"de\\" (default: \\"us\\")"},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match). Example: \\"domain\\""},"date":{"type":"string","required":false,"visibility":"user-only","description":"Date to report metrics on, in YYYY-MM-DD format (defaults to today)"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_paid_pages":{"id":"ahrefs_paid_pages","name":"Ahrefs Paid Pages","description":"Get a target domain\'s pages that receive paid search traffic, sorted by estimated paid traffic. Returns page URLs with their paid traffic, keyword counts, and estimated spend.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\""},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Country code for traffic data. Example: \\"us\\", \\"gb\\", \\"de\\" (default: \\"us\\")"},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match)"},"date":{"type":"string","required":false,"visibility":"user-only","description":"Date to report metrics on, in YYYY-MM-DD format (defaults to today)"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_rank_tracker_competitors_overview":{"id":"ahrefs_rank_tracker_competitors_overview","name":"Ahrefs Rank Tracker Competitors Overview","description":"Get competitor rankings for the keywords tracked in an Ahrefs Rank Tracker project: each tracked keyword\'s volume and difficulty alongside every competitor\'s position, traffic, and traffic value. This endpoint is free and does not consume API units.","version":"1.0.0","params":{"projectId":{"type":"number","required":true,"visibility":"user-or-llm","description":"The Rank Tracker project ID (found in the project URL in Ahrefs)"},"date":{"type":"string","required":true,"visibility":"user-only","description":"Date to report rankings for, in YYYY-MM-DD format"},"device":{"type":"string","required":true,"visibility":"user-or-llm","description":"Rankings device type: \\"desktop\\" or \\"mobile\\""},"dateCompared":{"type":"string","required":false,"visibility":"user-only","description":"Comparison date in YYYY-MM-DD format, to compute position/traffic deltas"},"volumeMode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Search volume calculation: \\"monthly\\" or \\"average\\" (default: \\"monthly\\")"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_rank_tracker_competitors_stats":{"id":"ahrefs_rank_tracker_competitors_stats","name":"Ahrefs Rank Tracker Competitors Stats","description":"Get aggregate competitor stats for an Ahrefs Rank Tracker project: each competitor\'s traffic, traffic value, average position, and share of voice across all tracked keywords. This endpoint is free and does not consume API units.","version":"1.0.0","params":{"projectId":{"type":"number","required":true,"visibility":"user-or-llm","description":"The Rank Tracker project ID (found in the project URL in Ahrefs)"},"date":{"type":"string","required":true,"visibility":"user-only","description":"Date to report metrics for, in YYYY-MM-DD format"},"device":{"type":"string","required":true,"visibility":"user-or-llm","description":"Rankings device type: \\"desktop\\" or \\"mobile\\""},"volumeMode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Search volume calculation: \\"monthly\\" or \\"average\\" (default: \\"monthly\\")"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_rank_tracker_overview":{"id":"ahrefs_rank_tracker_overview","name":"Ahrefs Rank Tracker Overview","description":"Get ranking overview metrics for the keywords tracked in an Ahrefs Rank Tracker project: position, search volume, keyword difficulty, and estimated traffic. This endpoint is free and does not consume API units.","version":"1.0.0","params":{"projectId":{"type":"number","required":true,"visibility":"user-or-llm","description":"The Rank Tracker project ID (found in the project URL in Ahrefs)"},"date":{"type":"string","required":true,"visibility":"user-only","description":"Date to report rankings for, in YYYY-MM-DD format"},"device":{"type":"string","required":true,"visibility":"user-or-llm","description":"Rankings device type: \\"desktop\\" or \\"mobile\\""},"dateCompared":{"type":"string","required":false,"visibility":"user-only","description":"Comparison date in YYYY-MM-DD format, to compute position/traffic deltas"},"volumeMode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Search volume calculation: \\"monthly\\" or \\"average\\" (default: \\"monthly\\")"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_rank_tracker_serp_overview":{"id":"ahrefs_rank_tracker_serp_overview","name":"Ahrefs Rank Tracker SERP Overview","description":"Get the full SERP (search engine results page) for a keyword tracked in an Ahrefs Rank Tracker project, including every ranking URL with its position, title, and authority metrics. This endpoint is free and does not consume API units.","version":"1.0.0","params":{"projectId":{"type":"number","required":true,"visibility":"user-or-llm","description":"The Rank Tracker project ID (found in the project URL in Ahrefs)"},"keyword":{"type":"string","required":true,"visibility":"user-or-llm","description":"The tracked keyword to retrieve SERP data for"},"country":{"type":"string","required":true,"visibility":"user-or-llm","description":"Country code for the tracked keyword. Example: \\"us\\", \\"gb\\", \\"de\\""},"device":{"type":"string","required":true,"visibility":"user-or-llm","description":"Rankings device type: \\"desktop\\" or \\"mobile\\""},"topPositions":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of top organic positions to return (defaults to all available)"},"date":{"type":"string","required":false,"visibility":"user-only","description":"Timestamp to return the last available SERP Overview at, in YYYY-MM-DDThh:mm:ss format"},"locationId":{"type":"number","required":false,"visibility":"user-or-llm","description":"Location ID of the tracked keyword, if tracked at a specific location"},"languageCode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Language code of the tracked keyword"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_refdomains_history":{"id":"ahrefs_refdomains_history","name":"Ahrefs Referring Domains History","description":"Get the historical referring domains trend for a target domain or URL over a date range, grouped daily, weekly, or monthly.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\""},"dateFrom":{"type":"string","required":true,"visibility":"user-only","description":"Start date of the historical period, in YYYY-MM-DD format"},"dateTo":{"type":"string","required":false,"visibility":"user-only","description":"End date of the historical period, in YYYY-MM-DD format (defaults to today)"},"historyGrouping":{"type":"string","required":false,"visibility":"user-or-llm","description":"Time interval for grouping data points: \\"daily\\", \\"weekly\\", or \\"monthly\\" (default: \\"monthly\\")"},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_referring_domains":{"id":"ahrefs_referring_domains","name":"Ahrefs Referring Domains","description":"Get a list of domains that link to a target domain or URL. Returns unique referring domains with their domain rating, backlink counts, and discovery dates.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\" or \\"https://example.com/page\\""},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match). Example: \\"domain\\""},"history":{"type":"string","required":false,"visibility":"user-or-llm","description":"Historical scope: \\"live\\" (currently live), \\"all_time\\" (default, includes lost domains), or \\"since:YYYY-MM-DD\\" (domains found since a date)."},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_related_terms":{"id":"ahrefs_related_terms","name":"Ahrefs Related Terms","description":"Get keyword ideas related to a seed keyword: terms the same top-ranking pages also rank for (\\"also rank for\\") or also discuss (\\"also talk about\\"), with volume, difficulty, and CPC.","version":"1.0.0","params":{"keyword":{"type":"string","required":true,"visibility":"user-or-llm","description":"The seed keyword to find related terms for"},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Country code for keyword data. Example: \\"us\\", \\"gb\\", \\"de\\" (default: \\"us\\")"},"terms":{"type":"string","required":false,"visibility":"user-or-llm","description":"Type of related keywords to return: \\"also_rank_for\\", \\"also_talk_about\\", or \\"all\\" (default: \\"all\\")"},"viewFor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Whether to derive related terms from the top 10 or top 100 ranking pages (default: \\"top_10\\")"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_site_audit_page_explorer":{"id":"ahrefs_site_audit_page_explorer","name":"Ahrefs Site Audit Page Explorer","description":"Get crawled pages from an Ahrefs Site Audit project with health and SEO metrics: HTTP status, title, link counts, backlinks, indexability, and traffic. Optionally filter to pages affected by a specific issue.","version":"1.0.0","params":{"projectId":{"type":"number","required":true,"visibility":"user-or-llm","description":"The Site Audit project ID (found in the project URL in Ahrefs)"},"date":{"type":"string","required":false,"visibility":"user-only","description":"Crawl date in YYYY-MM-DDThh:mm:ss format (defaults to the most recent crawl)"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"offset":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of results to skip, for pagination"},"issueId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Only return pages affected by this issue ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_top_pages":{"id":"ahrefs_top_pages","name":"Ahrefs Top Pages","description":"Get the top pages of a target domain sorted by organic traffic. Returns page URLs with their traffic, keyword counts, and estimated traffic value.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain to analyze. Example: \\"example.com\\""},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Country code for traffic data. Example: \\"us\\", \\"gb\\", \\"de\\" (default: \\"us\\")"},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match). Example: \\"domain\\""},"date":{"type":"string","required":false,"visibility":"user-only","description":"Date to report metrics on, in YYYY-MM-DD format (defaults to today)"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"airtable_create_records":{"id":"airtable_create_records","name":"Airtable Create Records","description":"Write new records to an Airtable table","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token"},"baseId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Airtable base ID (starts with \\"app\\", e.g., \\"appXXXXXXXXXXXXXX\\")"},"tableId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table ID (starts with \\"tbl\\") or table name"},"records":{"type":"json","required":true,"visibility":"user-or-llm","description":"Array of records to create, each with a `fields` object"},"typecast":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"When true, Airtable automatically converts string values to the field type"}},"oauth":{"required":true,"provider":"airtable"},"hostedApiKey":"none"},"airtable_delete_records":{"id":"airtable_delete_records","name":"Airtable Delete Records","description":"Delete one or more records from an Airtable table by ID","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token"},"baseId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Airtable base ID (starts with \\"app\\", e.g., \\"appXXXXXXXXXXXXXX\\")"},"tableId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table ID (starts with \\"tbl\\") or table name"},"recordIds":{"type":"json","required":true,"visibility":"user-or-llm","description":"Array of record IDs to delete (each starts with \\"rec\\", e.g., [\\"recXXXXXXXXXXXXXX\\"]). Pass a single-element array to delete one record."}},"oauth":{"required":true,"provider":"airtable"},"hostedApiKey":"none"},"airtable_get_base_schema":{"id":"airtable_get_base_schema","name":"Airtable Get Base Schema","description":"Get the schema of all tables, fields, and views in an Airtable base","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token"},"baseId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Airtable base ID (starts with \\"app\\", e.g., \\"appXXXXXXXXXXXXXX\\")"}},"oauth":{"required":true,"provider":"airtable"},"hostedApiKey":"none"},"airtable_get_record":{"id":"airtable_get_record","name":"Airtable Get Record","description":"Retrieve a single record from an Airtable table by its ID","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token"},"baseId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Airtable base ID (starts with \\"app\\", e.g., \\"appXXXXXXXXXXXXXX\\")"},"tableId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table ID (starts with \\"tbl\\") or table name"},"recordId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Record ID to retrieve (starts with \\"rec\\", e.g., \\"recXXXXXXXXXXXXXX\\")"}},"oauth":{"required":true,"provider":"airtable"},"hostedApiKey":"none"},"airtable_list_bases":{"id":"airtable_list_bases","name":"Airtable List Bases","description":"List all bases the authenticated user has access to","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token"},"offset":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination offset for retrieving additional bases"}},"oauth":{"required":true,"provider":"airtable"},"hostedApiKey":"none"},"airtable_list_records":{"id":"airtable_list_records","name":"Airtable List Records","description":"Read records from an Airtable table","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token"},"baseId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Airtable base ID (starts with \\"app\\", e.g., \\"appXXXXXXXXXXXXXX\\")"},"tableId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table ID (starts with \\"tbl\\") or table name"},"maxRecords":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum total number of records to return. Each request returns at most one page (pageSize, up to 100); use offset to fetch the next page"},"filterFormula":{"type":"string","required":false,"visibility":"user-or-llm","description":"Formula to filter records (e.g., \\"({Field Name} = \'Value\')\\")"},"pageSize":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of records per page (max 100, default 100)"},"offset":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination offset from a previous response, to fetch the next page of records"},"view":{"type":"string","required":false,"visibility":"user-or-llm","description":"View name or ID. Only records in the view are returned, sorted in the view order"}},"oauth":{"required":true,"provider":"airtable"},"hostedApiKey":"none"},"airtable_list_tables":{"id":"airtable_list_tables","name":"Airtable List Tables","description":"List all tables and their schema in an Airtable base","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token"},"baseId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Airtable base ID (starts with \\"app\\", e.g., \\"appXXXXXXXXXXXXXX\\")"}},"oauth":{"required":true,"provider":"airtable"},"hostedApiKey":"none"},"airtable_update_multiple_records":{"id":"airtable_update_multiple_records","name":"Airtable Update Multiple Records","description":"Update multiple existing records in an Airtable table","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token"},"baseId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Airtable base ID (starts with \\"app\\", e.g., \\"appXXXXXXXXXXXXXX\\")"},"tableId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table ID (starts with \\"tbl\\") or table name"},"records":{"type":"json","required":true,"visibility":"user-or-llm","description":"Array of records to update, each with an `id` and a `fields` object"},"typecast":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"When true, Airtable automatically converts string values to the field type"}},"oauth":{"required":true,"provider":"airtable"},"hostedApiKey":"none"},"airtable_update_record":{"id":"airtable_update_record","name":"Airtable Update Record","description":"Update an existing record in an Airtable table by ID","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token"},"baseId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Airtable base ID (starts with \\"app\\", e.g., \\"appXXXXXXXXXXXXXX\\")"},"tableId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table ID (starts with \\"tbl\\") or table name"},"recordId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Record ID to update (starts with \\"rec\\", e.g., \\"recXXXXXXXXXXXXXX\\")"},"fields":{"type":"json","required":true,"visibility":"user-or-llm","description":"An object containing the field names and their new values"},"typecast":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"When true, Airtable automatically converts string values to the field type"}},"oauth":{"required":true,"provider":"airtable"},"hostedApiKey":"none"},"airtable_upsert_records":{"id":"airtable_upsert_records","name":"Airtable Upsert Records","description":"Update existing records or create new ones in an Airtable table, matching on the specified merge fields","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token"},"baseId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Airtable base ID (starts with \\"app\\", e.g., \\"appXXXXXXXXXXXXXX\\")"},"tableId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table ID (starts with \\"tbl\\") or table name"},"records":{"type":"json","required":true,"visibility":"user-or-llm","description":"Array of records to upsert, each with a `fields` object"},"fieldsToMergeOn":{"type":"json","required":true,"visibility":"user-or-llm","description":"Array of field names used to match existing records (max 3). A record is updated when all merge fields match, otherwise it is created. Example: [\\"Name\\"]"},"typecast":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"When true, Airtable automatically converts string values to the field type"}},"oauth":{"required":true,"provider":"airtable"},"hostedApiKey":"none"},"algolia_add_record":{"id":"algolia_add_record","name":"Algolia Add Record","description":"Add or replace a record in an Algolia index","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Admin API Key"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index"},"objectID":{"type":"string","required":false,"visibility":"user-or-llm","description":"Object ID for the record (auto-generated if not provided)"},"record":{"type":"json","required":true,"visibility":"user-or-llm","description":"JSON object representing the record to add"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_batch_operations":{"id":"algolia_batch_operations","name":"Algolia Batch Operations","description":"Perform batch add, update, partial update, or delete operations on records in an Algolia index","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Admin API Key"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index"},"requests":{"type":"json","required":true,"visibility":"user-or-llm","description":"Array of batch operations. Each item has \\"action\\" (addObject, updateObject, partialUpdateObject, partialUpdateObjectNoCreate, deleteObject, delete, clear) and \\"body\\" (the record data; must include objectID for update/delete; use an empty object {} for the index-level delete/clear actions)"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_browse_records":{"id":"algolia_browse_records","name":"Algolia Browse Records","description":"Browse and iterate over all records in an Algolia index using cursor pagination","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia API Key (must have browse ACL)"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index to browse"},"query":{"type":"string","required":false,"visibility":"user-or-llm","description":"Search query to filter browsed records"},"filters":{"type":"string","required":false,"visibility":"user-or-llm","description":"Filter string to narrow down results"},"attributesToRetrieve":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated list of attributes to retrieve"},"hitsPerPage":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of hits per page (default: 1000, max: 1000)"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous browse response for pagination"},"aroundLatLng":{"type":"string","required":false,"visibility":"user-or-llm","description":"Coordinates for geo-search (e.g., \\"40.71,-74.01\\")"},"aroundRadius":{"type":"string","required":false,"visibility":"user-or-llm","description":"Maximum radius in meters for geo-search, or \\"all\\" for unlimited"},"insideBoundingBox":{"type":"json","required":false,"visibility":"user-or-llm","description":"Bounding box coordinates as [[lat1, lng1, lat2, lng2]] for geo-search"},"insidePolygon":{"type":"json","required":false,"visibility":"user-or-llm","description":"Polygon coordinates as [[lat1, lng1, lat2, lng2, lat3, lng3, ...]] for geo-search"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_clear_records":{"id":"algolia_clear_records","name":"Algolia Clear Records","description":"Clear all records from an Algolia index while keeping settings, synonyms, and rules","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Admin API Key (must have deleteIndex ACL)"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index to clear"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_copy_move_index":{"id":"algolia_copy_move_index","name":"Algolia Copy/Move Index","description":"Copy or move an Algolia index to a new destination","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Admin API Key"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the source index"},"operation":{"type":"string","required":true,"visibility":"user-or-llm","description":"Operation to perform: \\"copy\\" or \\"move\\""},"destination":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the destination index"},"scope":{"type":"json","required":false,"visibility":"user-or-llm","description":"Array of scopes to copy (only for \\"copy\\" operation): [\\"settings\\", \\"synonyms\\", \\"rules\\"]. Omit to copy everything including records."}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_delete_by_filter":{"id":"algolia_delete_by_filter","name":"Algolia Delete By Filter","description":"Delete all records matching a filter from an Algolia index","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Admin API Key (must have deleteIndex ACL)"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index"},"filters":{"type":"string","required":false,"visibility":"user-or-llm","description":"Filter expression to match records for deletion (e.g., \\"category:outdated\\")"},"facetFilters":{"type":"json","required":false,"visibility":"user-or-llm","description":"Array of facet filters (e.g., [\\"brand:Acme\\"])"},"numericFilters":{"type":"json","required":false,"visibility":"user-or-llm","description":"Array of numeric filters (e.g., [\\"price > 100\\"])"},"tagFilters":{"type":"json","required":false,"visibility":"user-or-llm","description":"Array of tag filters using the _tags attribute (e.g., [\\"published\\"])"},"aroundLatLng":{"type":"string","required":false,"visibility":"user-or-llm","description":"Coordinates for geo-search filter (e.g., \\"40.71,-74.01\\")"},"aroundRadius":{"type":"string","required":false,"visibility":"user-or-llm","description":"Maximum radius in meters for geo-search, or \\"all\\" for unlimited"},"insideBoundingBox":{"type":"json","required":false,"visibility":"user-or-llm","description":"Bounding box coordinates as [[lat1, lng1, lat2, lng2]] for geo-search filter"},"insidePolygon":{"type":"json","required":false,"visibility":"user-or-llm","description":"Polygon coordinates as [[lat1, lng1, lat2, lng2, lat3, lng3, ...]] for geo-search filter"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_delete_index":{"id":"algolia_delete_index","name":"Algolia Delete Index","description":"Delete an entire Algolia index and all its records","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Admin API Key (must have deleteIndex ACL)"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index to delete"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_delete_record":{"id":"algolia_delete_record","name":"Algolia Delete Record","description":"Delete a record by objectID from an Algolia index","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Admin API Key"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index"},"objectID":{"type":"string","required":true,"visibility":"user-or-llm","description":"The objectID of the record to delete"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_get_record":{"id":"algolia_get_record","name":"Algolia Get Record","description":"Get a record by objectID from an Algolia index","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia API Key"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index"},"objectID":{"type":"string","required":true,"visibility":"user-or-llm","description":"The objectID of the record to retrieve"},"attributesToRetrieve":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated list of attributes to retrieve"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_get_records":{"id":"algolia_get_records","name":"Algolia Get Records","description":"Retrieve multiple records by objectID from one or more Algolia indices","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia API Key"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Default index name for all requests"},"requests":{"type":"json","required":true,"visibility":"user-or-llm","description":"Array of objects specifying records to retrieve. Each must have \\"objectID\\" and optionally \\"indexName\\" and \\"attributesToRetrieve\\"."}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_get_settings":{"id":"algolia_get_settings","name":"Algolia Get Settings","description":"Retrieve the settings of an Algolia index","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia API Key"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_get_task_status":{"id":"algolia_get_task_status","name":"Algolia Get Task Status","description":"Check whether an Algolia indexing task has finished publishing","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia API Key"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index the task ran against"},"taskID":{"type":"number","required":true,"visibility":"user-or-llm","description":"The taskID returned by a previous write operation"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_list_indices":{"id":"algolia_list_indices","name":"Algolia List Indices","description":"List all indices in an Algolia application","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia API Key"},"page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Page number for paginating indices (default: not paginated)"},"hitsPerPage":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of indices per page (default: 100)"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_partial_update_record":{"id":"algolia_partial_update_record","name":"Algolia Partial Update Record","description":"Partially update a record in an Algolia index without replacing it entirely","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Admin API Key"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index"},"objectID":{"type":"string","required":true,"visibility":"user-or-llm","description":"The objectID of the record to update"},"attributes":{"type":"json","required":true,"visibility":"user-or-llm","description":"JSON object with attributes to update. Supports built-in operations like {\\"stock\\": {\\"_operation\\": \\"Decrement\\", \\"value\\": 1}}"},"createIfNotExists":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Whether to create the record if it does not exist (default: true)"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_search":{"id":"algolia_search","name":"Algolia Search","description":"Search an Algolia index","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia API Key"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index to search"},"query":{"type":"string","required":true,"visibility":"user-or-llm","description":"Search query text"},"hitsPerPage":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of hits per page (default: 20)"},"page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Page number to retrieve (default: 0)"},"filters":{"type":"string","required":false,"visibility":"user-or-llm","description":"Filter string (e.g., \\"category:electronics AND price < 100\\")"},"attributesToRetrieve":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated list of attributes to retrieve"},"facets":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated list of facet attribute names to retrieve counts for (use \\"*\\" for all)"},"getRankingInfo":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Whether to include detailed ranking information in each hit"},"aroundLatLng":{"type":"string","required":false,"visibility":"user-or-llm","description":"Coordinates for geo-search (e.g., \\"40.71,-74.01\\")"},"aroundRadius":{"type":"string","required":false,"visibility":"user-or-llm","description":"Maximum radius in meters for geo-search, or \\"all\\" for unlimited"},"insideBoundingBox":{"type":"json","required":false,"visibility":"user-or-llm","description":"Bounding box coordinates as [[lat1, lng1, lat2, lng2]] for geo-search"},"insidePolygon":{"type":"json","required":false,"visibility":"user-or-llm","description":"Polygon coordinates as [[lat1, lng1, lat2, lng2, lat3, lng3, ...]] for geo-search"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_update_settings":{"id":"algolia_update_settings","name":"Algolia Update Settings","description":"Update the settings of an Algolia index","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Admin API Key (must have editSettings ACL)"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index"},"settings":{"type":"json","required":true,"visibility":"user-or-llm","description":"JSON object with settings to update (e.g., {\\"searchableAttributes\\": [\\"name\\", \\"description\\"], \\"customRanking\\": [\\"desc(popularity)\\"]})"},"forwardToReplicas":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Whether to apply changes to replica indices (default: false)"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"amplitude_event_segmentation":{"id":"amplitude_event_segmentation","name":"Amplitude Event Segmentation","description":"Query event analytics data with segmentation. Get event counts, uniques, averages, and more.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"secretKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude Secret Key"},"eventType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Event type name to analyze"},"secondEventType":{"type":"string","required":false,"visibility":"user-or-llm","description":"Second event type to query alongside the first (event B in a formula such as \\"UNIQUES(A)/UNIQUES(B)\\")"},"start":{"type":"string","required":true,"visibility":"user-or-llm","description":"Start date in YYYYMMDD format"},"end":{"type":"string","required":true,"visibility":"user-or-llm","description":"End date in YYYYMMDD format"},"metric":{"type":"string","required":false,"visibility":"user-or-llm","description":"Metric type: uniques, totals, pct_dau, average, histogram, sums, value_avg, or formula (default: uniques)"},"interval":{"type":"string","required":false,"visibility":"user-or-llm","description":"Time interval: -300000 (real-time), -3600000 (hourly), 1 (daily), 7 (weekly), or 30 (monthly)"},"groupBy":{"type":"string","required":false,"visibility":"user-or-llm","description":"Property name to group by (prefix custom user properties with \\"gp:\\")"},"groupBy2":{"type":"string","required":false,"visibility":"user-or-llm","description":"Second property name to group by (prefix custom user properties with \\"gp:\\")"},"limit":{"type":"string","required":false,"visibility":"user-or-llm","description":"Maximum number of group-by values (default 1000, max 20000)"},"filters":{"type":"string","required":false,"visibility":"user-or-llm","description":"JSON array of filter objects applied to the event, e.g. [{\\"subprop_type\\":\\"event\\",\\"subprop_key\\":\\"city\\",\\"subprop_op\\":\\"is\\",\\"subprop_value\\":[\\"San Francisco\\"]}]"},"formula":{"type":"string","required":false,"visibility":"user-or-llm","description":"Required when metric is \\"formula\\", e.g. \\"UNIQUES(A)/UNIQUES(B)\\""},"segment":{"type":"string","required":false,"visibility":"user-or-llm","description":"JSON segment definition(s) applied to the query"},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"oauth":{"required":false,"provider":"amplitude","credentialKind":"service-account","credentialParams":{"apiKey":"providerWorkspaceId","secretKey":"accessToken","dataResidency":"domain"},"credentialSuppliedParams":["apiKey","secretKey","dataResidency"]},"hostedApiKey":"none"},"amplitude_funnels":{"id":"amplitude_funnels","name":"Amplitude Funnels","description":"Analyze conversion rates and drop-off between a sequence of events.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"secretKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude Secret Key"},"events":{"type":"string","required":true,"visibility":"user-or-llm","description":"JSON array of event objects, one per funnel step in order, e.g. [{\\"event_type\\":\\"signup\\"},{\\"event_type\\":\\"purchase\\"}]"},"start":{"type":"string","required":true,"visibility":"user-or-llm","description":"Start date in YYYYMMDD format"},"end":{"type":"string","required":true,"visibility":"user-or-llm","description":"End date in YYYYMMDD format"},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Funnel ordering: \\"ordered\\", \\"unordered\\", or \\"sequential\\" (default: ordered)"},"userType":{"type":"string","required":false,"visibility":"user-or-llm","description":"User type: \\"new\\" or \\"active\\" (default: active)"},"interval":{"type":"string","required":false,"visibility":"user-or-llm","description":"Time interval: -300000 (real-time), -3600000 (hourly), 1 (daily), 7 (weekly), or 30 (monthly)"},"conversionWindowSeconds":{"type":"string","required":false,"visibility":"user-or-llm","description":"Conversion window in seconds (default: 2592000, i.e. 30 days)"},"groupBy":{"type":"string","required":false,"visibility":"user-or-llm","description":"Property to group by (limit: one; prefix custom properties with \\"gp:\\")"},"limit":{"type":"string","required":false,"visibility":"user-or-llm","description":"Maximum number of group-by values (default and max: 1000)"},"segment":{"type":"string","required":false,"visibility":"user-or-llm","description":"JSON segment definition(s) applied to the query"},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"oauth":{"required":false,"provider":"amplitude","credentialKind":"service-account","credentialParams":{"apiKey":"providerWorkspaceId","secretKey":"accessToken","dataResidency":"domain"},"credentialSuppliedParams":["apiKey","secretKey","dataResidency"]},"hostedApiKey":"none"},"amplitude_get_active_users":{"id":"amplitude_get_active_users","name":"Amplitude Get Active Users","description":"Get active or new user counts over a date range from the Dashboard REST API.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"secretKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude Secret Key"},"start":{"type":"string","required":true,"visibility":"user-or-llm","description":"Start date in YYYYMMDD format"},"end":{"type":"string","required":true,"visibility":"user-or-llm","description":"End date in YYYYMMDD format"},"metric":{"type":"string","required":false,"visibility":"user-or-llm","description":"Metric type: \\"active\\" or \\"new\\" (default: active)"},"interval":{"type":"string","required":false,"visibility":"user-or-llm","description":"Time interval: 1 (daily), 7 (weekly), or 30 (monthly)"},"groupBy":{"type":"string","required":false,"visibility":"user-or-llm","description":"Property name to group by"},"segment":{"type":"string","required":false,"visibility":"user-or-llm","description":"JSON segment definition(s) applied to the query"},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"oauth":{"required":false,"provider":"amplitude","credentialKind":"service-account","credentialParams":{"apiKey":"providerWorkspaceId","secretKey":"accessToken","dataResidency":"domain"},"credentialSuppliedParams":["apiKey","secretKey","dataResidency"]},"hostedApiKey":"none"},"amplitude_get_revenue":{"id":"amplitude_get_revenue","name":"Amplitude Get Revenue","description":"Get revenue LTV data including ARPU, ARPPU, total revenue, and paying user counts.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"secretKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude Secret Key"},"start":{"type":"string","required":true,"visibility":"user-or-llm","description":"Start date in YYYYMMDD format"},"end":{"type":"string","required":true,"visibility":"user-or-llm","description":"End date in YYYYMMDD format"},"metric":{"type":"string","required":false,"visibility":"user-or-llm","description":"Metric: 0 (ARPU), 1 (ARPPU), 2 (Total Revenue), 3 (Paying Users)"},"interval":{"type":"string","required":false,"visibility":"user-or-llm","description":"Time interval: 1 (daily), 7 (weekly), or 30 (monthly)"},"groupBy":{"type":"string","required":false,"visibility":"user-or-llm","description":"Property name to group by (limit: one)"},"segment":{"type":"string","required":false,"visibility":"user-or-llm","description":"JSON segment definition(s) applied to the query"},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"oauth":{"required":false,"provider":"amplitude","credentialKind":"service-account","credentialParams":{"apiKey":"providerWorkspaceId","secretKey":"accessToken","dataResidency":"domain"},"credentialSuppliedParams":["apiKey","secretKey","dataResidency"]},"hostedApiKey":"none"},"amplitude_group_identify":{"id":"amplitude_group_identify","name":"Amplitude Group Identify","description":"Set group-level properties in Amplitude. Supports $set, $setOnce, $add, $append, $unset operations.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"groupType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Group classification (e.g., \\"company\\", \\"org_id\\")"},"groupValue":{"type":"string","required":true,"visibility":"user-or-llm","description":"Specific group identifier (e.g., \\"Acme Corp\\")"},"groupProperties":{"type":"string","required":true,"visibility":"user-or-llm","description":"JSON object of group properties. Use operations like $set, $setOnce, $add, $append, $unset."},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"oauth":{"required":false,"provider":"amplitude","credentialKind":"service-account","credentialParams":{"apiKey":"providerWorkspaceId","dataResidency":"domain"},"credentialSuppliedParams":["apiKey","dataResidency"]},"hostedApiKey":"none"},"amplitude_identify_user":{"id":"amplitude_identify_user","name":"Amplitude Identify User","description":"Set user properties in Amplitude using the Identify API. Supports $set, $setOnce, $add, $append, $unset operations.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"userId":{"type":"string","required":false,"visibility":"user-or-llm","description":"User ID (required if no device_id)"},"deviceId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Device ID (required if no user_id)"},"userProperties":{"type":"string","required":true,"visibility":"user-or-llm","description":"JSON object of user properties. Use operations like $set, $setOnce, $add, $append, $unset."},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"oauth":{"required":false,"provider":"amplitude","credentialKind":"service-account","credentialParams":{"apiKey":"providerWorkspaceId","dataResidency":"domain"},"credentialSuppliedParams":["apiKey","dataResidency"]},"hostedApiKey":"none"},"amplitude_list_events":{"id":"amplitude_list_events","name":"Amplitude List Events","description":"List all event types in the Amplitude project with their weekly totals and unique counts.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"secretKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude Secret Key"},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"oauth":{"required":false,"provider":"amplitude","credentialKind":"service-account","credentialParams":{"apiKey":"providerWorkspaceId","secretKey":"accessToken","dataResidency":"domain"},"credentialSuppliedParams":["apiKey","secretKey","dataResidency"]},"hostedApiKey":"none"},"amplitude_realtime_active_users":{"id":"amplitude_realtime_active_users","name":"Amplitude Real-time Active Users","description":"Get real-time active user counts at 5-minute granularity for the last 2 days.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"secretKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude Secret Key"},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"oauth":{"required":false,"provider":"amplitude","credentialKind":"service-account","credentialParams":{"apiKey":"providerWorkspaceId","secretKey":"accessToken","dataResidency":"domain"},"credentialSuppliedParams":["apiKey","secretKey","dataResidency"]},"hostedApiKey":"none"},"amplitude_retention":{"id":"amplitude_retention","name":"Amplitude Retention","description":"Measure how many users return to perform an action after a starting action.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"secretKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude Secret Key"},"startEvent":{"type":"string","required":true,"visibility":"user-or-llm","description":"JSON starting event object, e.g. {\\"event_type\\":\\"_new\\"} or {\\"event_type\\":\\"_active\\"}"},"returnEvent":{"type":"string","required":true,"visibility":"user-or-llm","description":"JSON returning event object, e.g. {\\"event_type\\":\\"_all\\"} or {\\"event_type\\":\\"_active\\"}"},"start":{"type":"string","required":true,"visibility":"user-or-llm","description":"Start date in YYYYMMDD format"},"end":{"type":"string","required":true,"visibility":"user-or-llm","description":"End date in YYYYMMDD format"},"retentionMode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Retention type: \\"n-day\\" (sent as nday), \\"rolling\\", \\"bracket\\", or \\"nday_or_before\\" (default: n-day)"},"retentionBrackets":{"type":"string","required":false,"visibility":"user-or-llm","description":"Required when Retention Mode is \\"bracket\\". Day ranges with an exclusive end day, e.g. [[0,5]] for Day 0 to Day 4"},"interval":{"type":"string","required":false,"visibility":"user-or-llm","description":"Time interval: 1 (daily), 7 (weekly), or 30 (monthly)"},"groupBy":{"type":"string","required":false,"visibility":"user-or-llm","description":"Property to group by (limit: one; prefix custom properties with \\"gp:\\")"},"segment":{"type":"string","required":false,"visibility":"user-or-llm","description":"JSON segment definition(s) applied to the query"},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"oauth":{"required":false,"provider":"amplitude","credentialKind":"service-account","credentialParams":{"apiKey":"providerWorkspaceId","secretKey":"accessToken","dataResidency":"domain"},"credentialSuppliedParams":["apiKey","secretKey","dataResidency"]},"hostedApiKey":"none"},"amplitude_send_event":{"id":"amplitude_send_event","name":"Amplitude Send Event","description":"Track an event in Amplitude using the HTTP V2 API.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"userId":{"type":"string","required":false,"visibility":"user-or-llm","description":"User ID (required if no device_id)"},"deviceId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Device ID (required if no user_id)"},"eventType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the event (e.g., \\"page_view\\", \\"purchase\\")"},"eventProperties":{"type":"string","required":false,"visibility":"user-or-llm","description":"JSON object of custom event properties"},"userProperties":{"type":"string","required":false,"visibility":"user-or-llm","description":"JSON object of user properties to set (supports $set, $setOnce, $add, $append, $unset)"},"time":{"type":"string","required":false,"visibility":"user-or-llm","description":"Event timestamp in milliseconds since epoch"},"sessionId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Session start time in milliseconds since epoch"},"insertId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Unique ID for deduplication (within 7-day window)"},"appVersion":{"type":"string","required":false,"visibility":"user-or-llm","description":"Application version string"},"platform":{"type":"string","required":false,"visibility":"user-or-llm","description":"Platform (e.g., \\"Web\\", \\"iOS\\", \\"Android\\")"},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Two-letter country code"},"language":{"type":"string","required":false,"visibility":"user-or-llm","description":"Language code (e.g., \\"en\\")"},"ip":{"type":"string","required":false,"visibility":"user-or-llm","description":"IP address for geo-location"},"price":{"type":"string","required":false,"visibility":"user-or-llm","description":"Price of the item purchased"},"quantity":{"type":"string","required":false,"visibility":"user-or-llm","description":"Quantity of items purchased"},"revenue":{"type":"string","required":false,"visibility":"user-or-llm","description":"Revenue amount"},"productId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Product identifier"},"revenueType":{"type":"string","required":false,"visibility":"user-or-llm","description":"Revenue type (e.g., \\"purchase\\", \\"refund\\")"},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"oauth":{"required":false,"provider":"amplitude","credentialKind":"service-account","credentialParams":{"apiKey":"providerWorkspaceId","dataResidency":"domain"},"credentialSuppliedParams":["apiKey","dataResidency"]},"hostedApiKey":"none"},"amplitude_user_activity":{"id":"amplitude_user_activity","name":"Amplitude User Activity","description":"Get the event stream for a specific user by their Amplitude ID.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"secretKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude Secret Key"},"amplitudeId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Amplitude internal user ID"},"offset":{"type":"string","required":false,"visibility":"user-or-llm","description":"Offset for pagination (default 0)"},"limit":{"type":"string","required":false,"visibility":"user-or-llm","description":"Maximum number of events to return (default 1000, max 1000)"},"direction":{"type":"string","required":false,"visibility":"user-or-llm","description":"Sort direction: \\"latest\\" or \\"earliest\\" (default: latest)"},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"oauth":{"required":false,"provider":"amplitude","credentialKind":"service-account","credentialParams":{"apiKey":"providerWorkspaceId","secretKey":"accessToken","dataResidency":"domain"},"credentialSuppliedParams":["apiKey","secretKey","dataResidency"]},"hostedApiKey":"none"},"amplitude_user_profile":{"id":"amplitude_user_profile","name":"Amplitude User Profile","description":"Get a user profile including properties, cohort memberships, and computed properties. Not available for EU data-residency projects.","version":"1.0.0","params":{"apiKey":{"type":"string","required":false,"visibility":"user-only","description":"Amplitude API Key. With it, the request authenticates with both keys over Basic auth"},"secretKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude Secret Key"},"userId":{"type":"string","required":false,"visibility":"user-or-llm","description":"External user ID (required if no device_id)"},"deviceId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Device ID (required if no user_id)"},"getAmpProps":{"type":"string","required":false,"visibility":"user-or-llm","description":"Include Amplitude user properties (true/false, default: false)"},"getCohortIds":{"type":"string","required":false,"visibility":"user-or-llm","description":"Include cohort IDs the user belongs to (true/false, default: false)"},"getComputations":{"type":"string","required":false,"visibility":"user-or-llm","description":"Include computed user properties (true/false, default: false)"}},"oauth":{"required":false,"provider":"amplitude","credentialKind":"service-account","credentialParams":{"apiKey":"providerWorkspaceId","secretKey":"accessToken"},"credentialSuppliedParams":["apiKey","secretKey"]},"hostedApiKey":"none"},"amplitude_user_search":{"id":"amplitude_user_search","name":"Amplitude User Search","description":"Search for a user by User ID, Device ID, or Amplitude ID using the Dashboard REST API.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"secretKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude Secret Key"},"user":{"type":"string","required":true,"visibility":"user-or-llm","description":"User ID, Device ID, or Amplitude ID to search for"},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"oauth":{"required":false,"provider":"amplitude","credentialKind":"service-account","credentialParams":{"apiKey":"providerWorkspaceId","secretKey":"accessToken","dataResidency":"domain"},"credentialSuppliedParams":["apiKey","secretKey","dataResidency"]},"hostedApiKey":"none"},"apify_get_dataset_items":{"id":"apify_get_dataset_items","name":"APIFY Get Dataset Items","description":"Retrieve items stored in an APIFY dataset","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"APIFY API token from console.apify.com/account#/integrations"},"datasetId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Dataset ID to read items from. Example: \\"9RnD3Pql2vGZkc5H5\\""},"itemLimit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Max items to return (1-250000). Default: all items. Example: 500"},"offset":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to skip at the start. Default: 0"},"fields":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated list of fields to include. Example: \\"title,url,price\\""}},"oauth":{"required":false,"provider":"apify","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apify_get_run":{"id":"apify_get_run","name":"APIFY Get Run","description":"Get the status and details of an APIFY actor run","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"APIFY API token from console.apify.com/account#/integrations"},"runId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Actor run ID to fetch. Example: \\"HG7ML7M8z78YcAPEB\\""}},"oauth":{"required":false,"provider":"apify","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apify_run_actor_async":{"id":"apify_run_actor_async","name":"APIFY Run Actor (Async)","description":"Start an APIFY Actor run and poll it within the same workflow step until completion or the polling deadline","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"APIFY API token from console.apify.com/account#/integrations"},"actorId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Actor ID or username/actor-name. Examples: \\"apify/web-scraper\\", \\"janedoe/my-actor\\", \\"moJRLRc85AitArpNN\\""},"input":{"type":"string","required":false,"visibility":"user-or-llm","description":"Actor input as JSON string. Example: { \\"startUrls\\": [ { \\"url\\": \\"https://example.com\\" } ], \\"maxPages\\": 10 }"},"waitForFinish":{"type":"number","required":false,"visibility":"user-or-llm","description":"Initial wait time in seconds (0-60) before polling starts. Example: 30"},"itemLimit":{"type":"number","required":false,"default":100,"visibility":"user-or-llm","description":"Max dataset items to fetch (1-250000). Default: 100. Example: 500"},"memory":{"type":"number","required":false,"visibility":"user-or-llm","description":"Memory in megabytes allocated for the actor run (128-32768). Example: 1024 for 1GB, 2048 for 2GB"},"timeout":{"type":"number","required":false,"visibility":"user-or-llm","description":"Timeout in seconds for the actor run. Example: 300 for 5 minutes, 3600 for 1 hour"},"build":{"type":"string","required":false,"visibility":"user-or-llm","description":"Actor build to run. Examples: \\"latest\\", \\"beta\\", \\"1.2.3\\", \\"build-tag-name\\""}},"oauth":{"required":false,"provider":"apify","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apify_run_actor_sync":{"id":"apify_run_actor_sync","name":"APIFY Run Actor (Sync)","description":"Run an APIFY actor synchronously and get results (max 5 minutes)","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"APIFY API token from console.apify.com/account#/integrations"},"actorId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Actor ID or username/actor-name. Examples: \\"apify/web-scraper\\", \\"janedoe/my-actor\\", \\"moJRLRc85AitArpNN\\""},"input":{"type":"string","required":false,"visibility":"user-or-llm","description":"Actor input as JSON string. Example: { \\"startUrls\\": [ { \\"url\\": \\"https://example.com\\" } ], \\"maxPages\\": 10 }"},"memory":{"type":"number","required":false,"visibility":"user-or-llm","description":"Memory in megabytes allocated for the actor run (128-32768). Example: 1024 for 1GB, 2048 for 2GB"},"timeout":{"type":"number","required":false,"visibility":"user-or-llm","description":"Timeout in seconds for the actor run. Example: 300 for 5 minutes, 3600 for 1 hour"},"build":{"type":"string","required":false,"visibility":"user-or-llm","description":"Actor build to run. Examples: \\"latest\\", \\"beta\\", \\"1.2.3\\", \\"build-tag-name\\""}},"oauth":{"required":false,"provider":"apify","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apify_run_task":{"id":"apify_run_task","name":"APIFY Run Task","description":"Run a saved APIFY actor task synchronously and get dataset items (max 5 minutes)","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"APIFY API token from console.apify.com/account#/integrations"},"taskId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Task ID or username/task-name. Examples: \\"janedoe/my-task\\", \\"moJRLRc85AitArpNN\\""},"input":{"type":"string","required":false,"visibility":"user-or-llm","description":"JSON string that overrides the task\'s saved input. Example: { \\"startUrls\\": [ { \\"url\\": \\"https://example.com\\" } ] }"},"itemLimit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Max dataset items to return (1-250000). Example: 500"},"memory":{"type":"number","required":false,"visibility":"user-or-llm","description":"Memory in megabytes allocated for the run (128-32768). Example: 1024 for 1GB"},"timeout":{"type":"number","required":false,"visibility":"user-or-llm","description":"Timeout in seconds for the run. Example: 300 for 5 minutes"},"build":{"type":"string","required":false,"visibility":"user-or-llm","description":"Actor build to run. Examples: \\"latest\\", \\"beta\\", \\"1.2.3\\""}},"oauth":{"required":false,"provider":"apify","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_account_bulk_create":{"id":"apollo_account_bulk_create","name":"Apollo Bulk Create Accounts","description":"Create up to 100 accounts at once in your Apollo database. Set run_dedupe=true to deduplicate by domain, organization_id, and name. Master key required.","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"},"accounts":{"type":"array","required":true,"visibility":"user-or-llm","description":"Array of accounts to create (max 100). Each account should include a name, and may optionally include domain, phone, phone_status_cd, raw_address, owner_id, linkedin_url, facebook_url, twitter_url, salesforce_id, and hubspot_id."},"append_label_names":{"type":"array","required":false,"visibility":"user-only","description":"Array of label names to add to ALL accounts in this request"},"run_dedupe":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"When true, performs aggressive deduplication by domain, organization_id, and name (defaults to false)"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_account_bulk_update":{"id":"apollo_account_bulk_update","name":"Apollo Bulk Update Accounts","description":"Update up to 1000 existing accounts at once in your Apollo database (higher limit than contacts!). Each account must include an id field. Master key required.","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"},"account_ids":{"type":"array","required":false,"visibility":"user-or-llm","description":"Array of account IDs to update with the same values (max 1000). Use with name/owner_id for uniform updates. Use either this OR account_attributes."},"name":{"type":"string","required":false,"visibility":"user-or-llm","description":"When using account_ids, apply this name to all accounts"},"owner_id":{"type":"string","required":false,"visibility":"user-or-llm","description":"When using account_ids, apply this owner to all accounts"},"account_stage_id":{"type":"string","required":false,"visibility":"user-or-llm","description":"When using account_ids, apply this account stage to all accounts"},"account_attributes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Array of account objects with individual updates (each must include id). Example: [{\\"id\\": \\"acc1\\", \\"name\\": \\"Acme\\", \\"owner_id\\": \\"u1\\", \\"account_stage_id\\": \\"s1\\", \\"typed_custom_fields\\": {\\"field_id\\": \\"value\\"}}]"},"async":{"type":"boolean","required":false,"visibility":"user-only","description":"When true, processes the update asynchronously. Only supported when using account_ids; returns 422 if used with account_attributes."}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_account_create":{"id":"apollo_account_create","name":"Apollo Create Account","description":"Create a new account (company) in your Apollo database","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Company name (e.g., \\"Acme Corporation\\")"},"domain":{"type":"string","required":false,"visibility":"user-or-llm","description":"Company domain without www. prefix (e.g., \\"acme.com\\")"},"phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Primary phone number for the account"},"owner_id":{"type":"string","required":false,"visibility":"user-only","description":"Apollo user ID of the account owner"},"account_stage_id":{"type":"string","required":false,"visibility":"user-only","description":"Apollo ID for the account stage to assign this account to"},"raw_address":{"type":"string","required":false,"visibility":"user-or-llm","description":"Corporate location (e.g., \\"San Francisco, CA, USA\\")"},"typed_custom_fields":{"type":"json","required":false,"visibility":"user-only","description":"Custom field values as { custom_field_id: value } map"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_account_search":{"id":"apollo_account_search","name":"Apollo Search Accounts","description":"Search your team\'s accounts in Apollo. Display limit: 50,000 records (100 records per page, 500 pages max). Use filters to narrow results. Master key required.","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"},"q_organization_name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Filter accounts by organization name (partial-match search)"},"account_stage_ids":{"type":"array","required":false,"visibility":"user-only","description":"Filter by account stage IDs"},"account_label_ids":{"type":"array","required":false,"visibility":"user-only","description":"Filter by account label IDs"},"sort_by_field":{"type":"string","required":false,"visibility":"user-or-llm","description":"Sort field: \\"account_last_activity_date\\", \\"account_created_at\\", or \\"account_updated_at\\""},"sort_ascending":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Sort ascending when true. Defaults to descending."},"page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Page number for pagination (e.g., 1, 2, 3)"},"per_page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Results per page, max 100 (e.g., 25, 50, 100)"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_account_update":{"id":"apollo_account_update","name":"Apollo Update Account","description":"Update an existing account in your Apollo database","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"account_id":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the account to update (e.g., \\"acc_abc123\\")"},"name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Company name (e.g., \\"Acme Corporation\\")"},"domain":{"type":"string","required":false,"visibility":"user-or-llm","description":"Company domain (e.g., \\"acme.com\\")"},"phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Company phone number"},"owner_id":{"type":"string","required":false,"visibility":"user-only","description":"Apollo user ID of the account owner"},"account_stage_id":{"type":"string","required":false,"visibility":"user-only","description":"Apollo ID for the account stage to assign this account to"},"raw_address":{"type":"string","required":false,"visibility":"user-or-llm","description":"Corporate location (e.g., \\"San Francisco, CA, USA\\")"},"typed_custom_fields":{"type":"json","required":false,"visibility":"user-only","description":"Custom field values as { custom_field_id: value } map"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_contact_bulk_create":{"id":"apollo_contact_bulk_create","name":"Apollo Bulk Create Contacts","description":"Create up to 100 contacts at once in your Apollo database. Supports deduplication to prevent creating duplicate contacts. Master key required.","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"},"contacts":{"type":"array","required":true,"visibility":"user-or-llm","description":"Array of contacts to create (max 100). Each contact may include first_name, last_name, email, title, organization_name, account_id, owner_id, contact_stage_id, linkedin_url, phone (single string) or phone_numbers (array of {raw_number, position}), contact_emails, typed_custom_fields, and CRM IDs (salesforce_contact_id, hubspot_id, team_id) for cross-system matching"},"append_label_names":{"type":"array","required":false,"visibility":"user-or-llm","description":"Label names to add to all contacts in this request (e.g., [\\"Hot Lead\\"])"},"run_dedupe":{"type":"boolean","required":false,"visibility":"user-only","description":"Enable deduplication to prevent creating duplicate contacts. When true, existing contacts are returned without modification"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_contact_bulk_update":{"id":"apollo_contact_bulk_update","name":"Apollo Bulk Update Contacts","description":"Update up to 100 existing contacts at once in your Apollo database. Each contact must include an id field. Master key required.","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"},"contact_ids":{"type":"array","required":false,"visibility":"user-or-llm","description":"Array of contact IDs to update. Must be paired with an object-form contact_attributes specifying the fields to apply uniformly to all listed contacts."},"contact_attributes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Required. Either an array of per-contact updates (each with id) — used standalone — or a single object of attributes to apply to all contact_ids. Supported fields: owner_id, email, organization_name, title, first_name, last_name, account_id, present_raw_address, linkedin_url, typed_custom_fields"},"async":{"type":"boolean","required":false,"visibility":"user-only","description":"Force asynchronous processing. Automatically enabled for >100 contacts"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_contact_create":{"id":"apollo_contact_create","name":"Apollo Create Contact","description":"Create a new contact in your Apollo database","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"first_name":{"type":"string","required":true,"visibility":"user-or-llm","description":"First name of the contact"},"last_name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Last name of the contact"},"email":{"type":"string","required":false,"visibility":"user-or-llm","description":"Email address of the contact"},"title":{"type":"string","required":false,"visibility":"user-or-llm","description":"Job title (e.g., \\"VP of Sales\\", \\"Software Engineer\\")"},"account_id":{"type":"string","required":false,"visibility":"user-or-llm","description":"Apollo account ID to associate with (e.g., \\"acc_abc123\\")"},"owner_id":{"type":"string","required":false,"visibility":"user-only","description":"User ID of the contact owner (accepted by Apollo but not officially documented for POST /contacts)"},"organization_name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Name of the contact\'s employer (e.g., \\"Apollo\\")"},"website_url":{"type":"string","required":false,"visibility":"user-or-llm","description":"Corporate website URL (e.g., \\"https://www.apollo.io/\\")"},"label_names":{"type":"array","required":false,"visibility":"user-or-llm","description":"Lists/labels to add the contact to (e.g., [\\"Prospects\\"])"},"contact_stage_id":{"type":"string","required":false,"visibility":"user-or-llm","description":"Apollo ID for the contact stage"},"present_raw_address":{"type":"string","required":false,"visibility":"user-or-llm","description":"Personal location for the contact (e.g., \\"Atlanta, United States\\")"},"direct_phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Primary phone number"},"corporate_phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Work/office phone number"},"mobile_phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Mobile phone number"},"home_phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Home phone number"},"other_phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Alternative phone number"},"typed_custom_fields":{"type":"json","required":false,"visibility":"user-or-llm","description":"Custom field values keyed by custom field ID"},"run_dedupe":{"type":"boolean","required":false,"visibility":"user-only","description":"When true, Apollo deduplicates against existing contacts"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_contact_search":{"id":"apollo_contact_search","name":"Apollo Search Contacts","description":"Search your team\'s contacts in Apollo","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"q_keywords":{"type":"string","required":false,"visibility":"user-or-llm","description":"Keywords to search for"},"contact_stage_ids":{"type":"array","required":false,"visibility":"user-only","description":"Filter by contact stage IDs"},"contact_label_ids":{"type":"array","required":false,"visibility":"user-only","description":"Filter by Apollo label IDs (lists)"},"sort_by_field":{"type":"string","required":false,"visibility":"user-only","description":"Sort field: contact_last_activity_date, contact_email_last_opened_at, contact_email_last_clicked_at, contact_created_at, or contact_updated_at"},"sort_ascending":{"type":"boolean","required":false,"visibility":"user-only","description":"When true, sort ascending. Must be used together with sort_by_field"},"page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Page number for pagination (e.g., 1, 2, 3)"},"per_page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Results per page, max 100 (e.g., 25, 50, 100)"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_contact_update":{"id":"apollo_contact_update","name":"Apollo Update Contact","description":"Update an existing contact in your Apollo database","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"contact_id":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the contact to update (e.g., \\"con_abc123\\")"},"first_name":{"type":"string","required":false,"visibility":"user-or-llm","description":"First name of the contact"},"last_name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Last name of the contact"},"email":{"type":"string","required":false,"visibility":"user-or-llm","description":"Email address"},"title":{"type":"string","required":false,"visibility":"user-or-llm","description":"Job title (e.g., \\"VP of Sales\\", \\"Software Engineer\\")"},"account_id":{"type":"string","required":false,"visibility":"user-or-llm","description":"Apollo account ID (e.g., \\"acc_abc123\\")"},"owner_id":{"type":"string","required":false,"visibility":"user-only","description":"User ID of the contact owner (accepted by Apollo but not officially documented for PATCH /contacts/{id})"},"organization_name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Name of the contact\'s employer (e.g., \\"Apollo\\")"},"website_url":{"type":"string","required":false,"visibility":"user-or-llm","description":"Corporate website URL (e.g., \\"https://www.apollo.io/\\")"},"label_names":{"type":"array","required":false,"visibility":"user-or-llm","description":"Lists/labels to add the contact to (e.g., [\\"Prospects\\"])"},"contact_stage_id":{"type":"string","required":false,"visibility":"user-or-llm","description":"Apollo ID for the contact stage"},"present_raw_address":{"type":"string","required":false,"visibility":"user-or-llm","description":"Personal location for the contact (e.g., \\"Atlanta, United States\\")"},"direct_phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Primary phone number"},"corporate_phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Work/office phone number"},"mobile_phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Mobile phone number"},"home_phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Home phone number"},"other_phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Alternative phone number"},"typed_custom_fields":{"type":"json","required":false,"visibility":"user-or-llm","description":"Custom field values keyed by custom field ID"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_email_accounts":{"id":"apollo_email_accounts","name":"Apollo Get Email Accounts","description":"Get list of team\'s linked email accounts in Apollo","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_opportunity_create":{"id":"apollo_opportunity_create","name":"Apollo Create Opportunity","description":"Create a new deal for an account in your Apollo database (master key required)","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the opportunity/deal (e.g., \\"Enterprise License - Q1\\")"},"account_id":{"type":"string","required":false,"visibility":"user-or-llm","description":"ID of the account this opportunity belongs to (e.g., \\"acc_abc123\\")"},"amount":{"type":"string","required":false,"visibility":"user-or-llm","description":"Monetary value as a plain number string with no commas or currency symbols"},"opportunity_stage_id":{"type":"string","required":false,"visibility":"user-only","description":"ID of the opportunity stage"},"owner_id":{"type":"string","required":false,"visibility":"user-only","description":"User ID of the opportunity owner"},"closed_date":{"type":"string","required":false,"visibility":"user-or-llm","description":"Expected close date in YYYY-MM-DD format"},"typed_custom_fields":{"type":"json","required":false,"visibility":"user-only","description":"Custom field values as { custom_field_id: value } map"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_opportunity_get":{"id":"apollo_opportunity_get","name":"Apollo Get Opportunity","description":"Retrieve complete details of a specific deal/opportunity by ID","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"opportunity_id":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the opportunity to retrieve (e.g., \\"opp_abc123\\")"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_opportunity_search":{"id":"apollo_opportunity_search","name":"Apollo Search Opportunities","description":"Search and list all deals/opportunities in your team\'s Apollo account","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"sort_by_field":{"type":"string","required":false,"visibility":"user-or-llm","description":"Sort field: \\"amount\\", \\"is_closed\\", or \\"is_won\\""},"page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Page number for pagination (e.g., 1, 2, 3)"},"per_page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Results per page, max 100 (e.g., 25, 50, 100)"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_opportunity_update":{"id":"apollo_opportunity_update","name":"Apollo Update Opportunity","description":"Update an existing deal/opportunity in your Apollo database","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"opportunity_id":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the opportunity to update (e.g., \\"opp_abc123\\")"},"name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Name of the opportunity/deal (e.g., \\"Enterprise License - Q1\\")"},"amount":{"type":"string","required":false,"visibility":"user-or-llm","description":"Monetary value as a plain number string with no commas or currency symbols"},"opportunity_stage_id":{"type":"string","required":false,"visibility":"user-only","description":"ID of the opportunity stage"},"owner_id":{"type":"string","required":false,"visibility":"user-only","description":"User ID of the opportunity owner"},"closed_date":{"type":"string","required":false,"visibility":"user-or-llm","description":"Expected close date in YYYY-MM-DD format"},"typed_custom_fields":{"type":"json","required":false,"visibility":"user-only","description":"Custom field values as { custom_field_id: value } map"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_organization_bulk_enrich":{"id":"apollo_organization_bulk_enrich","name":"Apollo Bulk Organization Enrichment","description":"Enrich data for up to 10 organizations at once using Apollo","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"domains":{"type":"array","required":true,"visibility":"user-or-llm","description":"Array of company domains to enrich (max 10, no www. or @, e.g., [\\"apollo.io\\", \\"stripe.com\\"])"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_organization_enrich":{"id":"apollo_organization_enrich","name":"Apollo Organization Enrichment","description":"Enrich data for a single organization using Apollo","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"domain":{"type":"string","required":true,"visibility":"user-or-llm","description":"Company domain (e.g., \\"apollo.io\\", \\"acme.com\\")"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_organization_search":{"id":"apollo_organization_search","name":"Apollo Organization Search","description":"Search Apollo\'s database for companies using filters","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"organization_locations":{"type":"array","required":false,"visibility":"user-or-llm","description":"Company HQ locations (cities, US states, or countries)"},"organization_not_locations":{"type":"array","required":false,"visibility":"user-or-llm","description":"Exclude companies whose HQ is in these locations"},"organization_num_employees_ranges":{"type":"array","required":false,"visibility":"user-or-llm","description":"Employee count ranges as \\"min,max\\" strings (e.g., [\\"1,10\\", \\"250,500\\", \\"10000,20000\\"])"},"q_organization_keyword_tags":{"type":"array","required":false,"visibility":"user-or-llm","description":"Industry or keyword tags"},"q_organization_name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Organization name to search for (e.g., \\"Acme\\", \\"TechCorp\\")"},"organization_ids":{"type":"array","required":false,"visibility":"user-or-llm","description":"Apollo organization IDs to include (e.g., [\\"5e66b6381e05b4008c8331b8\\"])"},"q_organization_domains_list":{"type":"array","required":false,"visibility":"user-or-llm","description":"Domain names to filter by (no www. or @, up to 1,000)"},"page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Page number for pagination (e.g., 1, 2, 3)"},"per_page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Results per page, max 100 (e.g., 25, 50, 100)"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_people_bulk_enrich":{"id":"apollo_people_bulk_enrich","name":"Apollo Bulk People Enrichment","description":"Enrich data for up to 10 people at once using Apollo","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"people":{"type":"array","required":true,"visibility":"user-or-llm","description":"Array of people to enrich (max 10)"},"reveal_personal_emails":{"type":"boolean","required":false,"visibility":"user-only","description":"Reveal personal email addresses (uses credits)"},"reveal_phone_number":{"type":"boolean","required":false,"visibility":"user-only","description":"Reveal phone numbers (uses credits, requires webhook_url)"},"webhook_url":{"type":"string","required":false,"visibility":"user-only","description":"Webhook URL for async phone number delivery (required when reveal_phone_number is true)"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_people_enrich":{"id":"apollo_people_enrich","name":"Apollo People Enrichment","description":"Enrich data for a single person using Apollo","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"first_name":{"type":"string","required":false,"visibility":"user-or-llm","description":"First name of the person"},"last_name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Last name of the person"},"name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Full name of the person (alternative to first_name/last_name)"},"id":{"type":"string","required":false,"visibility":"user-or-llm","description":"Apollo ID for the person"},"hashed_email":{"type":"string","required":false,"visibility":"user-or-llm","description":"MD5 or SHA-256 hashed email"},"email":{"type":"string","required":false,"visibility":"user-or-llm","description":"Email address of the person"},"organization_name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Company name where the person works"},"domain":{"type":"string","required":false,"visibility":"user-or-llm","description":"Company domain (e.g., \\"apollo.io\\", \\"acme.com\\")"},"linkedin_url":{"type":"string","required":false,"visibility":"user-or-llm","description":"LinkedIn profile URL"},"reveal_personal_emails":{"type":"boolean","required":false,"visibility":"user-only","description":"Reveal personal email addresses (uses credits)"},"reveal_phone_number":{"type":"boolean","required":false,"visibility":"user-only","description":"Reveal phone numbers (uses credits, requires webhook_url)"},"webhook_url":{"type":"string","required":false,"visibility":"user-only","description":"Webhook URL for async phone number delivery (required when reveal_phone_number is true)"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_people_search":{"id":"apollo_people_search","name":"Apollo People Search","description":"Search Apollo\'s database for people using demographic filters","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"person_titles":{"type":"array","required":false,"visibility":"user-or-llm","description":"Job titles to search for (e.g., [\\"CEO\\", \\"VP of Sales\\"])"},"include_similar_titles":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Whether to return people with job titles similar to person_titles"},"person_locations":{"type":"array","required":false,"visibility":"user-or-llm","description":"Locations to search in (e.g., [\\"San Francisco, CA\\", \\"New York, NY\\"])"},"person_seniorities":{"type":"array","required":false,"visibility":"user-or-llm","description":"Seniority levels (one of: owner, founder, c_suite, partner, vp, head, director, manager, senior, entry, intern)"},"organization_ids":{"type":"array","required":false,"visibility":"user-or-llm","description":"Apollo organization IDs to filter by (e.g., [\\"5e66b6381e05b4008c8331b8\\"])"},"organization_names":{"type":"array","required":false,"visibility":"user-or-llm","description":"Company names to search within (legacy filter)"},"organization_locations":{"type":"array","required":false,"visibility":"user-or-llm","description":"Headquarters locations of the people\'s current employer (e.g., [\'texas\', \'tokyo\', \'spain\'])"},"q_organization_domains_list":{"type":"array","required":false,"visibility":"user-or-llm","description":"Employer domain names (e.g., [\\"apollo.io\\", \\"microsoft.com\\"]) — up to 1,000, no www. or @"},"organization_num_employees_ranges":{"type":"array","required":false,"visibility":"user-or-llm","description":"Employee count ranges for the person\'s current employer. Each entry is \\"min,max\\" (e.g., [\\"1,10\\", \\"250,500\\", \\"10000,20000\\"])"},"contact_email_status":{"type":"array","required":false,"visibility":"user-or-llm","description":"Email statuses to filter by: \\"verified\\", \\"unverified\\", \\"likely to engage\\", \\"unavailable\\""},"q_keywords":{"type":"string","required":false,"visibility":"user-or-llm","description":"Keywords to search for"},"page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Page number for pagination, default 1 (e.g., 1, 2, 3)"},"per_page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Results per page, default 25, max 100 (e.g., 25, 50, 100)"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_sequence_add_contacts":{"id":"apollo_sequence_add_contacts","name":"Apollo Add Contacts to Sequence","description":"Add contacts to an Apollo sequence","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"},"sequence_id":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the sequence to add contacts to (e.g., \\"seq_abc123\\")"},"contact_ids":{"type":"array","required":false,"visibility":"user-or-llm","description":"Array of contact IDs to add to the sequence (e.g., [\\"con_abc123\\", \\"con_def456\\"]). Either contact_ids or label_names must be provided."},"label_names":{"type":"array","required":false,"visibility":"user-or-llm","description":"Array of label names to identify contacts to add to the sequence. Either contact_ids or label_names must be provided."},"send_email_from_email_account_id":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the email account to send from. Use the Get Email Accounts operation to look this up."},"send_email_from_email_address":{"type":"string","required":false,"visibility":"user-only","description":"Specific email address to send from within the email account."},"sequence_no_email":{"type":"boolean","required":false,"visibility":"user-only","description":"Add contacts even if they have no email address"},"sequence_unverified_email":{"type":"boolean","required":false,"visibility":"user-only","description":"Add contacts with unverified email addresses"},"sequence_job_change":{"type":"boolean","required":false,"visibility":"user-only","description":"Add contacts who recently changed jobs"},"sequence_active_in_other_campaigns":{"type":"boolean","required":false,"visibility":"user-only","description":"Add contacts active in other campaigns"},"sequence_finished_in_other_campaigns":{"type":"boolean","required":false,"visibility":"user-only","description":"Add contacts who finished other campaigns"},"sequence_same_company_in_same_campaign":{"type":"boolean","required":false,"visibility":"user-only","description":"Add contacts even if others from the same company are in the sequence"},"contacts_without_ownership_permission":{"type":"boolean","required":false,"visibility":"user-only","description":"Add contacts without ownership permission"},"add_if_in_queue":{"type":"boolean","required":false,"visibility":"user-only","description":"Add contacts even if they are in the queue"},"contact_verification_skipped":{"type":"boolean","required":false,"visibility":"user-only","description":"Skip contact verification when adding"},"user_id":{"type":"string","required":false,"visibility":"user-only","description":"ID of the user performing the action"},"status":{"type":"string","required":false,"visibility":"user-only","description":"Initial status for added contacts: \\"active\\" or \\"paused\\""},"auto_unpause_at":{"type":"string","required":false,"visibility":"user-only","description":"ISO 8601 datetime to automatically unpause contacts"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_sequence_search":{"id":"apollo_sequence_search","name":"Apollo Search Sequences","description":"Search for sequences/campaigns in your team\'s Apollo account (master key required)","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"},"q_name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Search sequences by name (e.g., \\"Outbound Q1\\", \\"Follow-up\\")"},"page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Page number for pagination (e.g., 1, 2, 3)"},"per_page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Results per page, max 100 (e.g., 25, 50, 100)"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_task_create":{"id":"apollo_task_create","name":"Apollo Create Task","description":"Create one or more tasks in Apollo (one task per contact_id, master key required)","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"},"user_id":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the Apollo user the task is assigned to"},"contact_ids":{"type":"array","required":true,"visibility":"user-or-llm","description":"Array of contact IDs. One task is created per contact."},"priority":{"type":"string","required":false,"visibility":"user-or-llm","description":"Task priority: \\"high\\", \\"medium\\", or \\"low\\" (defaults to \\"medium\\")"},"due_at":{"type":"string","required":true,"visibility":"user-or-llm","description":"Due date/time in ISO 8601 format (e.g., \\"2024-12-31T23:59:59Z\\")"},"type":{"type":"string","required":true,"visibility":"user-or-llm","description":"Task type: \\"call\\", \\"outreach_manual_email\\", \\"linkedin_step_connect\\", \\"linkedin_step_message\\", \\"linkedin_step_view_profile\\", \\"linkedin_step_interact_post\\", or \\"action_item\\""},"status":{"type":"string","required":true,"visibility":"user-or-llm","description":"Task status: \\"scheduled\\", \\"completed\\", or \\"skipped\\""},"note":{"type":"string","required":false,"visibility":"user-or-llm","description":"Free-form note providing context for the task"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"apollo_task_search":{"id":"apollo_task_search","name":"Apollo Search Tasks","description":"Search for tasks in Apollo","version":"1.0.0","params":{"credentialType":{"type":"string","required":false,"visibility":"hidden","description":"Stored credential type supplied by credential resolution"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"},"sort_by_field":{"type":"string","required":false,"visibility":"user-or-llm","description":"Sort field: \\"task_due_at\\" or \\"task_priority\\""},"open_factor_names":{"type":"array","required":false,"visibility":"user-or-llm","description":"Filter by status. Common values: [\\"task_types\\"] for open tasks, [\\"task_completed_at\\"] for completed tasks."},"page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Page number for pagination (e.g., 1, 2, 3)"},"per_page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Results per page, max 100 (e.g., 25, 50, 100)"}},"oauth":{"required":false,"provider":"apollo","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"],"authoritativeParams":["credentialType"]},"hostedApiKey":"none"},"appconfig_create_application":{"id":"appconfig_create_application","name":"AppConfig Create Application","description":"Create an application in AWS AppConfig","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the application to create"},"description":{"type":"string","required":false,"visibility":"user-or-llm","description":"Description of the application"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_create_configuration_profile":{"id":"appconfig_create_configuration_profile","name":"AppConfig Create Configuration Profile","description":"Create a configuration profile in an AWS AppConfig application","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID to create the configuration profile in"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the configuration profile"},"locationUri":{"type":"string","required":true,"visibility":"user-or-llm","description":"Where the configuration is stored. Use \\"hosted\\" for AppConfig-hosted configurations, or an SSM/S3 URI"},"description":{"type":"string","required":false,"visibility":"user-or-llm","description":"Description of the configuration profile"},"retrievalRoleArn":{"type":"string","required":false,"visibility":"user-or-llm","description":"ARN of an IAM role to retrieve the configuration (required for non-hosted URIs)"},"type":{"type":"string","required":false,"visibility":"user-or-llm","description":"Profile type: AWS.Freeform (default) or AWS.AppConfig.FeatureFlags"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_create_environment":{"id":"appconfig_create_environment","name":"AppConfig Create Environment","description":"Create an environment for an AWS AppConfig application","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID to create the environment in"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the environment to create"},"description":{"type":"string","required":false,"visibility":"user-or-llm","description":"Description of the environment"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_create_hosted_configuration_version":{"id":"appconfig_create_hosted_configuration_version","name":"AppConfig Create Hosted Configuration Version","description":"Create a new hosted configuration version for an AppConfig configuration profile","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the configuration profile"},"configurationProfileId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The configuration profile ID to add the version to"},"content":{"type":"string","required":true,"visibility":"user-or-llm","description":"The configuration content (e.g., a JSON or YAML document)"},"contentType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Content type of the configuration (e.g., application/json, text/plain)"},"description":{"type":"string","required":false,"visibility":"user-or-llm","description":"Description of the configuration version"},"latestVersionNumber":{"type":"number","required":false,"visibility":"user-or-llm","description":"The version number of the latest version, used for optimistic concurrency"},"versionLabel":{"type":"string","required":false,"visibility":"user-or-llm","description":"A user-defined label for the configuration version"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_delete_application":{"id":"appconfig_delete_application","name":"AppConfig Delete Application","description":"Delete an AWS AppConfig application","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID to delete"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_delete_configuration_profile":{"id":"appconfig_delete_configuration_profile","name":"AppConfig Delete Configuration Profile","description":"Delete an AWS AppConfig configuration profile","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the configuration profile"},"configurationProfileId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The configuration profile ID to delete"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_delete_environment":{"id":"appconfig_delete_environment","name":"AppConfig Delete Environment","description":"Delete an AWS AppConfig environment","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the environment"},"environmentId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The environment ID to delete"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_delete_hosted_configuration_version":{"id":"appconfig_delete_hosted_configuration_version","name":"AppConfig Delete Hosted Configuration Version","description":"Delete a specific hosted configuration version from an AppConfig profile","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the configuration profile"},"configurationProfileId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The configuration profile ID that owns the version"},"versionNumber":{"type":"number","required":true,"visibility":"user-or-llm","description":"The version number to delete"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_get_application":{"id":"appconfig_get_application","name":"AppConfig Get Application","description":"Get details about a single AWS AppConfig application","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID to retrieve"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_get_configuration":{"id":"appconfig_get_configuration","name":"AppConfig Get Configuration","description":"Retrieve the latest deployed configuration for an AppConfig application, environment, and profile","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID or name to retrieve configuration for"},"environmentId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The environment ID or name to retrieve configuration for"},"configurationProfileId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The configuration profile ID or name to retrieve"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_get_configuration_profile":{"id":"appconfig_get_configuration_profile","name":"AppConfig Get Configuration Profile","description":"Get details about a single AWS AppConfig configuration profile","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the configuration profile"},"configurationProfileId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The configuration profile ID to retrieve"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_get_deployment":{"id":"appconfig_get_deployment","name":"AppConfig Get Deployment","description":"Get details about a specific AWS AppConfig deployment","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID of the deployment"},"environmentId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The environment ID of the deployment"},"deploymentNumber":{"type":"number","required":true,"visibility":"user-or-llm","description":"The sequence number of the deployment"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_get_environment":{"id":"appconfig_get_environment","name":"AppConfig Get Environment","description":"Get details about a single AWS AppConfig environment","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the environment"},"environmentId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The environment ID to retrieve"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_get_hosted_configuration_version":{"id":"appconfig_get_hosted_configuration_version","name":"AppConfig Get Hosted Configuration Version","description":"Retrieve a specific hosted configuration version from an AppConfig profile","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the configuration profile"},"configurationProfileId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The configuration profile ID to read the version from"},"versionNumber":{"type":"number","required":true,"visibility":"user-or-llm","description":"The version number to retrieve"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_list_applications":{"id":"appconfig_list_applications","name":"AppConfig List Applications","description":"List applications in AWS AppConfig","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"maxResults":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of applications to return (1-50)"},"nextToken":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination token from a previous response"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_list_configuration_profiles":{"id":"appconfig_list_configuration_profiles","name":"AppConfig List Configuration Profiles","description":"List configuration profiles for an AWS AppConfig application","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the configuration profiles"},"maxResults":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of configuration profiles to return (1-50)"},"nextToken":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination token from a previous response"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_list_deployment_strategies":{"id":"appconfig_list_deployment_strategies","name":"AppConfig List Deployment Strategies","description":"List deployment strategies available in AWS AppConfig","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"maxResults":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of deployment strategies to return (1-50)"},"nextToken":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination token from a previous response"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_list_deployments":{"id":"appconfig_list_deployments","name":"AppConfig List Deployments","description":"List deployments for an AWS AppConfig environment","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID of the deployments"},"environmentId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The environment ID of the deployments"},"maxResults":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of deployments to return (1-50)"},"nextToken":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination token from a previous response"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_list_environments":{"id":"appconfig_list_environments","name":"AppConfig List Environments","description":"List environments for an AWS AppConfig application","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the environments"},"maxResults":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of environments to return (1-50)"},"nextToken":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination token from a previous response"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_list_hosted_configuration_versions":{"id":"appconfig_list_hosted_configuration_versions","name":"AppConfig List Hosted Configuration Versions","description":"List hosted configuration versions for an AWS AppConfig configuration profile","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the configuration profile"},"configurationProfileId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The configuration profile ID to list versions for"},"maxResults":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of versions to return (1-50)"},"nextToken":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination token from a previous response"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_start_deployment":{"id":"appconfig_start_deployment","name":"AppConfig Start Deployment","description":"Start deploying a configuration version to an AWS AppConfig environment","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID to deploy in"},"environmentId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The environment ID to deploy to"},"deploymentStrategyId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The deployment strategy ID to use"},"configurationProfileId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The configuration profile ID to deploy"},"configurationVersion":{"type":"string","required":true,"visibility":"user-or-llm","description":"The configuration version to deploy"},"description":{"type":"string","required":false,"visibility":"user-or-llm","description":"Description of the deployment"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_stop_deployment":{"id":"appconfig_stop_deployment","name":"AppConfig Stop Deployment","description":"Stop an in-progress AWS AppConfig deployment","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID of the deployment"},"environmentId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The environment ID of the deployment"},"deploymentNumber":{"type":"number","required":true,"visibility":"user-or-llm","description":"The sequence number of the deployment to stop"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_update_application":{"id":"appconfig_update_application","name":"AppConfig Update Application","description":"Update the name or description of an AWS AppConfig application","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID to update"},"name":{"type":"string","required":false,"visibility":"user-or-llm","description":"New name for the application"},"description":{"type":"string","required":false,"visibility":"user-or-llm","description":"New description for the application"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_update_configuration_profile":{"id":"appconfig_update_configuration_profile","name":"AppConfig Update Configuration Profile","description":"Update the name, description, or retrieval role of an AppConfig configuration profile","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the configuration profile"},"configurationProfileId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The configuration profile ID to update"},"name":{"type":"string","required":false,"visibility":"user-or-llm","description":"New name for the configuration profile"},"description":{"type":"string","required":false,"visibility":"user-or-llm","description":"New description for the configuration profile"},"retrievalRoleArn":{"type":"string","required":false,"visibility":"user-or-llm","description":"New ARN of the IAM role used to retrieve the configuration"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_update_environment":{"id":"appconfig_update_environment","name":"AppConfig Update Environment","description":"Update the name or description of an AWS AppConfig environment","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the environment"},"environmentId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The environment ID to update"},"name":{"type":"string","required":false,"visibility":"user-or-llm","description":"New name for the environment"},"description":{"type":"string","required":false,"visibility":"user-or-llm","description":"New description for the environment"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"arxiv_get_author_papers":{"id":"arxiv_get_author_papers","name":"ArXiv Get Author Papers","description":"Search for papers by a specific author on ArXiv.","version":"1.0.0","params":{"authorName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Author name to search for"},"maxResults":{"type":"number","required":false,"visibility":"user-only","description":"Maximum number of results to return (default: 10, max: 2000)"}},"hostedApiKey":"none"},"arxiv_get_paper":{"id":"arxiv_get_paper","name":"ArXiv Get Paper","description":"Get detailed information about a specific ArXiv paper by its ID.","version":"1.0.0","params":{"paperId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ArXiv paper ID (e.g., \\"1706.03762\\")"}},"hostedApiKey":"none"},"arxiv_search":{"id":"arxiv_search","name":"ArXiv Search","description":"Search for academic papers on ArXiv by keywords, authors, titles, or other fields.","version":"1.0.0","params":{"searchQuery":{"type":"string","required":true,"visibility":"user-or-llm","description":"The search query to execute"},"searchField":{"type":"string","required":false,"visibility":"user-only","description":"Field to search in: all, ti (title), au (author), abs (abstract), co (comment), jr (journal), cat (category), rn (report number)"},"maxResults":{"type":"number","required":false,"visibility":"user-only","description":"Maximum number of results to return (default: 10, max: 2000)"},"sortBy":{"type":"string","required":false,"visibility":"user-only","description":"Sort by: relevance, lastUpdatedDate, submittedDate (default: relevance)"},"sortOrder":{"type":"string","required":false,"visibility":"user-only","description":"Sort order: ascending, descending (default: descending)"}},"hostedApiKey":"none"},"asana_add_comment":{"id":"asana_add_comment","name":"Asana Add Comment","description":"Add a comment (story) to an Asana task","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"taskGid":{"type":"string","required":true,"visibility":"user-or-llm","description":"Asana task GID (numeric string)"},"text":{"type":"string","required":true,"visibility":"user-or-llm","description":"The text content of the comment"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_add_followers":{"id":"asana_add_followers","name":"Asana Add Followers","description":"Add one or more followers to an Asana task","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"taskGid":{"type":"string","required":true,"visibility":"user-or-llm","description":"GID of the Asana task (numeric string)"},"followers":{"type":"array","required":true,"visibility":"user-or-llm","description":"Array of user GIDs to add as followers to the task"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_create_project":{"id":"asana_create_project","name":"Asana Create Project","description":"Create a new project in an Asana workspace","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"workspace":{"type":"string","required":true,"visibility":"user-or-llm","description":"Asana workspace GID (numeric string) where the project will be created"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the project"},"notes":{"type":"string","required":false,"visibility":"user-or-llm","description":"Notes or description for the project"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_create_section":{"id":"asana_create_section","name":"Asana Create Section","description":"Create a new section in an Asana project","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"projectGid":{"type":"string","required":true,"visibility":"user-or-llm","description":"GID of the Asana project (numeric string) to add the section to"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the section"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_create_subtask":{"id":"asana_create_subtask","name":"Asana Create Subtask","description":"Create a subtask under an existing Asana task","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"taskGid":{"type":"string","required":true,"visibility":"user-or-llm","description":"GID of the parent Asana task (numeric string)"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the subtask"},"notes":{"type":"string","required":false,"visibility":"user-or-llm","description":"Notes or description for the subtask"},"assignee":{"type":"string","required":false,"visibility":"user-or-llm","description":"User GID to assign the subtask to"},"due_on":{"type":"string","required":false,"visibility":"user-or-llm","description":"Due date in YYYY-MM-DD format"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_create_task":{"id":"asana_create_task","name":"Asana Create Task","description":"Create a new task in Asana","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"workspace":{"type":"string","required":true,"visibility":"user-or-llm","description":"Asana workspace GID (numeric string) where the task will be created"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the task"},"notes":{"type":"string","required":false,"visibility":"user-or-llm","description":"Notes or description for the task"},"assignee":{"type":"string","required":false,"visibility":"user-or-llm","description":"User GID to assign the task to"},"due_on":{"type":"string","required":false,"visibility":"user-or-llm","description":"Due date in YYYY-MM-DD format"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_delete_task":{"id":"asana_delete_task","name":"Asana Delete Task","description":"Delete an Asana task by its GID (moves it to the trash)","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"taskGid":{"type":"string","required":true,"visibility":"user-or-llm","description":"GID of the Asana task to delete (numeric string)"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_get_project":{"id":"asana_get_project","name":"Asana Get Project","description":"Retrieve a single Asana project by its GID","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"projectGid":{"type":"string","required":true,"visibility":"user-or-llm","description":"Asana project GID (numeric string) to retrieve"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_get_projects":{"id":"asana_get_projects","name":"Asana Get Projects","description":"Retrieve all projects from an Asana workspace","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"workspace":{"type":"string","required":true,"visibility":"user-or-llm","description":"Asana workspace GID (numeric string) to retrieve projects from"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_get_task":{"id":"asana_get_task","name":"Asana Get Task","description":"Retrieve a single task by GID or get multiple tasks with filters","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"taskGid":{"type":"string","required":false,"visibility":"user-or-llm","description":"The globally unique identifier (GID) of the task. If not provided, will get multiple tasks."},"workspace":{"type":"string","required":false,"visibility":"user-or-llm","description":"Asana workspace GID (numeric string) to filter tasks. Asana requires an assignee alongside a workspace filter; use project instead to list a project"},"assignee":{"type":"string","required":false,"visibility":"user-or-llm","description":"Assignee to filter tasks on (user GID, email, or \\"me\\"). Required by Asana when filtering by workspace; ignored when filtering by project"},"project":{"type":"string","required":false,"visibility":"user-or-llm","description":"Asana project GID (numeric string) to filter tasks"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of tasks to return, 1-100 (default: 50)"},"offset":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination offset token from a previous response next_page.offset"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_list_sections":{"id":"asana_list_sections","name":"Asana List Sections","description":"List all sections in an Asana project","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"projectGid":{"type":"string","required":true,"visibility":"user-or-llm","description":"GID of the Asana project (numeric string) to list sections from"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_list_workspaces":{"id":"asana_list_workspaces","name":"Asana List Workspaces","description":"List all Asana workspaces and organizations the authenticated user belongs to","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_search_tasks":{"id":"asana_search_tasks","name":"Asana Search Tasks","description":"Search for tasks in an Asana workspace","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"workspace":{"type":"string","required":true,"visibility":"user-or-llm","description":"Asana workspace GID (numeric string) to search tasks in"},"text":{"type":"string","required":false,"visibility":"user-or-llm","description":"Full-text search on task names and descriptions"},"assignee":{"type":"string","required":false,"visibility":"user-or-llm","description":"Filter tasks by assignee user GID"},"projects":{"type":"array","required":false,"visibility":"user-or-llm","description":"Array of Asana project GIDs (numeric strings) to filter tasks by"},"completed":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Filter by completion status"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of tasks to return, 1-100"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_update_task":{"id":"asana_update_task","name":"Asana Update Task","description":"Update an existing task in Asana","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"taskGid":{"type":"string","required":true,"visibility":"user-or-llm","description":"Asana task GID (numeric string) of the task to update"},"name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Updated name for the task"},"notes":{"type":"string","required":false,"visibility":"user-or-llm","description":"Updated notes or description for the task"},"assignee":{"type":"string","required":false,"visibility":"user-or-llm","description":"Updated assignee user GID"},"completed":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Mark task as completed or not completed"},"due_on":{"type":"string","required":false,"visibility":"user-or-llm","description":"Updated due date in YYYY-MM-DD format"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"ashby_add_candidate_tag":{"id":"ashby_add_candidate_tag","name":"Ashby Add Candidate Tag","description":"Adds a tag to a candidate in Ashby and returns the updated candidate.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ashby API Key"},"onBehalfOfUserId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Active Ashby user UUID to attribute this mutation to; the API key must permit on-behalf-of calls"},"candidateId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The UUID of the candidate to add the tag to"},"tagId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The UUID of the tag to add"}},"oauth":{"required":false,"provider":"ashby","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ashby_anonymize_candidate":{"id":"ashby_anonymize_candidate","name":"Ashby Anonymize Candidate","description":"Remove personally identifiable information from an Ashby candidate while retaining the candidate record and its applications. This operation does not delete the candidate. Requires the candidatesWrite permission.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ashby API Key"},"onBehalfOfUserId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Active Ashby user UUID to attribute this mutation to; the API key must permit on-behalf-of calls"},"candidateId":{"type":"string","required":true,"visibility":"user-or-llm","description":"UUID of the candidate to anonymize"}},"oauth":{"required":false,"provider":"ashby","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ashby_change_application_source":{"id":"ashby_change_application_source","name":"Ashby Change Application Source","description":"Changes the source attributed to an existing application, so programmatically created applications report correctly on the recruiting side. Requires the candidatesWrite permission.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ashby API Key"},"onBehalfOfUserId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Active Ashby user UUID to attribute this mutation to; the API key must permit on-behalf-of calls"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"UUID of the application whose source should change"},"sourceId":{"type":"string","required":false,"visibility":"user-or-llm","description":"UUID of the source to attribute the application to, as returned by List Sources. Omit only when unsetSource is true."},"unsetSource":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Set true to deliberately clear the application source. Required to unset, so that a missing or empty sourceId cannot wipe attribution by accident."}},"oauth":{"required":false,"provider":"ashby","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ashby_change_application_stage":{"id":"ashby_change_application_stage","name":"Ashby Change Application Stage","description":"Moves an application to a different interview stage. Requires an archive reason when moving to an Archived stage.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ashby API Key"},"onBehalfOfUserId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Active Ashby user UUID to attribute this mutation to; the API key must permit on-behalf-of calls"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The UUID of the application to update the stage of"},"interviewStageId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The UUID of the interview stage to move the application to"},"archiveReasonId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Archive reason UUID. Required when moving to an Archived stage, ignored otherwise"},"archiveEmail":{"type":"json","required":false,"visibility":"user-or-llm","description":"Archive email configuration with communicationTemplateId and optional sendAt ISO 8601 timestamp. Pass null or omit to send no archive email."}},"oauth":{"required":false,"provider":"ashby","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ashby_create_application":{"id":"ashby_create_application","name":"Ashby Create Application","description":"Creates a new application for a candidate on a job. Optionally specify interview plan, stage, source, and credited user.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ashby API Key"},"onBehalfOfUserId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Active Ashby user UUID to attribute this mutation to; the API key must permit on-behalf-of calls"},"candidateId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The UUID of the candidate to consider for the job"},"jobId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The UUID of the job to consider the candidate for"},"interviewPlanId":{"type":"string","required":false,"visibility":"user-or-llm","description":"UUID of the interview plan to use (defaults to the job default plan)"},"interviewStageId":{"type":"string","required":false,"visibility":"user-or-llm","description":"UUID of the interview stage to place the application in, or FirstPreInterviewScreen (defaults to the first Lead stage)"},"sourceId":{"type":"string","required":false,"visibility":"user-or-llm","description":"UUID of the source to set on the application"},"creditedToUserId":{"type":"string","required":false,"visibility":"user-or-llm","description":"UUID of the user the application is credited to"},"createdAt":{"type":"string","required":false,"visibility":"user-or-llm","description":"ISO 8601 timestamp to set as the application creation date (defaults to now)"},"applicationHistory":{"type":"json","required":false,"visibility":"user-or-llm","description":"Optional documented application history entries to create with the application"}},"oauth":{"required":false,"provider":"ashby","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ashby_create_candidate":{"id":"ashby_create_candidate","name":"Ashby Create Candidate","description":"Creates a new candidate record in Ashby.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ashby API Key"},"onBehalfOfUserId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Active Ashby user UUID to attribute this mutation to; the API key must permit on-behalf-of calls"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"The candidate full name"},"email":{"type":"string","required":false,"visibility":"user-or-llm","description":"Primary email address for the candidate"},"phoneNumber":{"type":"string","required":false,"visibility":"user-or-llm","description":"Primary phone number for the candidate"},"linkedInUrl":{"type":"string","required":false,"visibility":"user-or-llm","description":"LinkedIn profile URL"},"githubUrl":{"type":"string","required":false,"visibility":"user-or-llm","description":"GitHub profile URL"},"website":{"type":"string","required":false,"visibility":"user-or-llm","description":"Personal website URL"},"sourceId":{"type":"string","required":false,"visibility":"user-or-llm","description":"UUID of the source to attribute the candidate to"},"creditedToUserId":{"type":"string","required":false,"visibility":"user-or-llm","description":"UUID of the Ashby user to credit with sourcing this candidate"},"createdAt":{"type":"string","required":false,"visibility":"user-or-llm","description":"Backdated creation timestamp in ISO 8601 (e.g. 2024-01-01T00:00:00Z). Defaults to now."},"alternateEmailAddresses":{"type":"json","required":false,"visibility":"user-or-llm","description":"Array of additional email address strings to add to the candidate, e.g. [\\"a@x.com\\",\\"b@y.com\\"]"},"location":{"type":"json","required":false,"visibility":"user-or-llm","description":"Candidate location object with optional city, region, and country"}},"oauth":{"required":false,"provider":"ashby","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ashby_create_note":{"id":"ashby_create_note","name":"Ashby Create Note","description":"Creates a note on a candidate in Ashby. Supports plain text and HTML content (bold, italic, underline, links, lists, code).","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ashby API Key"},"onBehalfOfUserId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Active Ashby user UUID to attribute this mutation to; the API key must permit on-behalf-of calls"},"candidateId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The UUID of the candidate to add the note to"},"note":{"type":"string","required":true,"visibility":"user-or-llm","description":"The note content. If noteType is text/html, supports: , , , ,