diff --git a/.agents/skills/ship/SKILL.md b/.agents/skills/ship/SKILL.md index b866ee9a149..d23da4562bd 100644 --- a/.agents/skills/ship/SKILL.md +++ b/.agents/skills/ship/SKILL.md @@ -55,7 +55,7 @@ When the user runs `/ship`: **Do NOT blanket-run the domain generators here.** `mship:generate` (`generate-mship-contracts.ts`) is an **umbrella** that drives all nine mothership contract generators (`mship-contracts`, `billing-protocol-contract`, `mship-tools`, the four `trace-*`, `metrics-contract`, `vfs-snapshot-contract`) and biome-formats `apps/sim/lib/copilot/generated/` — never run it *and* its constituents (they write the same files and corrupt each other in parallel), and never run it on an ordinary ship: it reads an **external** copilot-contract source that isn't checked out in most worktrees, so it hard-fails with `ENOENT` and would abort ship for an unrelated reason. `generate:pi-model-catalog` (under `apps/sim`) likewise regenerates from the installed Pi package, not repo source. `scripts/generate-docs.ts` rewrites the integration docs and client-safe catalog; run it when this PR changes their block/icon/landing-content inputs or when `integration-catalog:check` reports drift, then review its broad generated diff. Only when **this PR's diff actually touches** a domain generator's input do you regenerate it deliberately and run its matching `:check` (`bun run mship:check` / the individual `*:check`) — with the external source present. - **Phase B — run lint + every audit CI enforces, in parallel, and abort ship if any fails.** Before running the commands, compare this list with `.github/workflows/test-build.yml`; when CI adds an audit, run it and update this skill instead of trusting a stale snapshot. The env-flag audit is currently an inline workflow block rather than a package script: when `apps/sim/lib/core/config/env-flags.ts` changed, run that current workflow block verbatim instead of copying a second version into this skill. Run `bun run lint` first (it autofixes formatting and mutates files, so don't parallelize it with the read-only audits), then run the base-sensitive block-registry check, then fan the independent audits out and collect exit codes: + **Phase B — run lint + every audit CI enforces, in parallel, and abort ship if any fails.** Before running the commands, compare this list with `.github/workflows/test-build.yml`; when CI adds an audit, run it and update this skill instead of trusting a stale snapshot. Run the inline "Check reviewed Next.js release exception" workflow block when `bunfig.toml` or the root `package.json` changes; it bounds the temporary dependency exception to its reviewed version. The env-flag audit is currently an inline workflow block rather than a package script: when `apps/sim/lib/core/config/env-flags.ts` changed, run that current workflow block verbatim instead of copying a second version into this skill. Run `bun run lint` first (it autofixes formatting and mutates files, so don't parallelize it with the read-only audits), then run the base-sensitive block-registry check, then fan the independent audits out and collect exit codes: ```bash # autofix formatting first (mutating; not parallel-safe with the audits). Gate its exit too — # a non-zero lint (unfixable errors) must abort before the audits run, not be ignored. diff --git a/.github/workflows/test-build.yml b/.github/workflows/test-build.yml index 7be5eb1002d..8a767c52f74 100644 --- a/.github/workflows/test-build.yml +++ b/.github/workflows/test-build.yml @@ -213,6 +213,16 @@ jobs: with: bun-version: 1.4.1 + - name: Check reviewed Next.js release exception + run: | + bun -e ' + const config = Bun.TOML.parse(await Bun.file("bunfig.toml").text()); + const { overrides } = await Bun.file("package.json").json(); + if (config.install?.minimumReleaseAgeExcludes?.includes("next") && overrides?.next !== "16.3.6") { + throw new Error("Remove the Next.js 16.3.6 release-age exception before changing its pin"); + } + ' + - name: Setup Node uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6 with: @@ -477,3 +487,15 @@ jobs: ENCRYPTION_KEY: '0000000000000000000000000000000000000000000000000000000000000000' # dummy key for CI only TURBO_CACHE_DIR: .turbo run: bunx turbo run build --filter=@sim/app + + - name: Upload conflicting build assets + if: failure() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: build-collision-diagnostics + path: | + apps/sim/.next/????????????????.js + apps/sim/.next/????????????????.map + include-hidden-files: true + if-no-files-found: ignore + retention-days: 7 diff --git a/apps/docs/components/footer/footer.tsx b/apps/docs/components/footer/footer.tsx index 8ed44b21d40..5b18512517b 100644 --- a/apps/docs/components/footer/footer.tsx +++ b/apps/docs/components/footer/footer.tsx @@ -26,7 +26,7 @@ const PRODUCT_LINKS: FooterItem[] = [ { label: 'Workflows', href: '/workflows' }, { label: 'Knowledge Base', href: '/knowledgebase' }, { label: 'Tables', href: '/tables' }, - { label: 'MCP', href: '/agents/mcp' }, + { label: 'MCP', href: '/mcp' }, { label: 'API', href: '/api-reference/getting-started' }, { label: 'Self Hosting', href: '/platform/self-hosting' }, { label: 'Status', href: 'https://status.sim.ai', external: true }, diff --git a/apps/docs/content/docs/agents/mcp.mdx b/apps/docs/content/docs/agents/mcp.mdx index b5f5adea4a4..d249d9408b4 100644 --- a/apps/docs/content/docs/agents/mcp.mdx +++ b/apps/docs/content/docs/agents/mcp.mdx @@ -7,7 +7,13 @@ import { Image } from '@/components/ui/image' import { Video } from '@/components/ui/video' import { Callout } from 'fumadocs-ui/components/callout' -The Model Context Protocol ([MCP](https://modelcontextprotocol.com/)) is an open standard for connecting AI to external tools and data. Add an MCP server to your workspace and its tools become available to your agents — a way to integrate services Sim doesn't have a built-in integration for. +The Model Context Protocol ([MCP](https://modelcontextprotocol.io/)) is an open standard for connecting AI to external tools and data. Add an MCP server to your workspace and its tools become available to your agents — a way to integrate services Sim doesn't have a built-in integration for. + + + This guide connects **external tools to Sim agents**. To connect Codex or another + assistant to Sim's workspace API, use [Sim MCP](/mcp). To expose only selected + workflows, use [MCP deployment](/workflows/deployment/mcp). + ## Adding an MCP Server as a Tool diff --git a/apps/docs/content/docs/api-reference/(generated)/workflow-runs/meta.json b/apps/docs/content/docs/api-reference/(generated)/workflow-runs/meta.json index 66d2d156e60..b77ba7cfe63 100644 --- a/apps/docs/content/docs/api-reference/(generated)/workflow-runs/meta.json +++ b/apps/docs/content/docs/api-reference/(generated)/workflow-runs/meta.json @@ -1,5 +1,6 @@ { "pages": [ + "previewWorkflowRunFromBlock", "listWorkflowRunsV2", "getWorkflowRunV2", "downloadWorkflowRunFileV2", diff --git a/apps/docs/content/docs/api-reference/(generated)/workflows/meta.json b/apps/docs/content/docs/api-reference/(generated)/workflows/meta.json index 28453d1b10f..c3846e65135 100644 --- a/apps/docs/content/docs/api-reference/(generated)/workflows/meta.json +++ b/apps/docs/content/docs/api-reference/(generated)/workflows/meta.json @@ -3,6 +3,7 @@ "listWorkflows", "createWorkflowV2", "getWorkflow", + "inspectWorkflow", "updateWorkflowV2", "deleteWorkflowV2", "restoreWorkflow", diff --git a/apps/docs/content/docs/cli/authentication.mdx b/apps/docs/content/docs/cli/authentication.mdx index e9c8afb91f1..111dce01a6d 100644 --- a/apps/docs/content/docs/cli/authentication.mdx +++ b/apps/docs/content/docs/cli/authentication.mdx @@ -166,6 +166,38 @@ when the check could not be made at all — no workspace to check against, or an endpoint that did not answer. The split matters in CI: only `1` is fixed by logging in again. +## Choosing an integration credential + +Your Sim login controls which workspaces and operations you can access. A tool's +selected provider credential controls its external identity and grants. A workflow +and a direct tool call can use different provider credentials under the same Sim login. + +Discover the exact tool ID and its parameter schema, then inspect the connection +you intend to use: + +```bash +sim tools list --search slack +sim tools get slack_message +sim credentials list --provider-id slack +sim --output json credentials get "$CREDENTIAL_ID" +``` + +Use the returned tool ID and argument names. For standalone OAuth execution, pass +`--credential-id "$CREDENTIAL_ID"` to `sim tools execute`. HTTP and MCP callers +supply the top-level `credentialId` field, outside `input`. + +`credentials get` reports the credential type/provider, stored identity metadata, +and recorded scopes with their source. `diagnostics.identity.verifiedLive: false` +means it has not contacted the provider or verified token validity or resource access. +Display names are labels. A scopes source of `unknown` with an empty `values` array +means the grants are unknown, not that no scopes were granted. Custom bots may have +no separately stored identity metadata; inspection leaves it unknown without +reading secret payloads. + +See [Slack credentials](/integrations/slack#standalone-tool-credentials) for +OAuth versus bot-token selection and conversation-access limits. The +[credentials command reference](/cli/credentials) lists connection-management commands. + ## Signing out ```bash diff --git a/apps/docs/content/docs/cli/credentials.mdx b/apps/docs/content/docs/cli/credentials.mdx index 16763637d19..4efa674994b 100644 --- a/apps/docs/content/docs/cli/credentials.mdx +++ b/apps/docs/content/docs/cli/credentials.mdx @@ -37,6 +37,24 @@ Disconnect Credential (OAuth login or personal API key required) +## Inspect credential + +```bash +sim credentials get +``` + +Inspect Credential (OAuth login or personal API key required) + +**Arguments** + + + +| Argument | Required | Description | +| --- | --- | --- | +| `credentialId` | Yes | Selected credential to inspect. | + + + ## List credential providers ```bash diff --git a/apps/docs/content/docs/cli/index.mdx b/apps/docs/content/docs/cli/index.mdx index cf2b958cdef..afdbcb73d96 100644 --- a/apps/docs/content/docs/cli/index.mdx +++ b/apps/docs/content/docs/cli/index.mdx @@ -12,6 +12,8 @@ move files, search knowledge bases, and read run logs from the terminal. Use pipelines. See [Output formats](/cli/output) for commands that emit raw content or local configuration. +For workflow editing and retry recipes, see [Scripting](/cli/scripting). + ## Install diff --git a/apps/docs/content/docs/cli/logs.mdx b/apps/docs/content/docs/cli/logs.mdx index 4b35e0db28b..d755dd0c80c 100644 --- a/apps/docs/content/docs/cli/logs.mdx +++ b/apps/docs/content/docs/cli/logs.mdx @@ -31,7 +31,10 @@ sim logs get [options] | Option | Required | Description | | --- | --- | --- | +| `--include-workflow-state` | No | Include the saved workflow snapshot. Set false to avoid loading and returning block configuration when inspecting a run. Other run fields are unchanged. | +| `--no-include-workflow-state` | No | Send --include-workflow-state as false. | | `--trace` | No | Show expanded trace spans with inputs, outputs, errors, timing, and cost. | +| `--summary` | No | Show bounded run diagnostics and final output; omit binary content and the workflow snapshot. | diff --git a/apps/docs/content/docs/cli/output.mdx b/apps/docs/content/docs/cli/output.mdx index 234149a1a5d..d1b4bf78573 100644 --- a/apps/docs/content/docs/cli/output.mdx +++ b/apps/docs/content/docs/cli/output.mdx @@ -59,13 +59,66 @@ with span inputs, outputs, errors, timing, and cost: sim logs get 9c4f0b7e-2d81-4a35-b6e9-70f1c8a2d543 --trace ``` -`json` and `yaml` always carry the complete response, so `--trace` is a no-op -there: +By default, `json` and `yaml` carry the complete response, so `--trace` does not +change their output: ```bash sim logs get 9c4f0b7e-2d81-4a35-b6e9-70f1c8a2d543 --output json | jq '.traceSpans' ``` +### Compact run summaries + +Use `--summary` to inspect a run without printing its full trace and workflow +snapshot: + +```bash +sim --output json logs get "$RUN_ID" --summary +``` + +The summary includes execution status, the workflow's existing `finalOutput`, +recorded failures (including handled errors), compact failing inputs and outputs, +observed block statuses, and file metadata. It bounds trace traversal and field +sizes, reports `truncated` when detail is omitted, and omits recognized binary +fields and base64 data URLs. Use `--trace` or +[output selectors](/cli/scripting#selecting-workflow-output) when you need more detail. + +By default, `--summary` asks the server to omit the saved workflow snapshot, then +formats the remaining authorized log response locally; it still loads the trace. +To omit only the snapshot, use `--no-include-workflow-state`. HTTP and hosted MCP +callers can set `includeWorkflowState=false` on the log read. + +Execution status describes the run, not the quality of its output or whether an +external delivery succeeded. Inspect `finalOutput` and recorded tool failures +before treating a completed run as a successful result. Expired trace data can +leave no block-level evidence. Find failures that a workflow recovered from with +`sim logs list --level error --include-handled-errors`. + +The log's `cost` includes a reconciled total and itemized `fixed`, `model`, and +`tool` charges when a ledger is available. + +## Downloading output files + +Tools that store files return descriptors containing file IDs and metadata, +rather than inline base64. Download a personal output from a direct tool call +(`context: copilot`) with: + +```bash +sim tools files download "$FILE_ID" -o ./attachment.pdf +``` + +For a workflow output, use the workflow and run that produced it: + +```bash +sim workflows runs files download "$WORKFLOW_ID" "$RUN_ID" "$FILE_ID" -o ./attachment.pdf +``` + +These commands authenticate with the configured Sim credential and stream to +disk. Direct personal outputs require their original human owner and current +workspace access; workflow outputs use the run's access checks. A descriptor's +URL or storage key alone grants no access. Output files can expire; copy durable +artifacts into workspace files. See the [tool file](/cli/tools#download-a-direct-tool-output-owned-by-the-current-user) +and [run file](/cli/workflows#download-a-workflow-run-output-file) command references. + ## Exceptions `sim configure` prints local configuration for humans. `sim profiles` honors `--output`. diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 459a37af741..e37eb5e1f67 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -446,6 +446,24 @@ sim credentials delete [options] +### sim credentials get + +Inspect Credential (OAuth login or personal API key required) + +```bash +sim credentials get +``` + +**Arguments** + + + +| Argument | Required | Description | +| --- | --- | --- | +| `credentialId` | Yes | Selected credential to inspect. | + + + ### sim credentials providers list List Credential Providers @@ -2731,7 +2749,10 @@ sim logs get [options] | Option | Required | Description | | --- | --- | --- | +| `--include-workflow-state` | No | Include the saved workflow snapshot. Set false to avoid loading and returning block configuration when inspecting a run. Other run fields are unchanged. | +| `--no-include-workflow-state` | No | Send --include-workflow-state as false. | | `--trace` | No | Show expanded trace spans with inputs, outputs, errors, timing, and cost. | +| `--summary` | No | Show bounded run diagnostics and final output; omit binary content and the workflow snapshot. | @@ -5814,6 +5835,35 @@ sim tools list [options] +### sim tools files download + +Download a direct tool output owned by the current user (OAuth login or personal API key required) + +```bash +sim tools files download [options] +``` + +**Arguments** + + + +| Argument | Required | Description | +| --- | --- | --- | +| `fileId` | Yes | The returned file.id whose file.context is "copilot", passed unchanged | + + + +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `-o, --output-file ` | No | Write content to a file instead of stdout. | +| `--force` | No | Overwrite --output-file if it already exists. | + + + ## sim workflow-mcp-servers ### sim workflow-mcp-servers create @@ -6072,7 +6122,7 @@ sim workflows operations apply [options] | --- | --- | --- | | `--dry-run` | No | Validate and lint without writing, auditing, or notifying collaborators. Returns the same validation, preparation warnings, lint findings, and ID-ownership conflicts (`409`) as a committed write. `needsRedeployment` describes the pre-write state. For semantic operations, `mintedBlockIds` is empty; `previewBlockIds` contains provisional IDs with a warning, since committing mints new IDs. | | `--no-dry-run` | No | Send --dry-run as false. | -| `--operations ` | Yes | Edits to apply, in a single batch, keyed by operation_type: [{"operation_type":"add","block_id":"my-fn","params":{"type":"function","name":"My Fn","inputs":{"code":"return {ok:true}"}}},{"operation_type":"edit","block_id":"<uuid>","params":{"name":"Renamed","connections":{"success":"my-fn"}}},{"operation_type":"delete","block_id":"<uuid>"}]. Also extract_from_subflow, whose params carry {"subflowId":"<loop-id>"}, and insert_into_subflow, which creates a block and so takes an add’s params plus that subflowId (JSON, or @path / @- to read a file or stdin). | +| `--operations ` | No | Edits to apply, in a single batch, keyed by operation_type: [{"operation_type":"add","block_id":"my-fn","params":{"type":"function","name":"My Fn","inputs":{"code":"return {ok:true}"}}},{"operation_type":"edit","block_id":"<uuid>","params":{"name":"Renamed","connections":{"success":"my-fn"}}},{"operation_type":"delete","block_id":"<uuid>"}]. Also extract_from_subflow, whose params carry {"subflowId":"<loop-id>"}, and insert_into_subflow, which creates a block and so takes an add’s params plus that subflowId (JSON, or @path / @- to read a file or stdin). | | `--atomic` | No | Fail the whole batch when any operation is declined or any block input would be dropped. The default applies what it can and reports the rest in `skipped` and `inputValidationErrors`; `true` writes nothing and answers `409` instead. | | `--no-atomic` | No | Send --atomic as false. | | `--layout ` | No | Whether to reposition blocks the batch touched. `targeted` (default) nudges only the affected subgraph; `none` leaves every position exactly as supplied. Accepted values: `targeted`, `none`. | @@ -6196,6 +6246,35 @@ sim workflows runs list [options] +### sim workflows runs preview + +Preview candidate rerun blocks and cached upstream outputs without executing (OAuth login or personal API key required) + +```bash +sim workflows runs preview [options] +``` + +**Arguments** + + + +| Argument | Required | Description | +| --- | --- | --- | +| `workflowId` | Yes | Unique workflow identifier. | + + + +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `--from-block ` | Yes | Saved draft block at which a later manual run would start. | +| `--source-run ` | Yes | Existing run in this workflow whose persisted state would supply cached upstream outputs. | + + + ### sim workflows runs resume Resume a paused run (output is included in JSON or YAML output) @@ -6255,6 +6334,37 @@ sim workflows runs wait [options] +### sim workflows runs files download + +Download a workflow run output file + +```bash +sim workflows runs files download [options] +``` + +**Arguments** + + + +| Argument | Required | Description | +| --- | --- | --- | +| `workflowId` | Yes | Workflow identifier | +| `runId` | Yes | Run identifier | +| `fileId` | Yes | File identifier returned by the workflow run | + + + +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `-o, --output-file ` | No | Write content to a file instead of stdout. | +| `--force` | No | Overwrite --output-file if it already exists. | + + + ### sim workflows create Create Workflow @@ -6563,6 +6673,7 @@ sim workflows run [options] | Option | Required | Description | | --- | --- | --- | | `--input ` | No | Trigger input as JSON (JSON, or @path / @- to read a file or stdin). | +| `--stop-after ` | No | Stop scheduling after this block finishes. Runs real actions; already-running branches can finish. Not available with --async. | | `--async` | No | Queue the run and return immediately. | | `--execution-timeout-seconds ` | No | Maximum duration of an asynchronous run, in seconds, capped by the plan's execution timeout. Requires `async: true`; otherwise returns `400`. | | `--select-output ` | No | Return blockName.path values (e.g. agent_1.content), or childWorkflowId.blockName.path for a child workflow (applies to every invocation) — in blockOutputs on a sync run, or from the streamed result with --follow; missing paths are omitted. Not available with --async (space-separated, or @path / @- with one value per line; @@value for a literal leading @). | @@ -6834,6 +6945,36 @@ sim workflows import [options] +### sim workflows inspect + +Inspect Workflow + +```bash +sim workflows inspect [options] +``` + +**Arguments** + + + +| Argument | Required | Description | +| --- | --- | --- | +| `workflowId` | Yes | Unique workflow identifier. | + + + +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `--block-id ` | No | Inspect one block and its incident connections. Omit to inspect the draft graph. | +| `--include-code` | No | Include bounded code inputs. Code and free text can contain hardcoded secrets that automatic redaction cannot recognize. | +| `--no-include-code` | No | Send --include-code as false. | + + + ### sim workflows list List Workflows diff --git a/apps/docs/content/docs/cli/scripting.mdx b/apps/docs/content/docs/cli/scripting.mdx index 7c494033d0f..cbba7be78b8 100644 --- a/apps/docs/content/docs/cli/scripting.mdx +++ b/apps/docs/content/docs/cli/scripting.mdx @@ -222,6 +222,64 @@ case $? in esac ``` +## Inspecting and editing workflows + +Find the workflow in its workspace before reading its draft: + +```bash +sim workspaces list --output json +sim workflows list --workspace "$workspace_id" --search "Daily report" \ + --folder Reports --deployed-only --output json +``` + +`--search` matches names; `--folder` and `--deployed-only` narrow the results. +These lists [follow pages automatically](#pagination). There is no account-wide +workflow-content search: use metadata to narrow candidates, then inspect them. + +Start with a compact diagnostic view, then fetch editable state when you need to +change the saved workflow: + +```bash +sim workflows inspect "$workflow_id" --output json +sim workflows inspect "$workflow_id" --block-id "$block_id" --include-code --output json +sim workflows state get "$workflow_id" --output json > state.json +``` + +Inspection includes block IDs, names, enabled states, parents, connections, and +bounded inputs. It omits code by default and withholds credential fields and +opaque credential values; check `omittedInputs` and `truncated` for missing detail. +Redaction cannot recognize every secret embedded in arbitrary text or code. +The diagnostic view is not a format to save back. + +A tool ID from `tools get` selects a standalone operation. A block type and its +operation from `blocks get` define workflow behavior; a block ID identifies one +instance in the saved workflow. These IDs are not interchangeable. Preserve the +saved block type/version when editing; an unversioned catalog name can resolve +to a newer definition with different fields. + +For in-place edits, preserve the IDs and credential/table references from +`state get`, then validate with `state replace --dry-run` before saving. +`workflows export` is a sanitized portable format with credential bindings cleared; +use it for [import and sync](/cli/workflow-sync), not to replace editable state. +Review validation coverage, skipped checks, warnings, and `removedBindings`. +Static validation cannot prove provider access, model behavior, or runtime success. + +For a small change, use the existing operations command. An enablement-only batch +needs no graph edit: + +```bash +sim workflows operations apply "$workflow_id" --dry-run --atomic \ + --set-block-enabled "[{\"block_id\":\"$block_id\",\"enabled\":false}]" +``` + +Inspect `applied`, `skipped`, and `inputValidationErrors` before committing with +`--yes` in place of `--dry-run`. `--atomic` prevents the batch from saving if an +edit is declined or an input would be dropped. When adding blocks, dry-run +`previewBlockIds` are provisional and `mintedBlockIds` is empty; use the IDs from +the committed response. Read the saved state before deploying. Validation executes +no blocks; it is not a mode that suppresses external writes during a later run. +See the [workflow command reference](/cli/workflows) for full edit and validation flags. + ## Selecting workflow output `--select-output` returns the named values in `blockOutputs` on a sync run, or @@ -242,9 +300,22 @@ sim workflows runs get "$run_id" --workflow 3a9e21d8-5f47-4c0b-b2ea-91d7c6034ef8 --select-output 1d4c8f02-7b63-4a19-8e52-63f0a7c5d9b1.content --output json ``` +To inspect an intermediate result, combine a selector with `--stop-after`: + +```bash +sim workflows run "$workflow_id" --stop-after "$block_id" \ + --select-output "$block_id.result" --output json +``` + +This executes real actions and stops scheduling after the target finishes. +Already-running parallel branches can still act; a condition that skips the +target can let the remaining path complete. It does not edit the saved graph or +suppress external writes. It cannot be used with `--async`, and a later explicit +resume of a paused run does not inherit the limit. + ## Polling a long run -Start the run asynchronously, then use the CLI’s wait command: +Start a deployed run asynchronously, then use the CLI’s wait command: ```bash run_id=$(sim workflows run 3a9e21d8-5f47-4c0b-b2ea-91d7c6034ef8 --async --output json | jq -r '.runId') @@ -258,6 +329,55 @@ outcome; `--wait-timeout 0` waits indefinitely. Use `sim logs get "$run_id" --trace` for full diagnostics. A run paused for human input includes the context ID needed by `sim workflows runs resume`. +Ordinary runs use the active deployment; `--manual`, `--trigger`, and `--from-block` +use the current saved draft. Deployed runs support synchronous execution, +`--follow`, or `--async`. Manual runs support synchronous execution or `--follow`; +`--async` cannot be combined with manual execution or `--follow`. + +The CLI prints a run ID to stderr before sending a manual request. Use it with +`workflows runs get` or `workflows runs wait` in another terminal. A status record +appears only after server admission, so a rejected request may never have one. +The ID is a one-shot identifier, not a replayable idempotency key. After an +uncertain network failure, inspect that ID before starting another execution; +a fresh ID can repeat external actions. + +Deployed runs retain the default API-compatible trigger priority. A deployment +with one other runnable trigger can also run directly. If no API-compatible +entry exists and multiple triggers remain, select the deployed entry through the +API's `run.entry`; the CLI's `--trigger` instead selects an entry in the draft. +See the [run command reference](/cli/workflows#run-a-deployed-workflow-or-execute-saved-state-manually) +for all execution flags. + +## Previewing a partial retry + +Preview a retry using the source run's persisted upstream outputs before repeating +external actions: + +```bash +sim workflows runs preview "$workflow_id" \ + --from-block "$block_id" --source-run "$source_run_id" --output json +``` + +Review `validation`, `rerunBlocks`, and `upstreamBlocks`. Preview reports cached-output +availability without returning values, executing blocks, or reserving a run ID. +Its rerun blocks are candidates, not an execution order: conditions, disabled +blocks, loops, and failures still affect the path. Preview does not lock the draft; +the subsequent manual run uses the draft saved at that time. + +After reviewing the preview, start the retry and use its printed run ID to +[track it](#polling-a-long-run): + +```bash +sim workflows run "$workflow_id" \ + --from-block "$block_id" --source-run "$source_run_id" --follow +``` + +An error connection is an alternative path: a consumer reached through an error +bypass may lack the successful path's parser output. Keep required data on the +path that produces it or handle its absence. A disabled block stops its branch; +it is not a pass-through mock. Replay can reuse recorded ancestor outputs from +the selected source run, but cannot supply outputs that run never produced. + ## Working with folders Every folder-backed resource — `workflows`, `tables`, `files`, `knowledge` — diff --git a/apps/docs/content/docs/cli/tools.mdx b/apps/docs/content/docs/cli/tools.mdx index 93f264a8186..1c43f58ffe4 100644 --- a/apps/docs/content/docs/cli/tools.mdx +++ b/apps/docs/content/docs/cli/tools.mdx @@ -73,3 +73,32 @@ sim tools list [options] | `--limit ` | No | Maximum items to return (0 for everything). Defaults to `0`. | + +## Download a direct tool output owned by the current user + +```bash +sim tools files download [options] +``` + +Download a direct tool output owned by the current user (OAuth login or personal API key required) + +**Arguments** + + + +| Argument | Required | Description | +| --- | --- | --- | +| `fileId` | Yes | The returned file.id whose file.context is "copilot", passed unchanged | + + + +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `-o, --output-file ` | No | Write content to a file instead of stdout. | +| `--force` | No | Overwrite --output-file if it already exists. | + + diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index f2c37240f5e..e0df4e31358 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -64,7 +64,7 @@ Apply Workflow Operations (OAuth login or personal API key required) | --- | --- | --- | | `--dry-run` | No | Validate and lint without writing, auditing, or notifying collaborators. Returns the same validation, preparation warnings, lint findings, and ID-ownership conflicts (`409`) as a committed write. `needsRedeployment` describes the pre-write state. For semantic operations, `mintedBlockIds` is empty; `previewBlockIds` contains provisional IDs with a warning, since committing mints new IDs. | | `--no-dry-run` | No | Send --dry-run as false. | -| `--operations ` | Yes | Edits to apply, in a single batch, keyed by operation_type: [{"operation_type":"add","block_id":"my-fn","params":{"type":"function","name":"My Fn","inputs":{"code":"return {ok:true}"}}},{"operation_type":"edit","block_id":"<uuid>","params":{"name":"Renamed","connections":{"success":"my-fn"}}},{"operation_type":"delete","block_id":"<uuid>"}]. Also extract_from_subflow, whose params carry {"subflowId":"<loop-id>"}, and insert_into_subflow, which creates a block and so takes an add’s params plus that subflowId (JSON, or @path / @- to read a file or stdin). | +| `--operations ` | No | Edits to apply, in a single batch, keyed by operation_type: [{"operation_type":"add","block_id":"my-fn","params":{"type":"function","name":"My Fn","inputs":{"code":"return {ok:true}"}}},{"operation_type":"edit","block_id":"<uuid>","params":{"name":"Renamed","connections":{"success":"my-fn"}}},{"operation_type":"delete","block_id":"<uuid>"}]. Also extract_from_subflow, whose params carry {"subflowId":"<loop-id>"}, and insert_into_subflow, which creates a block and so takes an add’s params plus that subflowId (JSON, or @path / @- to read a file or stdin). | | `--atomic` | No | Fail the whole batch when any operation is declined or any block input would be dropped. The default applies what it can and reports the rest in `skipped` and `inputValidationErrors`; `true` writes nothing and answers `409` instead. | | `--no-atomic` | No | Send --atomic as false. | | `--layout ` | No | Whether to reposition blocks the batch touched. `targeted` (default) nudges only the affected subgraph; `none` leaves every position exactly as supplied. Accepted values: `targeted`, `none`. | @@ -182,6 +182,35 @@ sim workflows runs list [options] +## Preview candidate rerun blocks and cached upstream outputs without executing + +```bash +sim workflows runs preview [options] +``` + +Preview candidate rerun blocks and cached upstream outputs without executing (OAuth login or personal API key required) + +**Arguments** + + + +| Argument | Required | Description | +| --- | --- | --- | +| `workflowId` | Yes | Unique workflow identifier. | + + + +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `--from-block ` | Yes | Saved draft block at which a later manual run would start. | +| `--source-run ` | Yes | Existing run in this workflow whose persisted state would supply cached upstream outputs. | + + + ## Resume a paused run ```bash @@ -239,6 +268,35 @@ sim workflows runs wait [options] +## Download a workflow run output file + +```bash +sim workflows runs files download [options] +``` + +**Arguments** + + + +| Argument | Required | Description | +| --- | --- | --- | +| `workflowId` | Yes | Workflow identifier | +| `runId` | Yes | Run identifier | +| `fileId` | Yes | File identifier returned by the workflow run | + + + +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `-o, --output-file ` | No | Write content to a file instead of stdout. | +| `--force` | No | Overwrite --output-file if it already exists. | + + + ## Create workflow ```bash @@ -531,6 +589,7 @@ sim workflows run [options] | Option | Required | Description | | --- | --- | --- | | `--input ` | No | Trigger input as JSON (JSON, or @path / @- to read a file or stdin). | +| `--stop-after ` | No | Stop scheduling after this block finishes. Runs real actions; already-running branches can finish. Not available with --async. | | `--async` | No | Queue the run and return immediately. | | `--execution-timeout-seconds ` | No | Maximum duration of an asynchronous run, in seconds, capped by the plan's execution timeout. Requires `async: true`; otherwise returns `400`. | | `--select-output ` | No | Return blockName.path values (e.g. agent_1.content), or childWorkflowId.blockName.path for a child workflow (applies to every invocation) — in blockOutputs on a sync run, or from the streamed result with --follow; missing paths are omitted. Not available with --async (space-separated, or @path / @- with one value per line; @@value for a literal leading @). | @@ -786,6 +845,34 @@ sim workflows import [options] +## Inspect workflow + +```bash +sim workflows inspect [options] +``` + +**Arguments** + + + +| Argument | Required | Description | +| --- | --- | --- | +| `workflowId` | Yes | Unique workflow identifier. | + + + +**Options** + + + +| Option | Required | Description | +| --- | --- | --- | +| `--block-id ` | No | Inspect one block and its incident connections. Omit to inspect the draft graph. | +| `--include-code` | No | Include bounded code inputs. Code and free text can contain hardcoded secrets that automatic redaction cannot recognize. | +| `--no-include-code` | No | Send --include-code as false. | + + + ## List workflows ```bash diff --git a/apps/docs/content/docs/integrations/file.mdx b/apps/docs/content/docs/integrations/file.mdx index 0fc151aad4e..c86edcb392a 100644 --- a/apps/docs/content/docs/integrations/file.mdx +++ b/apps/docs/content/docs/integrations/file.mdx @@ -225,6 +225,8 @@ Compress one or more workspace files into a single .zip archive stored in the wo | `folderPaths` | array | No | Folders whose files are included, as canonical percent-encoded paths, e.g. \["/Reports/Q3%20Results"\]. Nested folders are included by default, and the folders are read at run time, so a file added later is picked up. | | `includeSubfolders` | boolean | No | Whether nested folders are read too. Defaults to true; set false to take only the folders’ direct files. | | `archiveName` | string | No | Name for the .zip archive \(e.g., "documents.zip"\). Defaults to the source file name when compressing a single file, otherwise "archive.zip". | +| `folderPath` | string | No | Existing destination folder as a canonical percent-encoded path, e.g. "/Generated/Archives". Defaults to the workspace root. Create the folder first with file_create_folder. | +| `onConflict` | string | No | Name collision behavior: "rename" \(default\) chooses an available name; "error" refuses an existing name. Existing files are never overwritten. | #### Output @@ -234,6 +236,7 @@ Compress one or more workspace files into a single .zip archive stored in the wo | `name` | string | Compressed archive file name | | `size` | number | Compressed archive size in bytes | | `url` | string | URL to access the compressed archive | +| `path` | string | Final workspace filesystem path, including the stored name | | `files` | file[] | Compressed archive file object, as a single-item array | ### File Decompress diff --git a/apps/docs/content/docs/integrations/slack.mdx b/apps/docs/content/docs/integrations/slack.mdx index 91179917dd9..cad9f9a8b88 100644 --- a/apps/docs/content/docs/integrations/slack.mdx +++ b/apps/docs/content/docs/integrations/slack.mdx @@ -23,6 +23,16 @@ List actions return one page. Use the returned cursor or page information to con User-token-only search, profile updates, and notification controls, Slack’s retired reminders APIs, and Enterprise administration APIs are not included. Use scheduled messages or a scheduled Sim workflow for reminders. +## Standalone tool credentials + +For direct CLI, API, or MCP calls, inspect the operation first, for example with `sim tools get slack_message`. OAuth is the default: supply the intended top-level `credentialId`. Tools that expose `authMethod` and `botToken` also accept `input.authMethod: "bot_token"` with `input.botToken`, including an authorized `{{SECRET_NAME}}` reference. Bot-token mode ignores `credentialId`; OAuth mode ignores an unused `botToken`. OAuth-only tools still require their connected credential. See [CLI authentication](/cli/authentication) for credential discovery. + +A direct call can use a different credential from a workflow started by the same Sim user. The selected Slack identity determines its scopes, channel membership, file access, and which messages it can update. Listing some channels does not establish access to a particular private channel or its files. + +## Preview a message + +Paste the message payload into Slack’s [Block Kit Builder](https://app.slack.com/block-kit-builder) to inspect the rendered layout. Review the top-level fallback text separately from the blocks. Previewing does not post the message; the builder’s **Send to Slack** action does. See [Slack Message](#slack-message) for fallback text and the different block/text behavior when attaching files. + ## Stream Trigger Responses Custom-bot Slack triggers can stream workflow outputs directly back into the conversation that started a run. Turn on **Enable agent session** (`streamResponse`) on a Message, App Mention, or Assistant Thread Started trigger, then select the outputs to deliver in **Outputs to stream** (`streamOutputs`). @@ -69,9 +79,9 @@ Send messages to Slack channels or direct messages. Supports Slack mrkdwn format | `botToken` | string | No | Bot token for Custom Bot | | `channel` | string | No | Slack channel ID \(e.g., C1234567890\) | | `dmUserId` | string | No | Slack user ID for direct messages \(e.g., U1234567890\) | -| `text` | string | Yes | Message text to send \(supports Slack mrkdwn formatting\) | +| `text` | string | No | Message text, required unless blocks are provided. With blocks, used for notifications and screen readers. | | `threadTs` | string | No | Thread timestamp to reply to \(creates thread reply\) | -| `blocks` | json | No | Block Kit layout blocks as a JSON array. When provided, text becomes the fallback notification text. | +| `blocks` | json | No | Block Kit layout blocks as a JSON array. For messages without files, text is the notification fallback. With file attachments, Slack accepts blocks or initial text, so blocks take precedence. | | `files` | file[] | No | Files to attach to the message | #### Output @@ -150,7 +160,7 @@ Send an ephemeral message visible only to a specific user in a channel. Optional | `botToken` | string | No | Bot token for Custom Bot | | `channel` | string | Yes | Slack channel ID \(e.g., C1234567890\) | | `user` | string | Yes | User ID who will see the ephemeral message \(e.g., U1234567890\). Must be a member of the channel. | -| `text` | string | Yes | Message text to send \(supports Slack mrkdwn formatting\) | +| `text` | string | No | Message text, required unless blocks are provided. With blocks, used for notifications and screen readers. | | `threadTs` | string | No | Thread timestamp to reply in. When provided, the ephemeral message appears as a thread reply. | | `blocks` | json | No | Block Kit layout blocks as a JSON array. When provided, text becomes the fallback notification text. | @@ -333,7 +343,7 @@ Retrieve a specific message by its timestamp. Useful for getting a thread parent ### Slack Get Thread -Retrieve an entire thread including the parent message and all replies. Useful for getting full conversation context. +Retrieve the first page of a thread, including the parent message and replies. Check hasMore for additional replies; use Get Thread Replies for cursor-based pagination. #### Input @@ -459,7 +469,7 @@ Retrieve an entire thread including the parent message and all replies. Useful f | ↳ `edited` | object | Edit information if message was edited | | ↳ `user` | string | User ID who edited the message | | ↳ `ts` | string | Timestamp of the edit | -| `messages` | array | All messages in the thread \(parent + replies\) in chronological order | +| `messages` | array | Messages in this page \(parent + replies\) in chronological order | | ↳ `type` | string | Message type \(usually "message"\) | | ↳ `ts` | string | Message timestamp \(unique identifier\) | | ↳ `text` | string | Message text content | @@ -1128,7 +1138,7 @@ Download a file from Slack | Parameter | Type | Description | | --------- | ---- | ----------- | -| `file` | file | Downloaded file stored in execution files | +| `file` | file | Stored file descriptor. Download bytes using tools files download for direct calls, or workflows runs files download for workflow outputs. | ### Slack Update Message @@ -1142,7 +1152,7 @@ Update a message previously sent by the bot in Slack | `botToken` | string | No | Bot token for Custom Bot | | `channel` | string | Yes | Channel ID where the message was posted \(e.g., C1234567890\) | | `timestamp` | string | Yes | Timestamp of the message to update \(e.g., 1405894322.002768\) | -| `text` | string | Yes | New message text \(supports Slack mrkdwn formatting\) | +| `text` | string | No | New message text, required unless blocks are provided. With blocks, used for notifications and screen readers. | | `blocks` | json | No | Block Kit layout blocks as a JSON array. When provided, text becomes the fallback notification text. | #### Output @@ -2042,7 +2052,7 @@ Schedule a message to be sent to a Slack channel or DM at a future time. | `botToken` | string | No | Bot token for Custom Bot | | `channel` | string | Yes | Channel, private group, or DM to receive the message \(e.g., C1234567890\) | | `postAt` | number | Yes | Unix timestamp \(seconds\) representing the future time the message should post | -| `text` | string | No | Message text to send \(supports Slack mrkdwn formatting\) | +| `text` | string | No | Message text, required unless blocks are provided. With blocks, used for notifications and screen readers. | | `blocks` | json | No | Block Kit layout blocks as a JSON array. When provided, text becomes the fallback notification text. | | `threadTs` | string | No | Thread timestamp to reply to \(creates a scheduled thread reply\) | diff --git a/apps/docs/content/docs/integrations/stripe.mdx b/apps/docs/content/docs/integrations/stripe.mdx index fc442753326..9131057a7ad 100644 --- a/apps/docs/content/docs/integrations/stripe.mdx +++ b/apps/docs/content/docs/integrations/stripe.mdx @@ -1071,7 +1071,7 @@ Update an existing subscription | --------- | ---- | -------- | ----------- | | `apiKey` | string | Yes | Stripe API key \(secret key\) | | `id` | string | Yes | Subscription ID \(e.g., sub_1234567890\) | -| `items` | json | No | Updated array of items with price IDs | +| `items` | json | No | Items with price IDs and optional quantities. Include the existing subscription item id to replace its price; omit id to add an item. | | `cancel_at_period_end` | boolean | No | Cancel subscription at period end | | `metadata` | json | No | Updated metadata | @@ -1222,7 +1222,7 @@ Cancel a subscription ### Stripe Resume Subscription -Resume a subscription that was scheduled for cancellation +Resume a paused subscription. To undo a scheduled cancellation, use Update Subscription with cancel_at_period_end=false before it ends. #### Input @@ -1299,7 +1299,7 @@ Resume a subscription that was scheduled for cancellation ### Stripe List Subscriptions -List all subscriptions +List one page of subscriptions. Follow starting_after while metadata.has_more is true. #### Input @@ -1309,6 +1309,8 @@ List all subscriptions | `limit` | number | No | Number of results to return \(default 10, max 100\) | | `customer` | string | No | Filter by customer ID | | `status` | string | No | Filter by status \(active, past_due, unpaid, canceled, incomplete, incomplete_expired, trialing, all\) | +| `starting_after` | string | No | Next-page cursor: last subscription ID from the previous page. Do not combine with ending_before. | +| `ending_before` | string | No | Previous-page cursor: first subscription ID from the current page. Do not combine with starting_after. | | `price` | string | No | Filter by price ID | #### Output @@ -1378,7 +1380,7 @@ List all subscriptions ### Stripe Search Subscriptions -Search for subscriptions using query syntax +Search one page of subscriptions using query syntax. Pass metadata.next_page as page to continue. #### Input @@ -1386,6 +1388,7 @@ Search for subscriptions using query syntax | --------- | ---- | -------- | ----------- | | `apiKey` | string | Yes | Stripe API key \(secret key\) | | `query` | string | Yes | Search query \(e.g., "status:'active' AND customer:'cus_xxx'"\) | +| `page` | string | No | Pagination token from metadata.next_page. Omit for the first page and keep the same query. | | `limit` | number | No | Number of results to return \(default 10, max 100\) | #### Output @@ -1452,6 +1455,7 @@ Search for subscriptions using query syntax | `metadata` | json | Search metadata | | ↳ `count` | number | Number of items returned | | ↳ `has_more` | boolean | Whether more items exist beyond this page | +| ↳ `next_page` | string | Token for the next page of search results, or null when there are no more results | ### Stripe Create Invoice diff --git a/apps/docs/content/docs/introduction/index.mdx b/apps/docs/content/docs/introduction/index.mdx index 63f54b5ba6d..5f65fcedb2c 100644 --- a/apps/docs/content/docs/introduction/index.mdx +++ b/apps/docs/content/docs/introduction/index.mdx @@ -72,7 +72,15 @@ Sim provides native integrations with supported services: - **Search and data.** Google Search, Perplexity, Firecrawl, Exa AI. - **Databases.** PostgreSQL, MySQL, Supabase, Pinecone, Qdrant. -For anything not built in, [MCP support](/agents/mcp) connects any external service or tool. +## Connect through MCP + +[MCP](/mcp) connects Sim and external assistants in three directions: + +- **[Connect an assistant to Sim](/mcp).** Give Codex, Claude, or another MCP client access to your workspace through `https://mcp.sim.ai/mcp`. +- **[Expose selected workflows as tools](/workflows/deployment/mcp).** Create a workflow MCP deployment for the workflows you choose. +- **[Use external tools inside Sim](/agents/mcp).** Add another service's MCP server to a Sim workspace for your agents to use. + +For organization-wide source search, use the dedicated [Search MCP](/search/mcp). ## Deployment options diff --git a/apps/docs/content/docs/mcp/authentication.mdx b/apps/docs/content/docs/mcp/authentication.mdx index de694a2066c..aca1fef51e9 100644 --- a/apps/docs/content/docs/mcp/authentication.mdx +++ b/apps/docs/content/docs/mcp/authentication.mdx @@ -5,6 +5,11 @@ description: Sign in with OAuth, or connect with an API key import { Callout } from 'fumadocs-ui/components/callout' +This page authenticates an external assistant to the hosted **Sim MCP server** +at `https://mcp.sim.ai/mcp`. Start with [Connect an assistant](/mcp). Selected +[workflow MCP deployments](/workflows/deployment/mcp) and +[external tools used inside Sim](/agents/mcp) have their own setup guides. + ## OAuth Most apps sign in with OAuth. The first time you connect, your app opens Sim in @@ -22,6 +27,11 @@ Most apps request full access. To connect an app for reads only, configure it to request the `api:read` scope; changes then fail with an insufficient-scope error. +For example, request read-only access in Codex with +`codex mcp login sim --scopes api:read`. Confirm the access shown on Sim's +approval screen. Authentication does not prove that the current task has loaded +the tools; complete the [connection checks](/mcp/troubleshooting). + Tokens are issued for the Sim MCP server itself. An app cannot take one to another service and use it there. @@ -58,8 +68,8 @@ reaches only its own workspace, and a few account-level operations refuse it; `search_operations` marks them `personalCredentialOnly`. - An API key does not expire until you revoke it. Prefer OAuth for any app that - can open a browser, and store keys in your app's secret or environment + API keys can have an expiration date and can be revoked. Prefer OAuth for any + app that can open a browser, and store keys in your app's secret or environment settings rather than in a shared config file. diff --git a/apps/docs/content/docs/mcp/index.mdx b/apps/docs/content/docs/mcp/index.mdx index dee6082ea4f..36ed5333a49 100644 --- a/apps/docs/content/docs/mcp/index.mdx +++ b/apps/docs/content/docs/mcp/index.mdx @@ -6,11 +6,23 @@ description: Build, run, and manage everything in your Sim workspace from Claude import { Callout } from 'fumadocs-ui/components/callout' import { Tab, Tabs } from 'fumadocs-ui/components/tabs' -The Sim MCP server gives an AI app the whole Sim API through the +The Sim MCP server gives an AI app access to Sim's JSON API operations through the [Model Context Protocol](https://modelcontextprotocol.io). Your agent can list workspaces, run and deploy workflows, query and edit tables, manage files and -knowledge bases, read run logs, and more. It covers the same operations as the -[API](/api-reference/getting-started) and the [CLI](/cli). +knowledge bases, read run logs, and more. Binary transfers and streaming use the +[API](/api-reference/getting-started) or [CLI](/cli); see the +[capability map](#choose-an-interface). + +## Choose your connection + +| You want to… | Connect | +| --- | --- | +| Let an external assistant operate your Sim workspace | **Sim MCP**, described on this page | +| Expose selected workflows as tools for an external assistant | [Workflow MCP deployment](/workflows/deployment/mcp) | +| Give Sim agents tools from another service | [External MCP tools in Sim](/agents/mcp) | + +You do not need to create or deploy a workflow to connect to Sim MCP. +The dedicated [Search MCP](/search/mcp) connection searches organization sources. | Deployment | Server URL | | --- | --- | @@ -20,9 +32,37 @@ knowledge bases, read run logs, and more. It covers the same operations as the The server uses the Streamable HTTP transport. Sign in with OAuth, the default in every app below, or send an [API key](/mcp/authentication#api-keys). -## Connect an app +## Connect Codex + +Run this in the terminal on the same host that runs your Codex task. These are +**Codex CLI** commands (`codex`), not Sim CLI commands (`sim`): + +```bash +codex mcp add sim --url https://mcp.sim.ai/mcp +codex mcp get sim --json +``` + +Complete the browser sign-in and approval. If sign-in was not offered or you +need to authenticate again, run `codex mcp login sim`. Check that the saved +server is enabled and its URL is `https://mcp.sim.ai/mcp`. + +For an already-open desktop client, open **Settings → MCP servers**, check the +Sim entry, and select **Restart** after configuration changes. The IDE extension +uses **Restart extension**. In the desktop composer or Codex terminal UI, `/mcp` +shows the active connections. These steps follow +[OpenAI's MCP setup guide](https://learn.chatgpt.com/docs/extend/mcp?surface=cli). + + + A saved server and successful OAuth login do not prove that its tools are + available in the current task. Check the active connection, then ask: + **“Use Sim MCP to list up to five workspaces I can access. Do not change anything.”** + A successful read is the final check. If the tools are missing, follow + [connection troubleshooting](/mcp/troubleshooting) instead of repeating setup. + + +## Connect another app - + ```bash claude mcp add --transport http sim https://mcp.sim.ai/mcp @@ -37,14 +77,6 @@ in every app below, or send an [API key](/mcp/authentication#api-keys). an owner first adds it under **Organization settings → Connectors**. See [Claude's custom connector instructions](https://support.claude.com/en/articles/11175166-get-started-with-custom-connectors-using-remote-mcp). - - ```bash - codex mcp add sim --url https://mcp.sim.ai/mcp - ``` - - Complete the browser sign-in. To sign in again later, run - `codex mcp login sim`. - Add `sim` to `mcpServers` in `~/.cursor/mcp.json`, then enable it in Cursor and sign in to Sim: @@ -100,10 +132,24 @@ same request to the API. Reads leave your resources unchanged, and apps can ask you to confirm each change. See [Authentication](/mcp/authentication) to limit an app to reads. -## Other Sim MCP surfaces - -This server is for operating Sim. Two other MCP features do different jobs: - -- [Search MCP](/search/mcp) searches your organization's live provider sources with current access checks. -- [MCP deployment](/workflows/deployment/mcp) exposes your own workflows as - tools, and [MCP tools](/agents/mcp) connect external servers to Sim agents. +## Choose an interface + +The hosted server exposes four discovery and execution tools, not a separately +named MCP tool for every operation. Use `search_operations` and +`describe_operation` to find the exact operation and current input schema. + +| Capability | Sim CLI (`sim`) | Hosted Sim MCP | Workflow MCP deployment | +| --- | --- | --- | --- | +| Workspace files: list, text reads, grep, edits, moves, versions | [Files commands](/cli/files) | JSON operations such as `listFiles`, `readFileText`, `searchFileContent`, and `editFileContent` | Only behavior implemented by the selected workflow | +| Upload/download local file bytes | [Files commands](/cli/files) | Use CLI/API for the byte transfer; upload-session control operations alone do not transfer a local file | Depends on the workflow's input/output contract | +| Edit an existing workflow | [Workflow commands](/cli/workflows) | `getWorkflowState` and `replaceWorkflowState` | Invokes the deployed workflow; does not expose the workspace editing API | +| Deploy a workflow | [Workflow commands](/cli/workflows) | `deployWorkflow` | Configure the deployment in Sim or through CLI/API/hosted MCP | +| Invoke a workflow | [Workflow commands](/cli/workflows) | `executeWorkflow`; async execution is deployment-only, while manual runs are synchronous or streamed through CLI/API | The selected workflows appear as their own tools | +| Preview a partial retry | [Partial retry recipe](/cli/scripting#previewing-a-partial-retry) | `previewWorkflowRunFromBlock` reports candidate reruns and cached-output availability without executing | Not part of the deployed workflow tool interface | +| Inspect runs and outputs | [Workflow commands](/cli/workflows) | `listWorkflowRuns`, `getWorkflowRun`, and other discovered run operations | Returns the invoked workflow's result | +| Search workspace knowledge | [Knowledge commands](/cli/knowledge) | `searchKnowledge` | Only if the workflow performs that search | +| Search live organization sources | Use the dedicated [Search MCP](/search/mcp) connection | Separate endpoint with `search` and `read_document` tools | Only if the workflow performs that search | + +The [external MCP settings](/agents/mcp) inside Sim configure tools that Sim +calls; they do not configure an external assistant's connection to this server. +See [Tools](/mcp/tools) for payload limits and the read/write boundary. diff --git a/apps/docs/content/docs/mcp/meta.json b/apps/docs/content/docs/mcp/meta.json index f111bfd9ece..0738ec5dbd8 100644 --- a/apps/docs/content/docs/mcp/meta.json +++ b/apps/docs/content/docs/mcp/meta.json @@ -1,5 +1,5 @@ { "title": "MCP", "root": true, - "pages": ["---Sim MCP---", "index", "authentication", "tools"] + "pages": ["---Sim MCP---", "index", "authentication", "tools", "troubleshooting"] } diff --git a/apps/docs/content/docs/mcp/tools.mdx b/apps/docs/content/docs/mcp/tools.mdx index 6bf6e0fee84..45b0adcb255 100644 --- a/apps/docs/content/docs/mcp/tools.mdx +++ b/apps/docs/content/docs/mcp/tools.mdx @@ -3,6 +3,10 @@ title: Tools description: How an agent finds, reads, and calls Sim operations through four tools --- +This guide covers the hosted [Sim MCP server](/mcp). A +[workflow MCP deployment](/workflows/deployment/mcp) exposes selected workflows, +while [external MCP tools](/agents/mcp) are called from inside Sim. + The Sim API has more than 200 operations. Instead of one tool per operation, which would crowd your app's tool list and your agent's context, the server exposes four tools. The agent searches for an operation, reads its inputs, and @@ -36,7 +40,7 @@ fills the parts of the request it needs: | --- | --- | | `params` | Path parameters, such as `tableId` or `workflowId` | | `query` | Query-string parameters; most operations need `workspaceId` | -| `body` | The JSON request body (write operations only) | +| `body` | The JSON request body; read-only searches and queries can also require one | | `headers` | Headers the operation declares, such as `upload-token` | The result is the same JSON the API returns, usually `{ "data": … }`. List @@ -53,3 +57,6 @@ correct its request. result, or with `async: true` and poll `getWorkflowRun`. - **No file bytes.** Downloads, knowledge base exports, and multipart document uploads are not available over MCP; use the [CLI](/cli/files) or the API. + +If the tools do not appear after sign-in, use the staged +[connection checks and read-only smoke test](/mcp/troubleshooting). diff --git a/apps/docs/content/docs/mcp/troubleshooting.mdx b/apps/docs/content/docs/mcp/troubleshooting.mdx new file mode 100644 index 00000000000..9b540119fe4 --- /dev/null +++ b/apps/docs/content/docs/mcp/troubleshooting.mdx @@ -0,0 +1,138 @@ +--- +title: Connection checks +description: Verify configuration, authentication, discovery, and a read-only call separately +--- + +This guide checks the hosted **Sim MCP server**, `https://mcp.sim.ai/mcp`. +For selected workflow tools, use [MCP deployment](/workflows/deployment/mcp); +for tools called by Sim, use [External MCP tools](/agents/mcp). The dedicated +[Search MCP](/search/mcp) endpoint has a different tool list. + +## Check each stage + +| Stage | Evidence | What it establishes | +| --- | --- | --- | +| Configuration | `codex mcp get sim --json` shows an enabled Streamable HTTP server at the expected URL | The server is saved on that Codex host | +| Authentication | Browser approval completes and the client reports a successful login | The client obtained credentials; it has not necessarily loaded tools | +| Initialization | The MCP `initialize` response includes `protocolVersion`, `serverInfo`, and tool capabilities | The endpoint speaks MCP to this authenticated connection | +| Discovery | `tools/list` returns `search_operations`, `describe_operation`, `call_read_operation`, and `call_write_operation` | The server exposed its tool catalog | +| Task usability | The assistant successfully calls `call_read_operation` for `listWorkspaces` | The active task can use the connection and read authorized data | + +There are four MCP tools, not hundreds of individually named workspace tools. +An empty list is unexpected for this endpoint. Seeing `call_write_operation` +does not grant write access: Sim still checks the credential's scope and current +resource permissions on every call. + +### Codex has saved the server, but this task has no tools + +1. Run `codex mcp get sim --json` on the host running the task. Check the URL and + enablement. A local CLI configuration does not configure a hosted web task. +2. In the desktop client, open **Settings → MCP servers**, find Sim, and select + **Restart** after changes. The IDE extension uses **Restart extension**. +3. Use `/mcp` in the desktop composer or terminal UI to inspect the active + connections. Check connection errors and any enabled/disabled tool filters. +4. Ask the assistant to use `search_operations` for `listWorkspaces`, inspect it + with `describe_operation`, then call `call_read_operation` with + `{"operation":"listWorkspaces","query":{"limit":5}}`. + +These client controls are documented in [OpenAI's MCP guide](https://learn.chatgpt.com/docs/extend/mcp?surface=cli). +Do not assume an already-open task hot-reloaded a CLI config edit or that starting +a new task alone fixes discovery. Verify the active connection and the read. +If direct discovery succeeds but the task still cannot call a tool, capture the +client version and MCP connection error before changing Sim's configuration. + +## Read-only protocol smoke test + +Use this to isolate server behavior from an assistant's tool-loading behavior. +It initializes MCP, discovers the tools, describes an operation, and reads up to +five workspaces. It does not create a workflow, run one, or change workspace data. + +Use `curl` with `--fail-with-body` support and a Sim API key supplied through +`SIM_API_KEY` in your local environment. Keep the key out of shared scripts and +support reports. For OAuth, use your MCP client's authenticated connection to +perform the same steps; the API-key test does not validate its stored OAuth grant. + +```bash +export SIM_MCP_URL="https://mcp.sim.ai/mcp" +export SIM_MCP_PROTOCOL_VERSION="2025-03-26" +: "${SIM_API_KEY:?Set SIM_API_KEY to your Sim API key}" + +mcp_request() { + curl -q --silent --show-error --fail-with-body --max-time 30 \ + "$SIM_MCP_URL" \ + -H "X-API-Key: $SIM_API_KEY" \ + -H 'Content-Type: application/json' \ + -H 'Accept: application/json, text/event-stream' \ + -H "MCP-Protocol-Version: $SIM_MCP_PROTOCOL_VERSION" \ + --data "$1" +} +``` + +For self-hosted Sim, set `SIM_MCP_URL` to your configured endpoint, usually +`https:///api/mcp`. + +### 1. Initialize + +```bash +mcp_request '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"sim-readonly-check","version":"1.0.0"}}}' +``` + +Expect a JSON-RPC `result` with `serverInfo.name` equal to `Sim`, a supported +`protocolVersion`, and `capabilities.tools`. Stop on an HTTP or JSON-RPC error. +Set `SIM_MCP_PROTOCOL_VERSION` to the returned protocol version for subsequent +requests if it differs. The function ignores local curl defaults and sends one +API-key header; do not add an OAuth bearer header to the same request. + +```bash +mcp_request '{"jsonrpc":"2.0","method":"notifications/initialized"}' +``` + +The notification has no JSON result. Sim's hosted server is stateless, so these +requests do not need an `Mcp-Session-Id`. Opening the endpoint in a browser sends +GET, which is not a connection test: this server accepts MCP messages through POST. + +### 2. Discover tools + +```bash +mcp_request '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}' +``` + +Expect the four tool names listed above in `result.tools`. If you instead see +workflow names or `search`/`read_document`/`chat`, check the endpoint: those belong +to a workflow deployment or Search MCP. Do not invoke a tool to guess what it does. + +### 3. Describe and perform one authorized read + +```bash +mcp_request '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"describe_operation","arguments":{"operation":"listWorkspaces"}}}' + +mcp_request '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"call_read_operation","arguments":{"operation":"listWorkspaces","query":{"limit":5}}}}' +``` + +Successful tool results contain JSON encoded in `result.content` text entries. +The final call contains the API's `data` list and pagination fields. An empty +workspace list can be a valid authorized result; it is different from an empty +MCP tool list. `result.isError: true` or a JSON-RPC `error` means the call failed, +even if HTTP returned 200. A workspace key can see only its bound workspace. + +## Resolve common failures + +| Symptom | Next action | +| --- | --- | +| No saved `sim` server | Follow [Connect Codex](/mcp#connect-codex) on the task's host. Do not substitute Sim's external-tool settings. | +| OAuth expired, revoked, or login incomplete | Run `codex mcp login sim` and complete approval; inspect the client connection error if it still fails. | +| HTTP 401 with an API key | Verify the key belongs to this Sim deployment, is current, and is sent in one supported credential header. | +| `insufficient_scope` | Reads need `api:read`; mutations and workflow execution need `api:write`. Reauthorize only for the access you intend to use. | +| HTTP 403 or an operation denied | Check current workspace membership, role, organization credential policy, and the credential's workspace binding. Successful login does not override these. | +| GET returns 405 | Use an MCP Streamable HTTP client or the POST smoke test; the endpoint is not a web page. | +| Initialization or discovery times out | Inspect the client's MCP connection error; verify endpoint reachability, TLS, and proxy support for POST and the MCP headers. A self-hosted server must be reachable from the client's host. | +| No tools after authentication | Compare `tools/list` with the active task inventory. Check enablement, client tool filters and organization policy, then use the documented client restart control. | +| Only four tools appear | Expected. Use `search_operations` followed by `describe_operation`; operation IDs are not separate MCP tools. | +| A known CLI command is absent | Check the [capability map](/mcp#choose-an-interface). Binary and streaming operations need CLI/API; Search MCP is separate. | +| HTTP 429 or result too large | Respect the retry delay and reduce page size. MCP results are limited to 1 MiB. | + +When reporting a failure, include the endpoint, client version, failed stage, +HTTP status, redacted error, and request ID if returned. Do not include tokens, +API keys, or private workspace contents. A successful direct smoke test narrows +the issue to the tested server/credential path; it does not prove another client's +OAuth session or active task is healthy. diff --git a/apps/docs/content/docs/search/mcp.mdx b/apps/docs/content/docs/search/mcp.mdx index 25fab917a3d..15796338795 100644 --- a/apps/docs/content/docs/search/mcp.mdx +++ b/apps/docs/content/docs/search/mcp.mdx @@ -5,6 +5,10 @@ description: Search your organization's sources from Claude, Codex, Cursor, and Use Sim Search from another app to search and read your organization's sources through their live APIs, or ask the Sim Assistant for cited answers. Your current Sim membership, provider access, and source restrictions apply. +Search MCP is a dedicated search connection. For workspace management, connect +to [Sim MCP](/mcp); for selected workflow tools, use [MCP deployment](/workflows/deployment/mcp). +To bring another server's tools into Sim, see [Using MCP tools](/agents/mcp). + ## Connect an app 1. Confirm you can find a document in the organization's **Search**. [Connect your source account](/search/connect-your-account) first if required. diff --git a/apps/docs/content/docs/workflows/blocks/function.mdx b/apps/docs/content/docs/workflows/blocks/function.mdx index 50dda68f46c..325ba5c520f 100644 --- a/apps/docs/content/docs/workflows/blocks/function.mdx +++ b/apps/docs/content/docs/workflows/blocks/function.mdx @@ -140,12 +140,19 @@ rather than returning part of what your code wrote. -Returned files live with the execution rather than in your workspace, and a text -file containing a resolved secret value is refused rather than returned — there is -nowhere on an execution file to record that it carries one. Write such a file to a -workspace path instead, or keep the secret out of the output. +Returned workflow files live with the execution rather than in your workspace. +A file containing a literal protected secret value is refused. Keep secrets out of +returned files, or use an explicit workspace export that records their provenance. +When called directly with `sim tools execute function_execute`, generated files +belong to the authenticated user and have `context: "copilot"`. Download one with +`sim tools files download "" --output-file ./result.txt` in the same +workspace context. Direct calls also check filenames and refuse files whose +secret provenance is uncertain, including binary output after a protected secret +was used. For code that needs no secrets, pass `secretScope: "selected"` and +`mountedSecrets: []` in the tool input. + ## Language JavaScript without imports runs in a fast local sandbox. JavaScript with `import` or `require`, Python, and Shell run in the configured remote sandbox provider. @@ -157,6 +164,13 @@ JavaScript without imports runs in a fast local sandbox. JavaScript with `import | **HTTP requests** | `fetch()` built in | `requests` or `httpx` | `curl` or an installed CLI | | **Best for** | quick transforms and JSON | scripts, data science, charts, complex math | CLI workflows and system utilities | +The fast local JavaScript runtime provides standard ECMAScript values, `fetch`, +`console`, and Sim helpers. It does not provide Node/browser globals such as +`process`, `Buffer`, `require`, `crypto`, `TextDecoder`, `atob`, or `setTimeout`. +Code that needs Node APIs or timers must use the remote JavaScript runtime with +an import, for example `import { setTimeout as delay } from 'node:timers/promises'`. +Use `{{SECRET_NAME}}` for selected secrets in either runtime. + Python and Shell require a remote sandbox. They are enabled by default on sim.ai; on a self-hosted instance, build and configure the provider's dedicated diff --git a/apps/docs/content/docs/workflows/deployment/mcp.mdx b/apps/docs/content/docs/workflows/deployment/mcp.mdx index 45429ab3c20..2f1fa124fc1 100644 --- a/apps/docs/content/docs/workflows/deployment/mcp.mdx +++ b/apps/docs/content/docs/workflows/deployment/mcp.mdx @@ -9,6 +9,13 @@ import { Callout } from 'fumadocs-ui/components/callout' Deploy your workflows as MCP tools to make them accessible to external AI assistants like Claude Desktop, Cursor, and other MCP-compatible clients. + + This guide exposes **selected workflows as tools**. To let an assistant manage + files, edit workflows, deploy them, and inspect runs, connect to the hosted + [Sim MCP server](/mcp). To give Sim agents tools from another server, see + [Using MCP tools](/agents/mcp). + + ## Creating and Managing MCP Servers MCP servers group your workflow tools together. Create and manage them in workspace settings: diff --git a/apps/docs/lib/redirects.ts b/apps/docs/lib/redirects.ts index fa6091908ca..cbec3f3e8d6 100644 --- a/apps/docs/lib/redirects.ts +++ b/apps/docs/lib/redirects.ts @@ -76,10 +76,9 @@ export const DOCS_REDIRECTS: DocsRedirect[] = [ destination: '/workflows/deployment/mcp', permanent: true, }, - // building-agents section renamed to agents; mcp and skills folded into it + /** The former building-agents section and skills live under agents. */ { source: '/building-agents', destination: '/agents', permanent: true }, { source: '/building-agents/:path*', destination: '/agents/:path*', permanent: true }, - { source: '/mcp', destination: '/agents/mcp', permanent: true }, { source: '/skills', destination: '/agents/skills', permanent: true }, // tools/ + triggers/ unified into per-service integrations/ pages. // Specific moves first (Next applies the first matching redirect): diff --git a/apps/docs/openapi-v2-logs.json b/apps/docs/openapi-v2-logs.json index a75e5fc7c7c..04ae8dba85a 100644 --- a/apps/docs/openapi-v2-logs.json +++ b/apps/docs/openapi-v2-logs.json @@ -383,6 +383,16 @@ "pattern": "^[A-Za-z0-9._:-]+$", "description": "Unique workflow run identifier." } + }, + { + "name": "includeWorkflowState", + "in": "query", + "required": false, + "description": "Include the saved workflow snapshot. Set false to avoid loading and returning block configuration when inspecting a run. Other run fields are unchanged.", + "schema": { + "description": "Include the saved workflow snapshot. Set false to avoid loading and returning block configuration when inspecting a run. Other run fields are unchanged.", + "type": "boolean" + } } ], "responses": { @@ -1602,7 +1612,7 @@ "type": "null" } ], - "description": "Workflow graph captured for the run, or null if unavailable. Sensitive values are redacted to null; environment-variable references may be preserved." + "description": "Credential-redacted workflow snapshot, or null when unavailable or includeWorkflowState=false." }, "traceSpans": { "type": "array", diff --git a/apps/docs/openapi-v2-resources.json b/apps/docs/openapi-v2-resources.json index e9ec3dde864..534c0f080f7 100644 --- a/apps/docs/openapi-v2-resources.json +++ b/apps/docs/openapi-v2-resources.json @@ -2758,43 +2758,43 @@ } } }, - "/api/v2/credentials/providers": { + "/api/v2/credentials/{credentialId}": { "get": { - "operationId": "listCredentialProviders", - "summary": "List Credential Providers", - "description": "List OAuth and service-account connection methods and their availability. OAuth options provide provider IDs for browser connections; service-account methods declare required fields and write-only secrets. Supports provider-name search. Returns the complete set in one page; `nextCursor` is always null.\n\nOAuth scope: `api:read`.", - "x-sim-operation": "credentials.providers.list", + "operationId": "getCredential", + "summary": "Inspect Credential", + "description": "Inspect one selected connection's stored provider identity, recorded OAuth scopes, and access limitations. This does not decrypt secrets, contact the provider, or verify live resource access. Custom bot identities/scopes may be unknown. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "credentials.inspect", "x-oauth-scope": "api:read", "tags": ["Credentials"], "parameters": [ { - "name": "workspaceId", - "in": "query", + "name": "credentialId", + "in": "path", "required": true, - "description": "Workspace used to evaluate credential-provider availability and integration policy.", + "description": "Selected credential to inspect.", "schema": { "type": "string", "minLength": 1, - "maxLength": 128, - "description": "Workspace used to evaluate credential-provider availability and integration policy." + "maxLength": 255, + "description": "Selected credential to inspect." } }, { - "name": "search", + "name": "workspaceId", "in": "query", - "required": false, - "description": "Case-insensitive substring match against the credential provider name.", + "required": true, + "description": "Workspace expected to own the selected credential.", "schema": { - "description": "Case-insensitive substring match against the credential provider name.", "type": "string", "minLength": 1, - "maxLength": 200 + "maxLength": 128, + "description": "Workspace expected to own the selected credential." } } ], "responses": { "200": { - "description": "Credential provider catalog with caller-specific availability.", + "description": "Selected credential metadata and diagnostic coverage.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -2809,7 +2809,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ListCredentialProvidersResponse" + "$ref": "#/components/schemas/GetCredentialResponse" } } } @@ -2836,30 +2836,43 @@ "$ref": "#/components/responses/ServiceUnavailable" } } - } - }, - "/api/v2/credentials/connections": { - "post": { - "operationId": "createCredentialConnection", - "summary": "Create Credential Connection", - "description": "Create a short-lived browser URL for connecting an OAuth provider or reconnecting an existing OAuth credential. Open the URL, sign in as the authenticated user, complete provider authorization, then refresh the credentials list. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", - "x-sim-operation": "credentials.connections.create", + }, + "delete": { + "operationId": "deleteCredential", + "summary": "Disconnect Credential", + "description": "Disconnect an OAuth or service-account credential and clear its stored workflow, deployment, paused-run, knowledge-connector, and webhook references. Credential admin access is required. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", + "x-sim-operation": "credentials.delete", "x-oauth-scope": "api:write", "tags": ["Credentials"], - "requestBody": { - "required": true, - "description": "For a new connection, provide providerId and displayName. For a reconnect, provide only credentialId; the existing display name is preserved.", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreateCredentialConnectionBody" - } + "parameters": [ + { + "name": "credentialId", + "in": "path", + "required": true, + "description": "Credential to disconnect.", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 255, + "description": "Credential to disconnect." + } + }, + { + "name": "workspaceId", + "in": "query", + "required": true, + "description": "Workspace expected to own the credential.", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Workspace expected to own the credential." } } - }, + ], "responses": { "200": { - "description": "A short-lived browser authorization URL.", + "description": "The credential was disconnected.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -2874,7 +2887,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CreateCredentialConnectionResponse" + "$ref": "#/components/schemas/DeleteCredentialResponse" } } } @@ -2891,15 +2904,6 @@ "404": { "$ref": "#/components/responses/NotFound" }, - "409": { - "$ref": "#/components/responses/Conflict" - }, - "413": { - "$ref": "#/components/responses/PayloadTooLarge" - }, - "415": { - "$ref": "#/components/responses/UnsupportedMediaType" - }, "429": { "$ref": "#/components/responses/RateLimited" }, @@ -2910,14 +2914,12 @@ "$ref": "#/components/responses/ServiceUnavailable" } } - } - }, - "/api/v2/credentials/{credentialId}": { - "delete": { - "operationId": "deleteCredential", - "summary": "Disconnect Credential", - "description": "Disconnect an OAuth or service-account credential and clear its stored workflow, deployment, paused-run, knowledge-connector, and webhook references. Credential admin access is required. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", - "x-sim-operation": "credentials.delete", + }, + "patch": { + "operationId": "updateCredential", + "summary": "Update Credential", + "description": "Rename a service-account credential or rotate its secret fields, preserving omitted values and the credential ID. Requires credential admin access. Provider rejection preserves the old secret and returns `400` with `providerErrorCode`; outages return `503`. Fields for a different credential type return `400`. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", + "x-sim-operation": "credentials.update", "x-oauth-scope": "api:write", "tags": ["Credentials"], "parameters": [ @@ -2925,12 +2927,12 @@ "name": "credentialId", "in": "path", "required": true, - "description": "Credential to disconnect.", + "description": "Credential to update.", "schema": { "type": "string", "minLength": 1, "maxLength": 255, - "description": "Credential to disconnect." + "description": "Credential to update." } }, { @@ -2946,9 +2948,20 @@ } } ], + "requestBody": { + "required": true, + "description": "Replacement display metadata and the write-only fields declared by provider discovery.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateCredentialRequest" + } + } + } + }, "responses": { "200": { - "description": "The credential was disconnected.", + "description": "The updated credential without secret material.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -2963,7 +2976,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DeleteCredentialResponse" + "$ref": "#/components/schemas/UpdateCredentialResponse" } } } @@ -2980,6 +2993,15 @@ "404": { "$ref": "#/components/responses/NotFound" }, + "409": { + "$ref": "#/components/responses/Conflict" + }, + "413": { + "$ref": "#/components/responses/PayloadTooLarge" + }, + "415": { + "$ref": "#/components/responses/UnsupportedMediaType" + }, "429": { "$ref": "#/components/responses/RateLimited" }, @@ -2990,54 +3012,110 @@ "$ref": "#/components/responses/ServiceUnavailable" } } - }, - "patch": { - "operationId": "updateCredential", - "summary": "Update Credential", - "description": "Rename a service-account credential or rotate its secret fields, preserving omitted values and the credential ID. Requires credential admin access. Provider rejection preserves the old secret and returns `400` with `providerErrorCode`; outages return `503`. Fields for a different credential type return `400`. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", - "x-sim-operation": "credentials.update", - "x-oauth-scope": "api:write", + } + }, + "/api/v2/credentials/providers": { + "get": { + "operationId": "listCredentialProviders", + "summary": "List Credential Providers", + "description": "List OAuth and service-account connection methods and their availability. OAuth options provide provider IDs for browser connections; service-account methods declare required fields and write-only secrets. Supports provider-name search. Returns the complete set in one page; `nextCursor` is always null.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "credentials.providers.list", + "x-oauth-scope": "api:read", "tags": ["Credentials"], "parameters": [ { - "name": "credentialId", - "in": "path", + "name": "workspaceId", + "in": "query", "required": true, - "description": "Credential to update.", + "description": "Workspace used to evaluate credential-provider availability and integration policy.", "schema": { "type": "string", "minLength": 1, - "maxLength": 255, - "description": "Credential to update." + "maxLength": 128, + "description": "Workspace used to evaluate credential-provider availability and integration policy." } }, { - "name": "workspaceId", + "name": "search", "in": "query", - "required": true, - "description": "Workspace expected to own the credential.", + "required": false, + "description": "Case-insensitive substring match against the credential provider name.", "schema": { + "description": "Case-insensitive substring match against the credential provider name.", "type": "string", "minLength": 1, - "maxLength": 128, - "description": "Workspace expected to own the credential." + "maxLength": 200 } } ], + "responses": { + "200": { + "description": "Credential provider catalog with caller-specific availability.", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListCredentialProvidersResponse" + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/InternalError" + }, + "503": { + "$ref": "#/components/responses/ServiceUnavailable" + } + } + } + }, + "/api/v2/credentials/connections": { + "post": { + "operationId": "createCredentialConnection", + "summary": "Create Credential Connection", + "description": "Create a short-lived browser URL for connecting an OAuth provider or reconnecting an existing OAuth credential. Open the URL, sign in as the authenticated user, complete provider authorization, then refresh the credentials list. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", + "x-sim-operation": "credentials.connections.create", + "x-oauth-scope": "api:write", + "tags": ["Credentials"], "requestBody": { "required": true, - "description": "Replacement display metadata and the write-only fields declared by provider discovery.", + "description": "For a new connection, provide providerId and displayName. For a reconnect, provide only credentialId; the existing display name is preserved.", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UpdateCredentialRequest" + "$ref": "#/components/schemas/CreateCredentialConnectionBody" } } } }, "responses": { "200": { - "description": "The updated credential without secret material.", + "description": "A short-lived browser authorization URL.", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -3052,7 +3130,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UpdateCredentialResponse" + "$ref": "#/components/schemas/CreateCredentialConnectionResponse" } } } @@ -4601,7 +4679,7 @@ "post": { "operationId": "executeTool", "summary": "Run Tool", - "description": "Run a built-in tool using published parameter IDs. Sim resolves `credentialId`, hosted keys, and whole-value `{{VAR_NAME}}` references for `user-only` parameters; other values pass through verbatim. Third-party refusal returns `200` with `status: \"failed\"`; the error envelope covers API failures. Hidden or missing tools return `404`; disallowed integrations return `403` with `error.details.code: INTEGRATION_NOT_ALLOWED`. Hosted-key use is billed to the workspace. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", + "description": "Run a built-in tool using published parameters and caller-owned credentials. Whole-value `{{VAR_NAME}}` references resolve for `user-only` parameters. Provider refusal returns `200` with `status: \"failed\"`; API failures use the error envelope. Hidden tools return `404`; blocked integrations return `403` with `error.details.code: INTEGRATION_NOT_ALLOWED`. Hosted-key use and measured Function sandbox costs are billed to the workspace. Function usage-limit checks can refuse execution with `402 USAGE_LIMIT_EXCEEDED`. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.", "x-sim-operation": "tools.execute", "x-oauth-scope": "api:write", "tags": ["Catalog"], @@ -4658,6 +4736,9 @@ "401": { "$ref": "#/components/responses/Unauthorized" }, + "402": { + "$ref": "#/components/responses/UsageLimitExceeded" + }, "403": { "$ref": "#/components/responses/Forbidden" }, @@ -4798,6 +4879,96 @@ } } }, + "/api/v2/tools/files/download": { + "get": { + "operationId": "downloadToolFileV2", + "summary": "Download Tool File", + "description": "Download a personal output from a direct tool call using its unchanged file.id. Requires its original owner and current workspace access. Use Download Workflow Run File for workflow outputs. Files can expire. Workspace API keys return `403`; use a personal API key or scoped OAuth token. `HEAD` checks access with the same authorization as `GET` but skips side effects, returning an empty `200` without payload headers on success. `HEAD` omits `Content-Length`; use file metadata to size downloads.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "tools.files.download", + "x-oauth-scope": "api:read", + "tags": ["Catalog"], + "parameters": [ + { + "name": "workspaceId", + "in": "query", + "required": true, + "description": "Workspace in which to authorize the download.", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Workspace in which to authorize the download." + } + }, + { + "name": "fileId", + "in": "query", + "required": true, + "description": "The file.id from a direct tool result whose file.context is \"copilot\". Workflow output files use Download Workflow Run File instead.", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 2048, + "description": "The file.id from a direct tool result whose file.context is \"copilot\". Workflow output files use Download Workflow Run File instead." + } + } + ], + "responses": { + "200": { + "description": "The tool file bytes.", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + }, + "Content-Type": { + "$ref": "#/components/headers/Content-Type" + }, + "Content-Disposition": { + "$ref": "#/components/headers/Content-Disposition" + }, + "Content-Length": { + "$ref": "#/components/headers/Content-Length" + } + }, + "content": { + "application/octet-stream": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/InternalError" + }, + "503": { + "$ref": "#/components/responses/ServiceUnavailable" + } + } + } + }, "/api/v2/organizations/{organizationId}/permission-groups": { "get": { "operationId": "listPermissionGroups", @@ -9109,6 +9280,31 @@ } }, "headers": { + "Content-Type": { + "description": "MIME type of the file, defaulting to application/octet-stream when the stored type is unavailable.", + "schema": { + "type": "string", + "title": "Content type", + "description": "MIME type of the file, defaulting to application/octet-stream when the stored type is unavailable." + } + }, + "Content-Disposition": { + "description": "Attachment disposition containing sanitized and RFC 5987 encoded filenames.", + "schema": { + "type": "string", + "title": "Content disposition", + "description": "Attachment disposition containing sanitized and RFC 5987 encoded filenames." + } + }, + "Content-Length": { + "description": "File size in bytes.", + "schema": { + "type": "string", + "pattern": "^(0|[1-9]\\d*)$", + "title": "Content length", + "description": "File size in bytes." + } + }, "X-RateLimit-Limit": { "description": "Maximum requests allowed in the current window.", "schema": { @@ -9192,6 +9388,22 @@ } } }, + "UsageLimitExceeded": { + "description": "The workspace has exceeded its usage or billing limits.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/V2Error" + }, + "example": { + "error": { + "code": "USAGE_LIMIT_EXCEEDED", + "message": "Usage limit exceeded. Please upgrade your plan to continue." + } + } + } + } + }, "Forbidden": { "description": "The caller lacks the rights this operation requires. When the cause is one a caller can act on, `error.details.code` names it. A resource in a workspace the caller cannot reach at all answers `404` instead, so absence and denial are indistinguishable.", "content": { @@ -11953,6 +12165,199 @@ } ] }, + "CredentialInspection": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Unique credential identifier." + }, + "type": { + "type": "string", + "enum": ["oauth", "service_account"], + "description": "Authenticated connection type." + }, + "displayName": { + "type": "string", + "description": "Credential display name." + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Optional credential description." + }, + "providerId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Integration provider authenticated by this credential." + }, + "accountId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Linked account identifier for OAuth credentials." + }, + "hasServiceAccountKey": { + "type": "boolean", + "description": "Whether a service-account payload is stored. Its contents are never returned." + }, + "role": { + "type": "string", + "enum": ["admin", "member"], + "description": "Caller role for the credential." + }, + "createdAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "ISO 8601 timestamp when the credential was created." + }, + "updatedAt": { + "type": "string", + "format": "date-time", + "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z))$", + "description": "ISO 8601 timestamp when the credential was last updated." + }, + "diagnostics": { + "type": "object", + "properties": { + "identity": { + "type": "object", + "properties": { + "source": { + "type": "string", + "enum": ["credential", "linked-account", "unknown"], + "description": "Stored metadata source for the reported identity; unknown means no identity is separately recorded." + }, + "subjectId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Stored provider subject ID when separately recorded; null means unknown." + }, + "tenantId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Stored provider tenant or Slack installation ID when available." + }, + "externalAccountId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Stored OAuth external account identifier; may include connection-specific suffixes and is not necessarily the acting bot/user ID." + }, + "verifiedLive": { + "type": "boolean", + "const": false, + "description": "Inspection never contacts the provider or validates secret material." + } + }, + "required": [ + "source", + "subjectId", + "tenantId", + "externalAccountId", + "verifiedLive" + ], + "additionalProperties": false, + "description": "Stored provider identity metadata; no live identity verification is performed." + }, + "scopes": { + "type": "object", + "properties": { + "source": { + "type": "string", + "enum": ["credential", "linked-account", "unknown"], + "description": "Stored metadata source for granted scopes; unknown means grants are not separately recorded." + }, + "values": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Recorded granted scopes. An unknown source with an empty array does not mean the credential has no scopes." + } + }, + "required": ["source", "values"], + "additionalProperties": false, + "description": "Recorded granted scopes and their source, without requesting provider access." + }, + "notes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Coverage limits and provider-specific access guidance." + } + }, + "required": ["identity", "scopes", "notes"], + "additionalProperties": false, + "description": "Non-secret credential identity, recorded grants, and diagnostic coverage limits." + } + }, + "required": [ + "id", + "type", + "displayName", + "description", + "providerId", + "accountId", + "hasServiceAccountKey", + "role", + "createdAt", + "updatedAt", + "diagnostics" + ], + "additionalProperties": false, + "title": "Credential inspection", + "description": "Credential metadata with stored identity and scope diagnostics; no live provider verification." + }, + "GetCredentialResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/CredentialInspection" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Get credential response", + "description": "Stored identity and scope diagnostics without secret material." + }, "V2CredentialProvider": { "oneOf": [ { @@ -14556,7 +14961,7 @@ "properties": { "required": { "type": "boolean", - "description": "Whether the tool cannot run without an OAuth credential." + "description": "Whether OAuth is mandatory. Slack tools declaring authMethod and botToken also accept explicit bot_token authentication; false does not mean the tool is unauthenticated." }, "provider": { "type": "string", @@ -15158,7 +15563,7 @@ "properties": { "required": { "type": "boolean", - "description": "Whether the tool cannot run without an OAuth credential." + "description": "Whether OAuth is mandatory. Slack tools declaring authMethod and botToken also accept explicit bot_token authentication; false does not mean the tool is unauthenticated." }, "provider": { "type": "string", @@ -15350,7 +15755,7 @@ }, "input": { "default": {}, - "description": "Tool arguments keyed by published parameter IDs. For `user-only` parameters, a whole-value `{{VAR_NAME}}` reference resolves a workspace environment variable. Other values pass through unchanged.", + "description": "Tool arguments keyed by published parameter IDs. For `user-only` parameters, a whole-value `{{VAR_NAME}}` reference resolves an environment variable in the acting user’s personal/workspace scope. Other values pass through unchanged.", "type": "object", "propertyNames": { "type": "string" @@ -15360,7 +15765,7 @@ } }, "credentialId": { - "description": "Credential to authenticate with. Required when the tool declares an OAuth requirement; the workspace credentials list names the candidates.", + "description": "Credential to authenticate with. Required for OAuth authentication; the workspace credentials list names the candidates. Slack tools that declare authMethod and botToken also accept input.authMethod=bot_token with input.botToken (literal or {{SECRET_NAME}}); that explicit mode ignores credentialId. Otherwise OAuth is the default and unused botToken is ignored.", "type": "string", "minLength": 1, "maxLength": 255 diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 9e1495379ee..76dcc737363 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -281,11 +281,101 @@ } } }, + "/api/v2/workflows/{workflowId}/inspect": { + "get": { + "operationId": "inspectWorkflow", + "summary": "Inspect Workflow", + "description": "Inspect a compact draft graph with block IDs, enabled states, connections, and bounded nonempty inputs. Credential fields and opaque credential-bearing inputs are withheld; code is omitted unless requested. This diagnostic representation is not suitable for Replace Workflow State. Automatic redaction cannot recognize every secret in arbitrary text or code.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "workflows.read", + "x-oauth-scope": "api:read", + "tags": ["Workflows"], + "parameters": [ + { + "name": "workflowId", + "in": "path", + "required": true, + "description": "Unique workflow identifier.", + "schema": { + "type": "string", + "minLength": 1, + "description": "Unique workflow identifier.", + "examples": ["3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36"] + } + }, + { + "name": "blockId", + "in": "query", + "required": false, + "description": "Inspect one block and its incident connections. Omit to inspect the draft graph.", + "schema": { + "description": "Inspect one block and its incident connections. Omit to inspect the draft graph.", + "type": "string", + "minLength": 1, + "maxLength": 128 + } + }, + { + "name": "includeCode", + "in": "query", + "required": false, + "description": "Include bounded code inputs. Code and free text can contain hardcoded secrets that automatic redaction cannot recognize.", + "schema": { + "description": "Include bounded code inputs. Code and free text can contain hardcoded secrets that automatic redaction cannot recognize.", + "type": "boolean" + } + } + ], + "responses": { + "200": { + "description": "A compact diagnostic view of the workflow draft.", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InspectWorkflowResponse" + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/InternalError" + }, + "503": { + "$ref": "#/components/responses/ServiceUnavailable" + } + } + } + }, "/api/v2/workflows/{workflowId}/state": { "get": { "operationId": "getWorkflowState", "summary": "Get Workflow State", - "description": "Get the editable draft graph, including blocks, edges, loop and parallel containers, and variables. Use this state with Replace Workflow State to preserve workspace bindings; Export Workflow removes those bindings for portability. This read records no audit event, and `HEAD` mirrors `GET`.\n\nOAuth scope: `api:read`.", + "description": "Get the full editable draft graph, including blocks, edges, loop and parallel containers, variables, and stored input values. Use Inspect Workflow for compact, redacted diagnostics. Use this state with Replace Workflow State to preserve workspace bindings; Export Workflow removes those bindings for portability. This read records no audit event, and `HEAD` mirrors `GET`.\n\nOAuth scope: `api:read`.", "x-sim-operation": "workflows.read", "x-oauth-scope": "api:read", "tags": ["Workflows"], @@ -2686,6 +2776,100 @@ } } }, + "/api/v2/workflows/{workflowId}/runs/preview": { + "get": { + "operationId": "previewWorkflowRunFromBlock", + "summary": "Preview Partial Workflow Run", + "description": "Inspect the current saved draft and one prior run without executing blocks or reserving a run ID. Returns executor entry validation, candidate rerun blocks, and upstream cached-output availability without output values. Requires write access to the workflow and OAuth api:read or a personal API key. Conditional paths are candidates, and a later run uses the draft saved at that time. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + "x-sim-operation": "workflows.manual.preview_from_block", + "x-oauth-scope": "api:read", + "tags": ["Workflow Runs"], + "parameters": [ + { + "name": "workflowId", + "in": "path", + "required": true, + "description": "Unique workflow identifier.", + "schema": { + "type": "string", + "minLength": 1, + "description": "Unique workflow identifier.", + "examples": ["3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36"] + } + }, + { + "name": "blockId", + "in": "query", + "required": true, + "description": "Saved draft block at which a later manual run would start.", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Saved draft block at which a later manual run would start." + } + }, + { + "name": "sourceRunId", + "in": "query", + "required": true, + "description": "Existing run in this workflow whose persisted state would supply cached upstream outputs.", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "pattern": "^[A-Za-z0-9._:-]+$", + "description": "Existing run in this workflow whose persisted state would supply cached upstream outputs.", + "examples": ["run_8f14e45f-ceea-467f-a"] + } + } + ], + "responses": { + "200": { + "description": "A read-only partial-run preview, including any entry-validation failure.", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PreviewWorkflowRunFromBlockResponse" + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/InternalError" + }, + "503": { + "$ref": "#/components/responses/ServiceUnavailable" + } + } + } + }, "/api/v2/workflows/{workflowId}/runs": { "get": { "operationId": "listWorkflowRunsV2", @@ -6055,6 +6239,170 @@ "title": "Create workflow request", "description": "Name, description, workspace, and optional folder for a new workflow." }, + "WorkflowInspection": { + "type": "object", + "properties": { + "representation": { + "type": "string", + "const": "diagnostic", + "description": "A read-only diagnostic projection, unsuitable for replacing workflow state." + }, + "workflowId": { + "type": "string", + "description": "Workflow whose saved draft is inspected." + }, + "workspaceId": { + "type": "string", + "description": "Workspace containing the workflow." + }, + "blocks": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Canonical saved block ID." + }, + "name": { + "type": "string", + "description": "Block display name." + }, + "type": { + "type": "string", + "description": "Registered block type." + }, + "enabled": { + "type": "boolean", + "description": "Whether the block is enabled in the saved draft." + }, + "parentId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Containing loop or parallel block ID, or null for a top-level block." + }, + "inputs": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "description": "User-authored block configuration after redaction and diagnostic size limits.", + "examples": ["send"] + }, + "description": "Bounded, redacted user-authored input values. Empty fields are omitted." + }, + "omittedInputs": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Nonempty fields withheld by credential, unknown-field, visibility, or code-inclusion rules." + } + }, + "required": ["id", "name", "type", "enabled", "parentId", "inputs", "omittedInputs"], + "additionalProperties": false + }, + "description": "Selected blocks without positions, output schemas, or runtime state." + }, + "edges": { + "type": "array", + "items": { + "type": "object", + "properties": { + "source": { + "type": "string", + "description": "Source block ID." + }, + "target": { + "type": "string", + "description": "Target block ID." + }, + "sourceHandle": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Source output handle, or null when unspecified." + }, + "targetHandle": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Target input handle, or null when unspecified." + } + }, + "required": ["source", "target", "sourceHandle", "targetHandle"], + "additionalProperties": false + }, + "description": "Draft connections, or only connections touching the selected block." + }, + "truncated": { + "type": "boolean", + "description": "Whether an input exceeded the diagnostic size or depth budget." + }, + "notes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Representation, redaction, and size-limit guidance." + } + }, + "required": [ + "representation", + "workflowId", + "workspaceId", + "blocks", + "edges", + "truncated", + "notes" + ], + "additionalProperties": false, + "title": "Workflow inspection", + "description": "Compact diagnostic workflow draft, with credential fields withheld and projected inputs bounded." + }, + "InspectWorkflowResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/WorkflowInspection" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Workflow inspection response", + "description": "A bounded diagnostic draft view, not an editable graph.", + "examples": [ + { + "data": { + "representation": "diagnostic", + "workflowId": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", + "workspaceId": "a91c4b2e-6d3f-4e8a-b5c7-0d9e2f1a8c64", + "blocks": [], + "edges": [], + "truncated": false, + "notes": [] + } + } + ] + }, "WorkflowBlock": { "type": "object", "properties": { @@ -6515,7 +6863,7 @@ "required": ["blocks", "edges", "loops", "parallels", "variables"], "additionalProperties": false, "title": "Workflow graph", - "description": "The editable draft graph of a workflow: blocks, edges, derived loop and parallel containers, and variables." + "description": "The editable draft graph of a workflow: preserves block IDs, credential references, table bindings, variables, and configuration for an in-place read-modify-write cycle. Unlike export, this is private workspace state, not a sanitized sharing format. Keep existing IDs and bindings; inspect state replace with dryRun=true before saving." }, "WorkflowStateResponse": { "type": "object", @@ -6544,6 +6892,126 @@ "WorkflowLintReport": { "type": "object", "properties": { + "checks": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "enum": [ + "graph", + "fields", + "block-output-references", + "branch-output-references", + "embedded-code-syntax", + "credential-resource-references", + "agent-tool-references", + "table-fields", + "runtime-execution" + ], + "description": "Validation pass." + }, + "status": { + "type": "string", + "enum": ["complete", "partial", "skipped"], + "description": "Whether this pass checked its full stated scope, a subset, or nothing. This never certifies runtime success." + }, + "detail": { + "type": "string", + "description": "Checks performed and limitations, including lookup failures and unsupported code languages." + } + }, + "required": ["name", "status", "detail"], + "additionalProperties": false + }, + "description": "Explicit validation coverage. Empty findings do not mean skipped checks passed; no code or external action is executed." + }, + "codeIssues": { + "type": "array", + "items": { + "type": "object", + "properties": { + "blockId": { + "type": "string", + "description": "Block the finding is about." + }, + "blockName": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Display name of the block, when it has one." + }, + "blockType": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Registered type of the block, when it has one." + }, + "field": { + "type": "string", + "description": "Embedded code field." + }, + "language": { + "type": "string", + "const": "javascript", + "description": "Language parsed without execution." + }, + "message": { + "type": "string", + "description": "Syntax error; code and secret values are not included." + }, + "line": { + "anyOf": [ + { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "One-based source line when known." + }, + "column": { + "anyOf": [ + { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740991 + }, + { + "type": "null" + } + ], + "description": "One-based source column when known." + } + }, + "required": [ + "blockId", + "blockName", + "blockType", + "field", + "language", + "message", + "line", + "column" + ], + "additionalProperties": false + }, + "description": "Syntax errors in enabled JavaScript Function bodies, including invalid regular expression flags. Python, Shell, generated source, dependencies, and resolved runtime values are not checked; inspect checks for scope." + }, "sources": { "type": "array", "items": { @@ -7006,6 +7474,8 @@ } }, "required": [ + "checks", + "codeIssues", "sources", "sinks", "orphanBlocks", @@ -7039,6 +7509,54 @@ "type": "boolean", "description": "Whether the live deployment differs from the draft. A graph write never changes what the deployed endpoint serves; deploy to publish it. On a dry run, this describes the state before the proposed write." }, + "removedBindings": { + "type": "array", + "items": { + "type": "object", + "properties": { + "blockId": { + "type": "string", + "description": "Original block whose binding is removed." + }, + "blockName": { + "type": "string", + "description": "Original block display name." + }, + "field": { + "type": "string", + "description": "Original binding field." + }, + "valuePath": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + } + ] + }, + "description": "Nested location inside the field value." + }, + "kind": { + "type": "string", + "enum": ["credential", "table"], + "description": "Kind of removed binding reference." + }, + "resourceId": { + "type": "string", + "description": "Non-secret identifier of the reference no longer present in this block. Never a credential secret value." + } + }, + "required": ["blockId", "blockName", "field", "valuePath", "kind", "resourceId"], + "additionalProperties": false + }, + "description": "Credential/table references removed relative to the saved graph, including removed blocks and changed IDs. Inspect this pre-save diff with dryRun=true. An empty list does not validate other resource bindings." + }, "lint": { "$ref": "#/components/schemas/WorkflowLintReport" }, @@ -7047,7 +7565,7 @@ "description": "Whether this request only validated. `true` means nothing was persisted; the findings describe what a committed write of the same body would produce." } }, - "required": ["id", "warnings", "needsRedeployment", "lint", "dryRun"], + "required": ["id", "warnings", "needsRedeployment", "removedBindings", "lint", "dryRun"], "additionalProperties": false, "title": "Replace workflow state result", "description": "Outcome of replacing a workflow draft graph, with its advisory findings." @@ -7071,7 +7589,10 @@ "warnings": [], "needsRedeployment": true, "dryRun": false, + "removedBindings": [], "lint": { + "checks": [], + "codeIssues": [], "sources": [], "sinks": [], "orphanBlocks": [], @@ -7748,6 +8269,8 @@ "triage": "a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77" }, "lint": { + "checks": [], + "codeIssues": [], "sources": [], "sinks": [], "orphanBlocks": [], @@ -8407,13 +8930,13 @@ "type": "object", "properties": { "operations": { - "minItems": 1, + "default": [], + "description": "Edits to apply in a single batch. May be omitted for enablement-only requests.", "maxItems": 200, "type": "array", "items": { "$ref": "#/components/schemas/WorkflowEditOperation" - }, - "description": "Edits to apply, in a single batch." + } }, "atomic": { "default": false, @@ -8448,7 +8971,6 @@ } } }, - "required": ["operations"], "additionalProperties": false, "title": "Apply workflow operations request", "description": "A batch of semantic edits against a workflow graph.", @@ -10380,6 +10902,18 @@ "additionalProperties": true, "description": "Secret-sanitized workflow graph, edges, loops, parallels, metadata, and variables." }, + "representation": { + "type": "string", + "const": "portable-export", + "description": "Sanitized copy format, not editable workflow state. Use workflows state get for in-place editing." + }, + "warnings": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Export limitations and instructions for preserving IDs and binding references while editing an existing workflow." + }, "referenceManifest": { "description": "Versioned non-secret identifiers and registered source field occurrences for mapped import.", "type": "object", @@ -10494,7 +11028,7 @@ "additionalProperties": false } }, - "required": ["version", "exportedAt", "workflow", "state"], + "required": ["version", "exportedAt", "workflow", "state", "representation", "warnings"], "additionalProperties": false, "title": "Workflow export payload", "description": "Portable, secret-sanitized workflow export. Workspace-scoped bindings must be selected again after import." @@ -10515,6 +11049,10 @@ { "data": { "version": "1.0", + "representation": "portable-export", + "warnings": [ + "Portable exports clear credential bindings. Use workflow state for in-place edits." + ], "exportedAt": "2026-08-09T18:04:11.000Z", "workflow": { "id": "3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36", @@ -11846,6 +12384,25 @@ "type": "string", "const": "deployment", "description": "Execute the active deployed workflow state." + }, + "entry": { + "description": "Optional explicit deployed trigger. Otherwise preserve the existing API entry priority, or select the sole runnable trigger when no API entry exists. Multiple non-API entries require an explicit choice.", + "type": "object", + "properties": { + "type": { + "type": "string", + "const": "trigger", + "description": "Enter through an enabled trigger in the active deployment." + }, + "blockId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "Enabled trigger block in the active deployment. Omit entry to preserve the default API-compatible trigger, or use its sole runnable trigger when it has no API entry." + } + }, + "required": ["type", "blockId"], + "additionalProperties": false } }, "required": ["source"], @@ -11913,6 +12470,12 @@ } ] }, + "stopAfterBlockId": { + "description": "Stop scheduling after this enabled top-level block completes (or all iterations of a loop/parallel container). Real execution: earlier and concurrent branches can still perform side effects; if a condition bypasses this block, the run can finish without stopping here. Applies to this invocation only; a later explicit resume does not inherit this limit. Does not change the saved graph. Use selectedOutputs to return formatter results. Incompatible with async.", + "type": "string", + "minLength": 1, + "maxLength": 128 + }, "async": { "default": false, "description": "Queue the run and return a 202 receipt when true. Requires an OAuth access token or API key, cannot be combined with `stream`, and rejects all streaming and output-shaping options (`selectedOutputs`, `includeThinking`, `includeToolCalls`, `includeFileBase64`, `base64MaxBytes`).", @@ -11997,6 +12560,134 @@ } ] }, + "WorkflowRunFromBlockPreview": { + "type": "object", + "properties": { + "workflowId": { + "type": "string", + "minLength": 1, + "description": "Unique workflow identifier.", + "examples": ["3b1f7c92-8d4e-4a6b-9c0d-5e2f8a714b36"] + }, + "sourceRunId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "pattern": "^[A-Za-z0-9._:-]+$", + "description": "Unique workflow run identifier.", + "examples": ["run_8f14e45f-ceea-467f-a"] + }, + "startBlockId": { + "type": "string", + "description": "Requested block at which a later manual run would start." + }, + "validation": { + "type": "object", + "properties": { + "valid": { + "type": "boolean", + "description": "Whether the executor accepts this starting block and source state." + }, + "error": { + "description": "Executor entry-validation failure, when invalid.", + "type": "string" + } + }, + "required": ["valid"], + "additionalProperties": false, + "description": "Entry validation only; does not validate credentials, provider inputs, or runtime behavior." + }, + "rerunBlocks": { + "type": "array", + "items": { + "type": "object", + "properties": { + "blockId": { + "type": "string", + "description": "Saved workflow block ID; internal sentinel nodes are omitted." + }, + "name": { + "type": "string", + "description": "Current saved block name." + }, + "type": { + "type": "string", + "description": "Current saved block type." + }, + "executedInSource": { + "type": "boolean", + "description": "The source snapshot marks this block or one of its runtime instances as executed." + } + }, + "required": ["blockId", "name", "type", "executedInSource"], + "additionalProperties": false + }, + "description": "Starting block and downstream graph candidates. Conditions and runtime behavior determine actual execution; this is not execution order." + }, + "upstreamBlocks": { + "type": "array", + "items": { + "type": "object", + "properties": { + "blockId": { + "type": "string", + "description": "Saved workflow block ID; internal sentinel nodes are omitted." + }, + "name": { + "type": "string", + "description": "Current saved block name." + }, + "type": { + "type": "string", + "description": "Current saved block type." + }, + "executedInSource": { + "type": "boolean", + "description": "The source snapshot marks this block or one of its runtime instances as executed." + }, + "hasCachedOutput": { + "type": "boolean", + "description": "The source snapshot contains an output entry for this block or a runtime instance. Does not verify referenced files or external resources; output values are not returned." + } + }, + "required": ["blockId", "name", "type", "executedInSource", "hasCachedOutput"], + "additionalProperties": false + }, + "description": "Upstream blocks, including sibling branches needed by downstream candidates, whose existing outputs may be reused." + }, + "notes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Limits of the preview and reuse of previously recorded outputs." + } + }, + "required": [ + "workflowId", + "sourceRunId", + "startBlockId", + "validation", + "rerunBlocks", + "upstreamBlocks", + "notes" + ], + "additionalProperties": false, + "title": "Partial workflow run preview" + }, + "PreviewWorkflowRunFromBlockResponse": { + "type": "object", + "properties": { + "data": { + "description": "Response data.", + "$ref": "#/components/schemas/WorkflowRunFromBlockPreview" + } + }, + "required": ["data"], + "additionalProperties": false, + "title": "Partial run preview response", + "description": "Current draft graph candidates and source snapshot availability; no blocks are executed." + }, "WorkflowRunListItem": { "type": "object", "properties": { diff --git a/apps/docs/package.json b/apps/docs/package.json index 5e9b39d8a81..ac76c05b669 100644 --- a/apps/docs/package.json +++ b/apps/docs/package.json @@ -28,7 +28,7 @@ "fumadocs-mdx": "14.3.2", "fumadocs-openapi": "10.8.1", "fumadocs-ui": "16.8.5", - "next": "16.3.4", + "next": "16.3.6", "next-themes": "^0.4.6", "react": "19.2.4", "react-dom": "19.2.4", diff --git a/apps/sim/app/(landing)/components/footer/footer.tsx b/apps/sim/app/(landing)/components/footer/footer.tsx index 4d8d7fae2bc..7aa648b0d56 100644 --- a/apps/sim/app/(landing)/components/footer/footer.tsx +++ b/apps/sim/app/(landing)/components/footer/footer.tsx @@ -66,7 +66,7 @@ const PRODUCT_LINKS: FooterItem[] = [ { label: 'Tables', href: '/tables' }, { label: 'Files', href: '/files' }, { label: 'Logs', href: '/logs' }, - { label: 'MCP', href: 'https://docs.sim.ai/agents/mcp', external: true }, + { label: 'MCP', href: 'https://docs.sim.ai/mcp', external: true }, { label: 'API', href: 'https://docs.sim.ai/api-reference/getting-started', external: true }, { label: 'CLI', href: 'https://docs.sim.ai/cli', external: true }, { label: 'Self Hosting', href: 'https://docs.sim.ai/platform/self-hosting', external: true }, diff --git a/apps/sim/app/api/v2/credentials/[credentialId]/route.test.ts b/apps/sim/app/api/v2/credentials/[credentialId]/route.test.ts index 74ef186d814..faf72483727 100644 --- a/apps/sim/app/api/v2/credentials/[credentialId]/route.test.ts +++ b/apps/sim/app/api/v2/credentials/[credentialId]/route.test.ts @@ -9,6 +9,7 @@ import { NextRequest } from 'next/server' import { beforeEach, describe, expect, it, vi } from 'vitest' const mocks = vi.hoisted(() => ({ + inspect: vi.fn(), update: vi.fn(), remove: vi.fn(), })) @@ -23,7 +24,11 @@ vi.mock('@/lib/credentials/application/service-account', () => ({ })) import { CredentialProviderOperationError } from '@/lib/credentials/application/credential-crud' -import { PATCH } from '@/app/api/v2/credentials/[credentialId]/route' +import { GET, PATCH } from '@/app/api/v2/credentials/[credentialId]/route' + +vi.mock('@/lib/credentials/application/inspect-credential', () => ({ + inspectCredential: { operation: { id: 'credentials.inspect' }, execute: mocks.inspect }, +})) vi.mock('@/lib/credentials/application/credential-crud', async () => { const { OrchestrationError: BaseError } = await import('@/lib/core/orchestration/types') @@ -170,3 +175,46 @@ describe('PATCH /api/v2/credentials/[credentialId]', () => { }) }) }) + +describe('GET /api/v2/credentials/[credentialId]', () => { + beforeEach(() => { + v2RouteMocks.authenticate.mockResolvedValue(auth) + v2RouteMocks.preauthRate.mockResolvedValue(V2_PREAUTH_RATE_LIMIT_ALLOWED) + v2RouteMocks.operationRate.mockResolvedValue(V2_OPERATION_RATE_LIMIT_ALLOWED) + mocks.inspect.mockResolvedValue({ + credential, + access: { isAdmin: false }, + diagnostics: { + identity: { + source: 'unknown', + subjectId: null, + tenantId: null, + externalAccountId: null, + verifiedLive: false, + }, + scopes: { source: 'unknown', values: [] }, + notes: ['Stored metadata only'], + }, + }) + }) + + function request() { + return new NextRequest( + `http://localhost:3000/api/v2/credentials/${CREDENTIAL_ID}?workspaceId=${WORKSPACE_ID}` + ) + } + + it('projects diagnostic metadata without encrypted or raw secret fields', async () => { + const response = await GET(request(), context) + expect(response.status).toBe(200) + expect(response.headers.get('Cache-Control')).toBe('private, no-store') + const text = await response.text() + expect(text).not.toContain('MUST_NOT_LEAK_CIPHERTEXT') + expect(text).not.toContain('encryptedServiceAccountKey') + expect(JSON.parse(text).data).toMatchObject({ + id: CREDENTIAL_ID, + role: 'member', + diagnostics: { scopes: { source: 'unknown', values: [] } }, + }) + }) +}) diff --git a/apps/sim/app/api/v2/credentials/[credentialId]/route.ts b/apps/sim/app/api/v2/credentials/[credentialId]/route.ts index b0b6a05895e..361d7629817 100644 --- a/apps/sim/app/api/v2/credentials/[credentialId]/route.ts +++ b/apps/sim/app/api/v2/credentials/[credentialId]/route.ts @@ -1,5 +1,6 @@ import { v2DeleteCredentialContract, + v2GetCredentialContract, v2UpdateCredentialContract, } from '@/lib/api/contracts/v2/credentials' import { @@ -12,6 +13,7 @@ import { CredentialProviderOperationError, updateWorkspaceCredentialUseCase, } from '@/lib/credentials/application/credential-crud' +import { inspectCredential } from '@/lib/credentials/application/inspect-credential' import { credentialOperations } from '@/lib/credentials/application/operations' import { toV2Credential } from '@/lib/credentials/application/presentation' import { deleteCredentialUseCase } from '@/lib/credentials/application/service-account' @@ -47,6 +49,29 @@ const credentialErrorPolicy = createV2ResourceConcealmentPolicy({ render: (error) => renderCredentialProviderError(error) ?? v2CaughtOrchestrationError(error), }) +export const GET = defineV2JsonRoute({ + contract: v2GetCredentialContract, + auth: v2ApiKeyAuth, + operation: credentialOperations.inspect, + rateLimit: v2RateLimits.publicApi, + errorPolicy: credentialErrorPolicy, + mapInput: ({ params, query }) => ({ + credentialId: params.credentialId, + assertedWorkspaceId: query.workspaceId, + }), + useCase: inspectCredential, + present: ({ credential, access, diagnostics }) => ({ + data: { + ...toV2Credential({ + ...credential, + hasServiceAccountKey: Boolean(credential.encryptedServiceAccountKey), + role: access.isAdmin ? 'admin' : 'member', + }), + diagnostics, + }, + }), +}) + /** * PATCH /api/v2/credentials/[credentialId] — Rotate secret material or rename. * diff --git a/apps/sim/app/api/v2/lib/catalog.ts b/apps/sim/app/api/v2/lib/catalog.ts index 9ff186b130d..ed857e39aa6 100644 --- a/apps/sim/app/api/v2/lib/catalog.ts +++ b/apps/sim/app/api/v2/lib/catalog.ts @@ -1,4 +1,6 @@ import { createV2ResourceConcealmentPolicy } from '@/lib/api/server/routes' +import { ToolExecutionUsageLimitError } from '@/lib/tool-execution/application/errors' +import { v2CaughtOrchestrationError, v2Error } from '@/app/api/v2/lib/response' /** * The error policy every catalog route shares. @@ -9,4 +11,10 @@ import { createV2ResourceConcealmentPolicy } from '@/lib/api/server/routes' */ export const catalogErrorPolicy = createV2ResourceConcealmentPolicy({ notFoundMessage: 'Workspace not found', + render(error) { + if (error instanceof ToolExecutionUsageLimitError) { + return v2Error('USAGE_LIMIT_EXCEEDED', error.message) + } + return v2CaughtOrchestrationError(error) + }, }) diff --git a/apps/sim/app/api/v2/lib/workflow-lint.ts b/apps/sim/app/api/v2/lib/workflow-lint.ts index ff6b514adb7..2fb7e3c9bea 100644 --- a/apps/sim/app/api/v2/lib/workflow-lint.ts +++ b/apps/sim/app/api/v2/lib/workflow-lint.ts @@ -20,6 +20,15 @@ function blockRef(ref: WorkflowLintBlockRef) { */ export function presentWorkflowLint(lint: WorkflowLintReport) { return { + checks: lint.checks, + codeIssues: lint.codeIssues.map((issue) => ({ + ...blockRef(issue), + field: issue.field, + language: issue.language, + message: issue.message, + line: issue.line ?? null, + column: issue.column ?? null, + })), sources: lint.sources.map(blockRef), sinks: lint.sinks.map(blockRef), orphanBlocks: lint.orphanBlocks.map(blockRef), 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 1bd2e63b9a2..bad5dd64acc 100644 --- a/apps/sim/app/api/v2/logs/[runId]/route.test.ts +++ b/apps/sim/app/api/v2/logs/[runId]/route.test.ts @@ -99,7 +99,7 @@ describe('GET /api/v2/logs/[runId]', () => { expect(body.data).not.toHaveProperty('executionData') expect(mocks.execute).toHaveBeenCalledWith({ principal: auth.principal, - input: { runId: 'run-1' }, + input: { runId: 'run-1', includeWorkflowState: true }, request, }) }) diff --git a/apps/sim/app/api/v2/logs/[runId]/route.ts b/apps/sim/app/api/v2/logs/[runId]/route.ts index af541aa72e9..4b848dca1c8 100644 --- a/apps/sim/app/api/v2/logs/[runId]/route.ts +++ b/apps/sim/app/api/v2/logs/[runId]/route.ts @@ -36,7 +36,10 @@ export const GET = defineV2JsonRoute({ operation: logOperations.readDetail, rateLimit: v2RateLimits.publicApi, errorPolicy: v2LogErrorPolicies.concealDetailAuthorization, - mapInput: ({ params }) => ({ runId: params.runId }), + mapInput: ({ params, query }) => ({ + runId: params.runId, + includeWorkflowState: query.includeWorkflowState, + }), useCase: getPublicLog, present: ({ log, workflowFolderPath, executionData, costLedger }) => { const detail: V2LogDetail = { diff --git a/apps/sim/app/api/v2/tools/[toolId]/execute/route.test.ts b/apps/sim/app/api/v2/tools/[toolId]/execute/route.test.ts index c3cd3203b75..2cd0d2f6ec1 100644 --- a/apps/sim/app/api/v2/tools/[toolId]/execute/route.test.ts +++ b/apps/sim/app/api/v2/tools/[toolId]/execute/route.test.ts @@ -16,6 +16,7 @@ vi.mock('@/lib/tool-execution/application/execute-tool', () => ({ executeToolForCaller: { operation: { id: 'tools.execute' }, execute: mocks.execute }, })) +import { ToolExecutionUsageLimitError } from '@/lib/tool-execution/application/errors' import { POST } from '@/app/api/v2/tools/[toolId]/execute/route' const WORKSPACE_ID = '11111111-2222-4333-8444-555555555555' @@ -76,6 +77,21 @@ describe('POST /api/v2/tools/{toolId}/execute', () => { expect(body.data.error.message).toBe('Firecrawl returned 402') }) + it('reports Function usage admission denial as 402 before any execution result', async () => { + mocks.execute.mockRejectedValue( + new ToolExecutionUsageLimitError('Organization usage limit exceeded') + ) + const response = await post( + { workspaceId: WORKSPACE_ID, input: { code: 'return 1' } }, + 'function_execute' + ) + expect(response.status).toBe(402) + expect(await response.json()).toMatchObject({ + error: { code: 'USAGE_LIMIT_EXCEEDED', message: 'Organization usage limit exceeded' }, + }) + expect(response.headers.has('Retry-After')).toBe(false) + }) + it('rejects a timeout beyond the ceiling', async () => { const response = await post({ workspaceId: WORKSPACE_ID, timeoutSeconds: 100_000 }) diff --git a/apps/sim/app/api/v2/tools/files/download/route.test.ts b/apps/sim/app/api/v2/tools/files/download/route.test.ts new file mode 100644 index 00000000000..623ec42ea7f --- /dev/null +++ b/apps/sim/app/api/v2/tools/files/download/route.test.ts @@ -0,0 +1,173 @@ +import { Readable } from 'node:stream' +import { + MockV2ApiKeyUnauthenticatedError, + V2_OPERATION_RATE_LIMIT_ALLOWED, + V2_PREAUTH_RATE_LIMIT_ALLOWED, + v2ApiKeyAuthModuleMock, + v2RateLimiterModuleMock, + v2RouteMocks, +} from '@sim/testing' +import { NextRequest } from 'next/server' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const mocks = vi.hoisted(() => ({ + workspace: vi.fn(), + metadata: vi.fn(), + permission: vi.fn(), + download: vi.fn(), + audit: vi.fn(), +})) +vi.mock('@/lib/api/server/routes/v2-api-key-auth', () => v2ApiKeyAuthModuleMock) +vi.mock('@/lib/core/rate-limiter', () => v2RateLimiterModuleMock) +vi.mock('@/lib/workspaces/application/workspace-context', () => ({ + loadActiveWorkspaceApplicationContext: mocks.workspace, +})) +vi.mock('@/lib/uploads/server/metadata', () => ({ getFileMetadataByKey: mocks.metadata })) +vi.mock('@/lib/uploads/core/storage-service', () => ({ downloadFileStream: mocks.download })) +vi.mock('@sim/platform-authz/workspace', () => ({ + resolveEffectiveWorkspacePermission: mocks.permission, + permissionSatisfies: (actual: string | null) => actual !== null, +})) +vi.mock('@sim/audit', () => ({ + AuditAction: { FILE_DOWNLOADED: 'file_downloaded' }, + AuditResourceType: { FILE: 'file' }, + recordAudit: mocks.audit, +})) + +import { GET } from '@/app/api/v2/tools/files/download/route' + +const FILE_ID = 'copilot/file-1/report.pdf' +const principal = { kind: 'personal_api_key' as const, userId: 'user-1', keyId: 'key-1' } +const auth = { + principal, + rateLimitSubjectIds: ['api-key:key-1'], + rateLimitSubscription: null, + keyType: 'personal' as const, +} +const file = { + id: 'metadata-1', + key: FILE_ID, + context: 'copilot', + originalName: 'report.pdf', + contentType: 'application/pdf', + sizeBytes: 3, + userId: 'user-1', + workspaceId: null, + organizationId: null, + deletedAt: null, +} +function request(query: Record = {}, method = 'GET') { + const params = new URLSearchParams({ workspaceId: 'workspace-1', fileId: FILE_ID, ...query }) + return new NextRequest(`http://localhost/api/v2/tools/files/download?${params}`, { method }) +} + +describe('authenticated direct tool file download', () => { + beforeEach(() => { + v2RouteMocks.authenticate.mockResolvedValue(auth) + v2RouteMocks.preauthRate.mockResolvedValue(V2_PREAUTH_RATE_LIMIT_ALLOWED) + v2RouteMocks.operationRate.mockResolvedValue(V2_OPERATION_RATE_LIMIT_ALLOWED) + mocks.workspace.mockResolvedValue({ + workspaceId: 'workspace-1', + workspaceOrganizationId: null, + allowPersonalApiKeys: true, + billedAccountUserId: 'billing-owner', + }) + mocks.permission.mockResolvedValue('read') + mocks.metadata.mockResolvedValue(file) + mocks.download.mockResolvedValue(Readable.from([Buffer.from('pdf')])) + }) + + it('streams canonical owner bytes through the real application authorization and audits the download', async () => { + const response = await GET(request()) + expect(response.status).toBe(200) + expect(await response.text()).toBe('pdf') + expect(response.headers.get('content-type')).toBe('application/pdf') + expect(response.headers.get('content-length')).toBe('3') + expect(response.headers.get('content-disposition')).toContain('report.pdf') + expect(response.headers.get('cache-control')).toBe('private, no-store') + expect(response.headers.get('x-content-type-options')).toBe('nosniff') + expect(mocks.metadata).toHaveBeenCalledWith(FILE_ID, 'copilot') + expect(mocks.download).toHaveBeenCalledWith({ key: file.key, context: 'copilot' }) + expect(mocks.audit).toHaveBeenCalledOnce() + }) + + it.each([ + { userId: 'another-user' }, + { userId: 'billing-owner' }, + { workspaceId: 'another-workspace' }, + { organizationId: 'another-org' }, + { context: 'execution' }, + { deletedAt: new Date() }, + ])('conceals unowned, scoped or deleted metadata: %j', async (overrides) => { + mocks.metadata.mockResolvedValue({ ...file, ...overrides }) + const response = await GET(request()) + expect(response.status).toBe(404) + expect((await response.json()).error.message).toBe('File not found') + expect(mocks.download).not.toHaveBeenCalled() + expect(mocks.audit).not.toHaveBeenCalled() + }) + + it.each(['execution/ws/wf/run/file', 'workspace/ws/file', 'https://example.com/file'])( + 'refuses unsupported descriptor %s', + async (fileId) => { + expect((await GET(request({ fileId }))).status).toBe(404) + expect(mocks.metadata).not.toHaveBeenCalled() + expect(mocks.download).not.toHaveBeenCalled() + } + ) + + it('conceals revoked workspace access even for the file owner', async () => { + mocks.permission.mockResolvedValue(null) + expect((await GET(request())).status).toBe(404) + expect(mocks.download).not.toHaveBeenCalled() + }) + + it('refuses a workspace key before metadata loading', async () => { + v2RouteMocks.authenticate.mockResolvedValue({ + ...auth, + principal: { kind: 'workspace_api_key', workspaceId: 'workspace-1', keyId: 'key-1' }, + keyType: 'workspace', + }) + const response = await GET(request()) + expect(response.status).toBe(403) + expect((await response.json()).error.details.code).toBe('WORKSPACE_KEY_OPERATION_NOT_PERMITTED') + expect(mocks.metadata).not.toHaveBeenCalled() + }) + + it('authenticates before resolving descriptors', async () => { + v2RouteMocks.authenticate.mockRejectedValue(new MockV2ApiKeyUnauthenticatedError()) + expect((await GET(request())).status).toBe(401) + expect(mocks.metadata).not.toHaveBeenCalled() + }) + + it('does not accept descriptor claims as authority', async () => { + expect( + (await GET(request({ userId: 'another-user', url: 'https://example.com' }))).status + ).toBe(400) + expect(mocks.metadata).not.toHaveBeenCalled() + }) + + it('authorizes HEAD without streaming bytes or recording a download', async () => { + const response = await GET(request({}, 'HEAD')) + expect(response.status).toBe(200) + expect(await response.text()).toBe('') + expect(mocks.metadata).toHaveBeenCalledOnce() + expect(mocks.download).not.toHaveBeenCalled() + expect(mocks.audit).not.toHaveBeenCalled() + }) + + it.each(['NoSuchKey', 'BlobNotFound', 'NotFound'])( + 'reports expired storage (%s) as not found', + async (name) => { + mocks.download.mockRejectedValue(Object.assign(new Error('expired'), { name })) + expect((await GET(request())).status).toBe(404) + expect(mocks.audit).not.toHaveBeenCalled() + } + ) + + it('keeps infrastructure failures distinct from absent files', async () => { + mocks.download.mockRejectedValue(new Error('storage unavailable')) + expect((await GET(request())).status).toBe(500) + expect(mocks.audit).not.toHaveBeenCalled() + }) +}) diff --git a/apps/sim/app/api/v2/tools/files/download/route.ts b/apps/sim/app/api/v2/tools/files/download/route.ts new file mode 100644 index 00000000000..41f8cd3ae3b --- /dev/null +++ b/apps/sim/app/api/v2/tools/files/download/route.ts @@ -0,0 +1,31 @@ +import { v2DownloadToolFileContract } from '@/lib/api/contracts/v2/tool-files' +import { + createV2ResourceConcealmentPolicy, + defineV2BinaryRoute, + v2ApiKeyAuth, + v2RateLimits, +} from '@/lib/api/server/routes' +import { downloadToolFile } from '@/lib/tool-execution/application/download-tool-file' +import { toolExecutionOperations } from '@/lib/tool-execution/application/operations' +import { encodeFilenameForHeader } from '@/app/api/files/utils' + +export const dynamic = 'force-dynamic' +export const revalidate = 0 + +export const GET = defineV2BinaryRoute({ + contract: v2DownloadToolFileContract, + auth: v2ApiKeyAuth, + operation: toolExecutionOperations.downloadFile, + rateLimit: v2RateLimits.publicApi, + errorPolicy: createV2ResourceConcealmentPolicy({ notFoundMessage: 'File not found' }), + headSafe: false, + mapInput: ({ query }) => query, + useCase: downloadToolFile, + present: ({ file, stream, contentType, contentLength }) => ({ + body: stream, + contentType, + contentLength, + contentDisposition: `attachment; ${encodeFilenameForHeader(file.originalName)}`, + headers: { 'X-Content-Type-Options': 'nosniff' }, + }), +}) 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 32a5eda9b59..be76cbe6ed5 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 @@ -1,4 +1,5 @@ import { + createBlock, createMockRequest, dbChainMockFns, executionPreprocessingMock, @@ -30,6 +31,7 @@ const { mockReleaseExecutionIdClaim, mockReleaseExecutionSlot, mockValidatePublicApiAllowed, + mockValidateStopAfterBlock, } = vi.hoisted(() => ({ MockV2ApiKeyUnauthenticatedError: class MockV2ApiKeyUnauthenticatedError extends Error {}, mockAdmissionRelease: vi.fn(), @@ -46,6 +48,7 @@ const { mockReleaseExecutionIdClaim: vi.fn(), mockReleaseExecutionSlot: vi.fn(), mockValidatePublicApiAllowed: vi.fn(), + mockValidateStopAfterBlock: vi.fn(), })) vi.mock('@/lib/core/admission/gate', () => ({ @@ -91,7 +94,13 @@ vi.mock('@/ee/access-control/utils/permission-check', () => ({ vi.mock('@/lib/workflows/utils', () => workflowsUtilsMock) vi.mock('@/lib/execution/preprocessing', () => executionPreprocessingMock) -vi.mock('@/lib/workflows/persistence/utils', () => workflowsPersistenceUtilsMock) +vi.mock('@/lib/workflows/persistence/utils', () => ({ + ...workflowsPersistenceUtilsMock, + NoActiveDeploymentError: class NoActiveDeploymentError extends Error {}, +})) +vi.mock('@/lib/workflows/executor/stop-after-block', () => ({ + validateStopAfterBlock: mockValidateStopAfterBlock, +})) vi.mock('@/lib/logs/execution/logging-session', () => loggingSessionMock) vi.mock('@/lib/workflows/executor/execution-core', () => ({ @@ -170,6 +179,8 @@ import { POST } from './route' const mockPreprocessExecution = executionPreprocessingMockFns.mockPreprocessExecution const mockAuthorize = workflowAuthzMockFns.mockAuthorizeWorkflowByWorkspacePermission const mockLoadDeployedWorkflowState = workflowsPersistenceUtilsMockFns.mockLoadDeployedWorkflowState +const mockLoadWorkflowDeploymentVersionState = + workflowsPersistenceUtilsMockFns.mockLoadWorkflowDeploymentVersionState const mockLoadWorkflowFromNormalizedTables = workflowsPersistenceUtilsMockFns.mockLoadWorkflowFromNormalizedTables @@ -308,13 +319,19 @@ describe('POST /api/v2/workflows/[workflowId]/execute', () => { billingAttribution, executionTimeout: { sync: 60_000, async: 300_000 }, }) - mockLoadDeployedWorkflowState.mockResolvedValue({ - blocks: {}, + const deployedState = { + deploymentVersionId: 'version-1', + blocks: { start: createBlock({ id: 'start', type: 'start_trigger' }) }, edges: [], loops: {}, parallels: {}, variables: {}, - }) + } + mockLoadDeployedWorkflowState.mockResolvedValue(deployedState) + mockLoadWorkflowDeploymentVersionState.mockImplementation(async () => + mockLoadDeployedWorkflowState() + ) + mockValidateStopAfterBlock.mockReset() mockExecuteWorkflowCore.mockResolvedValue({ success: true, output: { result: 'done' }, @@ -773,10 +790,96 @@ describe('POST /api/v2/workflows/[workflowId]/execute', () => { expect(mockPreprocessExecution).not.toHaveBeenCalled() }) + it('resolves Schedule in deployment state and executes the exact admitted version', async () => { + const deployed = { + deploymentVersionId: 'version-schedule', + blocks: { schedule: createBlock({ id: 'schedule', type: 'schedule' }) }, + edges: [], + loops: {}, + parallels: {}, + variables: { origin: 'deployed' }, + } + mockLoadDeployedWorkflowState.mockResolvedValueOnce(deployed) + mockLoadWorkflowDeploymentVersionState.mockResolvedValueOnce(deployed) + const res = await callExecute({ run: { source: 'deployment' } }) + expect(res.status).toBe(200) + expect(mockLoadWorkflowDeploymentVersionState).toHaveBeenCalledWith( + 'workflow-1', + 'version-schedule', + 'workspace-1' + ) + expect(mockLoadWorkflowFromNormalizedTables).not.toHaveBeenCalled() + expect(mockExecuteWorkflowCore.mock.calls[0][0].snapshot.metadata).toMatchObject({ + triggerBlockId: 'schedule', + workflowStateOverride: deployed, + }) + }) + + it('rejects ambiguous deployed triggers before claiming or logging a run', async () => { + mockLoadDeployedWorkflowState.mockResolvedValue({ + deploymentVersionId: 'version-1', + blocks: { + a: createBlock({ id: 'a', type: 'schedule' }), + b: createBlock({ id: 'b', type: 'schedule' }), + }, + }) + const res = await callExecute({ run: { source: 'deployment' } }) + expect(res.status).toBe(400) + expect((await res.json()).error.message).toContain('Set run.entry') + expect(mockClaimExecutionId).not.toHaveBeenCalled() + expect(mockPreprocessExecution).not.toHaveBeenCalled() + expect(mockExecuteWorkflowCore).not.toHaveBeenCalled() + }) + + it('validates a stop target before executing and pins the validated state', async () => { + const res = await callExecute({ stopAfterBlockId: 'start' }) + expect(res.status).toBe(200) + expect(mockValidateStopAfterBlock).toHaveBeenCalledWith( + expect.objectContaining({ blocks: expect.objectContaining({ start: expect.anything() }) }), + 'start', + 'start', + undefined + ) + expect(mockExecuteWorkflowCore).toHaveBeenCalledWith( + expect.objectContaining({ stopAfterBlockId: 'start' }) + ) + expect( + mockExecuteWorkflowCore.mock.calls[0][0].snapshot.metadata.workflowStateOverride + .deploymentVersionId + ).toBe('version-1') + }) + + it('rejects invalid stops without running any blocks', async () => { + mockValidateStopAfterBlock.mockImplementationOnce(() => { + throw new Error('stopAfterBlockId is not reachable') + }) + const res = await callExecute({ stopAfterBlockId: 'detached' }) + expect(res.status).toBe(400) + expect((await res.json()).error.message).toContain('not reachable') + expect(mockExecuteWorkflowCore).not.toHaveBeenCalled() + expect(mockReleaseExecutionSlot).toHaveBeenCalledWith('execution-123') + }) + + it('rejects async stop controls before admission and anonymous controls instead of ignoring them', async () => { + expect((await callExecute({ async: true, stopAfterBlockId: 'start' })).status).toBe(400) + resetDbChainMock() + queuePublicWorkflowReads() + const anonymous = await callPublicExecute({ stopAfterBlockId: 'start' }) + expect(anonymous.status).toBe(401) + expect((await anonymous.json()).error.message).toContain( + 'stopAfterBlockId require an OAuth access token or API key' + ) + expect(mockClaimExecutionId).not.toHaveBeenCalled() + expect(mockPreprocessExecution).not.toHaveBeenCalled() + }) + it('returns blockOutputs for selectedOutputs on a sync request', async () => { const agentBlockId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' mockLoadDeployedWorkflowState.mockResolvedValue({ - blocks: { [agentBlockId]: { id: agentBlockId, name: 'Agent 1' } }, + blocks: { + [agentBlockId]: { id: agentBlockId, name: 'Agent 1' }, + start: createBlock({ id: 'start', type: 'start_trigger' }), + }, edges: [], loops: {}, parallels: {}, @@ -822,7 +925,7 @@ describe('POST /api/v2/workflows/[workflowId]/execute', () => { mockLoadDeployedWorkflowState.mockResolvedValue({ blocks: { [agentBlockId]: { id: agentBlockId, name: 'Agent 1' }, - [startBlockId]: { id: startBlockId, name: 'Start' }, + [startBlockId]: createBlock({ id: startBlockId, name: 'Start', type: 'start_trigger' }), }, edges: [], loops: {}, 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 0bb2bc272a2..154fdf06945 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/execute/route.ts @@ -417,6 +417,22 @@ export const POST = withRouteHandler( const resultStream = !body.async && !body.stream && wantsResultStream(req) + if (body.async && body.stopAfterBlockId) { + return v2Error( + 'BAD_REQUEST', + 'stopAfterBlockId requires synchronous or streamed execution; it cannot be combined with async' + ) + } + if ( + !apiKeyPrincipal && + (body.stopAfterBlockId || (body.run?.source === 'deployment' && body.run.entry)) + ) { + return v2Error( + 'UNAUTHORIZED', + 'Deployment trigger selection and stopAfterBlockId require an OAuth access token or API key' + ) + } + /** Caller-supplied run IDs are a keyed-caller feature; anonymous callers must not probe the claim table. */ let requestedExecutionId: string | undefined const runIdHeader = parsed.data.headers['x-run-id'] @@ -433,6 +449,7 @@ export const POST = withRouteHandler( includeFileBase64: body.includeFileBase64, base64MaxBytes: body.base64MaxBytes, selectedOutputs: body.selectedOutputs, + stopAfterBlockId: body.stopAfterBlockId, abortSignal: req.signal, requestHeaders: req.headers, includeThinking: body.includeThinking, @@ -470,6 +487,8 @@ export const POST = withRouteHandler( ...commonInput, input: body.input ?? {}, requestedTimeoutSeconds: body.executionTimeoutSeconds, + triggerBlockId: + body.run?.source === 'deployment' ? body.run.entry?.blockId : undefined, mode: body.async ? 'async' : body.stream diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/export/route.ts b/apps/sim/app/api/v2/workflows/[workflowId]/export/route.ts index f61178c474f..131e4a013f3 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/export/route.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/export/route.ts @@ -25,9 +25,11 @@ export const GET = defineV2JsonRoute({ includeWorkspaceBindings: query.includeWorkspaceBindings, }), useCase: exportWorkflow, - present: ({ payload, folderPath }) => ({ + present: ({ payload, folderPath, representation, warnings }) => ({ data: { ...payload, + representation, + warnings, workflow: { id: payload.workflow.id, name: payload.workflow.name, diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/inspect/route.ts b/apps/sim/app/api/v2/workflows/[workflowId]/inspect/route.ts new file mode 100644 index 00000000000..9d249bc8398 --- /dev/null +++ b/apps/sim/app/api/v2/workflows/[workflowId]/inspect/route.ts @@ -0,0 +1,20 @@ +import { v2InspectWorkflowContract } from '@/lib/api/contracts/v2/workflow-inspection' +import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/routes' +import { v2WorkflowErrorPolicies } from '@/lib/workflows/api' +import { presentWorkflowInspection } from '@/lib/workflows/api/workflow-inspection' +import { workflowOperations } from '@/lib/workflows/application/operations' +import { readWorkflowGraph } from '@/lib/workflows/application/read-workflow-graph' + +export const dynamic = 'force-dynamic' +export const revalidate = 0 + +export const GET = defineV2JsonRoute({ + contract: v2InspectWorkflowContract, + auth: v2ApiKeyAuth, + operation: workflowOperations.read, + rateLimit: v2RateLimits.publicApi, + errorPolicy: v2WorkflowErrorPolicies.concealWorkflowAuthorization, + mapInput: ({ params }) => ({ workflowId: params.workflowId }), + useCase: readWorkflowGraph, + present: (graph, { query }) => ({ data: presentWorkflowInspection(graph, query) }), +}) diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/operations/route.test.ts b/apps/sim/app/api/v2/workflows/[workflowId]/operations/route.test.ts index 2d4dbd23ac5..a7f752c2610 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/operations/route.test.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/operations/route.test.ts @@ -43,6 +43,8 @@ const DROPPED_INPUT = { /** An empty report, with every field the contract publishes. */ const LINT = { + checks: [], + codeIssues: [], sources: [], sinks: [], orphanBlocks: [], diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/runs/preview/route.ts b/apps/sim/app/api/v2/workflows/[workflowId]/runs/preview/route.ts new file mode 100644 index 00000000000..1a86a1969e8 --- /dev/null +++ b/apps/sim/app/api/v2/workflows/[workflowId]/runs/preview/route.ts @@ -0,0 +1,19 @@ +import { v2PreviewWorkflowRunFromBlockContract } from '@/lib/api/contracts/v2/workflows' +import { defineV2JsonRoute, v2ApiKeyAuth, v2RateLimits } from '@/lib/api/server/routes' +import { v2WorkflowErrorPolicies } from '@/lib/workflows/api' +import { workflowOperations } from '@/lib/workflows/application/operations' +import { previewManualWorkflowFromBlock } from '@/lib/workflows/application/preview-manual-workflow-from-block' + +export const dynamic = 'force-dynamic' +export const revalidate = 0 + +export const GET = defineV2JsonRoute({ + contract: v2PreviewWorkflowRunFromBlockContract, + auth: v2ApiKeyAuth, + operation: workflowOperations.previewManualFromBlock, + rateLimit: v2RateLimits.publicApi, + errorPolicy: v2WorkflowErrorPolicies.concealWorkflowAuthorization, + mapInput: ({ params, query }) => ({ workflowId: params.workflowId, ...query }), + useCase: previewManualWorkflowFromBlock, + present: (data) => ({ data }), +}) diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/state/route.test.ts b/apps/sim/app/api/v2/workflows/[workflowId]/state/route.test.ts index 5828a6e47b0..1f23e2c7e61 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/state/route.test.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/state/route.test.ts @@ -64,6 +64,8 @@ function putRequest(body: unknown) { } const EMPTY_LINT = { + checks: [], + codeIssues: [], sources: [], sinks: [], orphanBlocks: [], @@ -95,6 +97,7 @@ describe('/api/v2/workflows/[workflowId]/state', () => { warnings: ['Dropped edge "edge-9": target block does not exist'], needsRedeployment: true, lint: EMPTY_LINT, + removedBindings: [], dryRun: false, }) }) diff --git a/apps/sim/app/api/v2/workflows/[workflowId]/state/route.ts b/apps/sim/app/api/v2/workflows/[workflowId]/state/route.ts index dd78278a92c..cc51f207100 100644 --- a/apps/sim/app/api/v2/workflows/[workflowId]/state/route.ts +++ b/apps/sim/app/api/v2/workflows/[workflowId]/state/route.ts @@ -65,7 +65,14 @@ export const PUT = defineV2JsonRoute({ variables: body.variables, }), useCase: replaceWorkflowState, - present: ({ workflowId, warnings, needsRedeployment, lint, dryRun }) => ({ - data: { id: workflowId, warnings, needsRedeployment, lint: presentWorkflowLint(lint), dryRun }, + present: ({ workflowId, warnings, removedBindings, needsRedeployment, lint, dryRun }) => ({ + data: { + id: workflowId, + warnings, + removedBindings, + needsRedeployment, + lint: presentWorkflowLint(lint), + dryRun, + }, }), }) diff --git a/apps/sim/background/workflow-execution.ts b/apps/sim/background/workflow-execution.ts index b04e5a0610c..72fe1c6ca2f 100644 --- a/apps/sim/background/workflow-execution.ts +++ b/apps/sim/background/workflow-execution.ts @@ -35,6 +35,7 @@ import { wasExecutionFinalizedByCore, } from '@/lib/workflows/executor/execution-core' import { handlePostExecutionPauseState } from '@/lib/workflows/executor/pause-persistence' +import { loadWorkflowDeploymentVersionState } from '@/lib/workflows/persistence/utils' import { WORKFLOW_EXECUTION_CONCURRENCY_LIMIT } from '@/background/concurrency-limits' import { ExecutionSnapshot } from '@/executor/execution/snapshot' import type { ExecutionMetadata } from '@/executor/execution/types' @@ -72,6 +73,8 @@ export type WorkflowExecutionPayload = { input?: any triggerType?: CoreTriggerType triggerBlockId?: string + /** Trusted immutable deployment selected by the admitting boundary, never a wire input. */ + deploymentVersionId?: string executionId?: string requestId?: string correlation?: AsyncExecutionCorrelation @@ -229,6 +232,13 @@ export async function executeWorkflowJob( logger.info(`[${requestId}] Preprocessing passed. Using actor: ${actorUserId}`) const workflow = preprocessResult.workflowRecord! + const deployedState = payload.deploymentVersionId + ? await loadWorkflowDeploymentVersionState( + workflowId, + payload.deploymentVersionId, + workspaceId + ) + : undefined const metadata: ExecutionMetadata = { requestId, @@ -242,6 +252,7 @@ export async function executeWorkflowJob( workflowUserId: workflow.userId, triggerType: payload.triggerType || 'api', triggerBlockId: payload.triggerBlockId, + workflowStateOverride: deployedState, useDraftState: false, startTime: new Date().toISOString(), isClientSession: false, @@ -256,7 +267,7 @@ export async function executeWorkflowJob( metadata, workflow, payload.input, - workflow.variables || {}, + deployedState ? (deployedState.variables ?? {}) : workflow.variables || {}, [] ) diff --git a/apps/sim/blocks/blocks/file.ts b/apps/sim/blocks/blocks/file.ts index 1bed85d5b5b..44ec56a1e79 100644 --- a/apps/sim/blocks/blocks/file.ts +++ b/apps/sim/blocks/blocks/file.ts @@ -1345,22 +1345,22 @@ export const FileV5Block: BlockConfig = { }, { id: 'writeFolderPath', - title: 'Folder', + title: 'Destination Folder', type: 'folder-selector' as SubBlockType, resourceType: 'file', placeholder: 'Workspace root', canonicalParamId: 'writeFolderRef', mode: 'basic', - condition: { field: 'operation', value: 'file_write' }, + condition: { field: 'operation', value: ['file_write', 'file_compress'] }, }, { id: 'manualWriteFolderPath', - title: 'Folder Path', + title: 'Destination Folder Path', type: 'short-input' as SubBlockType, canonicalParamId: 'writeFolderRef', mode: 'advanced', placeholder: '/Reports/Q3%20Results', - condition: { field: 'operation', value: 'file_write' }, + condition: { field: 'operation', value: ['file_write', 'file_compress'] }, }, { id: 'fileName', @@ -1673,7 +1673,18 @@ export const FileV5Block: BlockConfig = { title: 'Archive Name', type: 'short-input' as SubBlockType, placeholder: 'archive.zip (auto-named from source if omitted)', - condition: { field: 'operation', value: ['file_compress', 'file_compress_folder'] }, + condition: { field: 'operation', value: 'file_compress' }, + }, + { + id: 'archiveOnConflict', + title: 'If Archive Exists', + type: 'dropdown', + options: [ + { label: 'Choose an available name', id: 'rename' }, + { label: 'Fail without overwriting', id: 'error' }, + ], + value: () => 'rename', + condition: { field: 'operation', value: 'file_compress' }, }, { id: 'decompressFile', @@ -2090,6 +2101,8 @@ export const FileV5Block: BlockConfig = { return { ...fileFamilyInput(params, 'compress', params.compressInput), archiveName: optionalText(params.archiveName), + folderPath: optionalText(params.writeFolderRef), + onConflict: optionalText(params.archiveOnConflict), } } @@ -2248,6 +2261,10 @@ export const FileV5Block: BlockConfig = { endAnchor: { type: 'string', description: 'Ending line preserved by an anchored deletion' }, editOccurrence: { type: 'number', description: 'Matching anchor occurrence, starting at 1' }, archiveName: { type: 'string', description: 'Name for the compressed .zip archive' }, + archiveOnConflict: { + type: 'string', + description: 'Archive name collision behavior: rename or error', + }, decompressInput: { type: 'json', description: 'Selected .zip archive or canonical file ID to extract', @@ -2267,7 +2284,7 @@ export const FileV5Block: BlockConfig = { }, writeFolderRef: { type: 'string', - description: 'Folder to create the file in (write)', + description: 'Destination folder for a written file or compressed archive', }, folderRef: { type: 'string', @@ -2415,7 +2432,8 @@ export const FileV5Block: BlockConfig = { }, path: { type: 'string', - description: 'The folder that was listed or deleted (list and delete folder)', + description: + 'Final archive path (compress), or the folder that was listed or deleted (list and delete folder)', }, previousPath: { type: 'string', diff --git a/apps/sim/blocks/blocks/function.ts b/apps/sim/blocks/blocks/function.ts index 36c3e9319ad..a17b99c144d 100644 --- a/apps/sim/blocks/blocks/function.ts +++ b/apps/sim/blocks/blocks/function.ts @@ -17,6 +17,7 @@ export const FunctionBlock: BlockConfig = { - Python code always runs in a remote sandbox. - Shell code runs CLI commands in a remote sandbox. - To import third-party packages or add curated CLI tools, create a sandbox in Settings > Sandboxes and select it under the block's advanced options. Without one, only the default image's packages and commands are available. + - Read permitted workspace secrets with {{NAME}}, for example \`const token = {{SERVICE_API_KEY}};\` in JavaScript. Workspace secrets are not exposed through process.env.NAME. Select secretScope="selected" and mountedSecrets=["SERVICE_API_KEY"] when configuring this block as a tool to restrict secret access. - Can reference workflow variables using syntax as usual within code. Avoid XML/HTML tags. - To read a file from an earlier block, reference its path: mounts the file and resolves to its location on the sandbox filesystem, which any language can open. Use instead when you only want the contents inline in JavaScript. - Anything the code writes to ${SANDBOX_OUTPUT_DIR} is returned as \`files\`, ready to attach to an email or upload without any extra step. @@ -158,7 +159,11 @@ try { access: ['function_execute'], }, inputs: { - code: { type: 'string', description: 'JavaScript, Python, or Shell code to execute' }, + code: { + type: 'string', + description: + 'JavaScript, Python, or Shell code to execute. Read permitted workspace secrets with {{NAME}}, for example const token = {{SERVICE_API_KEY}}; in JavaScript, not process.env.NAME.', + }, language: { type: 'string', description: 'Language (javascript, python, or shell)' }, timeout: { type: 'number', description: 'Execution timeout' }, sandboxId: { diff --git a/apps/sim/blocks/blocks/slack.test.ts b/apps/sim/blocks/blocks/slack.test.ts index ba244f1b057..b8819cdaa86 100644 --- a/apps/sim/blocks/blocks/slack.test.ts +++ b/apps/sim/blocks/blocks/slack.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import { evaluateSubBlockCondition } from '@/lib/workflows/subblocks/visibility' -import { SlackV2Block } from '@/blocks/blocks/slack' +import { SlackBlock, SlackV2Block } from '@/blocks/blocks/slack' function mapSlackV2Params(params: Record): Record { const mapParams = SlackV2Block.tools.config?.params @@ -111,3 +111,33 @@ describe('Slack block release', () => { ) }) }) + +describe.each([SlackBlock, SlackV2Block])('$type channel target visibility', (block) => { + it('keeps both channel inputs visible for a channel-only operation after a DM action', () => { + const operation = 'update' + for (const fieldId of ['channel', 'manualChannel']) { + const field = block.subBlocks.find((candidate) => candidate.id === fieldId) + if (!field) throw new Error(`Missing ${fieldId}`) + expect( + evaluateSubBlockCondition(field.condition, { operation, destinationType: 'dm' }), + fieldId + ).toBe(true) + } + }) + + it.each(['send', 'read', 'schedule_message'])( + 'preserves the channel/DM switch for %s in both modes', + (operation) => { + for (const fieldId of ['channel', 'manualChannel']) { + const field = block.subBlocks.find((candidate) => candidate.id === fieldId) + if (!field) throw new Error(`Missing ${fieldId}`) + for (const destinationType of ['channel', 'dm']) { + expect( + evaluateSubBlockCondition(field.condition, { operation, destinationType }), + `${fieldId} ${destinationType}` + ).toBe(destinationType === 'channel') + } + } + } + ) +}) diff --git a/apps/sim/blocks/blocks/slack.ts b/apps/sim/blocks/blocks/slack.ts index 328db1a7ca9..c2cca68f22c 100644 --- a/apps/sim/blocks/blocks/slack.ts +++ b/apps/sim/blocks/blocks/slack.ts @@ -72,6 +72,31 @@ const MESSAGE_BODY_FIELD = ['text', 'blocks'] as const */ const SLACK_TRIGGER_CHANNEL_FIELD = ['channelFilter', 'manualChannelFilter'] as const +function getSlackChannelCondition(values?: Record) { + if (DESTINATION_SWITCH_OPERATIONS.some((operation) => operation === values?.operation)) { + return { field: 'destinationType', value: 'dm', not: true } + } + return { + field: 'operation', + value: [ + 'list_channels', + 'list_users', + 'get_user', + 'get_user_presence', + 'edit_canvas', + 'get_canvas', + 'lookup_canvas_sections', + 'delete_canvas', + 'create_conversation', + 'open_view', + 'update_view', + 'push_view', + 'publish_view', + ], + not: true, + } +} + export const SlackBlock: BlockConfig = { type: 'slack', name: 'Slack', @@ -467,45 +492,7 @@ export const SlackBlock: BlockConfig = { placeholder: 'Select Slack channel', mode: 'basic', dependsOn: { all: ['authMethod'], any: ['credential', 'botToken', 'customBotCredential'] }, - condition: (values?: Record) => { - const op = values?.operation as string - if (op === 'ephemeral') { - return { field: 'operation', value: 'ephemeral' } - } - /* - * Only the three operations that offer the channel/DM switch defer to - * it. Deferring everywhere left a stale `destinationType: 'dm'` — set - * under `send`, never cleared by an operation change — hiding the - * channel field on operations that have no DM mode at all, so their - * cards silently lost their only clause. - */ - if (DESTINATION_SWITCH_OPERATIONS.includes(op as never)) { - return { - field: 'destinationType', - value: 'dm', - not: true, - } - } - return { - field: 'operation', - value: [ - 'list_channels', - 'list_users', - 'get_user', - 'get_user_presence', - 'edit_canvas', - 'get_canvas', - 'lookup_canvas_sections', - 'delete_canvas', - 'create_conversation', - 'open_view', - 'update_view', - 'push_view', - 'publish_view', - ], - not: true, - } - }, + condition: getSlackChannelCondition, required: { field: 'operation', value: ['list_canvases', 'list_scheduled_messages'], @@ -520,36 +507,7 @@ export const SlackBlock: BlockConfig = { placeholder: 'Enter Slack channel ID (e.g., C1234567890)', dependsOn: { all: ['authMethod'], any: ['credential', 'botToken', 'customBotCredential'] }, mode: 'advanced', - condition: (values?: Record) => { - const op = values?.operation as string - if (op === 'ephemeral') { - return { field: 'operation', value: 'ephemeral' } - } - return { - field: 'operation', - value: [ - 'list_channels', - 'list_users', - 'get_user', - 'get_user_presence', - 'edit_canvas', - 'get_canvas', - 'lookup_canvas_sections', - 'delete_canvas', - 'create_conversation', - 'open_view', - 'update_view', - 'push_view', - 'publish_view', - ], - not: true, - and: { - field: 'destinationType', - value: 'dm', - not: true, - }, - } - }, + condition: getSlackChannelCondition, required: { field: 'operation', value: ['list_canvases', 'list_scheduled_messages'], @@ -634,11 +592,10 @@ export const SlackBlock: BlockConfig = { id: 'text', title: 'Message', type: 'long-input', - placeholder: 'Enter your message (supports Slack mrkdwn)', + placeholder: 'Message text; optional notification and accessibility fallback for Block Kit', condition: { field: 'operation', value: ['send', 'ephemeral', 'schedule_message'], - and: { field: 'messageFormat', value: 'blocks', not: true }, }, required: { field: 'operation', @@ -1159,11 +1116,10 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, id: 'updateText', title: 'New Message Text', type: 'long-input', - placeholder: 'Enter new message text (supports Slack mrkdwn)', + placeholder: 'New text; optional notification and accessibility fallback for Block Kit', condition: { field: 'operation', value: 'update', - and: { field: 'messageFormat', value: 'blocks', not: true }, }, required: { field: 'operation', @@ -1925,7 +1881,6 @@ Return ONLY the integer Unix timestamp - no explanations, no quotes, no extra te destinationType, channel, dmUserId, - messageFormat, text, title, content, @@ -2037,7 +1992,7 @@ Return ONLY the integer Unix timestamp - no explanations, no quotes, no extra te switch (operation) { case 'send': { - baseParams.text = messageFormat === 'blocks' && !text ? ' ' : text + baseParams.text = text if (threadTs) { baseParams.threadTs = threadTs } @@ -2053,7 +2008,7 @@ Return ONLY the integer Unix timestamp - no explanations, no quotes, no extra te } case 'ephemeral': { - baseParams.text = messageFormat === 'blocks' && !text ? ' ' : text + baseParams.text = text baseParams.user = ephemeralUser ? String(ephemeralUser).trim() : '' if (threadTs) { baseParams.threadTs = threadTs @@ -2204,7 +2159,7 @@ Return ONLY the integer Unix timestamp - no explanations, no quotes, no extra te case 'update': baseParams.timestamp = updateTimestamp - baseParams.text = messageFormat === 'blocks' && !updateText ? ' ' : updateText + baseParams.text = updateText if (blocks) { baseParams.blocks = blocks } @@ -2346,7 +2301,7 @@ Return ONLY the integer Unix timestamp - no explanations, no quotes, no extra te break case 'schedule_message': { - baseParams.text = messageFormat === 'blocks' && !text ? ' ' : text + baseParams.text = text if (blocks) { baseParams.blocks = blocks } diff --git a/apps/sim/blocks/blocks/stripe.ts b/apps/sim/blocks/blocks/stripe.ts index 505aed577e1..835cdbc1116 100644 --- a/apps/sim/blocks/blocks/stripe.ts +++ b/apps/sim/blocks/blocks/stripe.ts @@ -1,6 +1,11 @@ import { StripeIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' +import { + parseOptionalBooleanInput, + parseOptionalJsonInput, + parseOptionalNumberInput, +} from '@/blocks/utils' import type { StripeResponse } from '@/tools/stripe/types' import { getTrigger } from '@/triggers' @@ -457,7 +462,7 @@ export const StripeBlock: BlockConfig = { id: 'items', title: 'Items (JSON Array)', type: 'code', - placeholder: '[{"price": "price_1234567890", "quantity": 1}]', + placeholder: '[{"id": "si_1234567890", "price": "price_1234567890", "quantity": 1}]', condition: { field: 'operation', value: ['update_subscription'], @@ -689,6 +694,30 @@ export const StripeBlock: BlockConfig = { }, mode: 'advanced', }, + { + id: 'starting_after', + title: 'Starting After', + type: 'short-input', + placeholder: 'Last subscription ID from the previous page', + condition: { field: 'operation', value: 'list_subscriptions' }, + mode: 'advanced', + }, + { + id: 'ending_before', + title: 'Ending Before', + type: 'short-input', + placeholder: 'First subscription ID from the current page', + condition: { field: 'operation', value: 'list_subscriptions' }, + mode: 'advanced', + }, + { + id: 'page', + title: 'Search Page', + type: 'short-input', + placeholder: 'Token from metadata.next_page; omit for the first page', + condition: { field: 'operation', value: 'search_subscriptions' }, + mode: 'advanced', + }, { id: 'query', title: 'Search Query', @@ -874,62 +903,30 @@ export const StripeBlock: BlockConfig = { return `stripe_${params.operation}` }, params: (params) => { - const { - operation, - apiKey, - address, - metadata, - items, - images, - recurring, - cancel_at_period_end, - auto_advance, - capture, - active, - prorate, - invoice_now, - paid_out_of_band, - ...rest - } = params - - // Parse JSON fields - let parsedAddress: any | undefined - let parsedMetadata: any | undefined - let parsedItems: any | undefined - let parsedImages: any | undefined - let parsedRecurring: any | undefined - - try { - if (address) parsedAddress = JSON.parse(address) - if (metadata) parsedMetadata = JSON.parse(metadata) - if (items) parsedItems = JSON.parse(items) - if (images) parsedImages = JSON.parse(images) - if (recurring) parsedRecurring = JSON.parse(recurring) - } catch (error: any) { - throw new Error(`Invalid JSON input: ${error.message}`) - } - - // Convert string booleans to actual booleans - const parsedBooleans: Record = {} - if (cancel_at_period_end !== undefined) - parsedBooleans.cancel_at_period_end = cancel_at_period_end === 'true' - if (auto_advance !== undefined) parsedBooleans.auto_advance = auto_advance === 'true' - if (capture !== undefined) parsedBooleans.capture = capture === 'true' - if (active !== undefined) parsedBooleans.active = active === 'true' - if (prorate !== undefined) parsedBooleans.prorate = prorate === 'true' - if (invoice_now !== undefined) parsedBooleans.invoice_now = invoice_now === 'true' - if (paid_out_of_band !== undefined) - parsedBooleans.paid_out_of_band = paid_out_of_band === 'true' + const { operation, ...rest } = params return { - apiKey, ...rest, - ...(parsedAddress && { address: parsedAddress }), - ...(parsedMetadata && { metadata: parsedMetadata }), - ...(parsedItems && { items: parsedItems }), - ...(parsedImages && { images: parsedImages }), - ...(parsedRecurring && { recurring: parsedRecurring }), - ...parsedBooleans, + ...(operation === 'capture_payment_intent' && { + amount_to_capture: + parseOptionalNumberInput(params.amount_to_capture, 'Amount to capture') ?? + parseOptionalNumberInput(params.amount, 'Amount'), + }), + ...(operation === 'capture_charge' && { + amount: parseOptionalNumberInput(params.amount, 'Amount'), + }), + address: parseOptionalJsonInput(params.address, 'Address'), + metadata: parseOptionalJsonInput(params.metadata, 'Metadata'), + items: parseOptionalJsonInput(params.items, 'Items'), + images: parseOptionalJsonInput(params.images, 'Images'), + recurring: parseOptionalJsonInput(params.recurring, 'Recurring'), + cancel_at_period_end: parseOptionalBooleanInput(params.cancel_at_period_end), + auto_advance: parseOptionalBooleanInput(params.auto_advance), + capture: parseOptionalBooleanInput(params.capture), + active: parseOptionalBooleanInput(params.active), + prorate: parseOptionalBooleanInput(params.prorate), + invoice_now: parseOptionalBooleanInput(params.invoice_now), + paid_out_of_band: parseOptionalBooleanInput(params.paid_out_of_band), } }, }, @@ -976,6 +973,9 @@ export const StripeBlock: BlockConfig = { recurring: { type: 'json', description: 'Recurring billing configuration' }, // List/Search inputs limit: { type: 'number', description: 'Maximum results to return' }, + starting_after: { type: 'string', description: 'Next-page subscription ID cursor' }, + ending_before: { type: 'string', description: 'Previous-page subscription ID cursor' }, + page: { type: 'string', description: 'Subscription search token from metadata.next_page' }, query: { type: 'string', description: 'Search query' }, status: { type: 'string', description: 'Status filter' }, type: { type: 'string', description: 'Event type filter' }, @@ -1100,15 +1100,15 @@ export const StripeBlockMeta = { }, { name: 'manage-subscription', - description: 'Create, update, pause, or cancel a Stripe subscription for a customer.', + description: 'Create, update, cancel, or resume a paused Stripe subscription for a customer.', content: - '# Manage Subscription\n\nHandle the lifecycle of a recurring subscription.\n\n## Steps\n1. To start a subscription, run Create Subscription with the customer and price items.\n2. To change a plan, run Update Subscription with the new items. To pause and later restart, use Cancel Subscription or Resume Subscription as appropriate.\n3. Confirm the current state with Retrieve Subscription.\n\n## Output\nReturn the subscription ID, its status, current period end, and the plan items, and note exactly what changed.', + '# Manage Subscription\n\nHandle the lifecycle of a recurring subscription.\n\n## Steps\n1. To start a subscription, run Create Subscription with the customer and price items.\n2. To change a plan, run Update Subscription with the existing subscription item ID and replacement price. Omitting the item ID adds another item.\n3. To schedule cancellation, use Update Subscription with cancel_at_period_end=true; set it to false before the period ends to undo that schedule. Cancel Subscription ends the subscription immediately and cannot be undone. Resume Subscription applies only to paused subscriptions, not canceled ones.\n4. Confirm the current state with Retrieve Subscription.\n\n## Output\nReturn the subscription ID, status, and plan items, and note exactly what changed.', }, { name: 'issue-invoice', description: 'Create, finalize, and send a Stripe invoice to a customer, then track payment.', content: - '# Issue Invoice\n\nBill a customer with a Stripe invoice.\n\n## Steps\n1. Run Create Invoice for the customer with the line items.\n2. Run Finalize Invoice to lock it, then Send Invoice to deliver it to the customer.\n3. Track payment with Retrieve Invoice, or run Pay Invoice to charge a saved payment method. Use Void Invoice to cancel an unpaid invoice.\n\n## Output\nReturn the invoice ID, its status (draft, open, paid, or void), the amount due, and the hosted invoice URL when available.', + '# Issue Invoice\n\nBill a customer with a Stripe invoice.\n\n## Steps\n1. Run Create Invoice for the customer. This tool does not create line items; inspect the draft and any existing pending items with Retrieve Invoice.\n2. After verifying the amount and items, run Finalize Invoice to lock it, then Send Invoice to deliver it to the customer.\n3. Track payment with Retrieve Invoice, or run Pay Invoice to charge a saved payment method. Use Void Invoice to cancel an unpaid invoice.\n\n## Output\nReturn the invoice ID, its status (draft, open, paid, or void), the amount due, and the hosted invoice URL when available.', }, { name: 'find-customer-activity', diff --git a/apps/sim/executor/execution/engine.test.ts b/apps/sim/executor/execution/engine.test.ts index b36e88bffcf..ef907cd8a28 100644 --- a/apps/sim/executor/execution/engine.test.ts +++ b/apps/sim/executor/execution/engine.test.ts @@ -443,6 +443,97 @@ describe('ExecutionEngine', () => { pauseOutput ) }) + it('stops a sequential run after the selected formatter without scheduling its publishing successor', async () => { + const nodes = [ + createMockNode('start', 'starter'), + createMockNode('formatter', 'function'), + createMockNode('publish', 'slack'), + ] + nodes[0].outgoingEdges.set('a', { target: 'formatter' }) + nodes[1].outgoingEdges.set('b', { target: 'publish' }) + const context = createMockContext({ stopAfterBlockId: 'formatter' }) + const orchestrator = createMockNodeOrchestrator() + vi.mocked(orchestrator.executeNode).mockImplementation(async (_ctx, nodeId) => ({ + nodeId, + output: { result: nodeId }, + isFinalOutput: false, + })) + const edges = createMockEdgeManager((node) => + node.id === 'start' ? ['formatter'] : node.id === 'formatter' ? ['publish'] : [] + ) + const result = await new ExecutionEngine( + context, + createMockDAG(nodes), + edges, + orchestrator + ).run('start') + expect(result.success).toBe(true) + expect(vi.mocked(orchestrator.executeNode).mock.calls.map((call) => call[1])).toEqual([ + 'start', + 'formatter', + ]) + expect(orchestrator.handleNodeCompletion).toHaveBeenCalledWith(context, 'formatter', { + result: 'formatter', + }) + }) + + it('finishes the chosen branch if a condition bypasses the stop target', async () => { + const nodes = [ + createMockNode('start', 'starter'), + createMockNode('target', 'function'), + createMockNode('alternate', 'slack'), + ] + nodes[0].outgoingEdges.set('a', { target: 'target' }) + nodes[0].outgoingEdges.set('b', { target: 'alternate' }) + const context = createMockContext({ stopAfterBlockId: 'target' }) + const orchestrator = createMockNodeOrchestrator() + vi.mocked(orchestrator.executeNode).mockImplementation(async (_ctx, nodeId) => ({ + nodeId, + output: {}, + isFinalOutput: false, + })) + const result = await new ExecutionEngine( + context, + createMockDAG(nodes), + createMockEdgeManager((node) => (node.id === 'start' ? ['alternate'] : [])), + orchestrator + ).run('start') + expect(result.success).toBe(true) + expect(vi.mocked(orchestrator.executeNode).mock.calls.map((call) => call[1])).toEqual([ + 'start', + 'alternate', + ]) + }) + + it('waits for already running sibling actions when stop-after is reached', async () => { + const nodes = [ + createMockNode('start', 'starter'), + createMockNode('formatter', 'function'), + createMockNode('sibling', 'slack'), + ] + nodes[0].outgoingEdges.set('a', { target: 'formatter' }) + nodes[0].outgoingEdges.set('b', { target: 'sibling' }) + const context = createMockContext({ stopAfterBlockId: 'formatter' }) + const orchestrator = createMockNodeOrchestrator() + const formatterFinished = Promise.withResolvers() + const completed: string[] = [] + vi.mocked(orchestrator.executeNode).mockImplementation(async (_ctx, nodeId) => { + if (nodeId === 'sibling') await formatterFinished.promise + return { nodeId, output: {}, isFinalOutput: false } + }) + vi.mocked(orchestrator.handleNodeCompletion).mockImplementation((_ctx, nodeId) => { + completed.push(nodeId) + if (nodeId === 'formatter') formatterFinished.resolve() + }) + const result = await new ExecutionEngine( + context, + createMockDAG(nodes), + createMockEdgeManager((node) => (node.id === 'start' ? ['formatter', 'sibling'] : [])), + orchestrator + ).run('start') + expect(result.success).toBe(true) + expect(completed).toEqual(['start', 'formatter', 'sibling']) + }) }) describe('Cancellation via AbortSignal', () => { diff --git a/apps/sim/executor/execution/executor.run-from-block.test.ts b/apps/sim/executor/execution/executor.run-from-block.test.ts index c6fd537fd75..7dc2a197bd8 100644 --- a/apps/sim/executor/execution/executor.run-from-block.test.ts +++ b/apps/sim/executor/execution/executor.run-from-block.test.ts @@ -1,10 +1,13 @@ import type { SessionPrincipal } from '@sim/auth/principal' import { createSerializedBlock, createSerializedWorkflow } from '@sim/testing' import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { NormalizedBlockOutput } from '@/executor/types' -const { executed, gateChoice } = vi.hoisted(() => ({ +const { executed, gateChoice, inputsByBlock, outputsByBlock } = vi.hoisted(() => ({ executed: [] as string[], gateChoice: { value: 'if' as 'if' | 'else' }, + inputsByBlock: new Map>(), + outputsByBlock: new Map(), })) vi.mock('@/executor/handlers/registry', () => ({ @@ -13,13 +16,15 @@ vi.mock('@/executor/handlers/registry', () => ({ canHandle: () => true, execute: async ( _ctx: unknown, - block: { id: string; metadata?: { id?: string; name?: string } } + block: { id: string; metadata?: { id?: string; name?: string } }, + inputs: Record ) => { executed.push(block.id) + inputsByBlock.set(block.id, inputs) if (block.metadata?.id === 'condition') { return { selectedOption: `${block.metadata.name}-${gateChoice.value}` } } - return { ok: true } + return outputsByBlock.get(block.id) ?? { ok: true } }, }, ], @@ -118,6 +123,81 @@ const looped = workflow( describe('DAGExecutor run-from-block edge state', () => { beforeEach(() => { executed.length = 0 + inputsByBlock.clear() + outputsByBlock.clear() + }) + + it('restores persisted ancestor outputs across a disabled intermediate without rerunning it', async () => { + const graph = workflow([ + { source: 'start', target: 'parseAction' }, + { source: 'parseAction', target: 'acknowledge' }, + { source: 'acknowledge', target: 'lookup' }, + { source: 'lookup', target: 'publish' }, + { source: 'start', target: 'unrelated' }, + ]) + graph.blocks.find((block) => block.id === 'acknowledge')!.enabled = false + const lookup = graph.blocks.find((block) => block.id === 'lookup')! + lookup.metadata!.id = 'api' + lookup.config.params = { candidateId: '' } + outputsByBlock.set('parseAction', { result: { candidateId: 'candidate-test' } }) + outputsByBlock.set('unrelated', { result: 'not an ancestor' }) + + const first = await createExecutor(graph, 'source-run').execute('wf') + expect(first.success).toBe(true) + expect(executed).not.toContain('acknowledge') + expect(executed).not.toContain('lookup') + expect(first.executionState?.blockStates.parseAction.output).toEqual({ + result: { candidateId: 'candidate-test' }, + }) + + executed.length = 0 + const replay = await createExecutor(graph, 'replay-run').executeFromBlock( + 'wf', + 'lookup', + first.executionState! + ) + expect(replay.success).toBe(true) + expect(inputsByBlock.get('lookup')?.candidateId).toBe('candidate-test') + expect(executed).toEqual(['lookup', 'publish']) + expect(replay.executionState?.blockStates.unrelated).toBeUndefined() + expect(replay.executionState?.executedBlocks).not.toContain('acknowledge') + }) + + it('restores ancestors across a disabled bridge without restoring dirty outputs or old branch choices', async () => { + const graph = workflow([ + { source: 'start', target: 'prep' }, + { source: 'prep', target: 'acknowledge' }, + { source: 'acknowledge', target: 'lookup' }, + { source: 'lookup', target: 'gate' }, + { source: 'gate', target: 'oldBranch', sourceHandle: 'condition-gate-if' }, + { source: 'gate', target: 'newBranch', sourceHandle: 'condition-gate-else' }, + { source: 'oldBranch', target: 'join' }, + { source: 'newBranch', target: 'join' }, + ]) + const join = graph.blocks.find((block) => block.id === 'join')! + join.metadata!.id = 'api' + join.config.params = { version: '' } + outputsByBlock.set('lookup', { result: { version: 'old' } }) + gateChoice.value = 'if' + const first = await createExecutor(graph, 'source-run').execute('wf') + expect(first.success).toBe(true) + + graph.blocks.find((block) => block.id === 'acknowledge')!.enabled = false + outputsByBlock.set('lookup', { result: { version: 'new' } }) + gateChoice.value = 'else' + executed.length = 0 + const replay = await createExecutor(graph, 'replay-run').executeFromBlock( + 'wf', + 'lookup', + first.executionState! + ) + + expect(replay.success).toBe(true) + expect(executed).toEqual(['lookup', 'gate', 'newBranch', 'join']) + expect(inputsByBlock.get('join')?.version).toBe('new') + expect(replay.executionState?.blockStates.prep).toBeDefined() + expect(replay.executionState?.blockStates.oldBranch).toBeUndefined() + expect(replay.executionState?.executedBlocks).not.toContain('oldBranch') }) it.each([ @@ -186,6 +266,34 @@ describe('DAGExecutor run-from-block edge state', () => { expect(order.indexOf('join')).toBeGreaterThan(Math.max(order.indexOf('a'), order.indexOf('b'))) }) + it.each([ + { failedAt: null, expected: ['start', 'download', 'parseDoc', 'prepare'], text: 'resume text' }, + { failedAt: 'download', expected: ['start', 'download', 'prepare'], text: '' }, + { failedAt: 'parseDoc', expected: ['start', 'download', 'parseDoc', 'prepare'], text: '' }, + ])( + 'joins success/error paths after their active prerequisites ($failedAt)', + async ({ failedAt, expected, text }) => { + const graph = workflow([ + { source: 'start', target: 'download' }, + { source: 'download', target: 'parseDoc', sourceHandle: 'source' }, + { source: 'download', target: 'prepare', sourceHandle: 'error' }, + { source: 'parseDoc', target: 'prepare', sourceHandle: 'source' }, + { source: 'parseDoc', target: 'prepare', sourceHandle: 'error' }, + ]) + const prepare = graph.blocks.find((block) => block.id === 'prepare')! + prepare.metadata!.id = 'api' + prepare.config.params = { text: '' } + outputsByBlock.set('parseDoc', { result: { text: 'resume text' } }) + if (failedAt) outputsByBlock.set(failedAt, { error: 'provider failure' }) + + const result = await createExecutor(graph, 'fan-in-run').execute('wf') + + expect(result.success).toBe(true) + expect(executed).toEqual(expected) + expect(inputsByBlock.get('prepare')?.text).toBe(text) + } + ) + it('does not run a stale branch in any parallel branch copy', async () => { const parallel = workflow( [ diff --git a/apps/sim/executor/execution/executor.ts b/apps/sim/executor/execution/executor.ts index 4329b883762..8b0c3201ce9 100644 --- a/apps/sim/executor/execution/executor.ts +++ b/apps/sim/executor/execution/executor.ts @@ -149,7 +149,11 @@ export class DAGExecutor { ) } - const { dirtySet, upstreamSet, reachableUpstreamSet } = computeExecutionSets(dag, startBlockId) + const { dirtySet, upstreamSet, reachableUpstreamSet } = computeExecutionSets( + dag, + startBlockId, + this.workflow + ) const effectiveStartBlockId = resolveContainerToSentinelStart(startBlockId, dag) ?? startBlockId // Extract container IDs from sentinel IDs in reachable upstream set diff --git a/apps/sim/executor/types.ts b/apps/sim/executor/types.ts index b272ee17cf2..771fd05c05a 100644 --- a/apps/sim/executor/types.ts +++ b/apps/sim/executor/types.ts @@ -191,6 +191,7 @@ export interface BlockTokens { /** A single tool invocation recorded by an agent-type block. */ export interface BlockToolCall { name: string + success?: boolean duration?: number startTime?: string endTime?: string diff --git a/apps/sim/executor/utils/run-from-block-preview.test.ts b/apps/sim/executor/utils/run-from-block-preview.test.ts new file mode 100644 index 00000000000..e0bd6048060 --- /dev/null +++ b/apps/sim/executor/utils/run-from-block-preview.test.ts @@ -0,0 +1,280 @@ +import { describe, expect, it, vi } from 'vitest' +import { DAGExecutor } from '@/executor/execution/executor' +import { ExecutionState } from '@/executor/execution/state' +import type { SerializableExecutionState } from '@/executor/execution/types' +import { previewRunFromBlock } from '@/executor/utils/run-from-block-preview' +import { + buildClonedSubflowId, + buildParallelSentinelStartId, + buildSentinelStartId, +} from '@/executor/utils/subflow-utils' +import type { SerializedBlock, SerializedWorkflow } from '@/serializer/types' + +vi.mock('@/executor/handlers/registry', () => ({ + createBlockHandlers: () => [ + { canHandle: () => true, execute: async () => ({ result: 'value' }) }, + ], +})) + +function block(id: string, type = 'function'): SerializedBlock { + return { + id, + position: { x: 0, y: 0 }, + config: { tool: '', params: {} }, + inputs: {}, + outputs: {}, + metadata: { id: type, name: `${id} name` }, + enabled: true, + } +} + +function snapshot(executedBlocks: string[] = []): SerializableExecutionState { + return { + blockStates: Object.fromEntries( + executedBlocks.map((id) => [ + id, + { output: { result: 'private value' }, executed: true, executionTime: 1 }, + ]) + ), + executedBlocks, + blockLogs: [], + decisions: { router: {}, condition: {} }, + completedLoops: [], + activeExecutionPath: [], + } +} + +function workflow(): SerializedWorkflow { + return { + version: '1', + blocks: [ + block('start', 'starter'), + block('upstream'), + block('retry'), + block('sibling'), + block('join'), + block('unrelated'), + ], + connections: [ + { source: 'start', target: 'upstream' }, + { source: 'upstream', target: 'retry' }, + { source: 'retry', target: 'join' }, + { source: 'sibling', target: 'join' }, + ], + loops: {}, + } +} + +function containerWorkflow(kind: 'loop' | 'parallel'): SerializedWorkflow { + return { + version: '1', + blocks: [block('start', 'starter'), block('container', kind), block('inner'), block('after')], + connections: [ + { source: 'start', target: 'container' }, + { source: 'container', target: 'inner', sourceHandle: `${kind}-start-source` }, + { source: 'container', target: 'after', sourceHandle: `${kind}-end-source` }, + ], + loops: + kind === 'loop' + ? { container: { id: 'container', nodes: ['inner'], iterations: 1, loopType: 'for' } } + : {}, + parallels: + kind === 'parallel' + ? { container: { id: 'container', nodes: ['inner'], count: 1, parallelType: 'count' } } + : {}, + } +} + +describe('partial-run preview with the real DAG builder', () => { + it('includes rerun candidates and sibling cached dependencies without exposing values or mutating state', () => { + const graph = workflow() + const source = snapshot(['start', 'upstream', 'sibling', 'retry']) + const before = structuredClone({ graph, source }) + const result = previewRunFromBlock(graph, 'retry', source) + + expect(result.validation).toEqual({ valid: true }) + expect(result.rerunBlocks.map((item) => item.blockId)).toEqual(['retry', 'join']) + expect(result.rerunBlocks[0].executedInSource).toBe(true) + expect(result.upstreamBlocks.map((item) => item.blockId)).toEqual([ + 'start', + 'upstream', + 'sibling', + ]) + expect(result.upstreamBlocks.every((item) => item.hasCachedOutput)).toBe(true) + expect(JSON.stringify(result)).not.toContain('private value') + expect({ graph, source }).toEqual(before) + }) + + it('reports an unexecuted immediate dependency while still showing the candidate graph', () => { + const result = previewRunFromBlock(workflow(), 'retry', snapshot(['start'])) + expect(result.validation).toEqual({ + valid: false, + error: 'Upstream dependency not executed: upstream', + }) + expect(result.upstreamBlocks.find((item) => item.blockId === 'upstream')).toMatchObject({ + executedInSource: false, + hasCachedOutput: false, + }) + expect(result.rerunBlocks.map((item) => item.blockId)).toEqual(['retry', 'join']) + }) + + it('distinguishes recorded execution from output availability and excludes disabled downstream blocks', () => { + const graph = workflow() + graph.blocks.find((item) => item.id === 'join')!.enabled = false + const source = snapshot(['upstream']) + source.blockStates = {} + const result = previewRunFromBlock(graph, 'retry', source) + expect(result.validation.valid).toBe(true) + expect(result.rerunBlocks.map((item) => item.blockId)).toEqual(['retry']) + expect(result.upstreamBlocks.find((item) => item.blockId === 'upstream')).toMatchObject({ + executedInSource: true, + hasCachedOutput: false, + }) + }) + + it('shows recorded ancestors across disabled blocks without inventing cached outputs', () => { + const graph = workflow() + graph.blocks.find((item) => item.id === 'retry')!.enabled = false + const result = previewRunFromBlock(graph, 'join', snapshot(['start', 'upstream'])) + + expect(result.validation.valid).toBe(true) + expect(result.rerunBlocks.map((item) => item.blockId)).toEqual(['join']) + expect(result.upstreamBlocks.find((item) => item.blockId === 'upstream')).toMatchObject({ + executedInSource: true, + hasCachedOutput: true, + }) + expect(result.upstreamBlocks.find((item) => item.blockId === 'retry')).toMatchObject({ + executedInSource: false, + hasCachedOutput: false, + }) + expect(result.upstreamBlocks.find((item) => item.blockId === 'sibling')).toMatchObject({ + executedInSource: false, + hasCachedOutput: false, + }) + expect(result.upstreamBlocks.some((item) => item.blockId === 'unrelated')).toBe(false) + }) + + it('does not change cached ancestors when an unrelated block is disabled', () => { + const graph = workflow() + graph.blocks.push(block('note', 'note')) + graph.connections.push( + { source: 'unrelated', target: 'note' }, + { source: 'note', target: 'join' } + ) + const source = snapshot(['start', 'upstream', 'sibling', 'unrelated']) + const before = previewRunFromBlock(graph, 'retry', source) + + graph.blocks.push({ ...block('disabled'), enabled: false }) + graph.connections.push({ source: 'unrelated', target: 'disabled' }) + expect(previewRunFromBlock(graph, 'retry', source)).toEqual(before) + expect(before.upstreamBlocks.some((item) => item.blockId === 'unrelated')).toBe(false) + }) + + it.each(['loop', 'parallel'] as const)( + 'projects %s sentinels to containers and refuses interior starts', + (kind) => { + const graph = containerWorkflow(kind) + const result = previewRunFromBlock(graph, 'container', snapshot(['start'])) + expect(result.validation.valid).toBe(true) + expect(result.rerunBlocks.map((item) => item.blockId)).toEqual([ + 'container', + 'inner', + 'after', + ]) + expect(previewRunFromBlock(graph, 'inner', snapshot()).validation.valid).toBe(false) + const after = previewRunFromBlock(graph, 'after', snapshot(['container', 'inner₍0₎'])) + expect( + after.upstreamBlocks.find((item) => item.blockId === 'container')?.hasCachedOutput + ).toBe(true) + expect(after.upstreamBlocks.find((item) => item.blockId === 'inner')?.hasCachedOutput).toBe( + true + ) + graph.blocks.push({ ...block('disabled'), enabled: false }) + expect(previewRunFromBlock(graph, 'after', snapshot(['container', 'inner₍0₎']))).toEqual( + after + ) + } + ) + + it.each(['loop', 'parallel'] as const)( + 'distinguishes %s control state from a completed container output in real snapshots', + async (kind) => { + const graph = containerWorkflow(kind) + const sentinelStartId = + kind === 'loop' + ? buildSentinelStartId('container') + : buildParallelSentinelStartId('container') + const makeExecutor = (stopAfterBlockId?: string) => + new DAGExecutor({ + workflow: graph, + contextExtensions: { + workspaceId: 'workspace-test', + executionId: 'execution-test', + principal: { kind: 'session', userId: 'user-test', sessionId: 'session-test' }, + stopAfterBlockId, + }, + }) + const partial = await makeExecutor(sentinelStartId).execute('workflow-test') + const partialState = partial.executionState! + expect(partialState.blockStates[sentinelStartId].output).toEqual({ sentinelStart: true }) + expect(partialState.blockStates.container).toBeUndefined() + expect( + previewRunFromBlock(graph, 'after', partialState).upstreamBlocks.find( + (item) => item.blockId === 'container' + )?.hasCachedOutput + ).toBe(false) + + const complete = await makeExecutor().execute('workflow-test') + const completeState = complete.executionState! + expect(completeState.blockStates.container.output).toHaveProperty('results') + expect( + previewRunFromBlock(graph, 'after', completeState).upstreamBlocks.find( + (item) => item.blockId === 'container' + ) + ).toMatchObject({ executedInSource: true, hasCachedOutput: true }) + } + ) + + it.each(['loop', 'parallel'] as const)( + 'recognizes cloned %s aggregate outputs without mistaking cloned control state for them', + (kind) => { + const containerId = buildClonedSubflowId('container', 2) + const consumerId = buildClonedSubflowId('consumer', 2) + const sentinelId = + kind === 'loop' + ? buildSentinelStartId(containerId) + : buildParallelSentinelStartId(containerId) + const state = new ExecutionState() + state.setBlockOutput(sentinelId, { sentinelStart: true }) + const preview = () => + previewRunFromBlock(containerWorkflow(kind), 'after', { + ...snapshot(), + blockStates: Object.fromEntries(state.getBlockStates()), + executedBlocks: [...state.getExecutedBlocks()], + }).upstreamBlocks.find((item) => item.blockId === 'container') + + expect(state.getBlockOutput('container', consumerId)).toBeUndefined() + expect(preview()?.hasCachedOutput).toBe(false) + + const output = { results: [[{ result: 'value' }]] } + state.setBlockOutput(containerId, output) + expect(state.getBlockOutput('container', consumerId)).toEqual(output) + expect(preview()).toMatchObject({ executedInSource: true, hasCachedOutput: true }) + } + ) + + it('includes both conditional branches as candidates', () => { + const graph: SerializedWorkflow = { + version: '1', + blocks: [block('condition', 'condition'), block('yes'), block('no')], + connections: [ + { source: 'condition', target: 'yes', sourceHandle: 'condition-if' }, + { source: 'condition', target: 'no', sourceHandle: 'condition-else' }, + ], + loops: {}, + } + expect( + previewRunFromBlock(graph, 'condition', snapshot()).rerunBlocks.map((item) => item.blockId) + ).toEqual(['condition', 'yes', 'no']) + }) +}) diff --git a/apps/sim/executor/utils/run-from-block-preview.ts b/apps/sim/executor/utils/run-from-block-preview.ts new file mode 100644 index 00000000000..8e017e43458 --- /dev/null +++ b/apps/sim/executor/utils/run-from-block-preview.ts @@ -0,0 +1,66 @@ +import { type DAG, DAGBuilder } from '@/executor/dag/builder' +import type { SerializableExecutionState } from '@/executor/execution/types' +import { + computeExecutionSets, + type RunFromBlockValidation, + validateRunFromBlock, +} from '@/executor/utils/run-from-block' +import { stripCloneSuffixes } from '@/executor/utils/subflow-utils' +import type { SerializedWorkflow } from '@/serializer/types' + +export interface RunFromBlockPreviewBlock { + blockId: string + name: string + type: string + executedInSource: boolean +} + +export interface RunFromBlockPreview { + validation: RunFromBlockValidation + rerunBlocks: RunFromBlockPreviewBlock[] + upstreamBlocks: (RunFromBlockPreviewBlock & { hasCachedOutput: boolean })[] +} + +/** Projects internal sentinels and parallel instances back onto saved workflow blocks. */ +function workflowBlockIds(nodeIds: Set, dag: DAG): Set { + return new Set( + [...nodeIds].map((nodeId) => { + const node = dag.nodes.get(nodeId) + return stripCloneSuffixes( + node?.metadata.isSentinel ? (node.metadata.subflowId ?? nodeId) : nodeId + ) + }) + ) +} + +/** Uses the executor's full graph and entry validation without running blocks or resolving inputs. */ +export function previewRunFromBlock( + workflow: SerializedWorkflow, + startBlockId: string, + snapshot: SerializableExecutionState +): RunFromBlockPreview { + const dag = new DAGBuilder().build(workflow, { includeAllBlocks: true }) + const validation = validateRunFromBlock(startBlockId, dag, new Set(snapshot.executedBlocks)) + const { dirtySet, reachableUpstreamSet } = computeExecutionSets(dag, startBlockId, workflow) + const rerunIds = workflowBlockIds(dirtySet, dag) + const upstreamIds = workflowBlockIds(reachableUpstreamSet, dag) + const executedIds = new Set(snapshot.executedBlocks.map(stripCloneSuffixes)) + const cachedOutputIds = new Set( + Object.entries(snapshot.blockStates) + .filter(([, state]) => state.output !== undefined) + .map(([blockId]) => stripCloneSuffixes(blockId)) + ) + const blocks = workflow.blocks.map((block) => ({ + blockId: block.id, + name: block.metadata?.name ?? block.id, + type: block.metadata?.id ?? '', + executedInSource: executedIds.has(block.id), + })) + return { + validation, + rerunBlocks: blocks.filter((block) => rerunIds.has(block.blockId)), + upstreamBlocks: blocks + .filter((block) => upstreamIds.has(block.blockId) && !rerunIds.has(block.blockId)) + .map((block) => ({ ...block, hasCachedOutput: cachedOutputIds.has(block.blockId) })), + } +} diff --git a/apps/sim/executor/utils/run-from-block.ts b/apps/sim/executor/utils/run-from-block.ts index a95885e6caf..a85eb38244b 100644 --- a/apps/sim/executor/utils/run-from-block.ts +++ b/apps/sim/executor/utils/run-from-block.ts @@ -3,6 +3,7 @@ import { LOOP, normalizeName, PARALLEL } from '@/executor/constants' import type { DAG } from '@/executor/dag/builder' import type { SerializableExecutionState } from '@/executor/execution/types' import type { NormalizedBlockOutput } from '@/executor/types' +import { stripCloneSuffixes } from '@/executor/utils/subflow-utils' import type { SerializedWorkflow } from '@/serializer/types' /** @@ -76,6 +77,40 @@ export interface ExecutionSets { reachableUpstreamSet: Set } +/** Preserves cache ancestry through disabled blocks without adding runnable edges. */ +function disabledBlockIncomingEdges(dag: DAG, workflow?: SerializedWorkflow) { + const incoming = new Map>() + const disabledIds = new Set( + workflow?.blocks.filter((block) => block.enabled === false).map((block) => block.id) + ) + if (!workflow || disabledIds.size === 0) return incoming + + const nodeIdsByBlockId = new Map() + for (const [nodeId, node] of dag.nodes) { + const blockId = stripCloneSuffixes( + node.metadata.isSentinel ? (node.metadata.subflowId ?? nodeId) : nodeId + ) + const nodeIds = nodeIdsByBlockId.get(blockId) ?? [] + nodeIds.push(nodeId) + nodeIdsByBlockId.set(blockId, nodeIds) + } + for (const connection of workflow.connections) { + if (!disabledIds.has(connection.source) && !disabledIds.has(connection.target)) continue + const sources = disabledIds.has(connection.source) + ? [connection.source] + : (nodeIdsByBlockId.get(connection.source) ?? []) + const targets = disabledIds.has(connection.target) + ? [connection.target] + : (nodeIdsByBlockId.get(connection.target) ?? []) + for (const target of targets) { + const predecessors = incoming.get(target) ?? new Set() + for (const source of sources) predecessors.add(source) + incoming.set(target, predecessors) + } + } + return incoming +} + /** * Computes the dirty set, upstream set, and reachable upstream set. * - Dirty set: start block + all blocks reachable via outgoing edges (need re-execution) @@ -90,9 +125,18 @@ export interface ExecutionSets { * @param startBlockId - The block to start execution from * @returns Object containing dirtySet, upstreamSet, and reachableUpstreamSet */ -export function computeExecutionSets(dag: DAG, startBlockId: string): ExecutionSets { +export function computeExecutionSets( + dag: DAG, + startBlockId: string, + workflow?: SerializedWorkflow +): ExecutionSets { const dirty = new Set([startBlockId]) const upstream = new Set() + const disabledIncoming = disabledBlockIncomingEdges(dag, workflow) + const incomingSources = (nodeId: string) => [ + ...(dag.nodes.get(nodeId)?.incomingEdges ?? []), + ...(disabledIncoming.get(nodeId) ?? []), + ] const sentinelStartId = resolveContainerToSentinelStart(startBlockId, dag) const traversalStartId = sentinelStartId ?? startBlockId @@ -119,10 +163,8 @@ export function computeExecutionSets(dag: DAG, startBlockId: string): ExecutionS const upstreamQueue = [traversalStartId] while (upstreamQueue.length > 0) { const nodeId = upstreamQueue.shift()! - const node = dag.nodes.get(nodeId) - if (!node) continue - for (const sourceId of node.incomingEdges) { + for (const sourceId of incomingSources(nodeId)) { if (!upstream.has(sourceId)) { upstream.add(sourceId) upstreamQueue.push(sourceId) @@ -135,20 +177,14 @@ export function computeExecutionSets(dag: DAG, startBlockId: string): ExecutionS // sibling branches (like B when running from A) const reachableUpstream = new Set() for (const dirtyNodeId of dirty) { - const node = dag.nodes.get(dirtyNodeId) - if (!node) continue - // BFS upstream from this dirty node - const queue = [...node.incomingEdges] + const queue = incomingSources(dirtyNodeId) while (queue.length > 0) { const sourceId = queue.shift()! if (reachableUpstream.has(sourceId) || dirty.has(sourceId)) continue reachableUpstream.add(sourceId) - const sourceNode = dag.nodes.get(sourceId) - if (sourceNode) { - queue.push(...sourceNode.incomingEdges) - } + queue.push(...incomingSources(sourceId)) } } diff --git a/apps/sim/lib/api/contracts/tools/communication/slack.ts b/apps/sim/lib/api/contracts/tools/communication/slack.ts index d1f2b327cc1..263c73f97fe 100644 --- a/apps/sim/lib/api/contracts/tools/communication/slack.ts +++ b/apps/sim/lib/api/contracts/tools/communication/slack.ts @@ -6,16 +6,26 @@ import { import type { ContractBodyInput, ContractJsonResponse } from '@/lib/api/contracts/types' import { RawFileInputArraySchema } from '@/lib/uploads/utils/file-schemas' +function hasMessageContent(input: { text?: string; blocks?: unknown[] | null }): boolean { + return Boolean(input.text?.trim() || input.blocks?.length) +} + +const messageContentError = { + message: 'Provide message text or at least one Block Kit block', + path: ['text'], +} + export const slackSendMessageBodySchema = z .object({ accessToken: z.string().min(1, 'Access token is required'), channel: z.string().optional().nullable(), userId: z.string().optional().nullable(), - text: z.string().min(1, 'Message text is required'), + text: z.string().optional(), thread_ts: z.string().optional().nullable(), blocks: slackBlocksSchema.optional().nullable(), files: RawFileInputArraySchema.optional().nullable(), }) + .refine(hasMessageContent, messageContentError) .refine((data) => data.channel || data.userId, { message: 'Either channel or userId is required', }) @@ -51,22 +61,26 @@ export const slackDeleteMessageBodySchema = z.object({ timestamp: z.string().min(1, 'Message timestamp is required'), }) -export const slackUpdateMessageBodySchema = z.object({ - accessToken: z.string().min(1, 'Access token is required'), - channel: z.string().min(1, 'Channel is required'), - timestamp: z.string().min(1, 'Message timestamp is required'), - text: z.string().min(1, 'Message text is required'), - blocks: slackBlocksSchema.optional().nullable(), -}) +export const slackUpdateMessageBodySchema = z + .object({ + accessToken: z.string().min(1, 'Access token is required'), + channel: z.string().min(1, 'Channel is required'), + timestamp: z.string().min(1, 'Message timestamp is required'), + text: z.string().optional(), + blocks: slackBlocksSchema.optional().nullable(), + }) + .refine(hasMessageContent, messageContentError) -export const slackSendEphemeralBodySchema = z.object({ - accessToken: z.string().min(1, 'Access token is required'), - channel: z.string().min(1, 'Channel ID is required'), - user: z.string().min(1, 'User ID is required'), - text: z.string().min(1, 'Message text is required'), - thread_ts: z.string().optional().nullable(), - blocks: slackBlocksSchema.optional().nullable(), -}) +export const slackSendEphemeralBodySchema = z + .object({ + accessToken: z.string().min(1, 'Access token is required'), + channel: z.string().min(1, 'Channel ID is required'), + user: z.string().min(1, 'User ID is required'), + text: z.string().optional(), + thread_ts: z.string().optional().nullable(), + blocks: slackBlocksSchema.optional().nullable(), + }) + .refine(hasMessageContent, messageContentError) export const slackDownloadBodySchema = z.object({ accessToken: z.string().min(1, 'Access token is required'), diff --git a/apps/sim/lib/api/contracts/tools/file.ts b/apps/sim/lib/api/contracts/tools/file.ts index 9829ed78d50..d8f48af490a 100644 --- a/apps/sim/lib/api/contracts/tools/file.ts +++ b/apps/sim/lib/api/contracts/tools/file.ts @@ -244,6 +244,8 @@ export const fileManageCompressBodySchema = z fileId: fileIdSelectionSchema.optional(), fileInput: z.unknown().optional(), archiveName: z.string().min(1).max(255).optional(), + folderPath: v2FolderPathInputSchema.optional(), + onConflict: z.enum(['rename', 'error']).default('rename'), }) .refine( (data) => diff --git a/apps/sim/lib/api/contracts/v2/__tests__/workflow-graph.test.ts b/apps/sim/lib/api/contracts/v2/__tests__/workflow-graph.test.ts index 6b1de7058e4..128e69390fe 100644 --- a/apps/sim/lib/api/contracts/v2/__tests__/workflow-graph.test.ts +++ b/apps/sim/lib/api/contracts/v2/__tests__/workflow-graph.test.ts @@ -94,6 +94,8 @@ describe('v2WorkflowGraphSchema', () => { /** An empty report carrying every field the lint schema requires. */ const EMPTY_LINT = { + checks: [], + codeIssues: [], sources: [], sinks: [], orphanBlocks: [], @@ -108,6 +110,21 @@ const EMPTY_LINT = { /** A report exercising every finding kind the lint schema publishes. */ const FULL_LINT = { + checks: [ + { name: 'embedded-code-syntax', status: 'complete', detail: 'Checked one JavaScript block.' }, + ], + codeIssues: [ + { + blockId: 'block-2', + blockName: 'Triage', + blockType: 'function', + field: 'code', + language: 'javascript', + message: 'Unexpected token', + line: 1, + column: null, + }, + ], sources: [{ blockId: 'block-1', blockName: 'Start', blockType: 'starter' }], sinks: [{ blockId: 'block-2', blockName: 'Triage', blockType: 'agent' }], orphanBlocks: [{ blockId: 'block-3', blockName: null, blockType: null }], diff --git a/apps/sim/lib/api/contracts/v2/catalog.ts b/apps/sim/lib/api/contracts/v2/catalog.ts index 720b0ec5959..484e9a3380f 100644 --- a/apps/sim/lib/api/contracts/v2/catalog.ts +++ b/apps/sim/lib/api/contracts/v2/catalog.ts @@ -377,7 +377,11 @@ const v2HostedApiKeySchema = z ) const v2ToolOAuthSchema = z.object({ - required: z.boolean().describe('Whether the tool cannot run without an OAuth credential.'), + required: z + .boolean() + .describe( + 'Whether OAuth is mandatory. Slack tools declaring authMethod and botToken also accept explicit bot_token authentication; false does not mean the tool is unauthenticated.' + ), provider: z.string().describe('OAuth service the credential must authenticate.'), requiredScopes: z.array(z.string()).optional().describe('Scopes the credential must carry.'), }) @@ -431,12 +435,12 @@ export const v2ExecuteToolBodySchema = z ) .default({}) .describe( - 'Tool arguments keyed by published parameter IDs. For `user-only` parameters, a whole-value `{{VAR_NAME}}` reference resolves a workspace environment variable. Other values pass through unchanged.' + 'Tool arguments keyed by published parameter IDs. For `user-only` parameters, a whole-value `{{VAR_NAME}}` reference resolves an environment variable in the acting user’s personal/workspace scope. Other values pass through unchanged.' ), credentialId: catalogIdSchema .optional() .describe( - 'Credential to authenticate with. Required when the tool declares an OAuth requirement; the workspace credentials list names the candidates.' + 'Credential to authenticate with. Required for OAuth authentication; the workspace credentials list names the candidates. Slack tools that declare authMethod and botToken also accept input.authMethod=bot_token with input.botToken (literal or {{SECRET_NAME}}); that explicit mode ignores credentialId. Otherwise OAuth is the default and unused botToken is ignored.' ), timeoutSeconds: z .number() diff --git a/apps/sim/lib/api/contracts/v2/credentials.ts b/apps/sim/lib/api/contracts/v2/credentials.ts index 500c8b1d8ed..f9cbde1d53b 100644 --- a/apps/sim/lib/api/contracts/v2/credentials.ts +++ b/apps/sim/lib/api/contracts/v2/credentials.ts @@ -59,6 +59,87 @@ export const v2CredentialSchema = z }) export type V2Credential = z.output +export const v2CredentialDiagnosticsSchema = z + .object({ + identity: z + .object({ + source: z + .enum(['credential', 'linked-account', 'unknown']) + .describe( + 'Stored metadata source for the reported identity; unknown means no identity is separately recorded.' + ), + subjectId: z + .string() + .nullable() + .describe('Stored provider subject ID when separately recorded; null means unknown.'), + tenantId: z + .string() + .nullable() + .describe('Stored provider tenant or Slack installation ID when available.'), + externalAccountId: z + .string() + .nullable() + .describe( + 'Stored OAuth external account identifier; may include connection-specific suffixes and is not necessarily the acting bot/user ID.' + ), + verifiedLive: z + .literal(false) + .describe('Inspection never contacts the provider or validates secret material.'), + }) + .describe('Stored provider identity metadata; no live identity verification is performed.'), + scopes: z + .object({ + source: z + .enum(['credential', 'linked-account', 'unknown']) + .describe( + 'Stored metadata source for granted scopes; unknown means grants are not separately recorded.' + ), + values: z + .array(z.string()) + .describe( + 'Recorded granted scopes. An unknown source with an empty array does not mean the credential has no scopes.' + ), + }) + .describe('Recorded granted scopes and their source, without requesting provider access.'), + notes: z.array(z.string()).describe('Coverage limits and provider-specific access guidance.'), + }) + .describe('Non-secret credential identity, recorded grants, and diagnostic coverage limits.') +export type V2CredentialDiagnostics = z.output + +export const v2GetCredentialParamsSchema = z + .object({ + credentialId: nonEmptyIdSchema.max(255).describe('Selected credential to inspect.'), + }) + .strict() +export type V2GetCredentialParams = z.input + +export const v2GetCredentialQuerySchema = z + .object({ + workspaceId: workspaceIdSchema.describe('Workspace expected to own the selected credential.'), + }) + .strict() +export type V2GetCredentialQuery = z.input + +export const v2GetCredentialDataSchema = v2CredentialSchema + .extend({ + diagnostics: v2CredentialDiagnosticsSchema, + }) + .meta({ + id: 'CredentialInspection', + title: 'Credential inspection', + description: + 'Credential metadata with stored identity and scope diagnostics; no live provider verification.', + }) +export type V2GetCredentialData = z.output + +export const v2GetCredentialContract = defineRouteContract({ + method: 'GET', + path: '/api/v2/credentials/[credentialId]', + params: v2GetCredentialParamsSchema, + query: v2GetCredentialQuerySchema, + response: { mode: 'json', schema: v2DataResponse(v2GetCredentialDataSchema) }, +}) + export const v2CredentialProviderAuthorizationOptionSchema = z .object({ providerId: z diff --git a/apps/sim/lib/api/contracts/v2/logs.ts b/apps/sim/lib/api/contracts/v2/logs.ts index 93b1ac4af05..7b924b5cbb2 100644 --- a/apps/sim/lib/api/contracts/v2/logs.ts +++ b/apps/sim/lib/api/contracts/v2/logs.ts @@ -2,7 +2,6 @@ import { z } from 'zod' import { traceSpansSchema } from '@/lib/api/contracts/logs' import { booleanQueryFlagSchema, - noInputSchema, runIdSchema, workspaceIdSchema, } from '@/lib/api/contracts/primitives' @@ -301,7 +300,9 @@ export const v2LogDetailSchema = z deleted: z.boolean().describe('Whether the workflow has been deleted.'), }) .describe('Workflow snapshot associated with the execution.'), - workflowState: v2LogWorkflowStateSchema, + workflowState: v2LogWorkflowStateSchema.describe( + 'Credential-redacted workflow snapshot, or null when unavailable or includeWorkflowState=false.' + ), /** Materialized block-level execution trace spans. */ traceSpans: traceSpansSchema.describe('Materialized block-level execution trace spans.'), /** @@ -714,10 +715,29 @@ export const v2ListLogsContract = defineRouteContract({ }, }) +export const v2GetLogQuerySchema = z + .object({ + includeWorkflowState: booleanQueryFlagSchema + .describe( + 'Include the saved workflow snapshot. Set false to avoid loading and returning block configuration when inspecting a run. Other run fields are unchanged.' + ) + .optional() + .default(true), + }) + .strict() + .meta({ + id: 'GetLogQuery', + title: 'Execution log detail options', + description: 'Controls whether a log detail read includes its saved workflow snapshot.', + examples: [{ includeWorkflowState: false }], + }) + +export type V2GetLogQuery = z.input + export const v2GetLogContract = defineRouteContract({ method: 'GET', path: '/api/v2/logs/[runId]', - query: noInputSchema, + query: v2GetLogQuerySchema, params: v2LogParamsSchema, response: { mode: 'json', diff --git a/apps/sim/lib/api/contracts/v2/openapi/resources.ts b/apps/sim/lib/api/contracts/v2/openapi/resources.ts index 3a32461c0f7..4ea100e5d57 100644 --- a/apps/sim/lib/api/contracts/v2/openapi/resources.ts +++ b/apps/sim/lib/api/contracts/v2/openapi/resources.ts @@ -11,6 +11,7 @@ import { v2CreateCredentialConnectionContract, v2CreateServiceAccountCredentialContract, v2DeleteCredentialContract, + v2GetCredentialContract, v2ListCredentialProvidersContract, v2ListCredentialsContract, v2UpdateCredentialContract, @@ -40,11 +41,13 @@ import { type ErrorResponseId, FULL_SET_LIST, HEAD_MIRRORS_GET, + HEAD_OMITS_PAYLOAD_HEADERS, RATE_LIMIT_HEADERS, RESOURCE_CONFLICT_ERRORS, RESOURCE_ERRORS, V2_AUTH_SECURITY, V2_AUTH_SECURITY_SCHEMES, + V2_BINARY_DOWNLOAD_HEADERS, V2_COMMON_HEADERS, V2_ERROR_SCHEMA, WORKSPACE_API_KEY_DENIED, @@ -75,6 +78,7 @@ import { v2RevokeSkillEditorContract, v2UpdateSkillContract, } from '@/lib/api/contracts/v2/skills' +import { v2DownloadToolFileContract } from '@/lib/api/contracts/v2/tool-files' import { v2CreateWorkflowMcpServerContract, v2DeleteWorkflowMcpServerContract, @@ -1474,6 +1478,37 @@ const declaredRoutes = [ ), } ), + defineOpenApiRoute( + v2GetCredentialContract, + resourceOperation('Credentials', { + applicationOperation: credentialOperations.inspect, + operationId: 'getCredential', + summary: 'Inspect Credential', + description: `Inspect one selected connection's stored provider identity, recorded OAuth scopes, and access limitations. This does not decrypt secrets, contact the provider, or verify live resource access. Custom bot identities/scopes may be unknown. ${WORKSPACE_API_KEY_DENIED}`, + errors: RESOURCE_ERRORS, + success: { description: 'Selected credential metadata and diagnostic coverage.' }, + }), + { + params: documentedSchema( + v2GetCredentialContract.params, + 'GetCredentialParams', + 'Get credential parameters', + 'The selected credential identifier.' + ), + query: documentedSchema( + v2GetCredentialContract.query, + 'GetCredentialQuery', + 'Get credential query', + 'Expected workspace ownership.' + ), + response: documentedSchema( + v2GetCredentialContract.response.schema, + 'GetCredentialResponse', + 'Get credential response', + 'Stored identity and scope diagnostics without secret material.' + ), + } + ), defineOpenApiRoute( v2ListCredentialProvidersContract, resourceOperation('Credentials', { @@ -2105,8 +2140,8 @@ const declaredRoutes = [ applicationOperation: toolExecutionOperations.execute, operationId: 'executeTool', summary: 'Run Tool', - description: `Run a built-in tool using published parameter IDs. Sim resolves \`credentialId\`, hosted keys, and whole-value \`{{VAR_NAME}}\` references for \`user-only\` parameters; other values pass through verbatim. Third-party refusal returns \`200\` with \`status: "failed"\`; the error envelope covers API failures. Hidden or missing tools return \`404\`; disallowed integrations return \`403\` with \`error.details.code: INTEGRATION_NOT_ALLOWED\`. Hosted-key use is billed to the workspace. ${WORKSPACE_API_KEY_DENIED}`, - errors: RESOURCE_ERRORS, + description: `Run a built-in tool using published parameters and caller-owned credentials. Whole-value \`{{VAR_NAME}}\` references resolve for \`user-only\` parameters. Provider refusal returns \`200\` with \`status: "failed"\`; API failures use the error envelope. Hidden tools return \`404\`; blocked integrations return \`403\` with \`error.details.code: INTEGRATION_NOT_ALLOWED\`. Hosted-key use and measured Function sandbox costs are billed to the workspace. Function usage-limit checks can refuse execution with \`402 USAGE_LIMIT_EXCEEDED\`. ${WORKSPACE_API_KEY_DENIED}`, + errors: [...RESOURCE_ERRORS, 'UsageLimitExceeded'], success: { description: 'The outcome of the tool call.' }, }), { @@ -2168,6 +2203,29 @@ const declaredRoutes = [ ), } ), + defineOpenApiRoute( + v2DownloadToolFileContract, + resourceOperation('Catalog', { + applicationOperation: toolExecutionOperations.downloadFile, + operationId: 'downloadToolFileV2', + summary: 'Download Tool File', + description: `Download a personal output from a direct tool call using its unchanged file.id. Requires its original owner and current workspace access. Use Download Workflow Run File for workflow outputs. Files can expire. ${WORKSPACE_API_KEY_DENIED} ${HEAD_MIRRORS_GET} ${HEAD_OMITS_PAYLOAD_HEADERS}`, + errors: [...RESOURCE_ERRORS], + success: { + description: 'The tool file bytes.', + headers: [...RATE_LIMIT_HEADERS, 'Content-Type', 'Content-Disposition', 'Content-Length'], + contentTypes: ['application/octet-stream'], + }, + }), + { + query: documentedSchema( + v2DownloadToolFileContract.query, + 'DownloadToolFileQuery', + 'Tool file download query', + 'Original direct-call file identifier and workspace access context.' + ), + } + ), ...permissionGroupOpenApiRoutes, ...organizationOpenApiRoutes, ...workspacePermissionOpenApiRoutes, @@ -2251,7 +2309,7 @@ export const resourcesOpenApiDocument = defineOpenApiDocument({ ], security: V2_AUTH_SECURITY, securitySchemes: V2_AUTH_SECURITY_SCHEMES, - headers: V2_COMMON_HEADERS, + headers: { ...V2_BINARY_DOWNLOAD_HEADERS, ...V2_COMMON_HEADERS }, errorSchema: V2_ERROR_SCHEMA, /** * Most `409`s in this document are name collisions, but MCP tool discovery diff --git a/apps/sim/lib/api/contracts/v2/openapi/workflows.ts b/apps/sim/lib/api/contracts/v2/openapi/workflows.ts index 8969eb4293e..21f8b3ed153 100644 --- a/apps/sim/lib/api/contracts/v2/openapi/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/openapi/workflows.ts @@ -28,6 +28,7 @@ import { withRequestBodyErrors, } from '@/lib/api/contracts/v2/openapi/shared' import { workspaceSyncOpenApiRoutes } from '@/lib/api/contracts/v2/openapi/workspace-sync' +import { v2InspectWorkflowContract } from '@/lib/api/contracts/v2/workflow-inspection' import { EXECUTE_OPTION_CONSTRAINTS, v2ActivateWorkflowVersionContract, @@ -56,6 +57,7 @@ import { v2ListWorkflowsContract, v2ListWorkflowVersionsContract, v2MoveWorkflowsContract, + v2PreviewWorkflowRunFromBlockContract, v2RelocateWorkflowFolderContract, v2ReplaceWorkflowStateContract, v2RestoreWorkflowContract, @@ -107,6 +109,8 @@ const WORKFLOW_FOLDER_EXAMPLE = { /** An empty lint report, for examples where the findings are not the subject. */ const EMPTY_LINT_EXAMPLE = { + checks: [], + codeIssues: [], sources: [], sinks: [], orphanBlocks: [], @@ -301,6 +305,46 @@ const declaredRoutes = [ ), } ), + defineOpenApiRoute( + v2InspectWorkflowContract, + workflowOperation({ + applicationOperation: workflowOperations.read, + operationId: 'inspectWorkflow', + summary: 'Inspect Workflow', + description: + 'Inspect a compact draft graph with block IDs, enabled states, connections, and bounded nonempty inputs. Credential fields and opaque credential-bearing inputs are withheld; code is omitted unless requested. This diagnostic representation is not suitable for Replace Workflow State. Automatic redaction cannot recognize every secret in arbitrary text or code.', + errors: RESOURCE_ERRORS, + success: jsonSuccess('A compact diagnostic view of the workflow draft.'), + }), + { + params: v2InspectWorkflowContract.params, + query: documentedSchema( + v2InspectWorkflowContract.query, + 'InspectWorkflowQuery', + 'Workflow inspection query', + 'Optional block selection and code inclusion.' + ), + response: documentedSchema( + v2InspectWorkflowContract.response.schema, + 'InspectWorkflowResponse', + 'Workflow inspection response', + 'A bounded diagnostic draft view, not an editable graph.', + [ + { + data: { + representation: 'diagnostic', + workflowId: WORKFLOW_ID, + workspaceId: WORKSPACE_ID, + blocks: [], + edges: [], + truncated: false, + notes: [], + }, + }, + ] + ), + } + ), defineOpenApiRoute( v2GetWorkflowStateContract, workflowOperation({ @@ -308,7 +352,7 @@ const declaredRoutes = [ operationId: 'getWorkflowState', summary: 'Get Workflow State', description: - 'Get the editable draft graph, including blocks, edges, loop and parallel containers, and variables. Use this state with Replace Workflow State to preserve workspace bindings; Export Workflow removes those bindings for portability. This read records no audit event, and `HEAD` mirrors `GET`.', + 'Get the full editable draft graph, including blocks, edges, loop and parallel containers, variables, and stored input values. Use Inspect Workflow for compact, redacted diagnostics. Use this state with Replace Workflow State to preserve workspace bindings; Export Workflow removes those bindings for portability. This read records no audit event, and `HEAD` mirrors `GET`.', /** * No `413`: unlike the workflow reads beside it this one resolves no * folder path, so it never materializes the workspace's folder tree, and @@ -361,6 +405,7 @@ const declaredRoutes = [ warnings: [], needsRedeployment: true, dryRun: false, + removedBindings: [], lint: EMPTY_LINT_EXAMPLE, }, }, @@ -402,6 +447,8 @@ const declaredRoutes = [ inputValidationErrors: [], mintedBlockIds: { triage: 'a3f1c0b2-7a44-4c1d-9d3a-2b8e5f0a1c77' }, lint: { + checks: [], + codeIssues: [], sources: [], sinks: [], orphanBlocks: [], @@ -985,6 +1032,10 @@ const declaredRoutes = [ { data: { version: '1.0', + representation: 'portable-export', + warnings: [ + 'Portable exports clear credential bindings. Use workflow state for in-place edits.', + ], exportedAt: '2026-08-09T18:04:11.000Z', workflow: { id: WORKFLOW_ID, @@ -1180,6 +1231,34 @@ const declaredRoutes = [ responses: { 200: executeSyncResponseSchema, 202: executeQueuedResponseSchema }, } ), + defineOpenApiRoute( + v2PreviewWorkflowRunFromBlockContract, + workflowRunOperation({ + applicationOperation: workflowOperations.previewManualFromBlock, + operationId: 'previewWorkflowRunFromBlock', + summary: 'Preview Partial Workflow Run', + description: `Inspect the current saved draft and one prior run without executing blocks or reserving a run ID. Returns executor entry validation, candidate rerun blocks, and upstream cached-output availability without output values. Requires write access to the workflow and OAuth api:read or a personal API key. Conditional paths are candidates, and a later run uses the draft saved at that time. ${WORKSPACE_API_KEY_DENIED}`, + errors: RESOURCE_ERRORS, + success: jsonSuccess( + 'A read-only partial-run preview, including any entry-validation failure.' + ), + }), + { + params: v2PreviewWorkflowRunFromBlockContract.params, + query: documentedSchema( + v2PreviewWorkflowRunFromBlockContract.query, + 'PreviewWorkflowRunFromBlockQuery', + 'Partial run preview query', + 'Starting block and source run supplying cached upstream outputs.' + ), + response: documentedSchema( + v2PreviewWorkflowRunFromBlockContract.response.schema, + 'PreviewWorkflowRunFromBlockResponse', + 'Partial run preview response', + 'Current draft graph candidates and source snapshot availability; no blocks are executed.' + ), + } + ), defineOpenApiRoute( v2ListWorkflowRunsContract, workflowRunOperation({ diff --git a/apps/sim/lib/api/contracts/v2/tool-files.ts b/apps/sim/lib/api/contracts/v2/tool-files.ts new file mode 100644 index 00000000000..5667b3cf867 --- /dev/null +++ b/apps/sim/lib/api/contracts/v2/tool-files.ts @@ -0,0 +1,25 @@ +import { z } from 'zod' +import { workspaceIdSchema } from '@/lib/api/contracts/primitives' +import { defineRouteContract } from '@/lib/api/contracts/types' + +export const v2DownloadToolFileQuerySchema = z + .object({ + workspaceId: workspaceIdSchema.describe('Workspace in which to authorize the download.'), + fileId: z + .string() + .min(1, 'fileId cannot be empty') + .max(2048, 'fileId is too long') + .describe( + 'The file.id from a direct tool result whose file.context is "copilot". Workflow output files use Download Workflow Run File instead.' + ), + }) + .strict() + +export type V2DownloadToolFileQuery = z.input + +export const v2DownloadToolFileContract = defineRouteContract({ + method: 'GET', + path: '/api/v2/tools/files/download', + query: v2DownloadToolFileQuerySchema, + response: { mode: 'binary' }, +}) diff --git a/apps/sim/lib/api/contracts/v2/workflow-inspection.ts b/apps/sim/lib/api/contracts/v2/workflow-inspection.ts new file mode 100644 index 00000000000..19203d5d516 --- /dev/null +++ b/apps/sim/lib/api/contracts/v2/workflow-inspection.ts @@ -0,0 +1,99 @@ +import { z } from 'zod' +import { booleanQueryFlagSchema, MAX_ID_LENGTH } from '@/lib/api/contracts/primitives' +import { defineRouteContract } from '@/lib/api/contracts/types' +import { v2DataResponse } from '@/lib/api/contracts/v2/shared' +import { v2WorkflowIdParamsSchema } from '@/lib/api/contracts/v2/workflows' + +export const v2InspectWorkflowQuerySchema = z + .object({ + blockId: z + .string() + .min(1, 'blockId cannot be empty') + .max(MAX_ID_LENGTH) + .optional() + .describe('Inspect one block and its incident connections. Omit to inspect the draft graph.'), + includeCode: booleanQueryFlagSchema + .default(false) + .describe( + 'Include bounded code inputs. Code and free text can contain hardcoded secrets that automatic redaction cannot recognize.' + ), + }) + .strict() + +export type V2InspectWorkflowQuery = z.output + +export const v2WorkflowInspectionSchema = z + .object({ + representation: z + .literal('diagnostic') + .describe('A read-only diagnostic projection, unsuitable for replacing workflow state.'), + workflowId: z.string().describe('Workflow whose saved draft is inspected.'), + workspaceId: z.string().describe('Workspace containing the workflow.'), + blocks: z + .array( + z.object({ + id: z.string().describe('Canonical saved block ID.'), + name: z.string().describe('Block display name.'), + type: z.string().describe('Registered block type.'), + enabled: z.boolean().describe('Whether the block is enabled in the saved draft.'), + parentId: z + .string() + .nullable() + .describe('Containing loop or parallel block ID, or null for a top-level block.'), + /** Author-defined input values retain their JSON shape after bounded redaction. */ + inputs: z + .record( + z.string(), + z + .unknown() + .describe( + 'User-authored block configuration after redaction and diagnostic size limits.' + ) + .meta({ examples: ['send'] }) + ) + .describe('Bounded, redacted user-authored input values. Empty fields are omitted.'), + omittedInputs: z + .array(z.string()) + .describe( + 'Nonempty fields withheld by credential, unknown-field, visibility, or code-inclusion rules.' + ), + }) + ) + .describe('Selected blocks without positions, output schemas, or runtime state.'), + edges: z + .array( + z.object({ + source: z.string().describe('Source block ID.'), + target: z.string().describe('Target block ID.'), + sourceHandle: z + .string() + .nullable() + .describe('Source output handle, or null when unspecified.'), + targetHandle: z + .string() + .nullable() + .describe('Target input handle, or null when unspecified.'), + }) + ) + .describe('Draft connections, or only connections touching the selected block.'), + truncated: z + .boolean() + .describe('Whether an input exceeded the diagnostic size or depth budget.'), + notes: z.array(z.string()).describe('Representation, redaction, and size-limit guidance.'), + }) + .meta({ + id: 'WorkflowInspection', + title: 'Workflow inspection', + description: + 'Compact diagnostic workflow draft, with credential fields withheld and projected inputs bounded.', + }) + +export type V2WorkflowInspection = z.output + +export const v2InspectWorkflowContract = defineRouteContract({ + method: 'GET', + path: '/api/v2/workflows/[workflowId]/inspect', + params: v2WorkflowIdParamsSchema, + query: v2InspectWorkflowQuerySchema, + response: { mode: 'json', schema: v2DataResponse(v2WorkflowInspectionSchema) }, +}) diff --git a/apps/sim/lib/api/contracts/v2/workflows.ts b/apps/sim/lib/api/contracts/v2/workflows.ts index abb14342723..7b214d28aad 100644 --- a/apps/sim/lib/api/contracts/v2/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/workflows.ts @@ -1244,6 +1244,24 @@ export const v2WorkflowRunSelectionSchema = z.discriminatedUnion('source', [ z .object({ source: z.literal('deployment').describe('Execute the active deployed workflow state.'), + entry: z + .object({ + type: z + .literal('trigger') + .describe('Enter through an enabled trigger in the active deployment.'), + blockId: z + .string() + .min(1, 'run.entry.blockId cannot be empty') + .max(MAX_ID_LENGTH) + .describe( + 'Enabled trigger block in the active deployment. Omit entry to preserve the default API-compatible trigger, or use its sole runnable trigger when it has no API entry.' + ), + }) + .strict() + .optional() + .describe( + 'Optional explicit deployed trigger. Otherwise preserve the existing API entry priority, or select the sole runnable trigger when no API entry exists. Multiple non-API entries require an explicit choice.' + ), }) .strict(), z @@ -1298,6 +1316,79 @@ export const v2WorkflowRunSelectionSchema = z.discriminatedUnion('source', [ ]) export type V2WorkflowRunSelection = z.input +export const v2PreviewWorkflowRunFromBlockQuerySchema = z + .object({ + blockId: z + .string() + .min(1, 'blockId cannot be empty') + .max(MAX_ID_LENGTH, `blockId cannot exceed ${MAX_ID_LENGTH} characters`) + .describe('Saved draft block at which a later manual run would start.'), + sourceRunId: v2WorkflowRunIdSchema.describe( + 'Existing run in this workflow whose persisted state would supply cached upstream outputs.' + ), + }) + .strict() +export type V2PreviewWorkflowRunFromBlockQuery = z.input< + typeof v2PreviewWorkflowRunFromBlockQuerySchema +> + +const v2RunPreviewBlockSchema = z.object({ + blockId: z.string().describe('Saved workflow block ID; internal sentinel nodes are omitted.'), + name: z.string().describe('Current saved block name.'), + type: z.string().describe('Current saved block type.'), + executedInSource: z + .boolean() + .describe('The source snapshot marks this block or one of its runtime instances as executed.'), +}) + +export const v2WorkflowRunFromBlockPreviewSchema = z + .object({ + workflowId: v2WorkflowIdParamsSchema.shape.workflowId, + sourceRunId: v2WorkflowRunIdSchema, + startBlockId: z.string().describe('Requested block at which a later manual run would start.'), + validation: z + .object({ + valid: z + .boolean() + .describe('Whether the executor accepts this starting block and source state.'), + error: z.string().optional().describe('Executor entry-validation failure, when invalid.'), + }) + .describe( + 'Entry validation only; does not validate credentials, provider inputs, or runtime behavior.' + ), + rerunBlocks: z + .array(v2RunPreviewBlockSchema) + .describe( + 'Starting block and downstream graph candidates. Conditions and runtime behavior determine actual execution; this is not execution order.' + ), + upstreamBlocks: z + .array( + v2RunPreviewBlockSchema.extend({ + hasCachedOutput: z + .boolean() + .describe( + 'The source snapshot contains an output entry for this block or a runtime instance. Does not verify referenced files or external resources; output values are not returned.' + ), + }) + ) + .describe( + 'Upstream blocks, including sibling branches needed by downstream candidates, whose existing outputs may be reused.' + ), + notes: z + .array(z.string()) + .describe('Limits of the preview and reuse of previously recorded outputs.'), + }) + .meta({ id: 'WorkflowRunFromBlockPreview', title: 'Partial workflow run preview' }) +export type V2WorkflowRunFromBlockPreview = z.output + +export const v2PreviewWorkflowRunFromBlockContract = defineRouteContract({ + method: 'GET', + path: '/api/v2/workflows/[workflowId]/runs/preview', + params: v2WorkflowIdParamsSchema, + query: v2PreviewWorkflowRunFromBlockQuerySchema, + response: { mode: 'json', schema: v2DataResponse(v2WorkflowRunFromBlockPreviewSchema) }, +}) + /** * Strict public execute body. Async is body-selected (`async: true`) — v2 has * no `X-Execution-Mode`/`X-Stream-Response` headers. `run` selects the public @@ -1320,6 +1411,14 @@ export const v2ExecuteWorkflowBodySchema = z .describe( 'Workflow state and entry point to execute. Omit for the active deployment. Manual execution requires OAuth or personal-key write access and supports synchronous or streamed runs only.' ), + stopAfterBlockId: z + .string() + .min(1, 'stopAfterBlockId cannot be empty') + .max(MAX_ID_LENGTH) + .optional() + .describe( + 'Stop scheduling after this enabled top-level block completes (or all iterations of a loop/parallel container). Real execution: earlier and concurrent branches can still perform side effects; if a condition bypasses this block, the run can finish without stopping here. Applies to this invocation only; a later explicit resume does not inherit this limit. Does not change the saved graph. Use selectedOutputs to return formatter results. Incompatible with async.' + ), async: z .boolean() .optional() @@ -1967,6 +2066,16 @@ export const v2CancelWorkflowRunContract = defineRouteContract({ export const v2WorkflowExportPayloadSchema = v1WorkflowExportPayloadSchema .extend({ + representation: z + .literal('portable-export') + .describe( + 'Sanitized copy format, not editable workflow state. Use workflows state get for in-place editing.' + ), + warnings: z + .array(z.string()) + .describe( + 'Export limitations and instructions for preserving IDs and binding references while editing an existing workflow.' + ), referenceManifest: workflowReferenceManifestSchema .optional() .describe( @@ -2390,7 +2499,8 @@ export const v2ExportWorkflowQuerySchema = z .meta({ id: 'ExportWorkflowQuery', title: 'Export workflow query', - description: 'Whether the export keeps workspace-scoped bindings.', + description: + 'Portable, sanitized export for sharing or copying. For in-place edits, read workflows state get and preview workflows state replace with dryRun=true; exports clear credentials even when workspace bindings are retained.', }) export type V2ExportWorkflowQuery = z.output @@ -2729,7 +2839,7 @@ export const v2WorkflowGraphSchema = z id: 'WorkflowGraph', title: 'Workflow graph', description: - 'The editable draft graph of a workflow: blocks, edges, derived loop and parallel containers, and variables.', + 'The editable draft graph of a workflow: preserves block IDs, credential references, table bindings, variables, and configuration for an in-place read-modify-write cycle. Unlike export, this is private workspace state, not a sanitized sharing format. Keep existing IDs and bindings; inspect state replace with dryRun=true before saving.', }) export type V2WorkflowGraph = z.output @@ -2819,6 +2929,55 @@ const v2WorkflowLintBlockRefSchema = z.object({ const v2WorkflowLintSchema = z .object({ + checks: z + .array( + z.object({ + name: z + .enum([ + 'graph', + 'fields', + 'block-output-references', + 'branch-output-references', + 'embedded-code-syntax', + 'credential-resource-references', + 'agent-tool-references', + 'table-fields', + 'runtime-execution', + ]) + .describe('Validation pass.'), + status: z + .enum(['complete', 'partial', 'skipped']) + .describe( + 'Whether this pass checked its full stated scope, a subset, or nothing. This never certifies runtime success.' + ), + detail: z + .string() + .describe( + 'Checks performed and limitations, including lookup failures and unsupported code languages.' + ), + }) + ) + .describe( + 'Explicit validation coverage. Empty findings do not mean skipped checks passed; no code or external action is executed.' + ), + codeIssues: z + .array( + v2WorkflowLintBlockRefSchema.extend({ + field: z.string().describe('Embedded code field.'), + language: z.literal('javascript').describe('Language parsed without execution.'), + message: z.string().describe('Syntax error; code and secret values are not included.'), + line: z.number().int().min(1).nullable().describe('One-based source line when known.'), + column: z + .number() + .int() + .min(1) + .nullable() + .describe('One-based source column when known.'), + }) + ) + .describe( + 'Syntax errors in enabled JavaScript Function bodies, including invalid regular expression flags. Python, Shell, generated source, dependencies, and resolved runtime values are not checked; inspect checks for scope.' + ), sources: z .array(v2WorkflowLintBlockRefSchema) .describe( @@ -2942,6 +3101,26 @@ const v2GraphWriteDryRunQuerySchema = z export const v2ReplaceWorkflowStateDataSchema = v2WorkflowGraphWriteResultSchema .extend({ + removedBindings: z + .array( + z.object({ + blockId: z.string().describe('Original block whose binding is removed.'), + blockName: z.string().describe('Original block display name.'), + field: z.string().describe('Original binding field.'), + valuePath: z + .array(z.union([z.string(), z.number().int().min(0)])) + .describe('Nested location inside the field value.'), + kind: z.enum(['credential', 'table']).describe('Kind of removed binding reference.'), + resourceId: z + .string() + .describe( + 'Non-secret identifier of the reference no longer present in this block. Never a credential secret value.' + ), + }) + ) + .describe( + 'Credential/table references removed relative to the saved graph, including removed blocks and changed IDs. Inspect this pre-save diff with dryRun=true. An empty list does not validate other resource bindings.' + ), lint: v2WorkflowLintSchema, dryRun: z .boolean() @@ -3457,12 +3636,12 @@ export const v2ApplyWorkflowOperationsBodySchema = z .object({ operations: z .array(v2WorkflowOperationSchema) - .min(1, 'operations cannot be empty') .max( MAX_WORKFLOW_EDIT_OPERATIONS, `operations cannot exceed ${MAX_WORKFLOW_EDIT_OPERATIONS} entries` ) - .describe('Edits to apply, in a single batch.'), + .default([]) + .describe('Edits to apply in a single batch. May be omitted for enablement-only requests.'), atomic: z .boolean() .optional() @@ -3496,6 +3675,10 @@ export const v2ApplyWorkflowOperationsBodySchema = z ), }) .strict() + .refine((body) => body.operations.length > 0 || (body.setBlockEnabled?.length ?? 0) > 0, { + path: ['operations'], + message: 'Provide at least one operation or setBlockEnabled change', + }) .meta({ id: 'ApplyWorkflowOperationsRequest', title: 'Apply workflow operations request', diff --git a/apps/sim/lib/api/mcp/generated/v2-operations.ts b/apps/sim/lib/api/mcp/generated/v2-operations.ts index 1e32086349c..bbdaaea958d 100644 --- a/apps/sim/lib/api/mcp/generated/v2-operations.ts +++ b/apps/sim/lib/api/mcp/generated/v2-operations.ts @@ -45,6 +45,7 @@ import { v2CreateCredentialConnectionContract, v2CreateServiceAccountCredentialContract, v2DeleteCredentialContract, + v2GetCredentialContract, v2ListCredentialProvidersContract, v2ListCredentialsContract, v2UpdateCredentialContract, @@ -260,6 +261,7 @@ import { v2UpdateWorkflowGroupContract, v2UpsertTableRowContract, } from '@/lib/api/contracts/v2/tables' +import { v2InspectWorkflowContract } from '@/lib/api/contracts/v2/workflow-inspection' import { v2CreateWorkflowMcpServerContract, v2DeleteWorkflowMcpServerContract, @@ -295,6 +297,7 @@ import { v2ListWorkflowVersionsContract, v2MoveWorkflowsContract, v2PreviewWorkflowImportContract, + v2PreviewWorkflowRunFromBlockContract, v2RelocateWorkflowFolderContract, v2ReplaceWorkflowStateContract, v2RestoreWorkflowContract, @@ -1151,7 +1154,7 @@ export const V2_MCP_OPERATIONS = { contract: v2ExecuteToolContract, summary: 'Run Tool', description: - 'Run a built-in tool using published parameter IDs. Sim resolves `credentialId`, hosted keys, and whole-value `{{VAR_NAME}}` references for `user-only` parameters; other values pass through verbatim. Third-party refusal returns `200` with `status: "failed"`; the error envelope covers API failures. Hidden or missing tools return `404`; disallowed integrations return `403` with `error.details.code: INTEGRATION_NOT_ALLOWED`. Hosted-key use is billed to the workspace. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.', + 'Run a built-in tool using published parameters and caller-owned credentials. Whole-value `{{VAR_NAME}}` references resolve for `user-only` parameters. Provider refusal returns `200` with `status: "failed"`; API failures use the error envelope. Hidden tools return `404`; blocked integrations return `403` with `error.details.code: INTEGRATION_NOT_ALLOWED`. Hosted-key use and measured Function sandbox costs are billed to the workspace. Function usage-limit checks can refuse execution with `402 USAGE_LIMIT_EXCEEDED`. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:write`.', workspaceKeyUnsupported: true, handler: () => import('@/app/api/v2/tools/[toolId]/execute/route').then((route) => route.POST), }, @@ -1202,6 +1205,15 @@ export const V2_MCP_OPERATIONS = { "Get a block's fields, conditions, operations, tool schemas, and triggers. Unversioned types resolve to the newest visible version; the returned `id` identifies that version. Hidden or missing blocks return `404`.\n\nOAuth scope: `api:read`.", handler: () => import('@/app/api/v2/blocks/[blockId]/route').then((route) => route.GET), }, + getCredential: { + contract: v2GetCredentialContract, + summary: 'Inspect Credential', + description: + "Inspect one selected connection's stored provider identity, recorded OAuth scopes, and access limitations. This does not decrypt secrets, contact the provider, or verify live resource access. Custom bot identities/scopes may be unknown. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.", + workspaceKeyUnsupported: true, + handler: () => + import('@/app/api/v2/credentials/[credentialId]/route').then((route) => route.GET), + }, getCustomTool: { contract: v2GetCustomToolContract, summary: 'Get Custom Tool', @@ -1527,7 +1539,7 @@ export const V2_MCP_OPERATIONS = { contract: v2GetWorkflowStateContract, summary: 'Get Workflow State', description: - 'Get the editable draft graph, including blocks, edges, loop and parallel containers, and variables. Use this state with Replace Workflow State to preserve workspace bindings; Export Workflow removes those bindings for portability. This read records no audit event, and `HEAD` mirrors `GET`.\n\nOAuth scope: `api:read`.', + 'Get the full editable draft graph, including blocks, edges, loop and parallel containers, variables, and stored input values. Use Inspect Workflow for compact, redacted diagnostics. Use this state with Replace Workflow State to preserve workspace bindings; Export Workflow removes those bindings for portability. This read records no audit event, and `HEAD` mirrors `GET`.\n\nOAuth scope: `api:read`.', handler: () => import('@/app/api/v2/workflows/[workflowId]/state/route').then((route) => route.GET), }, @@ -1615,6 +1627,14 @@ export const V2_MCP_OPERATIONS = { 'Create an undeployed workflow from a portable export object, bare state, or JSON string. Mapping options require a preview fingerprint and stable request ID; unresolved required configuration creates nothing. Mapped imports return source-to-imported block IDs and an operation receipt. Workspace folder trees exceeding 10,000 folders return `413`.\n\nOAuth scope: `api:write`.', handler: () => import('@/app/api/v2/workflows/import/route').then((route) => route.POST), }, + inspectWorkflow: { + contract: v2InspectWorkflowContract, + summary: 'Inspect Workflow', + description: + 'Inspect a compact draft graph with block IDs, enabled states, connections, and bounded nonempty inputs. Credential fields and opaque credential-bearing inputs are withheld; code is omitted unless requested. This diagnostic representation is not suitable for Replace Workflow State. Automatic redaction cannot recognize every secret in arbitrary text or code.\n\nOAuth scope: `api:read`.', + handler: () => + import('@/app/api/v2/workflows/[workflowId]/inspect/route').then((route) => route.GET), + }, listAuditLogs: { contract: v2ListAuditLogsContract, summary: 'List Audit Logs', @@ -2127,6 +2147,15 @@ export const V2_MCP_OPERATIONS = { handler: () => import('@/app/api/v2/workflows/import/preview/route').then((route) => route.POST), }, + previewWorkflowRunFromBlock: { + contract: v2PreviewWorkflowRunFromBlockContract, + summary: 'Preview Partial Workflow Run', + description: + 'Inspect the current saved draft and one prior run without executing blocks or reserving a run ID. Returns executor entry validation, candidate rerun blocks, and upstream cached-output availability without output values. Requires write access to the workflow and OAuth api:read or a personal API key. Conditional paths are candidates, and a later run uses the draft saved at that time. Workspace API keys return `403`; use a personal API key or scoped OAuth token.\n\nOAuth scope: `api:read`.', + workspaceKeyUnsupported: true, + handler: () => + import('@/app/api/v2/workflows/[workflowId]/runs/preview/route').then((route) => route.GET), + }, previewWorkspaceFork: { contract: v2PreviewWorkspaceForkContract, summary: 'Preview Workspace Fork', diff --git a/apps/sim/lib/api/server/routes/copilot-route-inventory.test.ts b/apps/sim/lib/api/server/routes/copilot-route-inventory.test.ts index 55c235dc1eb..c3f409c7b20 100644 --- a/apps/sim/lib/api/server/routes/copilot-route-inventory.test.ts +++ b/apps/sim/lib/api/server/routes/copilot-route-inventory.test.ts @@ -292,6 +292,12 @@ it('inventories private operation admission without executing route requests', a "operation": "organizations.workspaces.list", "path": "/api/v2/organizations/[organizationId]/workspaces", }, + { + "audience": null, + "method": "GET", + "operation": "tools.files.download", + "path": "/api/v2/tools/files/download", + }, { "audience": null, "method": "GET", diff --git a/apps/sim/lib/api/server/routes/v2-route-table.generated.ts b/apps/sim/lib/api/server/routes/v2-route-table.generated.ts index f013946baf7..80c56f6dfab 100644 --- a/apps/sim/lib/api/server/routes/v2-route-table.generated.ts +++ b/apps/sim/lib/api/server/routes/v2-route-table.generated.ts @@ -585,6 +585,10 @@ export const V2_ROUTES: readonly V2RouteEntry[] = [ pattern: '/api/v2/tools/{toolId}/execute', load: () => import('@/app/api/v2/tools/[toolId]/execute/route'), }, + { + pattern: '/api/v2/tools/files/download', + load: () => import('@/app/api/v2/tools/files/download/route'), + }, { pattern: '/api/v2/uploads/{uploadId}', load: () => import('@/app/api/v2/uploads/[uploadId]/route'), @@ -641,6 +645,10 @@ export const V2_ROUTES: readonly V2RouteEntry[] = [ pattern: '/api/v2/workflows/{workflowId}/export', load: () => import('@/app/api/v2/workflows/[workflowId]/export/route'), }, + { + pattern: '/api/v2/workflows/{workflowId}/inspect', + load: () => import('@/app/api/v2/workflows/[workflowId]/inspect/route'), + }, { pattern: '/api/v2/workflows/{workflowId}/operations', load: () => import('@/app/api/v2/workflows/[workflowId]/operations/route'), @@ -673,6 +681,10 @@ export const V2_ROUTES: readonly V2RouteEntry[] = [ pattern: '/api/v2/workflows/{workflowId}/runs/{runId}/resume', load: () => import('@/app/api/v2/workflows/[workflowId]/runs/[runId]/resume/route'), }, + { + pattern: '/api/v2/workflows/{workflowId}/runs/preview', + load: () => import('@/app/api/v2/workflows/[workflowId]/runs/preview/route'), + }, { pattern: '/api/v2/workflows/{workflowId}/state', load: () => import('@/app/api/v2/workflows/[workflowId]/state/route'), diff --git a/apps/sim/lib/catalog/projection/tool-auth.test.ts b/apps/sim/lib/catalog/projection/tool-auth.test.ts new file mode 100644 index 00000000000..e2b7f24ce62 --- /dev/null +++ b/apps/sim/lib/catalog/projection/tool-auth.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from 'vitest' +import { v2ToolSummarySchema } from '@/lib/api/contracts/v2/catalog' +import { projectToolSummary } from '@/lib/catalog/projection/tool' +import { supportsSlackBotToken } from '@/tools/slack/auth' +import { slackListFilesTool } from '@/tools/slack/list_files' +import { slackMessageTool } from '@/tools/slack/message' +import { slackUpdateMessageTool } from '@/tools/slack/update_message' + +const deployment = { hostedKeys: false } + +describe('declared Slack authentication alternatives', () => { + it.each([slackMessageTool, slackUpdateMessageTool])( + 'publishes optional OAuth for $id with a declared bot-token alternative', + (tool) => { + expect(supportsSlackBotToken(tool)).toBe(true) + expect( + v2ToolSummarySchema.parse(projectToolSummary(tool.id, tool, deployment)).oauth + ).toMatchObject({ + required: false, + provider: 'slack', + requiredScopes: ['chat:write'], + }) + expect(tool.oauth?.required).toBe(true) + } + ) + + it('does not invent a bot-token option for an OAuth-only Slack tool', () => { + expect(supportsSlackBotToken(slackListFilesTool)).toBe(false) + expect( + projectToolSummary(slackListFilesTool.id, slackListFilesTool, deployment).oauth?.required + ).toBe(true) + }) + + it('does not exempt other OAuth providers with similarly named parameters', () => { + const tool = { ...slackMessageTool, oauth: { required: true, provider: 'github' as const } } + expect(supportsSlackBotToken(tool)).toBe(false) + expect(projectToolSummary(tool.id, tool, deployment).oauth?.required).toBe(true) + }) +}) diff --git a/apps/sim/lib/catalog/projection/tool.ts b/apps/sim/lib/catalog/projection/tool.ts index c9637fac7bb..78495ed7234 100644 --- a/apps/sim/lib/catalog/projection/tool.ts +++ b/apps/sim/lib/catalog/projection/tool.ts @@ -2,6 +2,7 @@ import { isHiddenFromDisplay } from '@/blocks/types' import type { HostedApiKeySupport } from '@/tools/hosted-api-key' import { getToolMetadata, type ToolMetadata } from '@/tools/metadata' import { getToolOutputsMetadata } from '@/tools/metadata-outputs' +import { supportsSlackBotToken } from '@/tools/slack/auth' import { resolveToolId } from '@/tools/tool-ids' import type { ToolConfig } from '@/tools/types' @@ -79,9 +80,13 @@ export interface CatalogToolDetail extends CatalogToolSummary { outputs: Record } -function projectOAuth(oauth: ToolMetadata['oauth']): CatalogToolOAuth | undefined { +function projectOAuth(metadata: ToolMetadata): CatalogToolOAuth | undefined { + const { oauth } = metadata if (!oauth) return undefined - const projected: CatalogToolOAuth = { required: oauth.required, provider: oauth.provider } + const projected: CatalogToolOAuth = { + required: oauth.required && !supportsSlackBotToken(metadata), + provider: oauth.provider, + } if (oauth.requiredScopes !== undefined) projected.requiredScopes = [...oauth.requiredScopes] return projected } @@ -111,7 +116,7 @@ export function projectToolSummary( hostedApiKey: deployment.hostedKeys ? (metadata.hostedApiKey ?? 'none') : 'none', } if (metadata.version !== undefined) summary.version = metadata.version - const oauth = projectOAuth(metadata.oauth) + const oauth = projectOAuth(metadata) if (oauth) summary.oauth = oauth return summary } diff --git a/apps/sim/lib/credentials/application/inspect-credential.test.ts b/apps/sim/lib/credentials/application/inspect-credential.test.ts new file mode 100644 index 00000000000..e9f4f024f48 --- /dev/null +++ b/apps/sim/lib/credentials/application/inspect-credential.test.ts @@ -0,0 +1,179 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const mocks = vi.hoisted(() => ({ + context: vi.fn(), + permission: vi.fn(), + actor: vi.fn(), + account: vi.fn(), +})) +vi.mock('@/lib/credentials/application/credential-context', () => ({ + resolveCredentialApplicationContext: mocks.context, +})) +vi.mock('@sim/platform-authz/workspace', () => ({ + permissionSatisfies: (permission: string | null) => Boolean(permission), + resolveEffectiveWorkspacePermission: mocks.permission, +})) +vi.mock('@/lib/credentials/access', () => ({ getCredentialActorContext: mocks.actor })) +vi.mock('@/lib/credentials/queries', () => ({ readCredentialAccountMetadata: mocks.account })) + +import { inspectCredential } from '@/lib/credentials/application/inspect-credential' +import { SLACK_CUSTOM_BOT_PROVIDER_ID } from '@/lib/oauth/types' + +const principal = { kind: 'personal_api_key' as const, userId: 'actor-1', keyId: 'key-1' } +const input = { credentialId: 'credential-1', assertedWorkspaceId: 'workspace-1' } +const credential = { + id: 'credential-1', + type: 'oauth', + workspaceId: 'workspace-1', + accountId: 'account-1', + providerId: 'slack', + displayName: 'A friendly label', +} +const context = { + workspaceId: 'workspace-1', + workspaceOrganizationId: null, + allowPersonalApiKeys: true, + billedAccountUserId: 'billing-owner', + credential, +} + +beforeEach(() => { + mocks.context.mockResolvedValue({ ...context }) + mocks.permission.mockResolvedValue('read') + mocks.actor.mockResolvedValue({ + credential, + member: { role: 'member', status: 'active' }, + hasWorkspaceAccess: true, + isAdmin: false, + }) + mocks.account.mockResolvedValue({ + externalAccountId: 'T123-U456-connection-id', + scope: 'chat:write, files:read\nchat:write', + }) +}) + +describe('inspectCredential', () => { + it('reports recorded OAuth identity and scopes without claiming a live bot identity', async () => { + const { diagnostics } = await inspectCredential.execute({ principal, input }) + expect(mocks.context).toHaveBeenCalledWith(input) + expect(mocks.actor).toHaveBeenCalledWith('credential-1', 'actor-1', { + workspaceId: 'workspace-1', + }) + expect(mocks.account).toHaveBeenCalledWith('account-1', 'slack') + expect(diagnostics.identity).toEqual({ + source: 'linked-account', + subjectId: null, + tenantId: 'T123', + externalAccountId: 'T123-U456-connection-id', + verifiedLive: false, + }) + expect(diagnostics.scopes).toEqual({ + source: 'linked-account', + values: ['chat:write', 'files:read'], + }) + expect(diagnostics.notes.join(' ')).toContain('conversation membership') + expect(JSON.stringify(diagnostics)).not.toContain('billing-owner') + expect(JSON.stringify(diagnostics)).not.toContain('A friendly label') + }) + + it('denies workspace access before reading account metadata', async () => { + mocks.permission.mockResolvedValue(null) + await expect(inspectCredential.execute({ principal, input })).rejects.toThrow() + expect(mocks.actor).not.toHaveBeenCalled() + expect(mocks.account).not.toHaveBeenCalled() + }) + + it('prefers explicit managed OAuth identity and grants when recorded', async () => { + mocks.context.mockResolvedValue({ + ...context, + credential: { + ...credential, + providerSubjectId: 'provider-user', + providerTenantId: 'tenant', + grantedScopes: ['read'], + }, + }) + const { diagnostics } = await inspectCredential.execute({ principal, input }) + expect(diagnostics.identity).toMatchObject({ + source: 'credential', + subjectId: 'provider-user', + tenantId: 'tenant', + verifiedLive: false, + }) + expect(diagnostics.scopes).toEqual({ source: 'credential', values: ['read'] }) + }) + + it('keeps custom-bot identity and grants unknown when stored only inside secret material', async () => { + mocks.context.mockResolvedValue({ + ...context, + credential: { + ...credential, + type: 'service_account', + providerId: SLACK_CUSTOM_BOT_PROVIDER_ID, + accountId: null, + encryptedServiceAccountKey: 'DO-NOT-DECRYPT', + }, + }) + const { diagnostics } = await inspectCredential.execute({ principal, input }) + expect(diagnostics.identity.source).toBe('unknown') + expect(diagnostics.scopes).toEqual({ source: 'unknown', values: [] }) + expect(diagnostics.notes.join(' ')).toContain('not decrypted') + expect(JSON.stringify(diagnostics)).not.toContain('DO-NOT-DECRYPT') + expect(mocks.account).not.toHaveBeenCalled() + }) + + it('reports missing linked account metadata as unknown', async () => { + mocks.account.mockResolvedValue(null) + const { diagnostics } = await inspectCredential.execute({ principal, input }) + expect(diagnostics.identity.source).toBe('unknown') + expect(diagnostics.scopes.source).toBe('unknown') + }) + + it('denies nonmembers before reading linked account metadata', async () => { + mocks.actor.mockResolvedValue({ + credential, + member: null, + hasWorkspaceAccess: true, + isAdmin: false, + }) + await expect(inspectCredential.execute({ principal, input })).rejects.toMatchObject({ + code: 'forbidden', + }) + expect(mocks.account).not.toHaveBeenCalled() + }) + + it('conceals an actor lookup in a different workspace', async () => { + mocks.actor.mockResolvedValue({ + credential: { ...credential, workspaceId: 'other' }, + member: { role: 'member' }, + hasWorkspaceAccess: true, + isAdmin: false, + }) + await expect(inspectCredential.execute({ principal, input })).rejects.toMatchObject({ + code: 'not_found', + }) + expect(mocks.account).not.toHaveBeenCalled() + }) + + it('denies workspace keys before canonical or account loading', async () => { + await expect( + inspectCredential.execute({ + principal: { kind: 'workspace_api_key', workspaceId: 'workspace-1', keyId: 'key' }, + input, + }) + ).rejects.toThrow() + expect(mocks.context).not.toHaveBeenCalled() + expect(mocks.account).not.toHaveBeenCalled() + }) + + it('does not expose secret credential types through an API principal', async () => { + mocks.context.mockResolvedValue({ + ...context, + credential: { ...credential, type: 'env_workspace' }, + }) + await expect(inspectCredential.execute({ principal, input })).rejects.toMatchObject({ + code: 'validation', + }) + expect(mocks.account).not.toHaveBeenCalled() + }) +}) diff --git a/apps/sim/lib/credentials/application/inspect-credential.ts b/apps/sim/lib/credentials/application/inspect-credential.ts new file mode 100644 index 00000000000..02e891cea50 --- /dev/null +++ b/apps/sim/lib/credentials/application/inspect-credential.ts @@ -0,0 +1,91 @@ +import { + defineAuthorizedCredentialUseCase, + requireCredentialAccess, + requireManageableCredentialType, +} from '@/lib/credentials/application/authorized-credential-use-case' +import { resolveCredentialApplicationContext } from '@/lib/credentials/application/credential-context' +import { credentialOperations } from '@/lib/credentials/application/operations' +import { readCredentialAccountMetadata } from '@/lib/credentials/queries' +import { extractSlackTeamId } from '@/lib/oauth/slack' +import { SLACK_CUSTOM_BOT_PROVIDER_ID } from '@/lib/oauth/types' + +export interface InspectCredentialInput { + credentialId: string + assertedWorkspaceId: string +} + +export interface CredentialDiagnostics { + identity: { + source: 'credential' | 'linked-account' | 'unknown' + subjectId: string | null + tenantId: string | null + externalAccountId: string | null + verifiedLive: false + } + scopes: { source: 'credential' | 'linked-account' | 'unknown'; values: string[] } + notes: string[] +} + +/** Reads only stored connection metadata after canonical workspace and credential authorization. */ +export const inspectCredential = defineAuthorizedCredentialUseCase({ + operation: credentialOperations.inspect, + resolveContext: ({ input }: { input: InspectCredentialInput }) => + resolveCredentialApplicationContext(input), + async execute({ principal, context }) { + const { credential } = context + requireManageableCredentialType(principal, credential) + const access = requireCredentialAccess(context) + const linked = + credential.type === 'oauth' && credential.accountId && credential.providerId + ? await readCredentialAccountMetadata(credential.accountId, credential.providerId) + : null + const storedScopes = credential.grantedScopes + const isSlack = + credential.providerId === 'slack' || credential.providerId === SLACK_CUSTOM_BOT_PROVIDER_ID + const diagnostics: CredentialDiagnostics = { + identity: { + source: + credential.providerSubjectId || credential.providerTenantId + ? 'credential' + : linked + ? 'linked-account' + : 'unknown', + subjectId: credential.providerSubjectId ?? null, + tenantId: + credential.providerTenantId ?? + (isSlack ? extractSlackTeamId(linked?.externalAccountId) : null), + externalAccountId: linked?.externalAccountId ?? null, + verifiedLive: false, + }, + scopes: { + source: + storedScopes != null + ? 'credential' + : linked?.scope != null + ? 'linked-account' + : 'unknown', + values: [...new Set(storedScopes ?? linked?.scope?.split(/[\s,]+/).filter(Boolean) ?? [])], + }, + notes: [ + 'Stored metadata only: this does not contact the provider, verify token validity, or prove access to a particular resource. Display names are labels, not verified identities.', + ], + } + if (linked) + diagnostics.notes.push( + 'externalAccountId is the stored OAuth connection identifier and may include installation suffixes; it is not necessarily the identity currently acting at the provider.' + ) + if (diagnostics.identity.source === 'unknown') + diagnostics.notes.push( + 'No non-secret identity metadata is stored for this connection. Secret payloads are not decrypted for inspection.' + ) + if (diagnostics.scopes.source === 'unknown') + diagnostics.notes.push( + 'Granted scopes are unknown. Provider defaults and available tool definitions do not establish this credential’s actual grants.' + ) + if (isSlack) + diagnostics.notes.push( + 'Slack bot access is limited by the installed app’s grants and conversation membership. Channel IDs and a connected credential do not prove access to private channels, messages, or files; invite the bot to the conversation and check missing_scope/not_in_channel errors for the selected credential.' + ) + return { credential, access, diagnostics } + }, +}) diff --git a/apps/sim/lib/credentials/application/operations.ts b/apps/sim/lib/credentials/application/operations.ts index 7a20c196f02..854d3f5719a 100644 --- a/apps/sim/lib/credentials/application/operations.ts +++ b/apps/sim/lib/credentials/application/operations.ts @@ -144,6 +144,17 @@ export const credentialOperations = { capability: 'integrations.manage', ...HUMAN_AND_COPILOT_PRINCIPALS, }), + inspect: defineCredentialOperation( + defineWorkspaceOperation({ + id: 'credentials.inspect', + oauthScope: 'api:read', + minimumRole: 'read', + workspaceApiKey: 'deny', + capability: 'integrations.manage', + ...HUMAN_AND_COPILOT_PRINCIPALS, + }), + 'member' + ), read: defineCredentialOperation( defineWorkspaceOperation({ id: 'credentials.read', diff --git a/apps/sim/lib/credentials/queries.test.ts b/apps/sim/lib/credentials/queries.test.ts index e59aa82f64b..ad9c735e4aa 100644 --- a/apps/sim/lib/credentials/queries.test.ts +++ b/apps/sim/lib/credentials/queries.test.ts @@ -6,6 +6,7 @@ import { getWorkspaceCredential, listVisibleWorkspaceCredentials, listWorkspacePrincipalCredentials, + readCredentialAccountMetadata, } from '@/lib/credentials/queries' describe('listVisibleWorkspaceCredentials', () => { @@ -111,3 +112,20 @@ describe('ordinary credential lookups', () => { ]) }) }) + +describe('readCredentialAccountMetadata', () => { + beforeEach(() => resetDbChainMock()) + + it('selects only non-secret metadata for the exact account/provider pair', async () => { + const row = { externalAccountId: 'T123-U456-connection', scope: 'files:read' } + dbChainMockFns.limit.mockResolvedValueOnce([row]) + expect(await readCredentialAccountMetadata('account-1', 'slack')).toEqual(row) + expect(dbChainMockFns.select).toHaveBeenCalledWith({ + externalAccountId: schemaMock.account.accountId, + scope: schemaMock.account.scope, + }) + expect(drizzleOrmMock.eq).toHaveBeenCalledWith(schemaMock.account.id, 'account-1') + expect(drizzleOrmMock.eq).toHaveBeenCalledWith(schemaMock.account.providerId, 'slack') + expect(dbChainMockFns.limit).toHaveBeenCalledWith(1) + }) +}) diff --git a/apps/sim/lib/credentials/queries.ts b/apps/sim/lib/credentials/queries.ts index 819fb20a27d..7d5a760e16f 100644 --- a/apps/sim/lib/credentials/queries.ts +++ b/apps/sim/lib/credentials/queries.ts @@ -1,5 +1,5 @@ import { db } from '@sim/db' -import { credential, credentialMember, member, workspace } from '@sim/db/schema' +import { account, credential, credentialMember, member, workspace } from '@sim/db/schema' import { and, eq, inArray, isNotNull, notInArray, or, sql } from 'drizzle-orm' import type { V2CredentialSortBy } from '@/lib/api/contracts/v2/credentials' import { @@ -415,3 +415,13 @@ export async function getCredentialById(credentialId: string): Promise { })) }) + it('skips every lookup when no names are selected', async () => { + const snapshot = await getPersonalAndWorkspaceEnv('user-1', 'workspace-1', { + requestedNames: [], + }) + expect(snapshot).toEqual({ + personalEncrypted: {}, + workspaceEncrypted: {}, + personalDecrypted: {}, + workspaceDecrypted: {}, + personalOwners: {}, + conflicts: [], + decryptionFailures: [], + workspaceUnredactedKeys: [], + }) + expect(mockCheckWorkspaceAccess).not.toHaveBeenCalled() + expect(mockGetAccessibleEnvCredentials).not.toHaveBeenCalled() + expect(encryptionMockFns.mockDecryptSecret).not.toHaveBeenCalled() + }) + + it('filters selection before decryption while retaining owner, precedence and visibility provenance', async () => { + mockGetAccessibleEnvCredentials.mockResolvedValue([ + { + type: 'env_workspace', + envKey: 'SELECTED', + envOwnerUserId: null, + updatedAt: new Date(), + unredacted: true, + }, + { + type: 'env_workspace', + envKey: 'OTHER', + envOwnerUserId: null, + updatedAt: new Date(), + unredacted: true, + }, + { + type: 'env_personal', + envKey: 'SHARED', + envOwnerUserId: 'owner-2', + updatedAt: new Date(), + unredacted: false, + }, + ]) + queueTableRows(environment, [ + { variables: { SELECTED: 'personal-cipher', OTHER: 'other-personal-cipher' } }, + ]) + queueTableRows(workspaceEnvironment, [ + { + variables: { + SELECTED: 'workspace-cipher', + OTHER: 'other-workspace-cipher', + DENIED: 'denied-cipher', + }, + }, + ]) + queueTableRows(environment, [ + { userId: 'owner-2', variables: { SHARED: 'shared-cipher', UNRELATED: 'unrelated-cipher' } }, + ]) + const snapshot = await getPersonalAndWorkspaceEnv('user-1', 'workspace-1', { + requestedNames: ['SELECTED', 'SHARED', 'DENIED', 'SELECTED'], + }) + expect(snapshot).toMatchObject({ + personalEncrypted: { SELECTED: 'personal-cipher', SHARED: 'shared-cipher' }, + workspaceEncrypted: { SELECTED: 'workspace-cipher' }, + personalDecrypted: { SELECTED: 'plain:personal-cipher', SHARED: 'plain:shared-cipher' }, + workspaceDecrypted: { SELECTED: 'plain:workspace-cipher' }, + personalOwners: { SELECTED: 'user-1', SHARED: 'owner-2' }, + conflicts: ['SELECTED'], + workspaceUnredactedKeys: ['SELECTED'], + }) + expect(encryptionMockFns.mockDecryptSecret.mock.calls.flat()).toEqual( + expect.arrayContaining(['personal-cipher', 'workspace-cipher', 'shared-cipher']) + ) + expect(encryptionMockFns.mockDecryptSecret).toHaveBeenCalledTimes(3) + }) + + it('rechecks selected credential access after a grant is revoked', async () => { + const credential = { + type: 'env_workspace', + envKey: 'SELECTED', + envOwnerUserId: null, + updatedAt: new Date(), + unredacted: false, + } + mockGetAccessibleEnvCredentials.mockResolvedValueOnce([credential]).mockResolvedValueOnce([]) + for (let index = 0; index < 2; index++) { + queueTableRows(environment, [{ variables: {} }]) + queueTableRows(workspaceEnvironment, [{ variables: { SELECTED: 'workspace-cipher' } }]) + } + expect( + (await getPersonalAndWorkspaceEnv('user-1', 'workspace-1', { requestedNames: ['SELECTED'] })) + .workspaceDecrypted + ).toEqual({ SELECTED: 'plain:workspace-cipher' }) + expect( + (await getPersonalAndWorkspaceEnv('user-1', 'workspace-1', { requestedNames: ['SELECTED'] })) + .workspaceDecrypted + ).toEqual({}) + expect(mockCheckWorkspaceAccess).toHaveBeenCalledTimes(2) + expect(mockGetAccessibleEnvCredentials).toHaveBeenCalledTimes(2) + expect(encryptionMockFns.mockDecryptSecret).toHaveBeenCalledOnce() + }) + it('filters every workspace secret when the caller has zero credential grants', async () => { queueTableRows(environment, [{ variables: { PERSONAL_KEY: 'personal-cipher' } }]) queueTableRows(workspaceEnvironment, [{ variables: { WORKSPACE_KEY: 'workspace-cipher' } }]) diff --git a/apps/sim/lib/environment/utils.ts b/apps/sim/lib/environment/utils.ts index 3e43c5f48ac..b56e274620b 100644 --- a/apps/sim/lib/environment/utils.ts +++ b/apps/sim/lib/environment/utils.ts @@ -353,10 +353,36 @@ export async function resolveEffectiveEnvironmentVariables( export async function getPersonalAndWorkspaceEnv( userId: string, workspaceId?: string, - options?: { workspaceAccess?: WorkspaceAccess } + options?: { workspaceAccess?: WorkspaceAccess; requestedNames?: readonly string[] } ): Promise { - const { personalEncrypted, workspaceEncrypted, personalOwners, workspaceUnredactedKeys } = - await loadAccessibleEncryptedEnvironment(userId, workspaceId, options) + if (options?.requestedNames?.length === 0) { + return { + personalEncrypted: {}, + workspaceEncrypted: {}, + personalDecrypted: {}, + workspaceDecrypted: {}, + personalOwners: {}, + conflicts: [], + decryptionFailures: [], + workspaceUnredactedKeys: [], + } + } + const accessible = await loadAccessibleEncryptedEnvironment(userId, workspaceId, options) + const requestedNames = options?.requestedNames ? new Set(options.requestedNames) : undefined + const selectRequested = (values: Record): Record => { + if (!requestedNames) return values + return Object.fromEntries( + [...requestedNames].flatMap((name) => + Object.hasOwn(values, name) ? [[name, values[name]]] : [] + ) + ) + } + const personalEncrypted = selectRequested(accessible.personalEncrypted) + const workspaceEncrypted = selectRequested(accessible.workspaceEncrypted) + const personalOwners = selectRequested(accessible.personalOwners) + const workspaceUnredactedKeys = accessible.workspaceUnredactedKeys.filter( + (name) => !requestedNames || requestedNames.has(name) + ) const decryptionFailures: string[] = [] diff --git a/apps/sim/lib/execution/javascript-imports.ts b/apps/sim/lib/execution/javascript-imports.ts new file mode 100644 index 00000000000..31a7b0610e8 --- /dev/null +++ b/apps/sim/lib/execution/javascript-imports.ts @@ -0,0 +1,19 @@ +import type ts from '@typescript/typescript6' + +/** Static imports lifted out of Function bodies by execution and syntax validation alike. */ +export function collectJavaScriptImportSegments( + sourceFile: ts.SourceFile, + parser: Pick +): { text: string; start: number; end: number }[] { + return sourceFile.statements.flatMap((statement) => + parser.isImportDeclaration(statement) || parser.isImportEqualsDeclaration(statement) + ? [ + { + text: statement.getFullText(sourceFile).trim(), + start: statement.getFullStart(), + end: statement.getEnd(), + }, + ] + : [] + ) +} diff --git a/apps/sim/lib/function-execution/application/execute-function.test.ts b/apps/sim/lib/function-execution/application/execute-function.test.ts index a5d02716fae..79ed24ef9b0 100644 --- a/apps/sim/lib/function-execution/application/execute-function.test.ts +++ b/apps/sim/lib/function-execution/application/execute-function.test.ts @@ -64,6 +64,42 @@ describe('executeFunction', () => { mocks.resolvePermission.mockResolvedValue('write') }) + it('rejects a direct OAuth token without write scope before loading workspace data', async () => { + await expect( + executeFunction.execute({ + principal: { + kind: 'oauth_access_token', + userId: 'caller', + tokenId: 'token', + clientId: 'client', + scopes: ['api:read'], + expiresAt: new Date('2099-01-01'), + }, + input: { + workspaceId: 'workspace-1', + body: { code: 'return 1', workspaceId: 'workspace-1' }, + headers: new Headers(), + }, + }) + ).rejects.toThrow() + expect(mocks.executeRequest).not.toHaveBeenCalled() + }) + + it('denies a direct caller without current workspace access', async () => { + mocks.resolvePermission.mockResolvedValue(null) + await expect( + executeFunction.execute({ + principal: { kind: 'personal_api_key', userId: 'caller', keyId: 'key' }, + input: { + workspaceId: 'workspace-1', + body: { code: 'return 1', workspaceId: 'workspace-1' }, + headers: new Headers(), + }, + }) + ).rejects.toThrow() + expect(mocks.executeRequest).not.toHaveBeenCalled() + }) + it('uses only the real workflow subject for legacy file contexts', async () => { const humanPrincipal: WorkflowExecutionDelegatedPrincipal = { ...principal, @@ -132,6 +168,7 @@ describe('executeFunction', () => { { attributedUserId: 'workspace-owner', principal, + meterSandboxUsage: false, } ) }) diff --git a/apps/sim/lib/function-execution/application/execute-function.ts b/apps/sim/lib/function-execution/application/execute-function.ts index c5a8e2998c4..e191f92c49b 100644 --- a/apps/sim/lib/function-execution/application/execute-function.ts +++ b/apps/sim/lib/function-execution/application/execute-function.ts @@ -13,6 +13,8 @@ export interface ExecuteFunctionInput { headers: Headers signal?: AbortSignal sandboxProfile?: 'mothership' + /** Direct tool calls own their sandbox usage ledger, unlike Copilot orchestration. */ + meterSandboxUsage?: boolean /** Trusted in-process provenance state; never accepted from the Function request body. */ resolvedSecretTraceRegistry?: ResolvedSecretTraceRegistry } @@ -60,6 +62,7 @@ export const executeFunction = defineAuthorizedWorkspaceUseCase({ { attributedUserId, principal, + meterSandboxUsage: input.meterSandboxUsage ?? principal.kind !== 'delegated', ...(input.resolvedSecretTraceRegistry ? { resolvedSecretTraceRegistry: input.resolvedSecretTraceRegistry } : {}), diff --git a/apps/sim/lib/function-execution/application/operations.ts b/apps/sim/lib/function-execution/application/operations.ts index bae1baceacd..9be18074280 100644 --- a/apps/sim/lib/function-execution/application/operations.ts +++ b/apps/sim/lib/function-execution/application/operations.ts @@ -1,13 +1,14 @@ import { defineWorkspaceOperation } from '@/lib/core/application/workspace-operation' export const functionExecutionOperations = { - // permission-group-exempt: running a Function block is the workflow executing its own code; no group key names code execution, and a gate here would fail runs the group permits + // permission-group-exempt: Function code runs under its authorized workflow or tool caller; no permission-group key names code execution, and tool admission enforces the integration and tool policies execute: defineWorkspaceOperation({ id: 'function-executions.execute', + oauthScope: 'api:write', minimumRole: 'read', workspaceApiKey: 'deny', capability: 'none', - principalKinds: ['delegated'], + principalKinds: ['session', 'personal_api_key', 'oauth_access_token', 'delegated'], delegatedServices: ['executor', 'copilot'], }), } as const diff --git a/apps/sim/lib/function-execution/execute-request.test.ts b/apps/sim/lib/function-execution/execute-request.test.ts index 133e6b7864c..3444bcfb498 100644 --- a/apps/sim/lib/function-execution/execute-request.test.ts +++ b/apps/sim/lib/function-execution/execute-request.test.ts @@ -409,6 +409,35 @@ describe('Function execution request', () => { expect(mockExecuteShellInSandbox).not.toHaveBeenCalled() }) + it('measures sandbox cost for a direct caller without a workflow', async () => { + envFlagsMock.isRemoteSandboxEnabled = true + const cost = { input: 0, output: 0, total: 0.001 } + mockExecuteInSandbox.mockResolvedValueOnce({ + result: 42, + stdout: '', + sandboxId: 'direct-sandbox', + cost, + }) + const response = await executeFunctionRequest( + { headers: new Headers(), signal: new AbortController().signal }, + functionExecuteBodySchema.parse({ + code: 'import path from "node:path"; return 42', + workspaceId: 'workspace-1', + }), + { + principal: { kind: 'personal_api_key', userId: 'actor', keyId: 'key' }, + attributedUserId: 'actor', + fileAccessUserId: 'actor', + meterSandboxUsage: true, + } + ) + expect(response.status).toBe(200) + expect(mockExecuteInSandbox).toHaveBeenCalledWith( + expect.objectContaining({ meterUsage: true, workspaceId: 'workspace-1' }) + ) + expect((await response.json()).output.cost).toEqual(cost) + }) + it.each([ { language: 'python', code: 'return 42', kind: 'code' }, { language: 'shell', code: 'echo ready', kind: 'shell' }, diff --git a/apps/sim/lib/function-execution/execute-request.ts b/apps/sim/lib/function-execution/execute-request.ts index 00966573e4f..dcf54657b84 100644 --- a/apps/sim/lib/function-execution/execute-request.ts +++ b/apps/sim/lib/function-execution/execute-request.ts @@ -1,8 +1,4 @@ -import type { - DelegatedPrincipal, - OrganizationDelegatedPrincipal, - Principal, -} from '@sim/auth/principal' +import type { Principal } from '@sim/auth/principal' import { createLogger } from '@sim/logger' import { sha256Hex } from '@sim/security/hash' import { getErrorMessage } from '@sim/utils/errors' @@ -30,6 +26,7 @@ import { } from '@/lib/execution/code-placeholders' import { parseExecutionDeadlineHeader } from '@/lib/execution/execution-deadline-header' import { executeInIsolatedVM, type IsolatedVMBrokerHandler } from '@/lib/execution/isolated-vm' +import { collectJavaScriptImportSegments } from '@/lib/execution/javascript-imports' import { CodeLanguage, DEFAULT_CODE_LANGUAGE, isValidCodeLanguage } from '@/lib/execution/languages' import { inspectPrivateSecretProvenanceRequest, @@ -102,6 +99,7 @@ import { validateWorkspaceFileWriteTarget, writeWorkspaceFileByPath, } from '@/lib/mothership/vfs/resource-writer' +import { uploadCopilotFile } from '@/lib/uploads/contexts/copilot' import { uploadExecutionFile } from '@/lib/uploads/contexts/execution/execution-file-manager' import { createWorkspaceFileSecretProvenanceFromRegistry, @@ -113,6 +111,7 @@ import { type WorkspaceFileSecretProvenanceIdentity, } from '@/lib/uploads/contexts/workspace/workspace-file-secret-provenance' import { deleteFiles } from '@/lib/uploads/core/storage-service' +import { deleteFileMetadata } from '@/lib/uploads/server/metadata' import { getFileExtension, getMimeTypeFromExtension } from '@/lib/uploads/utils/file-utils' import { getWorkflowById } from '@/lib/workflows/utils' import { rebindWorkspaceFileDelegatedPrincipal } from '@/lib/workspace-files/application/delegated-principal' @@ -406,7 +405,7 @@ async function extractJavaScriptImports(code: string): Promise<{ tsModule.ScriptKind.JS ) - const importSegments: Array<{ text: string; start: number; end: number }> = [] + const importSegments = collectJavaScriptImportSegments(sourceFile, tsModule) const identifierNames = new Set() let hasRequireCalls = false @@ -423,19 +422,6 @@ async function extractJavaScriptImports(code: string): Promise<{ } visit(sourceFile) - sourceFile.statements.forEach((statement) => { - if ( - tsModule.isImportDeclaration(statement) || - tsModule.isImportEqualsDeclaration(statement) - ) { - importSegments.push({ - text: statement.getFullText(sourceFile).trim(), - start: statement.getFullStart(), - end: statement.getEnd(), - }) - } - }) - if (importSegments.length === 0) { return { imports: '', remainingCode: code, hasRequireCalls, identifierNames } } @@ -1009,7 +995,7 @@ function serializeForShellEnv(value: unknown, nullValue = ''): string { } interface FunctionRouteExecutionContext { - principal: DelegatedPrincipal | OrganizationDelegatedPrincipal + principal: TrustedFunctionExecutionAuth['principal'] workflowId?: string workspaceId?: string executionId?: string @@ -2095,13 +2081,36 @@ function collectedFileName(relativePath: string): string { * and the harvest is all-or-nothing by design. Best-effort on purpose: the * caller needs to hear why its export was refused, not that the tidy-up failed. */ -async function discardUploadedExecutionFiles(files: readonly UserFile[]): Promise { +async function discardUploadedSandboxFiles(files: readonly UserFile[]): Promise { if (files.length === 0) return try { - await deleteFiles( + const context = files[0].context === 'copilot' ? 'copilot' : 'execution' + const result = await deleteFiles( files.map((file) => file.key), - 'execution' + context ) + if (context === 'copilot') { + const failedKeys = new Set(result.failed.map((failure) => failure.key)) + let metadataFailures = 0 + for (const file of files) { + if (failedKeys.has(file.key)) continue + try { + await deleteFileMetadata(file.key) + } catch { + metadataFailures++ + } + } + if (metadataFailures > 0) { + logger.warn('Could not remove some sandbox output file metadata', { + fileCount: metadataFailures, + }) + } + } + if (result.failed.length > 0) { + logger.warn('Could not remove some partially uploaded sandbox output files', { + fileCount: result.failed.length, + }) + } } catch (error) { logger.warn('Could not remove partially uploaded sandbox output files', { fileCount: files.length, @@ -2148,10 +2157,27 @@ async function collectSandboxOutputFiles(args: { const resolvedWorkspaceId = args.workspaceId || (args.workflowId ? (await getWorkflowById(args.workflowId))?.workspaceId : undefined) + const personalOwnerId = + (routeContext.principal.kind === 'session' || + routeContext.principal.kind === 'personal_api_key' || + routeContext.principal.kind === 'oauth_access_token') && + !args.workflowId && + !args.executionId + ? routeContext.fileAccessUserId + : undefined + const storageTarget = personalOwnerId + ? { context: 'copilot' as const, userId: personalOwnerId } + : args.workflowId && args.executionId + ? { + context: 'execution' as const, + workflowId: args.workflowId, + executionId: args.executionId, + } + : undefined // Fails rather than returning an empty list: the code did produce files, and // reporting success without them would read as "your script wrote nothing". - if (!resolvedWorkspaceId || !args.workflowId || !args.executionId) { + if (!resolvedWorkspaceId || !storageTarget) { return { response: exportFailure( 'Workspace, workflow, and execution context are required to return files from the sandbox.', @@ -2174,15 +2200,24 @@ async function collectSandboxOutputFiles(args: { const mimeType = getMimeTypeFromExtension(getFileExtension(name)) /** Literal secrets must be refused regardless of the export's name or encoding. */ - const scannedProvenance = await getOutputFileSecretProvenance(buffer, false, routeContext, { + let scannedProvenance = await getOutputFileSecretProvenance(buffer, false, routeContext, { userId: args.authUserId, workspaceId: resolvedWorkspaceId, }) + if (personalOwnerId) { + scannedProvenance = mergeWorkspaceFileSecretProvenance( + scannedProvenance, + await getOutputFileSecretProvenance(Buffer.from(name), false, routeContext, { + userId: personalOwnerId, + workspaceId: resolvedWorkspaceId, + }) + ) + } if ( scannedProvenance.status === 'unknown' || (scannedProvenance.status === 'exact' && scannedProvenance.entries.length > 0) ) { - await discardUploadedExecutionFiles(files) + await discardUploadedSandboxFiles(files) return { response: exportFailure( `Sandbox output file "${name}" contains a resolved secret value and was not returned. Write the file without embedding secret values, or export it to a workspace file where its provenance can be recorded.`, @@ -2208,22 +2243,46 @@ async function collectSandboxOutputFiles(args: { }) : scannedProvenance - const userFile = await uploadExecutionFile( - { - workspaceId: resolvedWorkspaceId, - workflowId: args.workflowId, - executionId: args.executionId, - }, - buffer, - name, - mimeType, - args.authUserId, - secretProvenance - ) + if ( + personalOwnerId && + (secretProvenance.status !== 'exact' || secretProvenance.entries.length > 0) + ) { + await discardUploadedSandboxFiles(files) + return { + response: exportFailure( + `Sandbox output file "${name}" cannot be returned because its secret provenance is uncertain. Return a text file without secret values, or export it from a workflow that records file provenance.`, + 400, + args.stdout, + args.executionTime, + args.cost + ), + } + } + + const userFile = + storageTarget.context === 'copilot' + ? await uploadCopilotFile({ + buffer, + fileName: name, + contentType: mimeType, + userId: storageTarget.userId, + }) + : await uploadExecutionFile( + { + workspaceId: resolvedWorkspaceId, + workflowId: storageTarget.workflowId, + executionId: storageTarget.executionId, + }, + buffer, + name, + mimeType, + args.authUserId, + secretProvenance + ) files.push(userFile) } } catch (error) { - await discardUploadedExecutionFiles(files) + await discardUploadedSandboxFiles(files) throw error } @@ -2244,8 +2303,19 @@ async function collectSandboxOutputFiles(args: { export interface TrustedFunctionExecutionAuth { attributedUserId: string fileAccessUserId?: string - principal: DelegatedPrincipal | OrganizationDelegatedPrincipal + principal: Extract< + Principal, + { + kind: + | 'session' + | 'personal_api_key' + | 'oauth_access_token' + | 'delegated' + | 'organization_delegated' + } + > sandboxProfile?: 'mothership' + meterSandboxUsage?: boolean resolvedSecretTraceRegistry?: ResolvedSecretTraceRegistry } @@ -2347,7 +2417,9 @@ export async function executeFunctionRequest( _sandboxFiles, } = body - const meterRemoteSandboxUsage = Boolean(workflowId && !isCustomTool && !usesMothershipSandbox) + const meterRemoteSandboxUsage = Boolean( + (workflowId || auth.meterSandboxUsage) && !isCustomTool && !usesMothershipSandbox + ) if (selectedSandboxId && !isRemoteSandboxEnabled) { return NextResponse.json( diff --git a/apps/sim/lib/internal/file/operations.test.ts b/apps/sim/lib/internal/file/operations.test.ts index 86d721e6e39..3f9ee21ee6e 100644 --- a/apps/sim/lib/internal/file/operations.test.ts +++ b/apps/sim/lib/internal/file/operations.test.ts @@ -7,6 +7,7 @@ import { isSupportedFileType, parseBuffer } from '@/lib/file-parsers' import { CsvParser } from '@/lib/file-parsers/csv-parser' import { FileParserError } from '@/lib/file-parsers/errors' import { XlsxParser } from '@/lib/file-parsers/xlsx-parser' +import { canonicalWorkspaceFilePath } from '@/lib/mothership/vfs/path-utils' import { extractIndexText } from '@/lib/workspace-files/search/extract' const { @@ -106,6 +107,7 @@ vi.mock('@sim/platform-authz/workspace', () => ({ })) vi.mock('@/lib/uploads/contexts/workspace/workspace-file-manager', () => ({ + workspaceFileVfsPath: canonicalWorkspaceFilePath, fetchWorkspaceFileBuffer: (...args: unknown[]) => mockFetchWorkspaceFileBuffer(...args), getWorkspaceFileByName: (...args: unknown[]) => mockGetWorkspaceFileByName(...args), getWorkspaceFile: (...args: unknown[]) => mockGetWorkspaceFile(...args), diff --git a/apps/sim/lib/internal/file/operations.ts b/apps/sim/lib/internal/file/operations.ts index 1ac6587c30f..0b58aab17a0 100644 --- a/apps/sim/lib/internal/file/operations.ts +++ b/apps/sim/lib/internal/file/operations.ts @@ -46,7 +46,10 @@ import type { getWorkspaceFileWithCurrentVersion, WorkspaceFileRecord, } from '@/lib/uploads/contexts/workspace/workspace-file-manager' -import { getWorkspaceFileVersionsByKey } from '@/lib/uploads/contexts/workspace/workspace-file-manager' +import { + getWorkspaceFileVersionsByKey, + workspaceFileVfsPath, +} from '@/lib/uploads/contexts/workspace/workspace-file-manager' import { getBoundWorkspaceFileSecretProvenance, mergeWorkspaceFileSecretProvenance, @@ -1798,7 +1801,15 @@ export async function executeFileManageOperation( } case 'compress': { - const { fileId, fileInput, archiveName, folderPaths, includeSubfolders } = body + const { + fileId, + fileInput, + archiveName, + folderPaths, + includeSubfolders, + folderPath, + onConflict, + } = body const selectedFileIds = resolveSelectedFileIds(fileId, fileInput) const selectedInputFiles = fileId ? [] : extractUserFilesFromInput(fileInput) @@ -1970,8 +1981,8 @@ export async function executeFileManageOperation( name: leafName, contentType: 'application/zip', content: zipBuffer, - folderId: null, - exactName: false, + ...(folderPath !== undefined ? { folderPath } : { folderId: null }), + exactName: onConflict === 'error', secretProvenance: archiveProvenance, }, }) @@ -1996,6 +2007,7 @@ export async function executeFileManageOperation( name: compressedFile.name, size: compressedFile.size, url: compressedFile.url, + path: workspaceFileVfsPath(result.file), files: [compressedFile], }, }) diff --git a/apps/sim/lib/internal/function/execute.test.ts b/apps/sim/lib/internal/function/execute.test.ts index 11eea000764..a01a8363c07 100644 --- a/apps/sim/lib/internal/function/execute.test.ts +++ b/apps/sim/lib/internal/function/execute.test.ts @@ -1,3 +1,4 @@ +import type { Principal } from '@sim/auth/principal' import { beforeEach, describe, expect, it, vi } from 'vitest' const mocks = vi.hoisted(() => ({ @@ -62,6 +63,11 @@ describe('executeFunctionTool', () => { executionId: 'execution-1', userId: 'workspace-owner', executorDelegationOrigin: origin, + callerPrincipal: { + kind: 'personal_api_key' as const, + userId: 'other-actor', + keyId: 'other-key', + }, resolvedSecretTraceRegistry: new ResolvedSecretTraceRegistry([], { userId: 'workspace-owner', workspaceId: 'workspace-1', @@ -103,6 +109,78 @@ describe('executeFunctionTool', () => { }), }) }) + it.each([ + { kind: 'session', userId: 'actor', sessionId: 'session' }, + { kind: 'personal_api_key', userId: 'actor', keyId: 'key' }, + { + kind: 'oauth_access_token', + userId: 'actor', + tokenId: 'token', + clientId: 'client', + scopes: ['api:write'], + expiresAt: new Date('2099-01-01'), + }, + ])( + 'preserves the trusted direct $kind principal without an executor origin', + async (callerPrincipal) => { + await executeFunctionTool({ + body: { + code: 'return {{TOKEN}}', + secretScope: 'selected', + mountedSecrets: ['TOKEN'], + userId: 'forged', + workspaceId: 'forged', + workflowId: 'forged', + }, + headers: new Headers(), + context: { workflowId: '', workspaceId: 'workspace-1', userId: 'actor', callerPrincipal }, + requestId: 'direct', + }) + expect(mocks.createPrincipal).not.toHaveBeenCalled() + expect(mocks.execute).toHaveBeenCalledWith( + expect.objectContaining({ + principal: callerPrincipal, + input: expect.objectContaining({ + workspaceId: 'workspace-1', + meterSandboxUsage: true, + body: expect.objectContaining({ + userId: undefined, + workspaceId: 'workspace-1', + workflowId: '', + secretScope: 'selected', + mountedSecrets: ['TOKEN'], + }), + }), + }) + ) + } + ) + + it('keeps Copilot delegation expiry and scope when adapting an authorized direct caller', async () => { + const callerPrincipal = { + kind: 'delegated' as const, + serviceId: 'copilot' as const, + subjectUserId: 'actor', + workspaceId: 'workspace-1', + audience: 'sim:tool-execution', + delegationId: 'caller', + issuedAt: new Date('2026-01-01'), + expiresAt: new Date('2026-01-01T00:01:00Z'), + resourceScope: { chatId: 'chat' }, + } + await executeFunctionTool({ + body: { code: 'return 1' }, + headers: new Headers(), + context: { workflowId: '', workspaceId: 'workspace-1', callerPrincipal }, + requestId: 'direct', + }) + expect(mocks.execute.mock.calls[0][0].principal).toEqual({ + ...callerPrincipal, + audience: FUNCTION_EXECUTION_DELEGATION_AUDIENCE, + }) + expect(mocks.createPrincipal).not.toHaveBeenCalled() + }) + it.each(['agent', 'plan'] as const)( 'binds workspace-free scratch to the trusted organization %s chat and strips forged owners', async (requestMode) => { diff --git a/apps/sim/lib/internal/function/execute.ts b/apps/sim/lib/internal/function/execute.ts index 5383a810faa..2bdf1e4512b 100644 --- a/apps/sim/lib/internal/function/execute.ts +++ b/apps/sim/lib/internal/function/execute.ts @@ -1,4 +1,4 @@ -import type { DelegatedPrincipal } from '@sim/auth/principal' +import type { Principal } from '@sim/auth/principal' import type { FunctionExecuteBody } from '@/lib/api/contracts' import type { InternalSandboxProfile } from '@/lib/auth/internal' import { DEFAULT_EXECUTION_TIMEOUT_MS } from '@/lib/core/execution-limits' @@ -78,8 +78,17 @@ export async function executeFunctionTool(input: ExecuteFunctionToolInput): Prom }, }) } - let principal: DelegatedPrincipal - if (context.copilotToolExecution === true) { + let principal: Principal + if (context.callerPrincipal && !context.executorDelegationOrigin) { + /** The authorized direct tool caller already carries its identity; it owns no workflow. */ + principal = context.callerPrincipal + if (principal.kind === 'delegated') { + if (principal.serviceId !== 'copilot' || principal.workspaceId !== context.workspaceId) { + throw new Error('Direct Function execution requires a matching Copilot workspace') + } + principal = { ...principal, audience: FUNCTION_EXECUTION_DELEGATION_AUDIENCE } + } + } else if (context.copilotToolExecution === true) { if (!context.userId) throw new Error('Copilot Function execution requires a user') principal = { kind: 'delegated', @@ -106,6 +115,7 @@ export async function executeFunctionTool(input: ExecuteFunctionToolInput): Prom input: { workspaceId: context.workspaceId, body: trustedBody, + meterSandboxUsage: Boolean(context.callerPrincipal && !context.executorDelegationOrigin), headers, ...(context.resolvedSecretTraceRegistry ? { resolvedSecretTraceRegistry: context.resolvedSecretTraceRegistry } diff --git a/apps/sim/lib/internal/slack/client.ts b/apps/sim/lib/internal/slack/client.ts index f40bb4b63b0..1f1c9a68b4a 100644 --- a/apps/sim/lib/internal/slack/client.ts +++ b/apps/sim/lib/internal/slack/client.ts @@ -23,7 +23,7 @@ export interface SlackApiRequest { export interface SlackMessage { channel: string - text: string + text?: string thread_ts?: string blocks?: unknown[] unfurl_links?: boolean diff --git a/apps/sim/lib/internal/slack/execute-tool.test.ts b/apps/sim/lib/internal/slack/execute-tool.test.ts index ba517dbb7c3..18c96f55316 100644 --- a/apps/sim/lib/internal/slack/execute-tool.test.ts +++ b/apps/sim/lib/internal/slack/execute-tool.test.ts @@ -2,59 +2,32 @@ import { createExecutionContext } from '@sim/testing' import { beforeEach, describe, expect, it, vi } from 'vitest' const mocks = vi.hoisted(() => ({ - addReaction: vi.fn(), - deleteMessage: vi.fn(), - download: vi.fn(), - listConversations: vi.fn(), - readMessages: vi.fn(), - removeReaction: vi.fn(), - sendEphemeral: vi.fn(), sendMessage: vi.fn(), updateMessage: vi.fn(), })) vi.mock('@/lib/internal/slack/operations/list-conversations', () => ({ - executeSlackListConversationsOperation: mocks.listConversations, + executeSlackListConversationsOperation: vi.fn(), })) vi.mock('@/lib/internal/slack/operations', () => ({ - executeSlackAddReaction: mocks.addReaction, - executeSlackDeleteMessage: mocks.deleteMessage, - executeSlackDownload: mocks.download, - executeSlackReadMessages: mocks.readMessages, - executeSlackRemoveReaction: mocks.removeReaction, - executeSlackSendEphemeral: mocks.sendEphemeral, + executeSlackAddReaction: vi.fn(), + executeSlackDeleteMessage: vi.fn(), + executeSlackDownload: vi.fn(), + executeSlackReadMessages: vi.fn(), + executeSlackRemoveReaction: vi.fn(), + executeSlackSendEphemeral: vi.fn(), executeSlackSendMessage: mocks.sendMessage, executeSlackUpdateMessage: mocks.updateMessage, })) import { executeSlackTool } from '@/lib/internal/slack/execute-tool' import type { InternalToolOperationCall } from '@/lib/internal/tool-operations/types' +import { slackMessageTool } from '@/tools/slack/message' +import { slackUpdateMessageTool } from '@/tools/slack/update_message' const INPUTS = { - slack_add_reaction: { - accessToken: 'token', - channel: 'C1', - timestamp: '1.0', - name: 'eyes', - }, - slack_delete_message: { accessToken: 'token', channel: 'C1', timestamp: '1.0' }, - slack_download: { accessToken: 'token', fileId: 'F1', fileName: 'report.pdf' }, - slack_list_channels: { accessToken: 'token', limit: 100, cursor: 'cursor-1' }, - slack_ephemeral_message: { - accessToken: 'token', - channel: 'C1', - user: 'U1', - text: 'hello', - }, slack_message: { accessToken: 'token', channel: 'C1', text: 'hello' }, - slack_message_reader: { accessToken: 'token', channel: 'C1', limit: 2 }, - slack_remove_reaction: { - accessToken: 'token', - channel: 'C1', - timestamp: '1.0', - name: 'eyes', - }, slack_update_message: { accessToken: 'token', channel: 'C1', @@ -64,14 +37,7 @@ const INPUTS = { } as const const DISPATCH = { - slack_add_reaction: mocks.addReaction, - slack_delete_message: mocks.deleteMessage, - slack_download: mocks.download, - slack_list_channels: mocks.listConversations, - slack_ephemeral_message: mocks.sendEphemeral, slack_message: mocks.sendMessage, - slack_message_reader: mocks.readMessages, - slack_remove_reaction: mocks.removeReaction, slack_update_message: mocks.updateMessage, } as const @@ -100,6 +66,35 @@ describe('executeSlackTool', () => { } }) + it.each(['slack_message', 'slack_update_message'] as const)( + 'rejects %s without text or blocks through the real tool input and dispatcher', + async (toolId) => { + const params = { + accessToken: 'token', + channel: 'C1', + timestamp: '1.0', + text: ' \n ', + blocks: '[]', + } + const input = + toolId === 'slack_message' + ? slackMessageTool.operation.input(params) + : slackUpdateMessageTool.operation.input(params) + const response = await executeSlackTool(request(toolId, { input })) + + expect(response.status).toBe(400) + await expect(response.json()).resolves.toMatchObject({ + error: 'Invalid request data', + details: expect.arrayContaining([ + expect.objectContaining({ + message: 'Provide message text or at least one Block Kit block', + }), + ]), + }) + expect(DISPATCH[toolId]).not.toHaveBeenCalled() + } + ) + it('keeps message file authority tied to the trusted execution context', async () => { const response = await executeSlackTool( request('slack_message', { diff --git a/apps/sim/lib/internal/slack/operations.test.ts b/apps/sim/lib/internal/slack/operations.test.ts index 575de08abc4..f8f8ddfb258 100644 --- a/apps/sim/lib/internal/slack/operations.test.ts +++ b/apps/sim/lib/internal/slack/operations.test.ts @@ -1,16 +1,17 @@ import { afterEach, assert, beforeEach, describe, expect, it, vi } from 'vitest' -import { - isInternalToolFileResult, - type StoredToolFile, -} from '@/lib/internal/tool-operations/file-result' +import { isInternalToolFileResult } from '@/lib/internal/tool-operations/file-result' const mocks = vi.hoisted(() => ({ resolveFiles: vi.fn(), + uploadExecution: vi.fn(), secureFetchWithPinnedIP: vi.fn(), secureFetchWithValidation: vi.fn(), validateUrlWithDNS: vi.fn(), })) +vi.mock('@/lib/uploads/contexts/execution', () => ({ uploadExecutionFile: mocks.uploadExecution })) +vi.mock('@/lib/uploads/contexts/copilot', () => ({ uploadCopilotFile: vi.fn() })) + vi.mock('@/lib/internal/slack/file-input', () => ({ forEachSlackAttachmentFile: mocks.resolveFiles, })) @@ -21,8 +22,30 @@ vi.mock('@/lib/core/security/input-validation.server', () => ({ validateUrlWithDNS: mocks.validateUrlWithDNS, })) -import { executeSlackDownload } from '@/lib/internal/slack/operations' +import { + slackSendEphemeralBodySchema, + slackSendMessageBodySchema, + slackUpdateMessageBodySchema, +} from '@/lib/api/contracts/tools/communication/slack' +import { projectToolOutputs } from '@/lib/catalog/projection/tool' +import { PayloadSizeLimitError } from '@/lib/core/utils/stream-limits' +import { + executeSlackDownload, + executeSlackSendEphemeral, + executeSlackSendMessage, + executeSlackUpdateMessage, +} from '@/lib/internal/slack/operations' +import { executeSlackGetChannelHistoryOperation } from '@/lib/internal/slack/operations/get-channel-history' +import { executeSlackGetThreadRepliesOperation } from '@/lib/internal/slack/operations/get-thread-replies' +import { presentInternalToolOperationResult } from '@/lib/internal/tool-operations/file-result.server' +import { MAX_TOOL_RESPONSE_BODY_BYTES } from '@/lib/internal/tool-operations/response-limits' import { MAX_FILE_SIZE } from '@/lib/uploads/utils/validation' +import type { UserFile } from '@/executor/types' +import { slackDownloadTool } from '@/tools/slack/download' +import { slackEphemeralMessageTool } from '@/tools/slack/ephemeral_message' +import { slackMessageTool } from '@/tools/slack/message' +import { slackScheduleMessageTool } from '@/tools/slack/schedule_message' +import { slackUpdateMessageTool } from '@/tools/slack/update_message' const originalFetch = global.fetch @@ -45,7 +68,128 @@ describe('Slack operations', () => { global.fetch = originalFetch }) - it('keeps private Slack downloads DNS-pinned, bounded, and cancellable', async () => { + describe.each(['send', 'ephemeral', 'update'] as const)('%s Block Kit payload', (operation) => { + const blocks = [{ type: 'section', text: { type: 'mrkdwn', text: '*Ready*' } }] + const params = { + accessToken: 'token', + channel: 'C1', + user: 'U1', + timestamp: '1.0', + blocks: JSON.stringify(blocks), + } + + async function execute(text?: string) { + const input = { ...params, text } + if (operation === 'send') { + const parsed = slackSendMessageBodySchema.parse(slackMessageTool.operation.input(input)) + return executeSlackSendMessage(parsed, { userId: 'user-1', requestId: 'request-1' }) + } + if (operation === 'ephemeral') { + const parsed = slackSendEphemeralBodySchema.parse( + slackEphemeralMessageTool.operation.input(input) + ) + return executeSlackSendEphemeral(parsed) + } + const parsed = slackUpdateMessageBodySchema.parse( + slackUpdateMessageTool.operation.input(input) + ) + return executeSlackUpdateMessage(parsed) + } + + it('sends explicit text alongside blocks unchanged for notifications and accessibility', async () => { + vi.mocked(global.fetch).mockResolvedValueOnce( + slackResponse({ ok: true, channel: 'C1', ts: '1.0', message_ts: '1.0' }) + ) + await execute('Deployment is ready.\nReview the release notes.') + const [url, request] = vi.mocked(global.fetch).mock.calls[0]! + expect(String(url)).toBe( + `https://slack.com/api/${{ send: 'chat.postMessage', ephemeral: 'chat.postEphemeral', update: 'chat.update' }[operation]}` + ) + expect(JSON.parse(String(request?.body))).toMatchObject({ + channel: 'C1', + text: 'Deployment is ready.\nReview the release notes.', + blocks, + }) + }) + + it.each([undefined, '', ' \n '])( + 'omits absent or blank fallback %j instead of inserting whitespace', + async (text) => { + vi.mocked(global.fetch).mockResolvedValueOnce( + slackResponse({ ok: true, channel: 'C1', ts: '1.0', message_ts: '1.0' }) + ) + await execute(text) + const body = JSON.parse(String(vi.mocked(global.fetch).mock.calls[0]?.[1]?.body)) + expect(body).toMatchObject({ blocks }) + expect(body).not.toHaveProperty('text') + } + ) + }) + + it('schedules Block Kit with explicit fallback text and omits blank fallback', () => { + const buildBody = slackScheduleMessageTool.request.body + if (typeof buildBody !== 'function') throw new Error('Schedule body builder is missing') + const params = { channel: 'C1', postAt: 2000000000, blocks: '[{"type":"divider"}]' } + expect(buildBody({ ...params, text: 'Release ready' })).toMatchObject({ + text: 'Release ready', + blocks: [{ type: 'divider' }], + }) + expect(buildBody({ ...params, text: ' ' })).not.toHaveProperty('text') + }) + + it.each([ + { text: 'hello', blocks: undefined }, + { text: 'hello', blocks: [{ type: 'divider' }] }, + { text: undefined, blocks: [{ type: 'divider' }] }, + ])('preserves file-sharing content precedence for %j', async ({ text, blocks }) => { + const controller = new AbortController() + mocks.resolveFiles.mockImplementation(async (_files, _context, consume) => { + await consume({ + buffer: Buffer.from('hello'), + contentType: 'text/plain', + name: 'hello.txt', + type: 'text/plain', + }) + }) + vi.mocked(global.fetch) + .mockResolvedValueOnce( + slackResponse({ + ok: true, + upload_url: 'https://files.slack.com/upload/signed', + file_id: 'F1', + }) + ) + .mockResolvedValueOnce( + slackResponse({ + ok: true, + files: [{ id: 'F1', name: 'hello.txt', created: 10, mimetype: 'text/plain' }], + }) + ) + + await executeSlackSendMessage( + { + accessToken: 'token', + channel: 'C1', + text, + blocks, + files: [{ key: 'workspace/file-1', name: 'hello.txt', size: 5 }], + }, + { + requestId: 'request-1', + signal: controller.signal, + userId: 'user-1', + } + ) + + expect(JSON.parse(String(vi.mocked(global.fetch).mock.calls[1]?.[1]?.body))).toEqual({ + files: [{ id: 'F1' }], + channel_id: 'C1', + ...(blocks ? { blocks } : { initial_comment: text }), + }) + }) + + it('keeps private Slack downloads DNS-pinned and publishes the actual descriptor contract', async () => { + const context = 'execution' as const const controller = new AbortController() vi.mocked(global.fetch).mockResolvedValueOnce( slackResponse({ @@ -80,16 +224,132 @@ describe('Slack operations', () => { expect(result.files).toEqual([ { name: 'report.pdf', mimeType: 'application/pdf', buffer: Buffer.from('pdf') }, ]) - const storedFile: StoredToolFile = { - id: 'stored-file-1', - key: 'execution/stored-file-1', + const storedFile: UserFile = { + id: `${context}/stored-file-1/report.pdf`, + key: `${context}/stored-file-1/report.pdf`, url: '/api/files/serve/stored-file-1', name: 'report.pdf', type: 'application/pdf', - mimeType: 'application/pdf', size: 3, - context: 'execution', + context, } - expect(result.present([storedFile])).toEqual({ success: true, output: { file: storedFile } }) + mocks.uploadExecution.mockResolvedValue({ ...storedFile, mimeType: 'application/pdf' }) + const response = await presentInternalToolOperationResult( + result, + { + workspaceId: 'workspace-1', + userId: 'user-1', + workflowId: 'workflow-1', + executionId: 'run-1', + }, + controller.signal + ) + const presented = await response.json() + expect(presented).toEqual({ success: true, output: { file: storedFile } }) + const published = projectToolOutputs(slackDownloadTool.outputs).file + expect(Object.keys(published.properties ?? {}).sort()).toEqual( + Object.keys(presented.output.file).sort() + ) + for (const [field, definition] of Object.entries(published.properties ?? {})) { + expect(typeof presented.output.file[field]).toBe(definition.type) + } + expect(published.properties).not.toHaveProperty('data') + expect(published.properties).not.toHaveProperty('mimeType') }) + + it.each([undefined, '1'])( + 'cancels an oversized streamed history page with content-length %s', + async (contentLength) => { + const chunk = new TextEncoder().encode('x'.repeat(64 * 1024)) + const totalChunks = MAX_TOOL_RESPONSE_BODY_BYTES / chunk.byteLength + 4 + let chunksRead = 0 + const cancel = vi.fn() + const body = new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('{"ok":true,"messages":[],"extra":"')) + }, + pull(controller) { + if (chunksRead < totalChunks) { + chunksRead += 1 + controller.enqueue(chunk) + } else { + controller.enqueue(new TextEncoder().encode('"}')) + controller.close() + } + }, + cancel, + }) + vi.mocked(global.fetch).mockResolvedValueOnce( + new Response(body, { + headers: contentLength ? { 'content-length': contentLength } : undefined, + }) + ) + + await expect( + executeSlackGetChannelHistoryOperation({ accessToken: 'token', channel: 'C1' }) + ).rejects.toBeInstanceOf(PayloadSizeLimitError) + expect(cancel).toHaveBeenCalledOnce() + expect(chunksRead).toBeLessThan(totalChunks) + expect(global.fetch).toHaveBeenCalledOnce() + } + ) + + it.each([ + ['history', executeSlackGetChannelHistoryOperation], + ['thread replies', executeSlackGetThreadRepliesOperation], + ] as const)( + 'rejects accumulated %s above the retained message limit before fetching another page', + async (_name, operation) => { + const text = 'x'.repeat(Math.ceil(MAX_TOOL_RESPONSE_BODY_BYTES * 0.6)) + for (const ts of ['1.0', '2.0', '3.0']) { + vi.mocked(global.fetch).mockResolvedValueOnce( + slackResponse({ + ok: true, + messages: [{ ts, text }], + response_metadata: { next_cursor: ts === '3.0' ? '' : ts }, + }) + ) + } + + await expect( + operation({ accessToken: 'token', channel: 'C1', threadTs: '1.0' }) + ).rejects.toBeInstanceOf(PayloadSizeLimitError) + expect(global.fetch).toHaveBeenCalledTimes(2) + } + ) + + it.each([ + ['history', executeSlackGetChannelHistoryOperation], + ['thread replies', executeSlackGetThreadRepliesOperation], + ] as const)( + 'preserves bounded page ordering and continuation when maxPages stops %s', + async (_name, operation) => { + for (const ts of ['1.0', '2.0']) { + vi.mocked(global.fetch).mockResolvedValueOnce( + slackResponse({ + ok: true, + messages: [{ ts, text: 'Release ✨\n"ready"' }], + response_metadata: { next_cursor: `after-${ts}` }, + }) + ) + } + const result = await operation({ + accessToken: 'token', + channel: 'C1', + threadTs: '1.0', + maxPages: 2, + }) + expect(result).toMatchObject({ + success: true, + output: { pages: 2, hasMore: true, nextCursor: 'after-2.0' }, + }) + expect(result.output.messages.map((message) => message.ts)).toEqual(['1.0', '2.0']) + expect(result.output.messages.map((message) => message.text)).toEqual([ + 'Release ✨\n"ready"', + 'Release ✨\n"ready"', + ]) + expect(global.fetch).toHaveBeenCalledTimes(2) + expect(String(vi.mocked(global.fetch).mock.calls[1]?.[0])).toContain('cursor=after-1.0') + } + ) }) diff --git a/apps/sim/lib/internal/slack/operations.ts b/apps/sim/lib/internal/slack/operations.ts index 8328b54301d..7514bbd9e40 100644 --- a/apps/sim/lib/internal/slack/operations.ts +++ b/apps/sim/lib/internal/slack/operations.ts @@ -174,7 +174,7 @@ export async function executeSlackUpdateMessage( body: { channel: input.channel, ts: input.timestamp, - text: input.text, + ...(input.text?.trim() ? { text: input.text } : {}), ...(input.blocks?.length ? { blocks: input.blocks } : {}), }, signal, @@ -183,7 +183,7 @@ export async function executeSlackUpdateMessage( const message = data.message ?? { type: 'message', ts: data.ts, - text: data.text || input.text, + text: data.text ?? input.text ?? '', channel: data.channel, } return { @@ -194,7 +194,7 @@ export async function executeSlackUpdateMessage( metadata: { channel: data.channel, timestamp: data.ts, - text: data.text || input.text, + text: data.text ?? input.text ?? '', }, }, } @@ -210,7 +210,7 @@ export async function executeSlackSendEphemeral( body: { channel: input.channel, user: input.user, - text: input.text, + ...(input.text?.trim() ? { text: input.text } : {}), ...(input.thread_ts ? { thread_ts: input.thread_ts } : {}), ...(input.blocks?.length ? { blocks: input.blocks } : {}), }, @@ -264,11 +264,11 @@ export async function executeSlackReadMessages(input: SlackReadMessagesBody, sig } } -function defaultMessage(ts: unknown, text: string, channel: unknown) { - return { type: 'message', ts, text, channel } +function defaultMessage(ts: unknown, text: string | undefined, channel: unknown) { + return { type: 'message', ts, text: text ?? '', channel } } -function sentMessageOutput(data: SlackJsonObject, text: string) { +function sentMessageOutput(data: SlackJsonObject, text: string | undefined) { return { message: data.message ?? defaultMessage(data.ts, text, data.channel), ts: data.ts, @@ -285,7 +285,7 @@ async function postSlackMessage( input.accessToken, { channel, - text: input.text, + ...(input.text?.trim() ? { text: input.text } : {}), ...(input.thread_ts ? { thread_ts: input.thread_ts } : {}), ...(input.blocks?.length ? { blocks: input.blocks } : {}), }, @@ -373,7 +373,7 @@ async function uploadSlackFiles( first.created !== undefined && first.created !== null ? String(first.created) : String(Date.now() / 1000), - text: input.text, + text: input.text ?? '', channel, files: slackFiles.map((value) => { const slackFile = record(value) diff --git a/apps/sim/lib/knowledge/__integration__/execution-archive-provenance.integration.ts b/apps/sim/lib/knowledge/__integration__/execution-archive-provenance.integration.ts index e7f4b4afc69..c7c4156de42 100644 --- a/apps/sim/lib/knowledge/__integration__/execution-archive-provenance.integration.ts +++ b/apps/sim/lib/knowledge/__integration__/execution-archive-provenance.integration.ts @@ -8,6 +8,7 @@ import { db } from '@sim/db' import { document, documentSecretProvenance, + folder, knowledgeBase, organization, outboxEvent, @@ -41,7 +42,10 @@ vi.mock('@/lib/embeddings', async () => ({ }), })) -import { fileManageDecompressBodySchema } from '@/lib/api/contracts/tools/file' +import { + fileManageCompressBodySchema, + fileManageDecompressBodySchema, +} from '@/lib/api/contracts/tools/file' import { processOutboxEventById } from '@/lib/core/outbox/service' import { encryptSecret } from '@/lib/core/security/encryption' import { isUserFile } from '@/lib/core/utils/user-file' @@ -475,6 +479,97 @@ describe('execution archive durable provenance', () => { } ) + it.each([ + { name: 'Finance/Legal', folderPath: '/Finance%2FLegal' }, + { name: 'Finance\\Legal', folderPath: '/Finance%5CLegal' }, + { name: 'Q3 Reports', folderPath: '/Q3%20Reports' }, + ])( + 'compresses into stored folder $name without overwriting a colliding archive', + async ({ name, folderPath }) => { + const ids = await seed() + const source = await extract(ids, await uploadArchive(ids, { status: 'exact', entries: [] })) + const folderId = generateId() + /** Stored legacy names can contain separators even though new folder creation forbids them. */ + await db.insert(folder).values({ + id: folderId, + workspaceId: ids.workspaceId, + userId: ids.aliceId, + name, + resourceType: 'file', + }) + const compress = (options: { folderPath?: string; onConflict?: 'rename' | 'error' } = {}) => + executeFileManageOperation( + fileManageCompressBodySchema.parse({ + operation: 'compress', + workspaceId: ids.workspaceId, + fileId: source.child.id, + archiveName: 'bundle.zip', + ...options, + }), + { + principal: sessionPrincipal(ids), + workspaceId: ids.workspaceId, + attributedUserId: ids.aliceId, + fileAccessUserId: ids.aliceId, + workflowId: '', + headers: new Headers(), + requestId: generateId(), + } + ) + + const first = await compress({ folderPath }) + const firstBody = await first.json() + expect(first.status, JSON.stringify(firstBody)).toBe(200) + expect(firstBody.data.path).toBe(`files${folderPath}/bundle.zip`) + const archive = await getWorkspaceFile(ids.workspaceId, firstBody.data.id) + if (!archive) throw new Error('Compression did not persist a workspace file') + expect(archive.folderId).toBe(folderId) + const originalBytes = await downloadFile({ key: archive.key, context: 'workspace' }) + const zipped = await JSZip.loadAsync(originalBytes) + expect(await zipped.file('report.csv')?.async('string')).toBe(REPORT_CSV) + expect( + await getBoundWorkspaceFileSecretProvenance(ids.workspaceId, { + fileId: archive.id, + key: archive.key, + context: 'workspace', + contentUpdatedAt: archive.contentUpdatedAt ?? undefined, + }) + ).toEqual({ status: 'exact', entries: [] }) + + const renamed = await compress({ folderPath }) + const renamedBody = await renamed.json() + expect(renamed.status, JSON.stringify(renamedBody)).toBe(200) + expect(renamedBody.data.name).toBe('bundle (1).zip') + expect(renamedBody.data.path).toBe(`files${folderPath}/bundle%20(1).zip`) + expect(renamedBody.data.id).not.toBe(archive.id) + expect((await getWorkspaceFile(ids.workspaceId, renamedBody.data.id))?.folderId).toBe( + folderId + ) + + const storedBeforeRefusal = await db + .select({ id: workspaceFiles.id }) + .from(workspaceFiles) + .where(eq(workspaceFiles.workspaceId, ids.workspaceId)) + expect((await compress({ folderPath, onConflict: 'error' })).status).toBe(409) + expect((await compress({ folderPath: '/Missing' })).status).toBe(404) + const storedAfterRefusal = await db + .select({ id: workspaceFiles.id }) + .from(workspaceFiles) + .where(eq(workspaceFiles.workspaceId, ids.workspaceId)) + expect(storedAfterRefusal.map((file) => file.id).sort()).toEqual( + storedBeforeRefusal.map((file) => file.id).sort() + ) + expect(await downloadFile({ key: archive.key, context: 'workspace' })).toEqual(originalBytes) + + const rootArchive = await compress() + const rootBody = await rootArchive.json() + expect(rootArchive.status, JSON.stringify(rootBody)).toBe(200) + expect(rootBody.data.name).toBe('bundle.zip') + expect(rootBody.data.path).toBe('files/bundle.zip') + expect((await getWorkspaceFile(ids.workspaceId, rootBody.data.id))?.folderId).toBeNull() + } + ) + it('refuses another execution before extracting any workspace files', async () => { const ids = await seed() const archive = await uploadArchive(ids, { status: 'exact', entries: [] }) diff --git a/apps/sim/lib/logs/application/get-public-log.ts b/apps/sim/lib/logs/application/get-public-log.ts index 7b7f9406bff..12e5f224a66 100644 --- a/apps/sim/lib/logs/application/get-public-log.ts +++ b/apps/sim/lib/logs/application/get-public-log.ts @@ -30,6 +30,7 @@ interface PublicLogContext extends ActiveWorkspaceApplicationContext { export interface GetPublicLogInput { runId: string + includeWorkflowState?: boolean } export interface GetPublicLogResult { @@ -94,7 +95,7 @@ export const getPublicLog = defineAuthorizedWorkspaceUseCase({ return { ...workspace, executionId: scope.executionId, workflowId: scope.workflowId } }, authorizationOptions: logDelegationAuthorization(), - execute: async ({ principal, context }): Promise => { + execute: async ({ principal, input, context }): Promise => { /** * Attribution and the projection subject in one value; a workspace API key * represents no user and therefore reads the run whole. See @@ -118,7 +119,8 @@ export const getPublicLog = defineAuthorizedWorkspaceUseCase({ const log = await getPublicWorkflowLog( { column: 'executionId', value: context.executionId }, - context.workspaceId + context.workspaceId, + { includeWorkflowState: input.includeWorkflowState !== false } ) if (!log || log.workflowId !== context.workflowId) { throw new OrchestrationError('not_found', 'Log not found') @@ -158,7 +160,10 @@ export const getPublicLog = defineAuthorizedWorkspaceUseCase({ log: { ...log, costTotal: projection.hideCostInfo ? null : log.costTotal, - workflowState: sanitizeExecutionSnapshotState(log.workflowState), + workflowState: + input.includeWorkflowState === false + ? null + : sanitizeExecutionSnapshotState(log.workflowState), }, costLedger, workflowFolderPath: publicLogFolderPath( diff --git a/apps/sim/lib/logs/application/public-log-use-cases.test.ts b/apps/sim/lib/logs/application/public-log-use-cases.test.ts index 564121f32a5..a36b164f718 100644 --- a/apps/sim/lib/logs/application/public-log-use-cases.test.ts +++ b/apps/sim/lib/logs/application/public-log-use-cases.test.ts @@ -138,7 +138,8 @@ describe('public log application use cases', () => { expect(mocks.loadWorkspace).toHaveBeenCalledWith('workspace-1') expect(mocks.getLog).toHaveBeenCalledWith( { column: 'executionId', value: 'run-1' }, - 'workspace-1' + 'workspace-1', + { includeWorkflowState: true } ) expect(mocks.materialize).toHaveBeenCalledWith( { pointer: true }, @@ -153,6 +154,25 @@ describe('public log application use cases', () => { expect(mocks.recordAudit).not.toHaveBeenCalled() }) + it('omits the workflow snapshot at the query and response boundary when requested', async () => { + mocks.getLog.mockResolvedValueOnce({ + ...log, + workflowState: { blocks: { large: { subBlocks: { code: { value: 'private' } } } } }, + }) + const result = await getPublicLog.execute({ + principal: workspacePrincipal, + input: { runId: 'run-1', includeWorkflowState: false }, + }) + + expect(mocks.getLog).toHaveBeenCalledWith( + { column: 'executionId', value: 'run-1' }, + 'workspace-1', + { includeWorkflowState: false } + ) + expect(result.log.workflowState).toBeNull() + expect(result.executionData.finalOutput).toEqual({ ok: true }) + }) + /** * `null` must not stand for both "at the workspace root" and "the path could * not be resolved" — a caller can tell neither apart nor feed it back to diff --git a/apps/sim/lib/logs/execution/trace-spans/span-factory.ts b/apps/sim/lib/logs/execution/trace-spans/span-factory.ts index 7abe0bcbc71..68bd7218fae 100644 --- a/apps/sim/lib/logs/execution/trace-spans/span-factory.ts +++ b/apps/sim/lib/logs/execution/trace-spans/span-factory.ts @@ -1,9 +1,11 @@ import { createLogger } from '@sim/logger' +import { toStringOrNull } from '@sim/utils/coerce' import { isRecordLike } from '@sim/utils/object' import type { ProviderTiming, TraceSpan } from '@/lib/logs/types' import { CHILD_EXECUTION_ID_OUTPUT_KEY, CHILD_TRACE_DISABLED_OUTPUT_KEY, + isAgentBlockType, isConditionBlockType, isWorkflowBlockType, stripCustomToolPrefix, @@ -26,6 +28,17 @@ function normalizeTraceOutput(value: unknown): Record | undefin return isRecordLike(value) ? value : { value } } +/** Provider failure metadata is authoritative; successful tool output may contain error-shaped data. */ +function getToolCallError(call: BlockToolCall | undefined): string | undefined { + if (call?.error) return call.error + if (call?.success !== false) return undefined + const result = call.result ?? call.output + return ( + (isRecordLike(result) && (toStringOrNull(result.message) || toStringOrNull(result.error))) || + 'Tool execution failed' + ) +} + /** * Lifts a custom block's child-run handle off a tool result onto the tool span, * the way {@link createBaseSpan} lifts it off a block log. @@ -251,6 +264,7 @@ function buildChildrenFromTimeSegments( const { output, handle } = liftChildTraceHandle( normalizeTraceOutput(match?.result ?? match?.output) ) + const errorMessage = segment.errorMessage || getToolCallError(match) const toolChild: TraceSpan = { id: `${span.id}-segment-${index}`, @@ -259,14 +273,18 @@ function buildChildrenFromTimeSegments( duration: segment.duration, startTime: segmentStartTime, endTime: segmentEndTime, - status: match?.error || segment.errorMessage ? 'error' : 'success', + status: errorMessage ? 'error' : 'success', input: match?.arguments ?? match?.input, output: match?.error ? { error: match.error, ...output } : output, ...handle, + ...(errorMessage && { errorMessage }), + ...(errorMessage && + isAgentBlockType(log.blockType) && + log.success && + !log.error && { errorHandled: true }), } if (segment.toolCallId) toolChild.toolCallId = segment.toolCallId if (segment.errorType) toolChild.errorType = segment.errorType - if (segment.errorMessage) toolChild.errorMessage = segment.errorMessage return toolChild } @@ -330,6 +348,7 @@ 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 errorMessage = getToolCallError(tc) return { id: `${span.id}-tool-${index}`, name: stripCustomToolPrefix(tc.name ?? 'unnamed-tool'), @@ -337,10 +356,15 @@ function buildChildrenFromToolCalls(span: TraceSpan, log: ValidBlockLog): TraceS duration: tc.duration ?? 0, startTime, endTime, - status: tc.error ? 'error' : 'success', + status: errorMessage ? 'error' : 'success', input: tc.arguments ?? tc.input, output: tc.error ? { error: tc.error, ...output } : output, ...handle, + ...(errorMessage && { errorMessage }), + ...(errorMessage && + isAgentBlockType(log.blockType) && + log.success && + !log.error && { errorHandled: true }), } }) } 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 495e8ddb28d..8c9faf42d44 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 @@ -1,9 +1,114 @@ import { describe, expect, it } from 'vitest' -import { buildTraceSpans, hasUnhandledError } from '@/lib/logs/execution/trace-spans/trace-spans' +import { traceSpansHaveHandledErrors } from '@/lib/logs/execution/trace-spans/handled-errors' +import { + buildTraceSpans, + hasUnhandledError, + traceSpansIndicateFailure, +} from '@/lib/logs/execution/trace-spans/trace-spans' import type { TraceSpan } from '@/lib/logs/types' import type { ExecutionResult } from '@/executor/types' describe('buildTraceSpans', () => { + it.each([true, false])( + 'marks provider tool failures as handled errors after a successful agent (timing segments: %s)', + (withTimingSegments) => { + const toolCall = { + name: 'exa_search', + arguments: { query: 'candidate research' }, + success: false, + result: { error: true, message: 'Search credits exhausted', tool: 'exa_search' }, + } + const result: ExecutionResult = { + success: true, + output: { content: 'Research could not be performed' }, + metadata: { duration: 1000, startTime: '2024-01-01T10:00:00.000Z' }, + logs: [ + { + blockId: 'research', + blockType: 'agent', + startedAt: '2024-01-01T10:00:00.000Z', + endedAt: '2024-01-01T10:00:01.000Z', + durationMs: 1000, + success: true, + output: { + toolCalls: { list: [toolCall], count: 1 }, + ...(withTimingSegments && { + providerTiming: { + duration: 1000, + startTime: '2024-01-01T10:00:00.000Z', + endTime: '2024-01-01T10:00:01.000Z', + timeSegments: [ + { + type: 'tool' as const, + name: 'exa_search', + startTime: 1704103200000, + endTime: 1704103201000, + duration: 1000, + }, + ], + }, + }), + }, + }, + ], + } + + const { traceSpans } = buildTraceSpans(result) + const workflowSpan = traceSpans[0] + const agentSpan = workflowSpan.children![0] + const toolSpan = agentSpan.children![0] + + expect(toolSpan).toMatchObject({ + status: 'error', + errorMessage: 'Search credits exhausted', + errorHandled: true, + output: toolCall.result, + }) + expect(agentSpan.status).toBe('success') + expect(workflowSpan.status).toBe('success') + expect(traceSpansIndicateFailure(traceSpans)).toBe(false) + expect(traceSpansHaveHandledErrors(traceSpans)).toBe(true) + + result.logs![0].success = false + result.logs![0].error = 'Agent failed to recover' + const failed = buildTraceSpans(result).traceSpans + expect(failed[0].status).toBe('error') + expect(failed[0].children![0].children![0].errorHandled).toBeUndefined() + expect(traceSpansIndicateFailure(failed)).toBe(true) + } + ) + + it.each([true, undefined])( + 'does not infer tool failure from user output when provider success is %s', + (success) => { + const toolCall = { + name: 'read_error_report', + arguments: {}, + success, + result: { error: true, message: 'Error record returned as data' }, + } + const { traceSpans } = buildTraceSpans({ + success: true, + output: {}, + logs: [ + { + blockId: 'agent', + blockType: 'agent', + startedAt: '2024-01-01T10:00:00.000Z', + endedAt: '2024-01-01T10:00:01.000Z', + durationMs: 1000, + success: true, + output: { toolCalls: { list: [toolCall], count: 1 } }, + }, + ], + }) + + expect(traceSpans[0].children![0].status).toBe('success') + expect(traceSpans[0].children![0].errorMessage).toBeUndefined() + expect(traceSpansHaveHandledErrors(traceSpans)).toBe(false) + } + ) + it.concurrent('extracts sequential segments from timeSegments data', () => { const mockExecutionResult: ExecutionResult = { success: true, diff --git a/apps/sim/lib/logs/public-queries.integration.ts b/apps/sim/lib/logs/public-queries.integration.ts new file mode 100644 index 00000000000..7a064da1d1b --- /dev/null +++ b/apps/sim/lib/logs/public-queries.integration.ts @@ -0,0 +1,79 @@ +import { db } from '@sim/db' +import { user, workflowExecutionLogs, workflowExecutionSnapshots, workspace } from '@sim/db/schema' +import { generateId } from '@sim/utils/id' +import { eq } from 'drizzle-orm' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { getPublicWorkflowLog } from '@/lib/logs/public-queries' + +const userId = generateId() +const workspaceId = generateId() +const snapshotId = generateId() +const runId = generateId() +const snapshot = { blocks: {}, edges: [], variables: { fixture: 'persisted configuration' } } + +/** Uses the real projection and joins; a SQL mock cannot prove snapshot omission or isolation. */ +describe('public log snapshot projection against PostgreSQL', () => { + beforeAll(async () => { + const now = new Date() + await db.insert(user).values({ + id: userId, + name: 'Log fixture', + email: `${userId}@logs.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + await db.insert(workspace).values({ + id: workspaceId, + name: 'Log fixture', + ownerId: userId, + billedAccountUserId: userId, + }) + await db.insert(workflowExecutionSnapshots).values({ + id: snapshotId, + stateHash: generateId(), + stateData: snapshot, + }) + await db.insert(workflowExecutionLogs).values({ + id: generateId(), + workspaceId, + executionId: runId, + stateSnapshotId: snapshotId, + level: 'info', + status: 'completed', + trigger: 'manual', + startedAt: now, + executionData: { finalOutput: { delivered: false } }, + }) + }) + + afterAll(async () => { + await db.delete(workspace).where(eq(workspace.id, workspaceId)) + await db.delete(workflowExecutionSnapshots).where(eq(workflowExecutionSnapshots.id, snapshotId)) + await db.delete(user).where(eq(user.id, userId)) + await db.$client.end() + }) + + it('keeps the legacy default and omits only the snapshot when explicitly requested', async () => { + const lookup = { column: 'executionId', value: runId } as const + const before = await getPublicWorkflowLog(lookup, workspaceId) + const explicit = await getPublicWorkflowLog(lookup, workspaceId, { includeWorkflowState: true }) + const compact = await getPublicWorkflowLog(lookup, workspaceId, { includeWorkflowState: false }) + + expect(before?.workflowState).toEqual(snapshot) + expect(explicit).toEqual(before) + expect(compact).toEqual({ ...before, workflowState: null }) + expect(await getPublicWorkflowLog(lookup, workspaceId)).toEqual(before) + }) + + it.each([true, false])( + 'keeps workspace isolation with includeWorkflowState=%s', + async (includeWorkflowState) => { + expect( + await getPublicWorkflowLog({ column: 'executionId', value: runId }, generateId(), { + includeWorkflowState, + }) + ).toBeNull() + } + ) +}) diff --git a/apps/sim/lib/logs/public-queries.ts b/apps/sim/lib/logs/public-queries.ts index 3b16f77322f..6acf1eb8d87 100644 --- a/apps/sim/lib/logs/public-queries.ts +++ b/apps/sim/lib/logs/public-queries.ts @@ -454,7 +454,11 @@ export async function getPublicWorkflowLogScope(executionId: string) { * is deliberately left-sided: a missing snapshot does not make an otherwise * valid execution disappear from the log resource. */ -export async function getPublicWorkflowLog(lookup: PublicWorkflowLogLookup, workspaceId?: string) { +export async function getPublicWorkflowLog( + lookup: PublicWorkflowLogLookup, + workspaceId?: string, + options: { includeWorkflowState?: boolean } = {} +) { const lookupCondition = lookup.column === 'id' ? eq(workflowExecutionLogs.id, lookup.value) @@ -478,7 +482,10 @@ export async function getPublicWorkflowLog(lookup: PublicWorkflowLogLookup, work costTotal: workflowExecutionLogs.costTotal, files: workflowExecutionLogs.files, createdAt: workflowExecutionLogs.createdAt, - workflowState: workflowExecutionSnapshots.stateData, + workflowState: + options.includeWorkflowState === false + ? sql`null` + : workflowExecutionSnapshots.stateData, workflowName: workflow.name, workflowDescription: workflow.description, workflowFolderId: workflow.folderId, diff --git a/apps/sim/lib/mothership/generated/docs-manifest.ts b/apps/sim/lib/mothership/generated/docs-manifest.ts index 4e54a71813b..b41376524f1 100644 --- a/apps/sim/lib/mothership/generated/docs-manifest.ts +++ b/apps/sim/lib/mothership/generated/docs-manifest.ts @@ -376,6 +376,7 @@ export const DOCS_MANIFEST: readonly string[] = [ 'mcp.mdx', 'mcp/authentication.mdx', 'mcp/tools.mdx', + 'mcp/troubleshooting.mdx', 'platform/connected-accounts.mdx', 'platform/costs.mdx', 'platform/credentials.mdx', diff --git a/apps/sim/lib/mothership/request/tools/executor.test.ts b/apps/sim/lib/mothership/request/tools/executor.test.ts index b49b5ef5326..e71e5e9eaeb 100644 --- a/apps/sim/lib/mothership/request/tools/executor.test.ts +++ b/apps/sim/lib/mothership/request/tools/executor.test.ts @@ -368,7 +368,15 @@ describe('executeToolAndReport provenance isolation', () => { const completion = await pending expect(tool.error).toBeUndefined() expect(completion.status).toBe('success') - expect(tool.result).toMatchObject({ success: true, output: { exitCode: 0, stderr: '' } }) + const runId = runWorkflow.mock.calls[0]?.[0].headers.get('x-run-id') + expect(runId).toBeTruthy() + expect(tool.result).toMatchObject({ + success: true, + output: { + exitCode: 0, + stderr: `Run ID: ${runId}. Inspect after admission: sim workflows runs get ${runId} --workflow workflow-1\n`, + }, + }) const output = tool.result?.output expect(output).toHaveProperty('stdout', expect.stringContaining('completed')) expect(runWorkflow).toHaveBeenCalledOnce() diff --git a/apps/sim/lib/tool-execution/application/direct-function.test.ts b/apps/sim/lib/tool-execution/application/direct-function.test.ts new file mode 100644 index 00000000000..b5a2773061a --- /dev/null +++ b/apps/sim/lib/tool-execution/application/direct-function.test.ts @@ -0,0 +1,602 @@ +import { runInNewContext } from 'node:vm' +import type { Principal } from '@sim/auth/principal' +import { + environmentUtilsMockFns, + resetEnvFlagsMock, + resetEnvironmentUtilsMock, + setEnvFlags, +} from '@sim/testing' +import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest' + +const mocks = vi.hoisted(() => ({ + sandbox: vi.fn(), + shell: vi.fn(), + local: vi.fn(), + upload: vi.fn(), + usage: vi.fn(), + deleteFiles: vi.fn(), + deleteMetadata: vi.fn(), +})) +vi.mock('@/lib/catalog/application/catalog-context', () => ({ + loadCatalogWorkspaceContext: async () => ({ + workspaceId: 'workspace-1', + workspaceOrganizationId: null, + allowPersonalApiKeys: true, + billedAccountUserId: 'billing-owner', + }), + resolveCatalogGate: async () => ({}), + isBlockTypeAllowed: () => true, +})) +vi.mock('@/lib/catalog/application/tool-scope', () => ({ + resolveVisibleToolOwners: async () => new Map([['function_execute', ['function']]]), + resolveVisibleToolId: (id: string) => id, +})) +vi.mock('@/lib/workspaces/application/workspace-context', () => ({ + resolveActiveWorkspaceApplicationContext: async () => ({ + workspaceId: 'workspace-1', + workspaceOrganizationId: null, + allowPersonalApiKeys: true, + billedAccountUserId: 'billing-owner', + }), +})) +vi.mock('@sim/platform-authz/workspace', () => ({ + resolveEffectiveWorkspacePermission: async () => 'write', + permissionSatisfies: () => true, +})) +vi.mock('@/lib/integrations/principal-scope.server', () => ({ + principalUserId: (p: { userId?: string; subjectUserId?: string }) => p.userId ?? p.subjectUserId, +})) +vi.mock('@/lib/billing/core/billing-attribution', async (original) => ({ + ...(await original()), + resolveBillingAttribution: async () => ({ + actorUserId: 'user-1', + workspaceId: 'workspace-1', + organizationId: null, + billedAccountUserId: 'billing-owner', + billingEntity: { type: 'user', id: 'billing-owner' }, + billingPeriod: { start: '2026-09-01T00:00:00.000Z', end: '2026-10-01T00:00:00.000Z' }, + payerSubscription: null, + }), + toBillingContext: () => ({ + billingEntity: { type: 'workspace', id: 'workspace-1' }, + billingPeriod: { start: new Date(), end: new Date() }, + }), +})) +vi.mock('@/lib/billing/core/usage-gate-cache', () => ({ + checkExecutionUsageLimits: async () => ({ isExceeded: false }), +})) +vi.mock('@/lib/billing/core/usage-log', () => ({ recordUsage: mocks.usage })) +vi.mock('@/ee/access-control/utils/permission-check', () => ({ + assertPermissionsAllowed: async () => {}, +})) +vi.mock('@/tools/registry', async () => { + const { functionExecuteTool } = await import('@/tools/function/execute') + return { tools: { function_execute: functionExecuteTool } } +}) +vi.mock('@/tools/utils.server', () => ({ getToolAsync: vi.fn() })) +vi.mock('@/lib/internal/tool-operations/registry.server', () => ({ + getInternalToolOperationHandler: vi.fn(), +})) +vi.mock('@/lib/execution/isolated-vm', () => ({ executeInIsolatedVM: mocks.local })) +vi.mock('@/lib/execution/remote-sandbox', () => ({ + executeInSandbox: mocks.sandbox, + executeShellInSandbox: mocks.shell, + SIM_RESULT_PREFIX: '__SIM_RESULT__=', +})) +vi.mock('@/lib/uploads/contexts/copilot', () => ({ uploadCopilotFile: mocks.upload })) +vi.mock('@/lib/uploads/core/storage-service', () => ({ deleteFiles: mocks.deleteFiles })) +vi.mock('@/lib/uploads/server/metadata', () => ({ deleteFileMetadata: mocks.deleteMetadata })) + +import { buildJavaScriptRuntimeBindingsSource } from '@/lib/execution/code-placeholders/javascript-runtime' +import type { IsolatedVMExecutionRequest } from '@/lib/execution/isolated-vm' +import { executeToolForCaller } from '@/lib/tool-execution/application/execute-tool' + +const principal = { kind: 'personal_api_key' as const, userId: 'user-1', keyId: 'key-1' } +function run(input: Record, caller: Principal = principal) { + return executeToolForCaller.execute({ + principal: caller, + input: { workspaceId: 'workspace-1', toolId: 'function_execute', input }, + }) +} +describe('direct Function execution', () => { + beforeEach(() => { + resetEnvironmentUtilsMock() + mocks.deleteFiles.mockResolvedValue({ deleted: 1, failed: [] }) + mocks.deleteMetadata.mockResolvedValue(undefined) + setEnvFlags({ + isHosted: false, + isRemoteSandboxEnabled: true, + isMothershipSandboxEnabled: false, + }) + environmentUtilsMockFns.mockGetPersonalAndWorkspaceEnv.mockResolvedValue({ + personalEncrypted: {}, + workspaceEncrypted: { TOKEN: 'encrypted-token' }, + personalDecrypted: {}, + workspaceDecrypted: { TOKEN: 'audit-secret' }, + decryptionFailures: [], + personalOwners: {}, + workspaceUnredactedKeys: [], + conflicts: [], + }) + mocks.local.mockImplementation(async (args: IsolatedVMExecutionRequest) => { + const stdout: string[] = [] + const context = { + ...args.params, + ...args.contextVariables, + environmentVariables: args.envVars, + console: { log: (...values: unknown[]) => stdout.push(values.map(String).join(' ')) }, + } + try { + const result = await runInNewContext( + `${buildJavaScriptRuntimeBindingsSource(args.runtimeBindings ?? [])}\n(async () => {${args.code}})()`, + context + ) + return { result, stdout: stdout.join('\n') } + } catch (error) { + return { + result: null, + error: { message: String(error), name: 'Error' }, + stdout: stdout.join('\n'), + } + } + }) + mocks.sandbox.mockResolvedValue({ result: 'ok', stdout: '', sandboxId: 'sandbox' }) + mocks.upload.mockImplementation(async ({ buffer, fileName, contentType }) => ({ + id: `copilot/file/${fileName}`, + key: `copilot/file/${fileName}`, + context: 'copilot', + name: fileName, + type: contentType, + url: '/api/files/copilot', + size: buffer.length, + })) + }) + afterAll(resetEnvFlagsMock) + it('runs basic direct JavaScript through the real registry and Function request', async () => { + const result = await run({ code: 'return 42' }) + expect(result, JSON.stringify(result)).toMatchObject({ + status: 'succeeded', + output: { result: 42 }, + }) + }) + it('resolves an explicitly mounted secret on the real direct call path', async () => { + const result = await run({ + code: 'return {{TOKEN}} === "audit-secret"', + secretScope: 'selected', + mountedSecrets: ['TOKEN'], + }) + expect(result, JSON.stringify(result)).toMatchObject({ + status: 'succeeded', + output: { result: true }, + }) + }) + it('returns a produced file on the real direct call path without workflow identity', async () => { + mocks.sandbox.mockResolvedValue({ + result: null, + stdout: '', + sandboxId: 'sandbox', + collectedFiles: [ + { + path: '/tmp/sim/outputs/report.txt', + relativePath: 'report.txt', + contentBase64: 'aGk=', + byteLength: 2, + }, + ], + }) + const result = await run({ + code: 'open("/tmp/sim/outputs/report.txt", "w").write("hi")', + language: 'python', + }) + expect(result, JSON.stringify(result)).toMatchObject({ + status: 'succeeded', + output: { files: [{ context: 'copilot', name: 'report.txt' }] }, + }) + }) + it('projects returned values and stdout after the private metadata consumer activates used secrets', async () => { + const result = await run({ + code: 'console.log({{TOKEN}}); return {{TOKEN}}', + secretScope: 'selected', + mountedSecrets: ['TOKEN'], + }) + expect(result).toMatchObject({ + status: 'succeeded', + output: { result: '{{TOKEN}}', stdout: '{{TOKEN}}' }, + }) + expect(JSON.stringify(result)).not.toContain('audit-secret') + expect(environmentUtilsMockFns.mockGetPersonalAndWorkspaceEnv).toHaveBeenCalledWith( + 'user-1', + 'workspace-1', + { requestedNames: ['TOKEN'] } + ) + }) + it('projects an error containing a used secret', async () => { + const result = await run({ + code: 'throw new Error({{TOKEN}})', + secretScope: 'selected', + mountedSecrets: ['TOKEN'], + }) + expect(result.status).toBe('failed') + expect(result.error?.message).toContain('{{TOKEN}}') + expect(JSON.stringify(result)).not.toContain('audit-secret') + }) + it.each([undefined, 'all'])( + 'preserves default/all scope (%s) and activates direct environment reads', + async (secretScope) => { + const result = await run({ + code: 'return environmentVariables.TOKEN', + ...(secretScope ? { secretScope } : {}), + }) + expect(result).toMatchObject({ status: 'succeeded', output: { result: '{{TOKEN}}' } }) + expect(environmentUtilsMockFns.mockGetPersonalAndWorkspaceEnv).toHaveBeenCalledWith( + 'user-1', + 'workspace-1', + {} + ) + } + ) + it('does not redact an unrelated literal matching an unused secret', async () => { + const result = await run({ code: 'return "audit-secret"' }) + expect(result).toMatchObject({ status: 'succeeded', output: { result: 'audit-secret' } }) + }) + it('keeps selected-empty scope empty even when the environment contains secrets', async () => { + const result = await run({ + code: 'return Object.keys(environmentVariables)', + secretScope: 'selected', + mountedSecrets: [], + }) + expect(result).toMatchObject({ status: 'succeeded', output: { result: [] } }) + expect(environmentUtilsMockFns.mockGetPersonalAndWorkspaceEnv).toHaveBeenCalledWith( + 'user-1', + 'workspace-1', + { requestedNames: [] } + ) + }) + it('does not mount an unselected secret', async () => { + const result = await run({ + code: 'return environmentVariables.TOKEN === undefined', + secretScope: 'selected', + mountedSecrets: ['OTHER'], + }) + expect(result).toMatchObject({ status: 'succeeded', output: { result: true } }) + }) + it('preserves the existing explicit workspace visibility flag', async () => { + environmentUtilsMockFns.mockGetPersonalAndWorkspaceEnv.mockResolvedValue({ + personalEncrypted: {}, + workspaceEncrypted: { TOKEN: 'encrypted-token' }, + personalDecrypted: {}, + workspaceDecrypted: { TOKEN: 'audit-secret' }, + decryptionFailures: [], + personalOwners: {}, + workspaceUnredactedKeys: ['TOKEN'], + conflicts: [], + }) + const result = await run({ + code: 'return {{TOKEN}}', + secretScope: 'selected', + mountedSecrets: ['TOKEN'], + }) + expect(result).toMatchObject({ status: 'succeeded', output: { result: 'audit-secret' } }) + }) + it.each([{ envVars: { TOKEN: 'forged' } }, { unredactedSecretNames: ['TOKEN'] }])( + 'rejects caller-supplied secret authority %o', + async (extra) => { + await expect(run({ code: 'return 1', ...extra })).rejects.toMatchObject({ + code: 'validation', + }) + expect(environmentUtilsMockFns.mockGetPersonalAndWorkspaceEnv).not.toHaveBeenCalled() + expect(mocks.local).not.toHaveBeenCalled() + } + ) + it.each([ + { secretScope: 'invalid' }, + { mountedSecrets: [1] }, + { mountedSecrets: Array.from({ length: 101 }, (_, index) => `SECRET_${index}`) }, + ])('rejects invalid mount selection before decrypting %o', async (selection) => { + await expect(run({ code: 'return 1', ...selection })).rejects.toMatchObject({ + code: 'validation', + }) + expect(environmentUtilsMockFns.mockGetPersonalAndWorkspaceEnv).not.toHaveBeenCalled() + }) + it('stores ordinary outputs under the real actor rather than the billing owner', async () => { + mocks.sandbox.mockResolvedValue({ + result: null, + stdout: '', + sandboxId: 'sandbox', + collectedFiles: [ + { + path: '/tmp/sim/outputs/report.txt', + relativePath: 'report.txt', + contentBase64: 'aGk=', + byteLength: 2, + }, + ], + }) + await run({ + code: 'print("hi")', + language: 'python', + secretScope: 'selected', + mountedSecrets: [], + }) + expect(mocks.upload).toHaveBeenCalledWith( + expect.objectContaining({ + userId: 'user-1', + fileName: 'report.txt', + buffer: Buffer.from('hi'), + }) + ) + }) + it('returns a binary output when no secret was used', async () => { + mocks.sandbox.mockResolvedValue({ + result: null, + stdout: '', + sandboxId: 'sandbox', + collectedFiles: [ + { + path: '/tmp/sim/outputs/report.pdf', + relativePath: 'report.pdf', + contentBase64: Buffer.from('%PDF-1.7').toString('base64'), + byteLength: 8, + }, + ], + }) + const result = await run({ + code: 'print("hi")', + language: 'python', + secretScope: 'selected', + mountedSecrets: [], + }) + expect(result).toMatchObject({ + status: 'succeeded', + output: { files: [{ context: 'copilot', name: 'report.pdf' }] }, + }) + }) + it('refuses literal secret file content before personal upload', async () => { + mocks.sandbox.mockResolvedValue({ + result: null, + stdout: '', + sandboxId: 'sandbox', + collectedFiles: [ + { + path: '/tmp/sim/outputs/report.txt', + relativePath: 'report.txt', + contentBase64: Buffer.from('audit-secret').toString('base64'), + byteLength: 12, + }, + ], + }) + const result = await run({ + code: 'token = {{TOKEN}}', + language: 'python', + secretScope: 'selected', + mountedSecrets: ['TOKEN'], + }) + expect(result.status).toBe('failed') + expect(mocks.upload).not.toHaveBeenCalled() + expect(JSON.stringify(result)).not.toContain('audit-secret') + }) + it('refuses uncertain binary output after secret use without persisting incomplete provenance', async () => { + mocks.sandbox.mockResolvedValue({ + result: null, + stdout: '', + sandboxId: 'sandbox', + collectedFiles: [ + { + path: '/tmp/sim/outputs/report.pdf', + relativePath: 'report.pdf', + contentBase64: Buffer.from('%PDF-1.7').toString('base64'), + byteLength: 8, + }, + ], + }) + const result = await run({ + code: 'token = {{TOKEN}}', + language: 'python', + secretScope: 'selected', + mountedSecrets: ['TOKEN'], + }) + expect(result.status).toBe('failed') + expect(result.error?.message).toContain('secret provenance is uncertain') + expect(mocks.upload).not.toHaveBeenCalled() + }) + it('removes earlier personal uploads if a later collected file is refused', async () => { + mocks.sandbox.mockResolvedValue({ + result: null, + stdout: '', + sandboxId: 'sandbox', + collectedFiles: [ + { + path: '/tmp/sim/outputs/report.txt', + relativePath: 'report.txt', + contentBase64: 'aGk=', + byteLength: 2, + }, + { + path: '/tmp/sim/outputs/secret.txt', + relativePath: 'secret.txt', + contentBase64: Buffer.from('audit-secret').toString('base64'), + byteLength: 12, + }, + ], + }) + const result = await run({ + code: 'token = {{TOKEN}}', + language: 'python', + secretScope: 'selected', + mountedSecrets: ['TOKEN'], + }) + expect(result.status).toBe('failed') + expect(mocks.deleteFiles).toHaveBeenCalledWith(['copilot/file/report.txt'], 'copilot') + expect(mocks.deleteMetadata).toHaveBeenCalledWith('copilot/file/report.txt') + }) + it('retains metadata for a partial upload whose object could not be removed', async () => { + mocks.deleteFiles.mockResolvedValue({ + deleted: 0, + failed: [{ key: 'copilot/file/report.txt', error: 'unavailable' }], + }) + mocks.upload + .mockResolvedValueOnce({ + id: 'copilot/file/report.txt', + key: 'copilot/file/report.txt', + context: 'copilot', + name: 'report.txt', + size: 2, + type: 'text/plain', + url: '/api/file', + }) + .mockRejectedValueOnce(new Error('upload unavailable')) + mocks.sandbox.mockResolvedValue({ + result: null, + stdout: '', + sandboxId: 'sandbox', + collectedFiles: [ + { + path: '/tmp/sim/outputs/report.txt', + relativePath: 'report.txt', + contentBase64: 'aGk=', + byteLength: 2, + }, + { + path: '/tmp/sim/outputs/second.txt', + relativePath: 'second.txt', + contentBase64: 'aGk=', + byteLength: 2, + }, + ], + }) + const result = await run({ + code: 'print("hi")', + language: 'python', + secretScope: 'selected', + mountedSecrets: [], + }) + expect(result.status).toBe('failed') + expect(mocks.deleteFiles).toHaveBeenCalledWith(['copilot/file/report.txt'], 'copilot') + expect(mocks.deleteMetadata).not.toHaveBeenCalled() + }) + it('continues metadata cleanup after an earlier metadata update fails', async () => { + mocks.deleteFiles.mockResolvedValue({ deleted: 2, failed: [] }) + mocks.deleteMetadata.mockRejectedValueOnce(new Error('metadata unavailable')) + mocks.sandbox.mockResolvedValue({ + result: null, + stdout: '', + sandboxId: 'sandbox', + collectedFiles: ['first.txt', 'second.txt', 'secret.txt'].map((name, index) => { + const content = index === 2 ? 'audit-secret' : 'hi' + return { + path: `/tmp/sim/outputs/${name}`, + relativePath: name, + contentBase64: Buffer.from(content).toString('base64'), + byteLength: Buffer.byteLength(content), + } + }), + }) + const result = await run({ + code: 'token = {{TOKEN}}', + language: 'python', + secretScope: 'selected', + mountedSecrets: ['TOKEN'], + }) + expect(result.status).toBe('failed') + expect(result.error?.message).toContain('contains a resolved secret value') + expect(mocks.deleteFiles).toHaveBeenCalledWith( + ['copilot/file/first.txt', 'copilot/file/second.txt'], + 'copilot' + ) + expect(mocks.deleteMetadata).toHaveBeenNthCalledWith(1, 'copilot/file/first.txt') + expect(mocks.deleteMetadata).toHaveBeenNthCalledWith(2, 'copilot/file/second.txt') + expect(JSON.stringify(result)).not.toContain('audit-secret') + }) + it('refuses a secret-bearing filename before personal upload or storage logging', async () => { + mocks.sandbox.mockResolvedValue({ + result: null, + stdout: '', + sandboxId: 'sandbox', + collectedFiles: [ + { + path: '/tmp/sim/outputs/audit-secret.txt', + relativePath: 'audit-secret.txt', + contentBase64: 'aGk=', + byteLength: 2, + }, + ], + }) + const result = await run({ + code: 'token = {{TOKEN}}', + language: 'python', + secretScope: 'selected', + mountedSecrets: ['TOKEN'], + }) + expect(result.status).toBe('failed') + expect(mocks.upload).not.toHaveBeenCalled() + expect(JSON.stringify(result)).not.toContain('audit-secret') + }) + it('preserves delegated Copilot execution without resolving a new environment', async () => { + const delegated: Principal = { + kind: 'delegated', + serviceId: 'copilot', + subjectUserId: 'user-1', + workspaceId: 'workspace-1', + delegationId: 'delegation-1', + audience: 'sim:tool-execution', + issuedAt: new Date(Date.now() - 1000), + expiresAt: new Date(Date.now() + 60000), + } + const result = await run({ code: 'return 42' }, delegated) + expect(result).toMatchObject({ status: 'succeeded', output: { result: 42 } }) + expect(environmentUtilsMockFns.mockGetPersonalAndWorkspaceEnv).not.toHaveBeenCalled() + expect(mocks.local).toHaveBeenCalledWith( + expect.objectContaining({ envVars: {} }), + expect.anything() + ) + }) + it('does not turn delegated Copilot sandbox outputs into personal files', async () => { + const delegated: Principal = { + kind: 'delegated', + serviceId: 'copilot', + subjectUserId: 'user-1', + workspaceId: 'workspace-1', + delegationId: 'delegation-1', + audience: 'sim:tool-execution', + issuedAt: new Date(Date.now() - 1000), + expiresAt: new Date(Date.now() + 60000), + } + mocks.sandbox.mockResolvedValue({ + result: null, + stdout: '', + sandboxId: 'sandbox', + collectedFiles: [ + { + path: '/tmp/sim/outputs/report.txt', + relativePath: 'report.txt', + contentBase64: 'aGk=', + byteLength: 2, + }, + ], + }) + const result = await run({ code: 'print("hi")', language: 'python' }, delegated) + expect(result.status).toBe('failed') + expect(result.error?.message).toContain('workflow, and execution context') + expect(environmentUtilsMockFns.mockGetPersonalAndWorkspaceEnv).not.toHaveBeenCalled() + expect(mocks.upload).not.toHaveBeenCalled() + }) + it('refuses organization delegation at the direct tool operation before sandbox dispatch', async () => { + const organizationCaller: Principal = { + kind: 'organization_delegated', + serviceId: 'copilot', + subjectUserId: 'user-1', + organizationId: 'organization-1', + resourceScope: { chatId: 'chat-1' }, + delegationId: 'delegation-1', + audience: 'sim:tool-execution', + issuedAt: new Date(Date.now() - 1000), + expiresAt: new Date(Date.now() + 60000), + } + await expect( + run({ code: 'print("hi")', language: 'python' }, organizationCaller) + ).rejects.toMatchObject({ code: 'forbidden' }) + expect(environmentUtilsMockFns.mockGetPersonalAndWorkspaceEnv).not.toHaveBeenCalled() + expect(mocks.sandbox).not.toHaveBeenCalled() + expect(mocks.upload).not.toHaveBeenCalled() + }) +}) diff --git a/apps/sim/lib/tool-execution/application/download-tool-file.ts b/apps/sim/lib/tool-execution/application/download-tool-file.ts new file mode 100644 index 00000000000..32297d2de11 --- /dev/null +++ b/apps/sim/lib/tool-execution/application/download-tool-file.ts @@ -0,0 +1,73 @@ +import { AuditAction, AuditResourceType } from '@sim/audit' +import { requirePrincipalSubjectUserId } from '@sim/auth/principal' +import { defineAuthorizedWorkspaceUseCase } from '@/lib/core/application' +import type { PrincipalForOperation } from '@/lib/core/application/workspace-operation' +import { OrchestrationError } from '@/lib/core/orchestration/types' +import { nodeReadableToWebStream } from '@/lib/core/utils/node-stream' +import { toolExecutionOperations } from '@/lib/tool-execution/application/operations' +import { isObjectNotFoundError } from '@/lib/uploads/core/errors' +import { downloadFileStream } from '@/lib/uploads/core/storage-service' +import { getFileMetadataByKey } from '@/lib/uploads/server/metadata' +import { getWorkspaceFileSize } from '@/lib/uploads/shared/types' +import { tryInferContextFromKey } from '@/lib/uploads/utils/file-utils' +import { loadActiveWorkspaceApplicationContext } from '@/lib/workspaces/application/workspace-context' + +interface DownloadToolFileInput { + workspaceId: string + fileId: string +} + +/** Downloads a direct tool call's stored output using canonical ownership, never descriptor claims. */ +export const downloadToolFile = defineAuthorizedWorkspaceUseCase({ + operation: toolExecutionOperations.downloadFile, + authorizationOptions: {}, + async resolveContext({ + principal, + input, + }: { + principal: PrincipalForOperation + input: DownloadToolFileInput + }) { + const workspace = await loadActiveWorkspaceApplicationContext(input.workspaceId) + if (!workspace) throw new OrchestrationError('not_found', 'File not found') + if (tryInferContextFromKey(input.fileId) !== 'copilot') { + throw new OrchestrationError('not_found', 'File not found') + } + const file = await getFileMetadataByKey(input.fileId, 'copilot') + if ( + !file || + file.deletedAt !== null || + file.context !== 'copilot' || + file.userId !== requirePrincipalSubjectUserId(principal) || + file.workspaceId !== null || + file.organizationId !== null + ) { + throw new OrchestrationError('not_found', 'File not found') + } + return { ...workspace, file } + }, + async execute({ context }) { + const { file } = context + let stream: Awaited> + try { + stream = await downloadFileStream({ key: file.key, context: 'copilot' }) + } catch (error) { + if (isObjectNotFoundError(error)) throw new OrchestrationError('not_found', 'File not found') + throw error + } + return { + file, + stream: nodeReadableToWebStream(stream), + contentType: file.contentType, + contentLength: getWorkspaceFileSize(file), + } + }, + projectAudit: ({ result }) => ({ + action: AuditAction.FILE_DOWNLOADED, + resourceType: AuditResourceType.FILE, + resourceId: result.file.id, + resourceName: result.file.originalName, + description: `Downloaded tool file "${result.file.originalName}"`, + metadata: { bytes: result.contentLength }, + }), +}) diff --git a/apps/sim/lib/tool-execution/application/errors.ts b/apps/sim/lib/tool-execution/application/errors.ts new file mode 100644 index 00000000000..25b4899cba4 --- /dev/null +++ b/apps/sim/lib/tool-execution/application/errors.ts @@ -0,0 +1,7 @@ +/** Direct execution was refused before dispatch because its payer or actor exceeded a limit. */ +export class ToolExecutionUsageLimitError extends Error { + constructor(message: string) { + super(message) + this.name = 'ToolExecutionUsageLimitError' + } +} diff --git a/apps/sim/lib/tool-execution/application/execute-tool.test.ts b/apps/sim/lib/tool-execution/application/execute-tool.test.ts index 0a1231c8351..39c05aa19a9 100644 --- a/apps/sim/lib/tool-execution/application/execute-tool.test.ts +++ b/apps/sim/lib/tool-execution/application/execute-tool.test.ts @@ -18,11 +18,13 @@ const mocks = vi.hoisted(() => ({ executeRegistryTool: vi.fn(), executeFileManage: vi.fn(), resolveBillingAttribution: vi.fn(), + checkExecutionUsageLimits: vi.fn(), recordUsage: vi.fn(), })) vi.mock('@/lib/workspaces/application/workspace-context', () => ({ loadActiveWorkspaceApplicationContext: mocks.loadWorkspace, + resolveActiveWorkspaceApplicationContext: mocks.loadWorkspace, })) vi.mock('@sim/platform-authz/workspace', () => ({ @@ -99,15 +101,24 @@ vi.mock('@/lib/billing/core/billing-attribution', () => ({ })) vi.mock('@/lib/billing/core/usage-log', () => ({ recordUsage: mocks.recordUsage })) +vi.mock('@/lib/billing/core/usage-gate-cache', () => ({ + checkExecutionUsageLimits: mocks.checkExecutionUsageLimits, +})) import { executeFileTool } from '@/lib/internal/file/execute-tool' import type { InternalToolOperationContext } from '@/lib/internal/tool-operations/types' import { executeToolForCaller } from '@/lib/tool-execution/application/execute-tool' import type { BlockConfig } from '@/blocks/types' +import { fileMoveTool } from '@/tools/file/folders' import { fileReadTool } from '@/tools/file/get' +import { functionExecuteTool } from '@/tools/function/execute' +import { slackUpdateMessageTool } from '@/tools/slack/update_message' const TOOL_METADATA: Record> = { + function_execute: { ...functionExecuteTool }, + slack_update_message: { ...slackUpdateMessageTool }, file_read: { ...fileReadTool }, + file_move: { ...fileMoveTool }, slack_message: { id: 'slack_message', name: 'Slack Send Message', @@ -187,8 +198,11 @@ function block(overrides: Partial & { type: string }): BlockConfig } as BlockConfig } -const fileBlock = block({ type: 'file_v5', tools: { access: ['file_read'] } }) -const slackBlock = block({ type: 'slack', tools: { access: ['slack_message'] } }) +const fileBlock = block({ type: 'file_v5', tools: { access: ['file_read', 'file_move'] } }) +const slackBlock = block({ + type: 'slack', + tools: { access: ['slack_message', 'slack_update_message'] }, +}) const firecrawlBlock = block({ type: 'firecrawl', tools: { access: ['firecrawl_scrape'] } }) const previewBlock = block({ type: 'preview_thing', @@ -229,6 +243,7 @@ describe('executeToolForCaller', () => { mocks.isDeploymentAvailable.mockReturnValue(true) mocks.getAllBlocks.mockReturnValue([ fileBlock, + block({ type: 'function', tools: { access: ['function_execute'] } }), slackBlock, firecrawlBlock, previewBlock, @@ -239,6 +254,7 @@ describe('executeToolForCaller', () => { ]) mocks.executeRegistryTool.mockResolvedValue({ success: true, output: { markdown: '# Hi' } }) mocks.resolveBillingAttribution.mockResolvedValue({ workspaceId: WORKSPACE_ID }) + mocks.checkExecutionUsageLimits.mockResolvedValue({ isExceeded: false }) }) it.each([ @@ -281,16 +297,119 @@ describe('executeToolForCaller', () => { expect(mocks.executeFileManage.mock.calls[0]?.[1].principal).toBe(caller) }) - it.each(['callerPrincipal', 'principal', 'operationContext', '_context'])( - 'rejects caller input attempting to supply %s authority', - async (key) => { - await expect( - run({ input: { url: 'https://a.co', [key]: { callerPrincipal: principal } } }) - ).rejects.toMatchObject({ code: 'validation' }) - expect(mocks.executeRegistryTool).not.toHaveBeenCalled() + it('refuses direct Function execution before dispatch when usage admission denies it', async () => { + mocks.checkExecutionUsageLimits.mockResolvedValueOnce({ + isExceeded: true, + scope: 'payer', + message: 'Organization usage limit exceeded', + }) + await expect( + run({ toolId: 'function_execute', input: { code: 'return 1' } }) + ).rejects.toMatchObject({ + name: 'ToolExecutionUsageLimitError', + message: 'Organization usage limit exceeded', + }) + expect(mocks.executeRegistryTool).not.toHaveBeenCalled() + expect(mocks.recordUsage).not.toHaveBeenCalled() + }) + + it('fails closed without provider dispatch or metering when Function usage admission is unavailable', async () => { + mocks.checkExecutionUsageLimits.mockRejectedValueOnce(new Error('ledger unavailable')) + await expect(run({ toolId: 'function_execute', input: { code: 'return 1' } })).rejects.toThrow( + 'ledger unavailable' + ) + expect(mocks.executeRegistryTool).not.toHaveBeenCalled() + expect(mocks.recordUsage).not.toHaveBeenCalled() + }) + + it.each([true, false])( + 'meters actual direct Function sandbox cost when success=%s', + async (success) => { + mocks.executeRegistryTool.mockResolvedValueOnce({ + success, + output: { result: null, cost: { input: 0, output: 0, total: 0.25 } }, + ...(success ? {} : { error: 'Code failed' }), + }) + await executeToolForCaller.execute({ + principal, + input: { + workspaceId: WORKSPACE_ID, + toolId: 'function_execute', + input: { code: 'return 1' }, + }, + }) + expect(mocks.recordUsage).toHaveBeenCalledWith( + expect.objectContaining({ + userId: 'user-1', + workspaceId: WORKSPACE_ID, + entries: [ + expect.objectContaining({ + cost: 0.25, + source: 'api-tool', + description: 'Tool call: function_execute', + }), + ], + }) + ) } ) + it('dispatches file_move with the authenticated principal and preserves its destination', async () => { + mocks.executeFileManage.mockResolvedValue( + Response.json({ + success: true, + data: { fileId: 'file-1', folderPath: '/Generated' }, + }) + ) + mocks.executeRegistryTool.mockImplementationOnce( + async ( + toolId: string, + params: Parameters[0], + options: { operationContext: InternalToolOperationContext } + ) => + fileMoveTool.transformResponse?.( + await executeFileTool({ + toolId, + input: fileMoveTool.operation.input(params), + context: options.operationContext, + headers: new Headers(), + requestId: 'direct-file-move', + }) + ) + ) + + const result = await run({ + toolId: 'file_move', + input: { fileId: 'file-1', folderPath: '/Generated' }, + }) + expect(result).toMatchObject({ + status: 'succeeded', + output: { fileId: 'file-1', folderPath: '/Generated' }, + }) + expect(mocks.executeFileManage).toHaveBeenCalledWith( + expect.objectContaining({ + operation: 'move', + fileId: 'file-1', + folderPath: '/Generated', + }), + expect.objectContaining({ principal, workspaceId: WORKSPACE_ID }) + ) + }) + + it.each([ + 'callerPrincipal', + 'principal', + 'operationContext', + 'executorDelegationOrigin', + 'meterSandboxUsage', + '_context', + ])('rejects caller input attempting to supply %s authority', async (key) => { + await expect( + run({ input: { url: 'https://a.co', [key]: { callerPrincipal: principal } } }) + ).rejects.toMatchObject({ code: 'validation' }) + expect(mocks.executeRegistryTool).not.toHaveBeenCalled() + }) + it('acts as the authenticated caller and enforces credential access', async () => { await run({ input: { url: 'https://example.com' } }) @@ -359,6 +478,96 @@ describe('executeToolForCaller', () => { expect(mocks.executeRegistryTool).not.toHaveBeenCalled() }) + it.each([undefined, 'unused-oauth-credential'])( + 'honors explicit Slack bot-token mode without resolving credential %s', + async (credentialId) => { + const input = { + authMethod: 'bot_token', + botToken: '{{SLACK_BOT_TOKEN}}', + channel: 'channel-1', + timestamp: '123.456', + text: 'Updated', + } + await run({ toolId: 'slack_update_message', input, credentialId }) + const [, params, options] = mocks.executeRegistryTool.mock.calls[0] + expect(params).toMatchObject(input) + expect(params).not.toHaveProperty('credential') + expect(params).not.toHaveProperty('accessToken') + expect(params._context).toMatchObject({ + userId: principal.userId, + workspaceId: WORKSPACE_ID, + enforceCredentialAccess: true, + envReferenceMode: 'explicit', + }) + expect(options.operationContext.callerPrincipal).toBe(principal) + expect(input.botToken).toBe('{{SLACK_BOT_TOKEN}}') + } + ) + + it.each([undefined, 'oauth'])( + 'drops inactive Slack bot secrets when selecting OAuth mode %s', + async (authMethod) => { + await run({ + toolId: 'slack_update_message', + credentialId: 'selected-credential', + input: { + authMethod, + botToken: '{{UNUSED_SECRET}}', + channel: 'channel-1', + timestamp: '123.456', + text: 'Updated', + }, + }) + const [, params] = mocks.executeRegistryTool.mock.calls[0] + expect(params.credential).toBe('selected-credential') + expect(params).not.toHaveProperty('botToken') + } + ) + + it.each([undefined, '', ' ', 123])( + 'rejects missing or invalid selected botToken %s', + async (botToken) => { + await expect( + run({ + toolId: 'slack_update_message', + credentialId: 'unused-credential', + input: { authMethod: 'bot_token', botToken, channel: 'channel-1', timestamp: '123.456' }, + }) + ).rejects.toMatchObject({ + code: 'validation', + message: expect.stringContaining('input.botToken'), + }) + expect(mocks.executeRegistryTool).not.toHaveBeenCalled() + } + ) + + it('rejects an invalid Slack auth mode without reflecting its value', async () => { + await expect( + run({ + toolId: 'slack_update_message', + credentialId: 'credential-1', + input: { authMethod: 'private-invalid-value', channel: 'channel-1', timestamp: '123.456' }, + }) + ).rejects.toMatchObject({ + code: 'validation', + message: 'input.authMethod must be oauth or bot_token', + }) + expect(mocks.executeRegistryTool).not.toHaveBeenCalled() + }) + + it('does not silently choose a bot token when OAuth is the default', async () => { + await expect( + run({ + toolId: 'slack_update_message', + input: { botToken: '{{TOKEN}}', channel: 'channel-1', timestamp: '123.456' }, + }) + ).rejects.toMatchObject({ + code: 'validation', + message: expect.stringContaining('credentialId is required'), + }) + expect(mocks.executeRegistryTool).not.toHaveBeenCalled() + }) + /** * The alias check has to run before the declared-key check, or a tool that * declares `oauthCredential` lets a caller bypass the top-level field and diff --git a/apps/sim/lib/tool-execution/application/execute-tool.ts b/apps/sim/lib/tool-execution/application/execute-tool.ts index ec4969336a0..f4de5d4cb02 100644 --- a/apps/sim/lib/tool-execution/application/execute-tool.ts +++ b/apps/sim/lib/tool-execution/application/execute-tool.ts @@ -1,7 +1,10 @@ import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' import { generateId } from '@sim/utils/id' +import { isRecordLike, omit } from '@sim/utils/object' +import { secretMountPolicyInputSchema } from '@/lib/api/contracts/secret-mount-policy' import { resolveBillingAttribution, toBillingContext } from '@/lib/billing/core/billing-attribution' +import { checkExecutionUsageLimits } from '@/lib/billing/core/usage-gate-cache' import { recordUsage } from '@/lib/billing/core/usage-log' import { isBlockTypeAllowed, @@ -16,9 +19,17 @@ import { defineAuthorizedWorkspaceUseCase } from '@/lib/core/application' import { ForbiddenOperationError } from '@/lib/core/application/forbidden' import { isHosted } from '@/lib/core/config/env-flags' import { OrchestrationError } from '@/lib/core/orchestration/types' +import { getPersonalAndWorkspaceEnv } from '@/lib/environment/utils' import { principalUserId } from '@/lib/integrations/principal-scope.server' +import { ToolExecutionUsageLimitError } from '@/lib/tool-execution/application/errors' import { toolExecutionOperations } from '@/lib/tool-execution/application/operations' +import { projectResolvedSecretModelJsonContent } from '@/executor/utils/resolved-secret-content-projection' +import { + createResolvedSecretTraceRegistry, + type ResolvedSecretTraceRegistry, +} from '@/executor/utils/resolved-secret-trace-registry' import { executeTool as executeRegistryTool } from '@/tools' +import { supportsSlackBotToken } from '@/tools/slack/auth' import type { ExecutableToolConfig } from '@/tools/types' import { getTool } from '@/tools/utils' @@ -269,27 +280,42 @@ export const executeToolForCaller = defineAuthorizedWorkspaceUseCase({ if (!tool) throw new OrchestrationError('not_found', 'Tool not found') assertNoUndeclaredInputs(tool, toolId, input.input) + let callerParams: Record = { ...input.input } + let credentialId = input.credentialId + let usesBotToken = false + if (supportsSlackBotToken(tool)) { + const authMethod = callerParams.authMethod === undefined ? 'oauth' : callerParams.authMethod + if (authMethod !== 'oauth' && authMethod !== 'bot_token') { + throw new OrchestrationError('validation', 'input.authMethod must be oauth or bot_token') + } + usesBotToken = authMethod === 'bot_token' + if (usesBotToken) { + if (typeof callerParams.botToken !== 'string' || !callerParams.botToken.trim()) { + throw new OrchestrationError( + 'validation', + 'input.botToken is required when input.authMethod is bot_token' + ) + } + credentialId = undefined + } else { + /** Inactive secrets must neither resolve nor become a provider fallback. */ + callerParams = omit(callerParams, ['botToken']) + } + } + const selector = declaredCredentialSelector(tool) const requiresCredential = - tool.oauth?.required === true || (selector !== undefined && tool.params[selector]?.required) - if (requiresCredential && !input.credentialId) { + !usesBotToken && + (tool.oauth?.required === true || (selector !== undefined && tool.params[selector]?.required)) + if (requiresCredential && !credentialId) { throw new OrchestrationError( 'validation', `credentialId is required: ${toolId} authenticates with a ${tool.oauth?.provider ?? 'connected'} credential` ) } - /** - * What the executor will receive, minus `_context`. The credential lands - * under the selector the tool declares, so a declared required - * `oauthCredential` is satisfied by the top-level `credentialId` rather than - * rejected as missing; a tool that declares none gets `credential`, which the - * executor reads for OAuth resolution. - */ - const callerParams: Record = { - ...input.input, - ...(input.credentialId ? { [selector ?? 'credential']: input.credentialId } : {}), - } + /** Map the top-level selector to the spelling this tool declares. */ + if (credentialId) callerParams[selector ?? 'credential'] = credentialId assertRequiredCallerInputsPresent(tool, toolId, callerParams) const userId = principalUserId(principal) @@ -301,6 +327,14 @@ export const executeToolForCaller = defineAuthorizedWorkspaceUseCase({ actorUserId: userId, workspaceId: context.workspaceId, }) + if (toolId === 'function_execute') { + const usage = await checkExecutionUsageLimits(billingAttribution) + if (usage.isExceeded) { + throw new ToolExecutionUsageLimitError( + usage.message || 'Usage limit exceeded. Please upgrade your plan to continue.' + ) + } + } const params: Record = { ...callerParams, @@ -318,6 +352,27 @@ export const executeToolForCaller = defineAuthorizedWorkspaceUseCase({ }, } + let resolvedSecretTraceRegistry: ResolvedSecretTraceRegistry | undefined + if (toolId === 'function_execute' && principal.kind !== 'delegated') { + const selection = secretMountPolicyInputSchema.safeParse(callerParams) + if (!selection.success) { + throw new OrchestrationError('validation', selection.error.issues[0].message) + } + const environment = await getPersonalAndWorkspaceEnv(userId, context.workspaceId, { + ...(selection.data.secretScope === 'selected' + ? { requestedNames: selection.data.mountedSecrets ?? [] } + : {}), + }) + resolvedSecretTraceRegistry = await createResolvedSecretTraceRegistry({ + ...environment, + scope: { userId, workspaceId: context.workspaceId }, + }) + Object.assign(params, selection.data, { + envVars: { ...environment.personalDecrypted, ...environment.workspaceDecrypted }, + unredactedSecretNames: [...resolvedSecretTraceRegistry.getUnredactedSecretNames()], + }) + } + /** * The ledger de-duplicates on `eventKey`, and the derived key is a hash of * actor, workspace, source and description — identical for every call to the @@ -330,6 +385,7 @@ export const executeToolForCaller = defineAuthorizedWorkspaceUseCase({ const result = await executeRegistryTool(toolId, params, { signal: AbortSignal.timeout((input.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS) * 1000), + ...(resolvedSecretTraceRegistry ? { resolvedSecretTraceRegistry } : {}), operationContext: { /** * No workflow owns this call. The empty string is what the Copilot @@ -346,8 +402,8 @@ export const executeToolForCaller = defineAuthorizedWorkspaceUseCase({ }) /** - * Only a successful call that spent Sim's key — and that verdict is the - * registry's, not re-derived here. + * Meter successful hosted-key calls and measured Function sandbox costs, including failed + * sandbox runs. The registry supplies the measured cost; local Function runs have none. * * The registry decides whether Sim's key was used inside * `injectHostedKeyIfNeeded`, and a workspace or organization BYOK key is @@ -365,8 +421,8 @@ export const executeToolForCaller = defineAuthorizedWorkspaceUseCase({ * metered elsewhere. That no hosted tool does the same is what * `check-tool-param-reachability` now pins. */ - if (result.success && tool.hosting) { - await meterHostedKeySpend({ + if ((result.success && tool.hosting) || toolId === 'function_execute') { + await meterToolSpend({ callId, toolId, userId, @@ -376,17 +432,35 @@ export const executeToolForCaller = defineAuthorizedWorkspaceUseCase({ }) } + let output = result.output + let error = result.error + if (resolvedSecretTraceRegistry) { + const projection = projectResolvedSecretModelJsonContent( + { output, error }, + resolvedSecretTraceRegistry + ) + if ( + !projection.safe || + !isRecordLike(projection.value) || + !isRecordLike(projection.value.output) + ) { + throw new OrchestrationError('internal', 'Function output secret projection is unavailable') + } + output = projection.value.output + error = typeof projection.value.error === 'string' ? projection.value.error : undefined + } + return { toolId, status: result.success ? 'succeeded' : 'failed', - output: result.output, - error: result.success ? null : { message: result.error ?? `${toolId} did not succeed` }, + output, + error: result.success ? null : { message: error ?? `${toolId} did not succeed` }, } }, }) /** - * Charges hosted-key spend this call incurred. + * Charges measured provider or Function sandbox spend this direct call incurred. * * `@/tools` computes the cost and hands it back on `output.cost.total`, but it * writes no ledger row: a workflow run bills through the execution ledger and @@ -399,7 +473,7 @@ export const executeToolForCaller = defineAuthorizedWorkspaceUseCase({ * reconciliation and the call still answers, the same choice * `applyHostedKeyCostToResult` makes one layer down. */ -async function meterHostedKeySpend(args: { +async function meterToolSpend(args: { callId: string toolId: string userId: string @@ -428,7 +502,7 @@ async function meterHostedKeySpend(args: { ], }) } catch (error) { - logger.error('Hosted-key metering failed; tool call succeeded unbilled', { + logger.error('Direct tool metering failed; measured spend was not recorded', { toolId: args.toolId, workspaceId: args.workspaceId, cost, diff --git a/apps/sim/lib/tool-execution/application/operations.ts b/apps/sim/lib/tool-execution/application/operations.ts index 3dbe325c164..724ce043614 100644 --- a/apps/sim/lib/tool-execution/application/operations.ts +++ b/apps/sim/lib/tool-execution/application/operations.ts @@ -28,6 +28,15 @@ import { defineWorkspaceOperation } from '@/lib/core/application/workspace-opera * kinds ahead of a surface that uses them. */ export const toolExecutionOperations = { + // permission-group-exempt: reads an already-produced personal tool file; canonical ownership and current workspace access govern retrieval, not a workspace resource-module capability. + downloadFile: defineWorkspaceOperation({ + id: 'tools.files.download', + oauthScope: 'api:read', + minimumRole: 'read', + workspaceApiKey: 'deny', + principalKinds: ['session', 'personal_api_key', 'oauth_access_token'], + capability: 'none', + }), // permission-group-exempt: declares capability: 'none' because no static capability names running one built-in tool — the per-tool denial is the deniedTools key, applied inside @/tools against the resolved id, and the per-integration denial is the parameterized allowedIntegrations key, which the funnel cannot apply because it never sees which integration a tool id reaches. That decision is enforced from the use case by the owning-block-type check in executeToolForCaller, ahead of dispatch. execute: defineWorkspaceOperation({ id: 'tools.execute', diff --git a/apps/sim/lib/uploads/contexts/workspace/workspace-file-manager.ts b/apps/sim/lib/uploads/contexts/workspace/workspace-file-manager.ts index 8b7519e0189..cc6b88b018b 100644 --- a/apps/sim/lib/uploads/contexts/workspace/workspace-file-manager.ts +++ b/apps/sim/lib/uploads/contexts/workspace/workspace-file-manager.ts @@ -100,6 +100,7 @@ import { import { getWorkspaceFileSize, MAX_WORKSPACE_FILE_SIZE } from '@/lib/uploads/shared/types' import { isMarkdownFile } from '@/lib/uploads/utils/file-utils' import type { ServableFile } from '@/lib/uploads/utils/file-utils.server' +import { buildWorkspaceFileFolderDisplayPath } from '@/lib/workspace-files/folder-display-path' import { SIM_PAGE_CONTENT_TYPE } from '@/lib/workspace-files/page-compile' import { MAX_SIM_PAGE_UPLOAD_SNIFF_BYTES, @@ -449,7 +450,7 @@ export async function uploadWorkspaceFile( throw new OrchestrationError('not_found', 'Target folder not found') } folderId = resolvedFolderId - folderPath = resolvedFolderId ? folderPathSegments.join('/') : null + folderPath = resolvedFolderId ? buildWorkspaceFileFolderDisplayPath(folderPathSegments) : null } else { const folderTarget = await resolveWorkspaceFileFolderTarget(workspaceId, options?.folderId) folderId = folderTarget?.id ?? null diff --git a/apps/sim/lib/workflows/api/workflow-inspection.test.ts b/apps/sim/lib/workflows/api/workflow-inspection.test.ts new file mode 100644 index 00000000000..8d6da3ae895 --- /dev/null +++ b/apps/sim/lib/workflows/api/workflow-inspection.test.ts @@ -0,0 +1,203 @@ +import type { BlockState } from '@sim/workflow-types/workflow' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { v2WorkflowInspectionSchema } from '@/lib/api/contracts/v2/workflow-inspection' +import { presentWorkflowInspection } from '@/lib/workflows/api/workflow-inspection' +import type { ReadWorkflowGraphResult } from '@/lib/workflows/application/read-workflow-graph' +import * as credentialExtractor from '@/lib/workflows/credentials/credential-extractor' +import { getBlock } from '@/blocks/registry' + +function graph(): ReadWorkflowGraphResult { + const block: BlockState = { + id: 'block-1', + name: 'Format report', + type: 'test-block', + enabled: false, + position: { x: 0, y: 0 }, + outputs: {}, + subBlocks: { + code: { id: 'code', type: 'code', value: 'return 42' }, + apiKey: { id: 'apiKey', type: 'short-input', value: 'secret-value' }, + headers: { id: 'headers', type: 'table', value: [['Authorization', 'private-value']] }, + text: { id: 'text', type: 'long-input', value: 'A report' }, + operation: { id: 'operation', type: 'dropdown', value: 'send' }, + unknown: { id: 'unknown', type: 'short-input', value: 'unrecognized-private-value' }, + empty: { id: 'empty', type: 'short-input', value: null }, + }, + } + return { + workflowId: 'workflow-1', + workspaceId: 'workspace-1', + blocks: { 'block-1': block }, + edges: [{ id: 'edge-1', source: 'block-1', target: 'block-2', sourceHandle: 'source' }], + loops: {}, + parallels: {}, + variables: {}, + } +} + +describe('workflow diagnostic projection', () => { + beforeEach(() => { + vi.mocked(getBlock).mockReturnValue({ + subBlocks: [ + { id: 'code', type: 'code' }, + { id: 'apiKey', type: 'short-input', password: true }, + { id: 'headers', type: 'table' }, + { id: 'text', type: 'long-input' }, + { id: 'operation', type: 'dropdown' }, + { id: 'empty', type: 'short-input' }, + ], + } as never) + }) + + it('returns canonical topology and nonempty inputs without credentials, code, UI state, or mutation', () => { + const source = graph() + const original = structuredClone(source) + const result = presentWorkflowInspection(source, { includeCode: false }) + expect(v2WorkflowInspectionSchema.parse(result)).toEqual(result) + expect(result.blocks).toEqual([ + { + id: 'block-1', + name: 'Format report', + type: 'test-block', + enabled: false, + parentId: null, + inputs: { text: 'A report', operation: 'send' }, + omittedInputs: ['code', 'apiKey', 'headers', 'unknown'], + }, + ]) + expect(result.edges).toEqual([ + { source: 'block-1', target: 'block-2', sourceHandle: 'source', targetHandle: null }, + ]) + expect(JSON.stringify(result)).not.toContain('secret-value') + expect(JSON.stringify(result)).not.toContain('private-value') + expect(source).toEqual(original) + }) + + it('includes code only when requested, redacting recognizable embedded secrets', () => { + const source = graph() + source.blocks['block-1'].subBlocks.code.value = + 'const apiKey = "sk_abcdefghijklmnopqrstuvwxyz"; return apiKey' + const result = presentWorkflowInspection(source, { includeCode: true }) + expect(result.blocks[0].inputs.code).toContain('[REDACTED]') + expect(JSON.stringify(result)).not.toContain('sk_abcdefghijklmnopqrstuvwxyz') + expect(result.blocks[0].omittedInputs).not.toContain('code') + }) + + it('bounds oversized and deeply nested inputs and marks truncation', () => { + const source = graph() + source.blocks['block-1'].subBlocks.text.value = 'x'.repeat(100_000) + source.blocks['block-1'].subBlocks.operation.value = { + a: { b: { c: { d: { e: { f: { g: 'deep' } } } } } }, + } + const result = presentWorkflowInspection(source, { includeCode: true }) + expect(result.truncated).toBe(true) + expect(String(result.blocks[0].inputs.text).length).toBeLessThanOrEqual(4096) + expect(JSON.stringify(result)).not.toContain('deep') + expect(JSON.stringify(result)).toContain('[TRUNCATED]') + }) + + it('focuses on one block and rejects unknown block IDs', () => { + const source = graph() + source.blocks['block-2'] = { ...source.blocks['block-1'], id: 'block-2', enabled: true } + source.edges.push({ id: 'edge-2', source: 'block-3', target: 'block-4' }) + const result = presentWorkflowInspection(source, { blockId: 'block-2', includeCode: false }) + expect(result.blocks.map(({ id }) => id)).toEqual(['block-2']) + expect(result.edges).toHaveLength(1) + expect(() => + presentWorkflowInspection(source, { blockId: 'missing', includeCode: false }) + ).toThrow('Block not found') + }) + + it('uses registered code types even when stored type metadata is stale', () => { + vi.mocked(getBlock).mockReturnValue({ + subBlocks: [ + { id: 'body', type: 'code' }, + { id: 'tools', type: 'tool-input' }, + ], + } as never) + const source = graph() + source.blocks['block-1'].subBlocks = { + body: { id: 'body', type: 'short-input', value: 'return "private source"' }, + tools: { id: 'tools', type: 'short-input', value: [] }, + } + const result = presentWorkflowInspection(source, { includeCode: false }) + expect(result.blocks[0].inputs).toEqual({}) + expect(result.blocks[0].omittedInputs).toEqual(['body', 'tools']) + }) + + it('counts keys and stops projecting after the shared budget is exhausted', () => { + const source = graph() + source.blocks['block-1'].subBlocks.text.value = { ['k'.repeat(100_000)]: 'value' } + source.blocks['block-1'].subBlocks.operation.value = Array.from({ length: 50 }, () => + 'x'.repeat(4096) + ) + const result = presentWorkflowInspection(source, { includeCode: true }) + expect(result.truncated).toBe(true) + expect(JSON.stringify(result.blocks[0].inputs).length).toBeLessThan(66_000) + expect(result.blocks[0].inputs.text).toEqual({}) + expect(result.blocks[0].inputs.operation).toHaveLength(16) + }) + + it('bounds omitted input names as well as projected values', () => { + const source = graph() + const oversizedKey = 'unknown_'.repeat(100_000) + source.blocks['block-1'].subBlocks = { + [oversizedKey]: { id: oversizedKey, type: 'short-input', value: 'private-input-value' }, + ...Object.fromEntries( + Array.from({ length: 3000 }, (_, index) => { + const key = `unknown_${index}` + return [key, { id: key, type: 'short-input', value: 'private-input-value' }] + }) + ), + } + + const result = presentWorkflowInspection(source, { includeCode: false }) + + expect(result.truncated).toBe(true) + expect(result.blocks[0].inputs).toEqual({}) + expect(result.blocks[0].omittedInputs).toHaveLength(2000) + expect(result.blocks[0].omittedInputs).not.toContain(oversizedKey) + expect(JSON.stringify(result)).not.toContain('private-input-value') + expect(JSON.stringify(result).length).toBeLessThan(66_000) + }) + + it('skips malformed persisted sub-block entries without losing valid inputs or mutating state', () => { + const source = graph() + source.blocks['block-1'].subBlocks = { + text: { id: 'text', type: 'long-input', value: 'A report' }, + nullEntry: null, + numberEntry: 42, + stringEntry: 'stale', + arrayEntry: [], + } as never + const before = structuredClone(source) + + const result = presentWorkflowInspection(source, { includeCode: false }) + + expect(result.blocks[0].inputs).toEqual({ text: 'A report' }) + expect(result.blocks[0].omittedInputs).toEqual([]) + expect(source).toEqual(before) + }) + + it('reads only the first 50 own values of a wide sanitized input', () => { + const source = graph() + const readValue = vi.fn(() => 'diagnostic value') + const wide: Record = Object.create({ inherited: 'not an input' }) + for (let index = 0; index < 5000; index++) { + Object.defineProperty(wide, `entry_${index}`, { enumerable: true, get: readValue }) + } + source.blocks['block-1'].subBlocks = { + text: { id: 'text', type: 'long-input', value: wide }, + } + vi.spyOn(credentialExtractor, 'sanitizeWorkflowForSharing').mockReturnValueOnce({ + blocks: source.blocks, + }) + + const result = presentWorkflowInspection(source, { includeCode: false }) + + expect(readValue).toHaveBeenCalledTimes(50) + expect(Object.keys(result.blocks[0].inputs.text as Record)).toHaveLength(50) + expect(result.blocks[0].inputs.text).not.toHaveProperty('inherited') + expect(result.truncated).toBe(true) + }) +}) diff --git a/apps/sim/lib/workflows/api/workflow-inspection.ts b/apps/sim/lib/workflows/api/workflow-inspection.ts new file mode 100644 index 00000000000..03c5fe62a0e --- /dev/null +++ b/apps/sim/lib/workflows/api/workflow-inspection.ts @@ -0,0 +1,179 @@ +import { isRecordLike } from '@sim/utils/object' +import { truncate } from '@sim/utils/string' +import type { + V2InspectWorkflowQuery, + V2WorkflowInspection, +} from '@/lib/api/contracts/v2/workflow-inspection' +import { OrchestrationError } from '@/lib/core/orchestration/types' +import { + isSensitiveKey, + REDACTED_MARKER, + redactSensitiveValues, + TRUNCATED_MARKER, +} from '@/lib/core/security/redaction' +import type { ReadWorkflowGraphResult } from '@/lib/workflows/application/read-workflow-graph' +import { sanitizeWorkflowForSharing } from '@/lib/workflows/credentials/credential-extractor' +import { getBlock } from '@/blocks/registry' + +/** A diagnostic projection; never an editable or portable workflow representation. */ +export function presentWorkflowInspection( + graph: ReadWorkflowGraphResult, + query: V2InspectWorkflowQuery +): V2WorkflowInspection { + if (query.blockId && !Object.hasOwn(graph.blocks, query.blockId)) { + throw new OrchestrationError('not_found', 'Block not found in workflow') + } + const selected = query.blockId ? { [query.blockId]: graph.blocks[query.blockId] } : graph.blocks + const sanitized = sanitizeWorkflowForSharing( + { blocks: selected }, + { + preserveEnvVars: true, + preserveWorkspaceBindings: true, + preserveReferenceMetadata: true, + redactOpaqueCredentialInputs: true, + } + ) + let remainingCharacters = 64 * 1024 + let remainingValues = 2000 + let truncated = false + + function projectString(value: string): string | undefined { + const limit = Math.min(4096, remainingCharacters) + if (limit < TRUNCATED_MARKER.length) { + truncated = true + return undefined + } + const result = + value.length <= limit + ? value + : truncate(value, limit - TRUNCATED_MARKER.length, TRUNCATED_MARKER) + remainingCharacters -= result.length + if (result !== value) truncated = true + return result + } + + function reserveKey(key: string): boolean { + if (key.length > 256 || key.length > remainingCharacters) { + truncated = true + return false + } + remainingCharacters -= key.length + return true + } + + function project(value: unknown, depth = 0): unknown { + if (remainingValues <= 0 || remainingCharacters <= 0) { + truncated = true + return undefined + } + remainingValues-- + if (depth > 6) { + truncated = true + return projectString(TRUNCATED_MARKER) + } + if (typeof value === 'string') { + return projectString(redactSensitiveValues(value)) + } + if (Array.isArray(value)) { + if (value.length > 50) truncated = true + const result: unknown[] = [] + for (const item of value.slice(0, 50)) { + const projected = project(item, depth + 1) + if (projected === undefined) break + result.push(projected) + } + return result + } + if (isRecordLike(value)) { + const result: [string, unknown][] = [] + let entryCount = 0 + for (const key in value) { + if (!Object.hasOwn(value, key)) continue + if (entryCount === 50) { + truncated = true + break + } + entryCount++ + if (!reserveKey(key)) continue + const projected = project(isSensitiveKey(key) ? REDACTED_MARKER : value[key], depth + 1) + if (projected === undefined) break + result.push([key, projected]) + } + return Object.fromEntries(result) + } + return value + } + + const blocks = Object.entries(selected).map(([id, block]) => { + const inputs: Record = {} + const omittedInputs: string[] = [] + const definitions = new Map( + (getBlock(block.type)?.subBlocks ?? []).map((field) => [field.id, field]) + ) + for (const [key, field] of Object.entries(block.subBlocks)) { + if ( + !isRecordLike(field) || + field.value === null || + field.value === undefined || + field.value === '' + ) + continue + if (remainingValues <= 0 || remainingCharacters <= 0) { + truncated = true + break + } + if (!reserveKey(key)) continue + const definition = definitions.get(key) + const value = sanitized.blocks?.[id]?.subBlocks?.[key]?.value + if ( + !definition || + definition.hideFromCopilot || + value == null || + (!query.includeCode && + (definition.type === 'code' || + definition.type === 'tool-input' || + field.type === 'code' || + key === 'code' || + field.type === 'tool-input')) + ) { + remainingValues-- + omittedInputs.push(key) + continue + } + const projected = project(isSensitiveKey(key) ? REDACTED_MARKER : value) + if (projected === undefined) omittedInputs.push(key) + else inputs[key] = projected + } + return { + id, + name: block.name, + type: block.type, + enabled: block.enabled !== false, + parentId: block.data?.parentId ?? null, + inputs, + omittedInputs, + } + }) + return { + representation: 'diagnostic', + workflowId: graph.workflowId, + workspaceId: graph.workspaceId, + blocks, + edges: graph.edges + .filter( + (edge) => !query.blockId || edge.source === query.blockId || edge.target === query.blockId + ) + .map((edge) => ({ + source: edge.source, + target: edge.target, + sourceHandle: edge.sourceHandle ?? null, + targetHandle: edge.targetHandle ?? null, + })), + truncated, + notes: [ + 'Diagnostic draft view only. Use Get Workflow State for an editable round trip; never write this representation back.', + 'Credential fields and opaque credential-bearing inputs are withheld. Automatic redaction cannot identify every secret in arbitrary text or code.', + 'Inputs are bounded to 4096 characters per string, 256 characters per key, 50 entries per container, six nested levels, and shared budgets of 65536 string/key characters and 2000 values. Use blockId to focus the budget.', + ], + } +} 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 5cbc88fe5dd..e28e377d468 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-operations.test.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-operations.test.ts @@ -23,6 +23,7 @@ const mocks = vi.hoisted(() => ({ assertIdsUnclaimed: vi.fn(), collectGraphIds: vi.fn(), lintGraph: vi.fn(), + layoutImpact: vi.fn(), })) vi.mock('@sim/audit', () => ({ @@ -75,6 +76,10 @@ vi.mock('@/lib/workflows/editing/validation', () => ({ vi.mock('@/lib/workflows/editing/lint', () => ({ collectWorkflowFieldIssues: () => [], collectDanglingBlockOutputReferences: () => [], + collectBranchDependentBlockOutputReferences: () => ({ + issues: [], + check: { name: 'branch-output-references', status: 'partial', detail: 'Static branches only' }, + }), lintEditedWorkflowState: mocks.lintGraph, })) vi.mock('@/lib/billing/core/subscription', () => ({ @@ -106,11 +111,7 @@ vi.mock('@/stores/workflows/workflow/validation', () => ({ })) vi.mock('@/lib/workflows/autolayout', () => ({ applyTargetedLayout: vi.fn(), - getTargetedLayoutImpact: () => ({ - layoutBlockIds: [], - resizedBlockIds: [], - shiftSourceBlockIds: [], - }), + getTargetedLayoutImpact: mocks.layoutImpact, transferBlockHeights: vi.fn(), })) @@ -203,6 +204,11 @@ describe('applyWorkflowOperations', () => { mocks.collectGraphIds.mockReturnValue(GRAPH_IDS) mocks.assertIdsUnclaimed.mockResolvedValue(undefined) mocks.lintGraph.mockReturnValue(EMPTY_GRAPH_LINT) + mocks.layoutImpact.mockReturnValue({ + layoutBlockIds: [], + resizedBlockIds: [], + shiftSourceBlockIds: [], + }) }) /** @@ -230,7 +236,7 @@ describe('applyWorkflowOperations', () => { expect(result.applied).toBe(1) expect(mocks.lintGraph).toHaveBeenCalledTimes(1) expect(mocks.lintGraph.mock.calls[0][0].blocks).not.toHaveProperty('block-2') - expect(result.lint).toEqual({ + expect(result.lint).toMatchObject({ ...EMPTY_GRAPH_LINT, orphanBlocks: [orphan], fieldIssues: [], @@ -262,13 +268,19 @@ describe('applyWorkflowOperations', () => { expect(dry.mintedBlockIds).toEqual({}) expect(dry.previewBlockIds).toEqual({ triage: 'preview-uuid' }) expect(dry.warnings).toContain(DRY_RUN_PREVIEW_BLOCK_IDS_WARNING) + mocks.applyOperations.mockReturnValueOnce({ + state: graph(), + validationErrors: [], + skippedItems: [], + mintedBlockIds: { triage: 'committed-uuid' }, + }) const committed = await applyWorkflowOperations.execute({ principal: sessionPrincipal, input: { workflowId: 'workflow-1', operations }, }) - expect(committed.mintedBlockIds).toEqual({ triage: 'preview-uuid' }) + expect(committed.mintedBlockIds).toEqual({ triage: 'committed-uuid' }) expect(committed.previewBlockIds).toBeUndefined() expect(committed.warnings).not.toContain(DRY_RUN_PREVIEW_BLOCK_IDS_WARNING) }) @@ -434,7 +446,7 @@ describe('applyWorkflowOperations', () => { expect(mocks.replace).not.toHaveBeenCalled() }) - it('honours a caller-supplied base graph only for a delegated principal', async () => { + it('honours a caller-supplied base graph for the delegated Copilot principal', async () => { const baseGraph = graph({ 'block-9': { ...BLOCK, id: 'block-9' } }) await applyWorkflowOperations.execute({ @@ -443,34 +455,135 @@ describe('applyWorkflowOperations', () => { }) expect(mocks.loadNormalized).not.toHaveBeenCalled() expect(mocks.applyOperations).toHaveBeenCalledWith(baseGraph, operations, null, true) + }) - vi.clearAllMocks() - mocks.customBlocks.mockResolvedValue([]) - mocks.resolveContext.mockResolvedValue(context) - mocks.resolvePermission.mockResolvedValue('write') - mocks.sandboxAccess.mockResolvedValue(true) - mocks.blockVisibility.mockResolvedValue({ revealed: [], disabled: [], previewTagged: [] }) - mocks.permissionConfig.mockResolvedValue(null) - mocks.loadNormalized.mockResolvedValue(graph()) - mocks.normalizeState.mockReturnValue({ state: graph(), warnings: [] }) - mocks.preValidate.mockResolvedValue({ filteredOperations: operations, errors: [] }) + it('loads the stored graph despite a caller-supplied base graph for a session principal', async () => { + const baseGraph = graph({ 'block-9': { ...BLOCK, id: 'block-9' } }) + + await applyWorkflowOperations.execute({ + principal: sessionPrincipal, + input: { workflowId: 'workflow-1', operations, baseGraph }, + }) + expect(mocks.loadNormalized).toHaveBeenCalledWith('workflow-1', undefined, { + persistMigrations: false, + }) + expect(mocks.applyOperations).toHaveBeenCalledWith(graph(), operations, null, false) + }) + + it('preserves positions, inputs, and edges for default-layout enablement-only edits', async () => { + const { getTargetedLayoutImpact } = await import('@/lib/workflows/autolayout/change-set') + mocks.layoutImpact.mockImplementationOnce(getTargetedLayoutImpact) + const before = { + ...graph({ + 'block-1': { + ...BLOCK, + position: { x: 120, y: 250 }, + subBlocks: { input: { id: 'input', type: 'short-input', value: 'unchanged' } }, + }, + 'block-2': { ...BLOCK, id: 'block-2', position: { x: 520, y: 310 } }, + }), + edges: [ + { + id: 'edge-1', + source: 'block-1', + target: 'block-2', + sourceHandle: 'source', + targetHandle: 'target', + }, + ], + } + mocks.loadNormalized.mockResolvedValue(before) + mocks.normalizeState.mockReturnValue({ state: structuredClone(before), warnings: [] }) + mocks.preValidate.mockResolvedValue({ filteredOperations: [], errors: [] }) mocks.applyOperations.mockReturnValue({ - state: graph(), + state: structuredClone(before), validationErrors: [], skippedItems: [], + mintedBlockIds: {}, }) - mocks.collectReferences.mockResolvedValue([]) - mocks.collectToolReferences.mockResolvedValue([]) - mocks.validate.mockReturnValue({ valid: true, errors: [], warnings: [] }) - mocks.replace.mockResolvedValue({ warnings: [], state: graph() }) - mocks.needsRedeployment.mockResolvedValue(true) + const result = await applyWorkflowOperations.execute({ + principal: sessionPrincipal, + input: { + workflowId: 'workflow-1', + operations: [], + blockEnabledChanges: [{ blockId: 'block-1', enabled: false }], + }, + }) + expect(mocks.layoutImpact).toHaveReturnedWith({ + layoutBlockIds: [], + resizedBlockIds: [], + shiftSourceBlockIds: [], + }) + expect(result.graph).toEqual({ + ...before, + blocks: { ...before.blocks, 'block-1': { ...before.blocks['block-1'], enabled: false } }, + }) + expect(before.blocks['block-1'].enabled).toBe(true) + expect(result.applied).toBe(1) + }) - await applyWorkflowOperations.execute({ + it.each([false, true])('supports enablement-only batches with dryRun=%s', async (dryRun) => { + mocks.preValidate.mockResolvedValue({ filteredOperations: [], errors: [] }) + const result = await applyWorkflowOperations.execute({ principal: sessionPrincipal, - input: { workflowId: 'workflow-1', operations, baseGraph }, + input: { + workflowId: 'workflow-1', + operations: [], + layout: 'none', + dryRun, + blockEnabledChanges: [{ blockId: 'block-1', enabled: false }], + }, + }) + expect(result.applied).toBe(1) + expect(result.operationCount).toBe(0) + expect(result.graph.blocks['block-1'].enabled).toBe(false) + expect(result.skipped).toEqual([]) + expect(mocks.applyOperations).toHaveBeenCalledWith(expect.anything(), [], null, false) + expect(mocks.loadNormalized).toHaveBeenCalledWith('workflow-1', undefined, { + persistMigrations: false, }) - expect(mocks.loadNormalized).toHaveBeenCalledWith('workflow-1') - expect(mocks.applyOperations).not.toHaveBeenCalledWith(baseGraph, operations, null, true) + expect(mocks.replace).toHaveBeenCalledTimes(dryRun ? 0 : 1) + expect(mocks.recordAudit).toHaveBeenCalledTimes(dryRun ? 0 : 1) + expect(mocks.notify).toHaveBeenCalledTimes(dryRun ? 0 : 1) + }) + + it.each([false, true])( + 'preserves atomic refusal for enablement-only locked blocks with dryRun=%s', + async (dryRun) => { + mocks.preValidate.mockResolvedValue({ filteredOperations: [], errors: [] }) + mocks.applyOperations.mockReturnValue({ + state: graph({ 'block-1': { ...BLOCK, locked: true } }), + validationErrors: [], + skippedItems: [], + mintedBlockIds: {}, + }) + await expect( + applyWorkflowOperations.execute({ + principal: sessionPrincipal, + input: { + workflowId: 'workflow-1', + operations: [], + atomic: true, + dryRun, + blockEnabledChanges: [{ blockId: 'block-1', enabled: false }], + }, + }) + ).rejects.toBeInstanceOf(WorkflowOperationsNotAppliedError) + expect(mocks.replace).not.toHaveBeenCalled() + expect(mocks.recordAudit).not.toHaveBeenCalled() + expect(mocks.notify).not.toHaveBeenCalled() + } + ) + + it('rejects a batch with neither graph edits nor enablement changes', async () => { + await expect( + applyWorkflowOperations.execute({ + principal: sessionPrincipal, + input: { workflowId: 'workflow-1', operations: [], blockEnabledChanges: [] }, + }) + ).rejects.toMatchObject({ code: 'validation' }) + expect(mocks.loadNormalized).not.toHaveBeenCalled() + expect(mocks.replace).not.toHaveBeenCalled() }) it('applies the block enablement slice and declines a locked block as a skipped item', async () => { diff --git a/apps/sim/lib/workflows/application/apply-workflow-operations.ts b/apps/sim/lib/workflows/application/apply-workflow-operations.ts index ef73c302c92..102df4838fa 100644 --- a/apps/sim/lib/workflows/application/apply-workflow-operations.ts +++ b/apps/sim/lib/workflows/application/apply-workflow-operations.ts @@ -146,7 +146,9 @@ function asGraph(value: Record): Pick> { - const normalized = await loadWorkflowFromNormalizedTables(workflowId) + const normalized = await loadWorkflowFromNormalizedTables(workflowId, undefined, { + persistMigrations: false, + }) if (!normalized) { throw new OrchestrationError('validation', `Workflow ${workflowId} has no normalized state`) } @@ -265,8 +267,11 @@ export const applyWorkflowOperations = defineAuthorizedWorkflowUseCase({ assertedWorkspaceId: assertedWorkflowWorkspaceId(principal, input.assertedWorkspaceId), }), async execute({ principal, input, context }): Promise { - if (input.operations.length === 0) { - throw new OrchestrationError('validation', 'operations cannot be empty') + if (input.operations.length === 0 && !input.blockEnabledChanges?.length) { + throw new OrchestrationError( + 'validation', + 'Provide at least one operation or blockEnabledChanges entry' + ) } await requireMutableWorkflow(context.workflowId) diff --git a/apps/sim/lib/workflows/application/execute-manual-workflow.ts b/apps/sim/lib/workflows/application/execute-manual-workflow.ts index 2ba1c8e5afb..5b10b53c81d 100644 --- a/apps/sim/lib/workflows/application/execute-manual-workflow.ts +++ b/apps/sim/lib/workflows/application/execute-manual-workflow.ts @@ -4,13 +4,15 @@ import { OrchestrationError } from '@/lib/core/orchestration/types' import { defineAuthorizedWorkflowUseCase } from '@/lib/workflows/application/authorized-workflow-use-case' import { resolveActiveWorkflowApplicationContext } from '@/lib/workflows/application/context' import type { ExecuteWorkflowInput } from '@/lib/workflows/application/execute-workflow' +import { + loadManualWorkflowFromBlockState, + loadManualWorkflowState, +} from '@/lib/workflows/application/manual-workflow-state' import { workflowOperations } from '@/lib/workflows/application/operations' import { type ExecuteWorkflowServiceResult, executeWorkflowService, } from '@/lib/workflows/executor/execute-service' -import { getExecutionStateForWorkflow } from '@/lib/workflows/executor/execution-state' -import { loadWorkflowFromNormalizedTables } from '@/lib/workflows/persistence/utils' import { resolveTriggerRunOptions, validateTriggerInput, @@ -36,17 +38,6 @@ function resolveContext({ input }: { input: I }) return resolveActiveWorkflowApplicationContext({ workflowId: input.workflowId }) } -async function loadManualState(workflowId: string) { - const state = await loadWorkflowFromNormalizedTables(workflowId) - if (!state) { - throw new OrchestrationError( - 'validation', - `Workflow ${workflowId} has no saved state to run manually.` - ) - } - return state -} - function listTriggers(options: ReturnType): string { return options.map((option) => `${option.triggerBlockId} (${option.blockName})`).join(', ') } @@ -68,6 +59,7 @@ function executionServiceInput(params: { includeFileBase64: params.input.includeFileBase64, base64MaxBytes: params.input.base64MaxBytes, selectedOutputs: params.input.selectedOutputs, + stopAfterBlockId: params.input.stopAfterBlockId, rateLimitCounter: 'sync' as const, abortSignal: params.input.abortSignal, mode: params.input.mode, @@ -89,7 +81,7 @@ export const executeManualWorkflowOperation = defineAuthorizedWorkflowUseCase({ 'input and run.entry.useMockPayload cannot be combined' ) } - const state = await loadManualState(context.workflowId) + const state = await loadManualWorkflowState(context.workflowId) const options = resolveTriggerRunOptions( mergeSubblockStateWithValues(state.blocks), state.edges @@ -137,21 +129,11 @@ export const executeManualWorkflowFromBlockOperation = defineAuthorizedWorkflowU operation: workflowOperations.executeManualFromBlock, resolveContext: resolveContext, async execute({ principal, context, input }): Promise { - const state = await loadManualState(context.workflowId) - if (!Object.hasOwn(state.blocks, input.blockId)) { - throw new OrchestrationError( - 'validation', - `run.entry.blockId "${input.blockId}" is not a block in the current saved workflow.` - ) - } - - const sourceSnapshot = await getExecutionStateForWorkflow(input.sourceRunId, context.workflowId) - if (!sourceSnapshot) { - throw new OrchestrationError( - 'not_found', - `No execution state found for source run "${input.sourceRunId}" in this workflow.` - ) - } + const { sourceSnapshot } = await loadManualWorkflowFromBlockState({ + workflowId: context.workflowId, + blockId: input.blockId, + sourceRunId: input.sourceRunId, + }) return executeWorkflowService({ ...executionServiceInput({ principal, context, input }), diff --git a/apps/sim/lib/workflows/application/execute-workflow.test.ts b/apps/sim/lib/workflows/application/execute-workflow.test.ts index 3dae55522b5..8e8fb8d0b2e 100644 --- a/apps/sim/lib/workflows/application/execute-workflow.test.ts +++ b/apps/sim/lib/workflows/application/execute-workflow.test.ts @@ -1,10 +1,12 @@ import type { Principal } from '@sim/auth/principal' +import { createBlock } from '@sim/testing' import { beforeEach, describe, expect, it, vi } from 'vitest' const mocks = vi.hoisted(() => ({ executeService: vi.fn(), resolvePermission: vi.fn(), resolveWorkflowContext: vi.fn(), + loadDeployedState: vi.fn(), })) vi.mock('@sim/platform-authz/workspace', () => ({ @@ -25,6 +27,11 @@ vi.mock('@/lib/workflows/executor/execute-service', () => ({ executeWorkflowService: mocks.executeService, })) +vi.mock('@/lib/workflows/persistence/utils', () => ({ + loadDeployedWorkflowState: mocks.loadDeployedState, + NoActiveDeploymentError: class NoActiveDeploymentError extends Error {}, +})) + import { PersonalApiKeysDisabledError } from '@/lib/core/application' import { executeWorkflowOperation } from '@/lib/workflows/application/execute-workflow' @@ -62,6 +69,24 @@ describe('executeWorkflowOperation', () => { }) }) + it('rejects a draft-only trigger before claiming, billing or executing a deployed run', async () => { + mocks.resolveWorkflowContext.mockResolvedValue({ + ...workflowContext, + workflow: { ...workflow, isDeployed: true }, + }) + mocks.loadDeployedState.mockResolvedValue({ + deploymentVersionId: 'version-1', + blocks: { schedule: createBlock({ id: 'schedule', type: 'schedule' }) }, + }) + await expect( + executeWorkflowOperation.execute({ + principal: { kind: 'session', userId: 'user-1', sessionId: 'session-1' }, + input: { ...baseInput, triggerBlockId: 'draft-only' }, + }) + ).rejects.toThrow('active deployment') + expect(mocks.executeService).not.toHaveBeenCalled() + }) + it.each([ { principal: { kind: 'session', userId: 'user-1', sessionId: 'session-1' } as Principal, diff --git a/apps/sim/lib/workflows/application/execute-workflow.ts b/apps/sim/lib/workflows/application/execute-workflow.ts index d7c8f74aed4..903ebb89bbb 100644 --- a/apps/sim/lib/workflows/application/execute-workflow.ts +++ b/apps/sim/lib/workflows/application/execute-workflow.ts @@ -1,5 +1,6 @@ import type { Principal } from '@sim/auth/principal' import { resolvePrincipalAttribution } from '@sim/auth/principal' +import { OrchestrationError } from '@/lib/core/orchestration/types' import { defineAuthorizedWorkflowUseCase } from '@/lib/workflows/application/authorized-workflow-use-case' import { resolveActiveWorkflowApplicationContext } from '@/lib/workflows/application/context' import { workflowOperations } from '@/lib/workflows/application/operations' @@ -7,6 +8,11 @@ import { type ExecuteWorkflowServiceResult, executeWorkflowService, } from '@/lib/workflows/executor/execute-service' +import { + loadDeployedWorkflowState, + NoActiveDeploymentError, +} from '@/lib/workflows/persistence/utils' +import { resolveDeploymentTriggerBlockId } from '@/lib/workflows/triggers/deployment-entry' export interface ExecuteWorkflowInput { workflowId: string @@ -16,6 +22,8 @@ export interface ExecuteWorkflowInput { includeFileBase64?: boolean base64MaxBytes?: number selectedOutputs?: string[] + triggerBlockId?: string + stopAfterBlockId?: string requestedTimeoutSeconds?: number abortSignal?: AbortSignal mode: 'sync' | 'async' | 'stream' | 'sync-result-stream' @@ -38,6 +46,23 @@ export const executeWorkflowOperation = defineAuthorizedWorkflowUseCase({ resolveContext: ({ input }: { input: ExecuteWorkflowInput }) => resolveActiveWorkflowApplicationContext({ workflowId: input.workflowId }), async execute({ principal, context, input }): Promise { + let deploymentVersionId: string | undefined + let triggerBlockId: string | undefined + if (context.workflow.isDeployed) { + try { + const deployed = await loadDeployedWorkflowState(context.workflowId, context.workspaceId) + deploymentVersionId = deployed.deploymentVersionId + triggerBlockId = resolveDeploymentTriggerBlockId(deployed.blocks, input.triggerBlockId) + } catch (error) { + if (error instanceof NoActiveDeploymentError) { + throw new OrchestrationError( + 'validation', + 'The workflow has no active deployment. Deploy it before running.' + ) + } + throw error + } + } const attribution = resolvePrincipalAttribution(principal, { workspaceBillingOwnerUserId: context.billedAccountUserId, }) @@ -55,6 +80,9 @@ export const executeWorkflowOperation = defineAuthorizedWorkflowUseCase({ includeFileBase64: input.includeFileBase64, base64MaxBytes: input.base64MaxBytes, selectedOutputs: input.selectedOutputs, + triggerBlockId, + deploymentVersionId, + stopAfterBlockId: input.stopAfterBlockId, rateLimitCounter: input.mode === 'async' ? 'async' : 'sync', requestedTimeoutSeconds: input.requestedTimeoutSeconds, abortSignal: input.abortSignal, diff --git a/apps/sim/lib/workflows/application/import-export.ts b/apps/sim/lib/workflows/application/import-export.ts index 5c3e719230f..424d137c802 100644 --- a/apps/sim/lib/workflows/application/import-export.ts +++ b/apps/sim/lib/workflows/application/import-export.ts @@ -64,6 +64,8 @@ export interface ExportWorkflowInput { export interface ExportWorkflowResult { payload: WorkflowExportPayload + representation: 'portable-export' + warnings: string[] folderPath: string } @@ -155,6 +157,13 @@ export const exportWorkflow = defineAuthorizedWorkflowUseCase({ ) return { payload, + representation: 'portable-export', + warnings: [ + 'This portable export clears credentials, secret values, and opaque table values. For in-place edits that preserve block IDs and binding references, use workflows state get, then workflows state replace --dry-run before saving. Treat editable state as private workspace configuration.', + input.includeWorkspaceBindings + ? 'Workspace resource bindings are retained, but credentials are still cleared. This export is not a complete editable-state snapshot.' + : 'Workspace resource bindings (including tables) are cleared. includeWorkspaceBindings=true retains resource references for same-workspace copies; includeReferences=true adds non-secret identifiers for mapped imports.', + ], folderPath: workflowFolderPathForId(folderIndex, context.workflow.folderId), } }, diff --git a/apps/sim/lib/workflows/application/manual-workflow-state.ts b/apps/sim/lib/workflows/application/manual-workflow-state.ts new file mode 100644 index 00000000000..3837cf3f8a9 --- /dev/null +++ b/apps/sim/lib/workflows/application/manual-workflow-state.ts @@ -0,0 +1,40 @@ +import { OrchestrationError } from '@/lib/core/orchestration/types' +import { getExecutionStateForWorkflow } from '@/lib/workflows/executor/execution-state' +import { loadWorkflowFromNormalizedTables } from '@/lib/workflows/persistence/utils' + +/** Loads the saved draft after the caller has authorized the manual operation. */ +export async function loadManualWorkflowState( + workflowId: string, + options: { persistMigrations?: boolean } = {} +) { + const state = await loadWorkflowFromNormalizedTables(workflowId, undefined, options) + if (!state) { + throw new OrchestrationError( + 'validation', + `Workflow ${workflowId} has no saved state to run manually.` + ) + } + return state +} + +/** Binds a manual entry point and its cached state to the authorized workflow. */ +export async function loadManualWorkflowFromBlockState( + input: { workflowId: string; blockId: string; sourceRunId: string }, + options: { persistMigrations?: boolean } = {} +) { + const state = await loadManualWorkflowState(input.workflowId, options) + if (!Object.hasOwn(state.blocks, input.blockId)) { + throw new OrchestrationError( + 'validation', + `run.entry.blockId "${input.blockId}" is not a block in the current saved workflow.` + ) + } + const sourceSnapshot = await getExecutionStateForWorkflow(input.sourceRunId, input.workflowId) + if (!sourceSnapshot) { + throw new OrchestrationError( + 'not_found', + `No execution state found for source run "${input.sourceRunId}" in this workflow.` + ) + } + return { state, sourceSnapshot } +} diff --git a/apps/sim/lib/workflows/application/operations.ts b/apps/sim/lib/workflows/application/operations.ts index 7ddf0466452..30dc3d1a942 100644 --- a/apps/sim/lib/workflows/application/operations.ts +++ b/apps/sim/lib/workflows/application/operations.ts @@ -498,6 +498,16 @@ export const workflowOperations = { principalKinds: ['personal_api_key', 'oauth_access_token', 'delegated'], delegatedServices: ['copilot'], }), + /** permission-group-exempt: preview reads the draft and cached state under the same authoring role as manual execution. */ + previewManualFromBlock: defineWorkspaceOperation({ + id: 'workflows.manual.preview_from_block', + oauthScope: 'api:read', + minimumRole: 'write', + workspaceApiKey: 'deny', + capability: 'none', + principalKinds: ['personal_api_key', 'oauth_access_token', 'delegated'], + delegatedServices: ['copilot'], + }), // permission-group-exempt: execution history is governed by workspace role; logs.cost and logs.trace_spans withhold fields inside a run, not the right to read one listRuns: defineWorkspaceOperation({ id: 'workflows.runs.list', diff --git a/apps/sim/lib/workflows/application/preview-manual-workflow-from-block.test.ts b/apps/sim/lib/workflows/application/preview-manual-workflow-from-block.test.ts new file mode 100644 index 00000000000..4cada2875a4 --- /dev/null +++ b/apps/sim/lib/workflows/application/preview-manual-workflow-from-block.test.ts @@ -0,0 +1,201 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const mocks = vi.hoisted(() => ({ + context: vi.fn(), + permission: vi.fn(), + loadDraft: vi.fn(), + loadSource: vi.fn(), + serialize: vi.fn(), + blockScope: vi.fn(), +})) + +vi.mock('@sim/platform-authz/workspace', () => ({ + permissionSatisfies: (actual: string | null, required: string) => + actual === 'admin' || actual === required || (actual === 'write' && required === 'read'), + resolveEffectiveWorkspacePermission: mocks.permission, +})) +vi.mock('@/lib/workflows/application/context', () => ({ + resolveActiveWorkflowApplicationContext: mocks.context, +})) +vi.mock('@/lib/workflows/persistence/utils', () => ({ + loadWorkflowFromNormalizedTables: mocks.loadDraft, +})) +vi.mock('@/lib/workflows/executor/execution-state', () => ({ + getExecutionStateForWorkflow: mocks.loadSource, +})) +vi.mock('@/lib/workflows/application/workflow-block-scope', () => ({ + withWorkflowBlockScope: mocks.blockScope, +})) +vi.mock('@/serializer', () => ({ + Serializer: class { + serializeWorkflow = mocks.serialize + }, +})) + +import type { OAuthAccessTokenPrincipal } from '@sim/auth/principal' +import { v2WorkflowRunFromBlockPreviewSchema } from '@/lib/api/contracts/v2/workflows' +import { previewManualWorkflowFromBlock } from '@/lib/workflows/application/preview-manual-workflow-from-block' + +const personal = { kind: 'personal_api_key' as const, userId: 'user-1', keyId: 'key-1' } +const oauth: OAuthAccessTokenPrincipal = { + kind: 'oauth_access_token', + userId: 'user-1', + clientId: 'client-1', + tokenId: 'token-1', + scopes: ['api:read'], + expiresAt: new Date('2099-01-01'), +} +const input = { workflowId: 'workflow-1', blockId: 'target', sourceRunId: 'source-run' } +const context = { + workflowId: 'workflow-1', + workspaceId: 'workspace-1', + workspaceOrganizationId: null, + allowPersonalApiKeys: true, +} + +describe('authorized read-only manual workflow preview', () => { + beforeEach(() => { + mocks.context.mockResolvedValue(context) + mocks.permission.mockResolvedValue('write') + mocks.blockScope.mockImplementation(async (_context, run) => run()) + mocks.loadDraft.mockResolvedValue({ + blocks: { target: { id: 'target', subBlocks: {} } }, + edges: [], + loops: {}, + parallels: {}, + }) + mocks.loadSource.mockResolvedValue({ + blockStates: { + target: { output: { secret: 'never return this' }, executed: true, executionTime: 1 }, + }, + executedBlocks: ['target'], + blockLogs: [], + decisions: { router: {}, condition: {} }, + completedLoops: [], + activeExecutionPath: [], + }) + mocks.serialize.mockReturnValue({ + version: '1', + loops: {}, + connections: [], + blocks: [ + { + id: 'target', + position: { x: 0, y: 0 }, + config: { tool: '', params: {} }, + inputs: {}, + outputs: {}, + metadata: { id: 'function', name: 'Target' }, + enabled: true, + }, + ], + }) + }) + + it.each([personal, oauth])( + 'reads under $kind without writes or disclosing cached output values', + async (principal) => { + const result = await previewManualWorkflowFromBlock.execute({ principal, input }) + expect(mocks.loadDraft).toHaveBeenCalledWith('workflow-1', undefined, { + persistMigrations: false, + }) + expect(mocks.loadSource).toHaveBeenCalledWith('source-run', 'workflow-1') + expect(mocks.blockScope).toHaveBeenCalledWith(context, expect.any(Function)) + expect(result.validation).toEqual({ valid: true }) + expect(v2WorkflowRunFromBlockPreviewSchema.parse(result)).toEqual(result) + expect(JSON.stringify(result)).not.toContain('never return this') + expect(result).not.toHaveProperty('runId') + expect(result.notes.join(' ')).toContain('can repeat actions') + } + ) + + it('requires current write permission before loading draft or execution state', async () => { + mocks.permission.mockResolvedValue('read') + await expect( + previewManualWorkflowFromBlock.execute({ principal: personal, input }) + ).rejects.toMatchObject({ code: 'forbidden' }) + expect(mocks.loadDraft).not.toHaveBeenCalled() + expect(mocks.loadSource).not.toHaveBeenCalled() + expect(mocks.blockScope).not.toHaveBeenCalled() + }) + + it('rejects workspace keys before canonical loading', async () => { + await expect( + previewManualWorkflowFromBlock.execute({ + principal: { + kind: 'workspace_api_key', + workspaceId: 'workspace-1', + keyId: 'workspace-key', + }, + input, + }) + ).rejects.toMatchObject({ code: 'forbidden' }) + expect(mocks.context).not.toHaveBeenCalled() + }) + + it('rejects insufficient OAuth scopes before canonical loading', async () => { + await expect( + previewManualWorkflowFromBlock.execute({ principal: { ...oauth, scopes: [] }, input }) + ).rejects.toThrow() + expect(mocks.context).not.toHaveBeenCalled() + }) + + it('supports valid Copilot delegation but refuses a different workspace before state loading', async () => { + const principal = { + kind: 'delegated' as const, + serviceId: 'copilot' as const, + subjectUserId: 'actor', + workspaceId: 'workspace-1', + audience: 'sim:workflows', + delegationId: 'call-1', + issuedAt: new Date(), + expiresAt: new Date(Date.now() + 60_000), + } + await expect( + previewManualWorkflowFromBlock.execute({ principal, input }) + ).resolves.toMatchObject({ validation: { valid: true } }) + mocks.loadDraft.mockClear() + await expect( + previewManualWorkflowFromBlock.execute({ + principal: { ...principal, workspaceId: 'elsewhere' }, + input, + }) + ).rejects.toMatchObject({ code: 'forbidden' }) + expect(mocks.loadDraft).not.toHaveBeenCalled() + }) + + it('does not load source state for a nonexistent draft block', async () => { + await expect( + previewManualWorkflowFromBlock.execute({ + principal: personal, + input: { ...input, blockId: 'missing' }, + }) + ).rejects.toMatchObject({ code: 'validation' }) + expect(mocks.loadSource).not.toHaveBeenCalled() + }) + + it('returns not found for unavailable source state scoped to the canonical workflow', async () => { + mocks.loadSource.mockResolvedValue(null) + await expect( + previewManualWorkflowFromBlock.execute({ principal: personal, input }) + ).rejects.toMatchObject({ code: 'not_found' }) + expect(mocks.serialize).not.toHaveBeenCalled() + }) + + it('classifies invalid saved graph errors without masking storage failures', async () => { + mocks.serialize.mockImplementationOnce(() => { + throw new Error('Target is missing required fields: code') + }) + await expect( + previewManualWorkflowFromBlock.execute({ principal: personal, input }) + ).rejects.toMatchObject({ + code: 'validation', + message: 'Target is missing required fields: code', + }) + const storageError = new Error('storage unavailable') + mocks.loadSource.mockRejectedValue(storageError) + await expect( + previewManualWorkflowFromBlock.execute({ principal: personal, input }) + ).rejects.toBe(storageError) + }) +}) diff --git a/apps/sim/lib/workflows/application/preview-manual-workflow-from-block.ts b/apps/sim/lib/workflows/application/preview-manual-workflow-from-block.ts new file mode 100644 index 00000000000..b139f57f83f --- /dev/null +++ b/apps/sim/lib/workflows/application/preview-manual-workflow-from-block.ts @@ -0,0 +1,55 @@ +import { getErrorMessage } from '@sim/utils/errors' +import { mergeSubblockStateWithValues } from '@sim/workflow-persistence/subblocks' +import { OrchestrationError } from '@/lib/core/orchestration/types' +import { defineAuthorizedWorkflowUseCase } from '@/lib/workflows/application/authorized-workflow-use-case' +import { resolveActiveWorkflowApplicationContext } from '@/lib/workflows/application/context' +import { loadManualWorkflowFromBlockState } from '@/lib/workflows/application/manual-workflow-state' +import { workflowOperations } from '@/lib/workflows/application/operations' +import { withWorkflowBlockScope } from '@/lib/workflows/application/workflow-block-scope' +import { previewRunFromBlock } from '@/executor/utils/run-from-block-preview' +import { Serializer } from '@/serializer' + +export interface PreviewManualWorkflowFromBlockInput { + workflowId: string + blockId: string + sourceRunId: string +} + +export const previewManualWorkflowFromBlock = defineAuthorizedWorkflowUseCase({ + operation: workflowOperations.previewManualFromBlock, + resolveContext: ({ input }: { input: PreviewManualWorkflowFromBlockInput }) => + resolveActiveWorkflowApplicationContext({ workflowId: input.workflowId }), + async execute({ context, input }) { + return withWorkflowBlockScope(context, async () => { + const { state, sourceSnapshot } = await loadManualWorkflowFromBlockState( + { ...input, workflowId: context.workflowId }, + { persistMigrations: false } + ) + try { + const workflow = new Serializer().serializeWorkflow( + mergeSubblockStateWithValues(state.blocks), + state.edges, + state.loops, + state.parallels, + true + ) + return { + workflowId: context.workflowId, + sourceRunId: input.sourceRunId, + startBlockId: input.blockId, + ...previewRunFromBlock(workflow, input.blockId, sourceSnapshot), + notes: [ + 'Rerun blocks are graph candidates, not an execution order or guarantee. Conditions, disabled blocks, loops, and runtime failures determine which blocks actually run.', + 'Cached outputs come from the source run; they are not refreshed. Availability describes stored output entries, not the continued availability of referenced files or external resources.', + 'This preview does not execute blocks, reserve a run ID, or validate credentials and provider inputs. A later run uses the saved draft at that time and can repeat actions in rerun blocks.', + ], + } + } catch (error) { + throw new OrchestrationError( + 'validation', + getErrorMessage(error, 'The saved workflow cannot be prepared for a partial run.') + ) + } + }) + }, +}) diff --git a/apps/sim/lib/workflows/application/replace-workflow-state.integration.ts b/apps/sim/lib/workflows/application/replace-workflow-state.integration.ts new file mode 100644 index 00000000000..8dc287cb1dc --- /dev/null +++ b/apps/sim/lib/workflows/application/replace-workflow-state.integration.ts @@ -0,0 +1,192 @@ +/** Actual authorization, normalization, and PostgreSQL replacement transactions; no provider calls. */ +import { db } from '@sim/db' +import { permissions, user, workflow, workflowBlocks, workspace } from '@sim/db/schema' +import { readTestDatabaseUrl } from '@sim/db/testing/test-infrastructure' +import { createDeferred } from '@sim/testing' +import { generateId } from '@sim/utils/id' +import { eq } from 'drizzle-orm' +import postgres from 'postgres' +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest' +import { withPermissionGroupScope } from '@/lib/permission-groups/request-scope.server' +import { replaceWorkflowState } from '@/lib/workflows/application/replace-workflow-state' +import { loadWorkflowDeploymentSnapshot } from '@/lib/workflows/persistence/utils' +import { loadWorkflowReadSnapshot } from '@/lib/workflows/queries' +import type { BlockState } from '@/stores/workflows/workflow/types' + +const userId = generateId() +const workspaceId = generateId() +const principal = { kind: 'session' as const, userId, sessionId: generateId() } +const control = postgres(readTestDatabaseUrl(), { max: 2 }) +let workflowId: string +let start: BlockState +let boundBlockId: string + +async function storedBlocks() { + return db.select().from(workflowBlocks).where(eq(workflowBlocks.workflowId, workflowId)) +} + +describe('workflow replacement with real PostgreSQL isolation', () => { + beforeAll(async () => { + const now = new Date() + await db.insert(user).values({ + id: userId, + name: 'Workflow authoring fixture', + email: `${userId}@workflow.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + await db.insert(workspace).values({ + id: workspaceId, + name: 'Workflow authoring fixture', + ownerId: userId, + billedAccountUserId: userId, + }) + await db.insert(permissions).values({ + id: generateId(), + userId, + entityType: 'workspace', + entityId: workspaceId, + permissionType: 'admin', + }) + }) + + beforeEach(async () => { + workflowId = generateId() + boundBlockId = generateId() + start = { + id: generateId(), + type: 'start_trigger', + name: 'Start', + enabled: true, + position: { x: 0, y: 0 }, + subBlocks: {}, + outputs: {}, + } + await db.insert(workflow).values({ + id: workflowId, + userId, + workspaceId, + name: `Replace fixture ${workflowId}`, + lastSynced: new Date(), + createdAt: new Date(), + updatedAt: new Date(), + }) + await db.insert(workflowBlocks).values([ + { + id: start.id, + workflowId, + type: start.type, + name: start.name, + positionX: '0', + positionY: '0', + enabled: true, + subBlocks: { + _removed_oldSecret: { id: '_removed_oldSecret', type: 'short-input', value: 'old' }, + }, + outputs: {}, + data: {}, + }, + { + id: boundBlockId, + workflowId, + type: 'slack', + name: 'Bound Slack', + positionX: '200', + positionY: '0', + enabled: true, + subBlocks: { + operation: { id: 'operation', type: 'dropdown', value: 'send' }, + authMethod: { id: 'authMethod', type: 'dropdown', value: 'oauth' }, + credential: { id: 'credential', type: 'oauth-input', value: 'cred_before' }, + }, + outputs: {}, + data: {}, + }, + ]) + }) + + afterAll(async () => { + try { + await db.delete(workspace).where(eq(workspace.id, workspaceId)) + await db.delete(user).where(eq(user.id, userId)) + } finally { + await control.end() + await db.$client.end() + } + }) + + it('reports the committed binding baseline after waiting for a competing writer', async () => { + const locked = createDeferred() + const release = createDeferred() + const competing = control.begin(async (tx) => { + const [{ pid }] = await tx<{ pid: number }[]>`SELECT pg_backend_pid() AS pid` + await tx`SELECT id FROM workflow WHERE id = ${workflowId} FOR UPDATE` + locked.resolve(pid) + await release.promise + await tx`UPDATE workflow_blocks SET sub_blocks = jsonb_set( + sub_blocks, '{credential,value}', '"cred_committed_while_waiting"'::jsonb + ) WHERE id = ${boundBlockId}` + }) + void competing.catch((error) => locked.reject(error)) + const blockerPid = await locked.promise + const replacing = withPermissionGroupScope(() => + replaceWorkflowState.execute({ + principal, + input: { workflowId, blocks: { [start.id]: start }, edges: [] }, + }) + ) + /** Observe PostgreSQL's actual lock wait, not a mocked transaction callback. */ + let blocked = false + let completed = false + void replacing.then( + () => { + completed = true + }, + () => { + completed = true + } + ) + try { + for (let attempt = 0; attempt < 500 && !completed; attempt++) { + const [{ waiting }] = await control<{ waiting: boolean }[]>` + SELECT EXISTS ( + SELECT 1 FROM pg_stat_activity + WHERE ${blockerPid} = ANY(pg_blocking_pids(pid)) + ) AS waiting` + if (waiting) { + blocked = true + break + } + } + } finally { + release.resolve() + await competing + } + const result = await replacing + expect(blocked).toBe(true) + expect(result.removedBindings.map(({ resourceId }) => resourceId)).toEqual([ + 'cred_committed_while_waiting', + ]) + expect((await storedBlocks()).map(({ id }) => id)).toEqual([start.id]) + }) + + it('normalizes legacy state for reads and dry runs without changing persisted rows', async () => { + const before = await storedBlocks() + const read = await loadWorkflowReadSnapshot(workflowId, workspaceId) + const snapshot = await loadWorkflowDeploymentSnapshot(workflowId) + const preview = await withPermissionGroupScope(() => + replaceWorkflowState.execute({ + principal, + input: { workflowId, blocks: { [start.id]: start }, edges: [], dryRun: true }, + }) + ) + expect(read?.normalizedData?.blocks[start.id].subBlocks).not.toHaveProperty( + '_removed_oldSecret' + ) + expect(snapshot?.blocks[start.id].subBlocks).not.toHaveProperty('_removed_oldSecret') + expect(preview.removedBindings.map(({ resourceId }) => resourceId)).toEqual(['cred_before']) + /** Query after pending migration microtasks; both contents and update timestamps must survive. */ + expect(await storedBlocks()).toEqual(before) + }) +}) diff --git a/apps/sim/lib/workflows/application/replace-workflow-state.test.ts b/apps/sim/lib/workflows/application/replace-workflow-state.test.ts index c698924606d..804de629e72 100644 --- a/apps/sim/lib/workflows/application/replace-workflow-state.test.ts +++ b/apps/sim/lib/workflows/application/replace-workflow-state.test.ts @@ -1,3 +1,4 @@ +import { db } from '@sim/db' import { WorkflowLockedError } from '@sim/platform-authz/workflow' import { workflowAuthzMockFns } from '@sim/testing' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -8,12 +9,15 @@ const mocks = vi.hoisted(() => ({ resolvePermission: vi.fn(), notify: vi.fn(), replace: vi.fn(), + replacementResult: vi.fn(), + resolvedState: vi.fn(), prepare: vi.fn(), collectGraphIds: vi.fn(), assertIdsUnclaimed: vi.fn(), validate: vi.fn(), needsRedeployment: vi.fn(), loadNormalized: vi.fn(), + admitBlockTypes: vi.fn(), })) vi.mock('@sim/audit', () => ({ @@ -54,9 +58,14 @@ vi.mock('@/lib/workflows/persistence/utils', () => ({ loadWorkflowFromNormalizedTables: mocks.loadNormalized, })) +vi.mock('@/lib/workflows/persistence/block-access-guard', () => ({ + assertNoWithheldBlockType: mocks.admitBlockTypes, +})) + import { OrchestrationError } from '@/lib/core/orchestration/types' import { replaceWorkflowState } from '@/lib/workflows/application/replace-workflow-state' import { validateInputsForBlock } from '@/lib/workflows/editing/validation' +import type { ReplaceWorkflowNormalizedStateInput } from '@/lib/workflows/persistence/replace-normalized-state' import { AgentBlock } from '@/blocks/blocks/agent' import { ExaBlock } from '@/blocks/blocks/exa' import { getBlock } from '@/blocks/registry' @@ -97,9 +106,14 @@ describe('replaceWorkflowState', () => { ) mocks.resolveContext.mockResolvedValue(context) mocks.resolvePermission.mockResolvedValue('write') + mocks.admitBlockTypes.mockResolvedValue(undefined) workflowAuthzMockFns.mockAssertWorkflowMutable.mockResolvedValue(undefined) mocks.validate.mockReturnValue({ valid: true, errors: [], warnings: [] }) - mocks.replace.mockResolvedValue({ + mocks.replace.mockImplementation(async ({ state }: ReplaceWorkflowNormalizedStateInput) => { + mocks.resolvedState(typeof state === 'function' ? await state(db) : state) + return mocks.replacementResult() + }) + mocks.replacementResult.mockReturnValue({ warnings: [], state: { blocks: { 'block-1': BLOCK }, edges: [], loops: {}, parallels: {} }, }) @@ -113,6 +127,45 @@ describe('replaceWorkflowState', () => { mocks.loadNormalized.mockResolvedValue({ blocks: {}, edges: [], loops: {}, parallels: {} }) }) + it.each([true, false])( + 'allows an initially absent normalized graph (dryRun=%s)', + async (dryRun) => { + mocks.loadNormalized.mockResolvedValue(null) + const result = await replaceWorkflowState.execute({ + principal: sessionPrincipal, + input: { ...input, dryRun }, + }) + expect(result.removedBindings).toEqual([]) + expect(result.blocksCount).toBe(1) + expect(mocks.replace).toHaveBeenCalledTimes(dryRun ? 0 : 1) + } + ) + + it('refuses a withheld block before acquiring the replacement lock', async () => { + mocks.admitBlockTypes.mockRejectedValueOnce( + new OrchestrationError('forbidden', 'Block type is not allowed') + ) + await expect( + replaceWorkflowState.execute({ principal: sessionPrincipal, input }) + ).rejects.toMatchObject({ code: 'forbidden' }) + expect(mocks.admitBlockTypes).toHaveBeenCalledWith( + { workspaceId: context.workspaceId, subjectUserId: sessionPrincipal.userId }, + [BLOCK] + ) + expect(mocks.replace).not.toHaveBeenCalled() + expect(mocks.loadNormalized).not.toHaveBeenCalled() + expect(mocks.recordAudit).not.toHaveBeenCalled() + }) + + it('does not read saved bindings before access is authorized', async () => { + mocks.resolvePermission.mockResolvedValue('read') + await expect( + replaceWorkflowState.execute({ principal: sessionPrincipal, input }) + ).rejects.toThrow() + expect(mocks.loadNormalized).not.toHaveBeenCalled() + expect(mocks.replace).not.toHaveBeenCalled() + }) + /** * Two things this pins that a same-shape input and output cannot: the write * carries the **sanitized** graph, not the caller's body, and the reported @@ -150,7 +203,12 @@ describe('replaceWorkflowState', () => { workflowId: 'workflow-1', workspaceId: 'workspace-1', attributedUserId: 'user-1', - state: { blocks: { 'block-1': BLOCK }, edges: [], variables: undefined }, + state: expect.any(Function), + }) + expect(mocks.resolvedState).toHaveBeenCalledWith({ + blocks: { 'block-1': BLOCK }, + edges: [], + variables: undefined, }) }) @@ -174,15 +232,13 @@ describe('replaceWorkflowState', () => { }, }) - expect(mocks.replace).toHaveBeenCalledWith( + expect(mocks.resolvedState).toHaveBeenCalledWith( expect.objectContaining({ - state: expect.objectContaining({ - variables: { - 'var-1': { id: 'var-1', name: 'retries', type: 'number', value: 42 }, - 'var-2': { id: 'var-2', name: 'enabled', type: 'boolean', value: true }, - 'var-3': { id: 'var-3', name: 'tags', type: 'array', value: ['a', 'b'] }, - }, - }), + variables: { + 'var-1': { id: 'var-1', name: 'retries', type: 'number', value: 42 }, + 'var-2': { id: 'var-2', name: 'enabled', type: 'boolean', value: true }, + 'var-3': { id: 'var-3', name: 'tags', type: 'array', value: ['a', 'b'] }, + }, }) ) }) @@ -370,14 +426,15 @@ describe('replaceWorkflowState', () => { } const replacement = { ...input, blocks: { [BLOCK.id]: block } } - it.each([false, true])('rejects new aliases before persistence (dryRun=%s)', async (dryRun) => { + it.each([false, true])('rejects new aliases before writing (dryRun=%s)', async (dryRun) => { await expect( replaceWorkflowState.execute({ principal: copilotPrincipal, input: { ...replacement, dryRun }, }) ).rejects.toThrow('attachment names are read-only') - expect(mocks.replace).not.toHaveBeenCalled() + expect(mocks.replace).toHaveBeenCalledTimes(dryRun ? 0 : 1) + expect(mocks.resolvedState).not.toHaveBeenCalled() expect(mocks.notify).not.toHaveBeenCalled() }) @@ -394,11 +451,9 @@ describe('replaceWorkflowState', () => { input: { ...replacement, blocks: { [BLOCK.id]: { ...block, name: 'Updated Agent' } } }, }) ).resolves.toMatchObject({ dryRun: false }) - expect(mocks.replace).toHaveBeenCalledWith( + expect(mocks.resolvedState).toHaveBeenCalledWith( expect.objectContaining({ - state: expect.objectContaining({ - blocks: { [BLOCK.id]: { ...block, name: 'Updated Agent' } }, - }), + blocks: { [BLOCK.id]: { ...block, name: 'Updated Agent' } }, }) ) }) diff --git a/apps/sim/lib/workflows/application/replace-workflow-state.ts b/apps/sim/lib/workflows/application/replace-workflow-state.ts index 346afe660e2..d23a227c6d2 100644 --- a/apps/sim/lib/workflows/application/replace-workflow-state.ts +++ b/apps/sim/lib/workflows/application/replace-workflow-state.ts @@ -19,9 +19,14 @@ import { withWorkflowBlockScope } from '@/lib/workflows/application/workflow-blo import { requireMutableWorkflow } from '@/lib/workflows/application/workflow-mutability' import { normalizeWorkflowVariables } from '@/lib/workflows/application/workflow-variables' import { checkNeedsRedeployment } from '@/lib/workflows/deployment-status' +import { + collectRemovedWorkflowBindings, + type RemovedWorkflowBinding, +} from '@/lib/workflows/editing/binding-changes' import type { WorkflowLintReport } from '@/lib/workflows/editing/lint' import { buildWorkflowLintReport } from '@/lib/workflows/editing/lint-report' import { validateValueForSubBlockType } from '@/lib/workflows/editing/validation' +import { assertNoWithheldBlockType } from '@/lib/workflows/persistence/block-access-guard' import { prepareWorkflowStateForPersistence } from '@/lib/workflows/persistence/prepare-state' import { assertWorkflowGraphIdsUnclaimed, @@ -68,9 +73,8 @@ export interface ReplaceWorkflowStateInput { /** Omitted leaves the stored variables untouched. */ variables?: Record /** - * Validate and lint without persisting. The response is byte-identical to a - * committed write of the same body, so a caller can inspect the findings it - * would get and then send the same request for real. + * Validate and lint without persisting. Binding removals describe the current + * snapshot; a later committed write compares against the state it replaces. */ dryRun?: boolean } @@ -82,6 +86,8 @@ export interface ReplaceWorkflowStateResult { blocksCount: number edgesCount: number warnings: string[] + /** Non-secret credential/table references removed by this proposed replacement. */ + removedBindings: RemovedWorkflowBinding[] needsRedeployment: boolean /** Advisory findings about the graph. Never blocks the write. */ lint: WorkflowLintReport @@ -89,6 +95,43 @@ export interface ReplaceWorkflowStateResult { dryRun: boolean } +/** Validates saved attachment identity against the same baseline the replacement will overwrite. */ +function assertSavedToolBindings( + blocks: Record, + previous: Record | undefined +): void { + if (!previous) { + throw new OrchestrationError( + 'validation', + 'Cannot validate tool edits without the saved workflow state' + ) + } + for (const [blockId, block] of Object.entries(blocks)) { + const config = getBlock(block.type) + if (!config) continue + for (const field of config.subBlocks) { + if (field.type !== 'tool-input' || !block.subBlocks[field.id]) continue + const savedBlock = previous[blockId] + const error = validateToolBindingAuthoring( + block.type, + block.subBlocks[field.id].value, + savedBlock?.type === block.type ? savedBlock.subBlocks[field.id]?.value : undefined + ) + if (error) + throw new OrchestrationError('validation', `Block ${block.name || blockId}: ${error}`) + } + } +} + +/** Binding loss is advisory and accompanies the exact baseline used for the comparison. */ +function bindingRemovalWarnings(removedBindings: RemovedWorkflowBinding[]): string[] { + return removedBindings.length + ? [ + `This replacement removes ${removedBindings.length} credential/table binding references. Inspect removedBindings before saving; use workflows state get for in-place edits, not workflows export.`, + ] + : [] +} + /** * Replaces a workflow's editable draft graph wholesale. * @@ -138,15 +181,6 @@ export const replaceWorkflowState = defineAuthorizedWorkflowUseCase({ principal.kind === 'delegated' && principal.serviceId === 'copilot' && Object.values(blocks).some((block) => getToolBindingAuthoringSchema(block.type)) - const previous = enforceToolBindings - ? await loadWorkflowFromNormalizedTables(context.workflowId) - : undefined - if (enforceToolBindings && !previous) { - throw new OrchestrationError( - 'validation', - 'Cannot validate tool edits without the saved workflow state' - ) - } for (const [blockId, block] of Object.entries(blocks)) { const config = getBlock(block.type) if (!config) continue @@ -154,16 +188,6 @@ export const replaceWorkflowState = defineAuthorizedWorkflowUseCase({ for (const [fieldId, stored] of Object.entries(block.subBlocks ?? {})) { const field = fields.get(fieldId) if (!field) continue - if (enforceToolBindings && field.type === 'tool-input') { - const savedBlock = previous?.blocks[blockId] - const error = validateToolBindingAuthoring( - block.type, - stored.value, - savedBlock?.type === block.type ? savedBlock.subBlocks[fieldId]?.value : undefined - ) - if (error) - throw new OrchestrationError('validation', `Block ${block.name || blockId}: ${error}`) - } const result = validateValueForSubBlockType( field, stored.value, @@ -187,13 +211,7 @@ export const replaceWorkflowState = defineAuthorizedWorkflowUseCase({ edges: sanitized.edges as WorkflowState['edges'], } - /** - * Linted before the write so a dry run and a committed write report the - * same findings for the same body. Unlike its sibling `applyOperations`, - * this operation admits workspace API keys, which have no human subject — - * the reference pass is skipped for them rather than resolved against the - * billing owner. See {@link buildWorkflowLintReport}. - */ + /** Validate references as the acting human, never as the workspace billing owner. */ const subjectUserId = humanSubjectUserId(principal) const lint = await buildWorkflowLintReport(graph, { @@ -203,11 +221,16 @@ export const replaceWorkflowState = defineAuthorizedWorkflowUseCase({ }) if (input.dryRun) { + const previous = await loadWorkflowFromNormalizedTables(context.workflowId, undefined, { + persistMigrations: false, + }) + if (enforceToolBindings) assertSavedToolBindings(blocks, previous?.blocks) + /** * The same preparation the committed write runs, so a dry run reports the * notes that write would produce and checks the ids it would actually - * insert — the prepared graph, not the caller's body. Preparing here and - * again inside the write is the cost of the two paths never disagreeing. + * insert — the prepared graph, not the caller's body. Concurrent writes + * can still change the binding baseline or claim ids after this preview. */ const prepared = prepareWorkflowStateForPersistence(graph) await assertWorkflowGraphIdsUnclaimed( @@ -216,6 +239,10 @@ export const replaceWorkflowState = defineAuthorizedWorkflowUseCase({ collectWorkflowGraphIds(prepared.state) ) + const removedBindings = collectRemovedWorkflowBindings( + previous?.blocks ?? {}, + prepared.state.blocks + ) logger.info('Validated workflow state without persisting', { workflowId: context.workflowId, workspaceId: context.workspaceId, @@ -227,7 +254,12 @@ export const replaceWorkflowState = defineAuthorizedWorkflowUseCase({ workspaceId: context.workspaceId, blocksCount: Object.keys(graph.blocks).length, edgesCount: graph.edges.length, - warnings: [...validation.warnings, ...prepared.warnings], + warnings: [ + ...validation.warnings, + ...prepared.warnings, + ...bindingRemovalWarnings(removedBindings), + ], + removedBindings, needsRedeployment: await checkNeedsRedeployment(context.workflowId), lint, dryRun: true, @@ -237,6 +269,16 @@ export const replaceWorkflowState = defineAuthorizedWorkflowUseCase({ const attribution = resolvePrincipalAttribution(principal, { workspaceBillingOwnerUserId: context.billedAccountUserId, }) + /** The locked reader supplies a caller-authored graph; preserve its pre-transaction admission. */ + await assertNoWithheldBlockType( + { workspaceId: context.workspaceId, subjectUserId }, + Object.values(graph.blocks) + ) + let previousBlocks: Record = {} + const variables = + input.variables === undefined + ? undefined + : normalizeWorkflowVariables(input.variables, { coerceValues: true }) const persisted = await replaceWorkflowNormalizedState({ workflowId: context.workflowId, workspaceId: context.workspaceId, @@ -250,22 +292,18 @@ export const replaceWorkflowState = defineAuthorizedWorkflowUseCase({ * reachable state. */ subjectUserId, - state: { - blocks: graph.blocks, - edges: graph.edges, - /** - * Re-keyed by variable id and coerced onto each declared type by the - * same helper `PATCH /workflows/{id}/variables` uses, so a full - * replacement cannot write a shape the incremental path never - * produces. Omitted stays omitted — that leaves the column untouched. - */ - variables: - input.variables === undefined - ? undefined - : normalizeWorkflowVariables(input.variables, { coerceValues: true }), + state: async (tx) => { + const previous = await loadWorkflowFromNormalizedTables(context.workflowId, tx, { + persistMigrations: false, + }) + if (enforceToolBindings) assertSavedToolBindings(blocks, previous?.blocks) + previousBlocks = previous?.blocks ?? {} + return { blocks: graph.blocks, edges: graph.edges, variables } }, }) + const removedBindings = collectRemovedWorkflowBindings(previousBlocks, persisted.state.blocks) + logger.info('Replaced workflow state', { workflowId: context.workflowId, workspaceId: context.workspaceId, @@ -278,7 +316,12 @@ export const replaceWorkflowState = defineAuthorizedWorkflowUseCase({ workspaceId: context.workspaceId, blocksCount: Object.keys(persisted.state.blocks).length, edgesCount: persisted.state.edges.length, - warnings: [...validation.warnings, ...persisted.warnings], + warnings: [ + ...validation.warnings, + ...persisted.warnings, + ...bindingRemovalWarnings(removedBindings), + ], + removedBindings, needsRedeployment: await checkNeedsRedeployment(context.workflowId), lint, dryRun: false, diff --git a/apps/sim/lib/workflows/application/workflow-custom-block-authoring.test.ts b/apps/sim/lib/workflows/application/workflow-custom-block-authoring.test.ts index 890d83ea22d..1ebd0124681 100644 --- a/apps/sim/lib/workflows/application/workflow-custom-block-authoring.test.ts +++ b/apps/sim/lib/workflows/application/workflow-custom-block-authoring.test.ts @@ -1,3 +1,4 @@ +import { db } from '@sim/db' import { workflowAuthzMockFns } from '@sim/testing' import type { BlockState } from '@sim/workflow-types/workflow' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -66,6 +67,7 @@ import { replaceWorkflowState } from '@/lib/workflows/application/replace-workfl import type { CustomBlockWithInputs } from '@/lib/workflows/custom-blocks/operations' import type { EditWorkflowOperation } from '@/lib/workflows/editing/types' import { prepareWorkflowStateForPersistence } from '@/lib/workflows/persistence/prepare-state' +import type { ReplaceWorkflowNormalizedStateInput } from '@/lib/workflows/persistence/replace-normalized-state' import { withCustomBlockOverlay } from '@/blocks/custom/server-overlay' import { getBlock } from '@/blocks/registry' @@ -148,6 +150,10 @@ const add: EditWorkflowOperation = { params: { type: customBlock.type, name: 'New Worker', inputs: { 'input-text': 'hello' } }, } +async function prepareReplacement({ state }: ReplaceWorkflowNormalizedStateInput) { + return prepareWorkflowStateForPersistence(typeof state === 'function' ? await state(db) : state) +} + describe('custom blocks in authorized workflow authoring', () => { beforeEach(() => { mocks.resolveContext.mockResolvedValue(context) @@ -159,7 +165,7 @@ describe('custom blocks in authorized workflow authoring', () => { workflowRecord: context.workflow, normalizedData: graph(true), })) - mocks.replace.mockImplementation(async ({ state }) => prepareWorkflowStateForPersistence(state)) + mocks.replace.mockImplementation(prepareReplacement) }) it.each([session, copilot])( @@ -206,7 +212,7 @@ describe('custom blocks in authorized workflow authoring', () => { expect(result.lint.fieldIssues).toEqual([]) expect(mocks.replace).toHaveBeenCalledTimes(dryRun ? 0 : 1) if (!dryRun) { - const persisted = mocks.replace.mock.calls[0][0].state + const persisted = (await mocks.replace.mock.results[0].value).state expect(persisted.blocks.worker.subBlocks['input-text']).toMatchObject({ value: 'updated', type: 'short-input', @@ -250,10 +256,10 @@ describe('custom blocks in authorized workflow authoring', () => { await barrier return graph() }) - mocks.replace.mockImplementation(async ({ state, workspaceId }) => { - const foreignType = workspaceId === 'one' ? other.type : customBlock.type + mocks.replace.mockImplementation(async (replacement: ReplaceWorkflowNormalizedStateInput) => { + const foreignType = replacement.workspaceId === 'one' ? other.type : customBlock.type expect(getBlock(foreignType)).toBeUndefined() - return prepareWorkflowStateForPersistence(state) + return prepareReplacement(replacement) }) const results = await Promise.all( [customBlock, other].map((row, index) => @@ -286,7 +292,10 @@ describe('custom blocks in authorized workflow authoring', () => { expect(result.lint.fieldIssues).toEqual([]) expect(mocks.replace).toHaveBeenCalledTimes(dryRun ? 0 : 1) if (!dryRun) { - const persisted = mocks.replace.mock.calls[0][0].state + expect(mocks.loadNormalized).toHaveBeenCalledWith(context.workflowId, db, { + persistMigrations: false, + }) + const persisted = (await mocks.replace.mock.results[0].value).state expect(persisted.blocks.worker.subBlocks['input-text']).toMatchObject({ value: 'hello', type: 'short-input', diff --git a/apps/sim/lib/workflows/editing/binding-changes.test.ts b/apps/sim/lib/workflows/editing/binding-changes.test.ts new file mode 100644 index 00000000000..7159cb987d8 --- /dev/null +++ b/apps/sim/lib/workflows/editing/binding-changes.test.ts @@ -0,0 +1,163 @@ +import type { BlockState } from '@sim/workflow-types/workflow' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { collectRemovedWorkflowBindings } from '@/lib/workflows/editing/binding-changes' +import { buildWorkflowReferenceManifest } from '@/lib/workflows/references/manifest' +import { getBlock } from '@/blocks/registry' +import type { BlockConfig } from '@/blocks/types' + +const config = { + subBlocks: [ + { id: 'credential', type: 'oauth-input', canonicalParamId: 'oauthCredential', mode: 'basic' }, + { + id: 'manualCredential', + type: 'short-input', + canonicalParamId: 'oauthCredential', + mode: 'advanced', + }, + { id: 'operation', type: 'dropdown' }, + { id: 'apiKey', type: 'short-input', password: true }, + { id: 'tableSelector', type: 'table-selector', canonicalParamId: 'tableId', mode: 'basic' }, + { id: 'manualTableId', type: 'short-input', canonicalParamId: 'tableId', mode: 'advanced' }, + ], +} as BlockConfig + +function block(values: Record): BlockState { + return { + id: 'block', + type: 'table_v2', + name: 'Bound block', + enabled: true, + position: { x: 0, y: 0 }, + outputs: {}, + subBlocks: Object.fromEntries( + Object.entries(values).map(([id, value]) => [ + id, + { id, type: config.subBlocks.find((field) => field.id === id)!.type, value }, + ]) + ), + } +} + +beforeEach(() => vi.mocked(getBlock).mockReturnValue(config)) + +describe('binding removal preview', () => { + it('reports removed credential/table identifiers without copying secret values', () => { + const previous = { + block: block({ + credential: 'credential-1', + tableSelector: 'table-1', + apiKey: 'PRIVATE-API-KEY', + }), + } + const result = collectRemovedWorkflowBindings(previous, { + block: block({ credential: null, tableSelector: null, apiKey: null }), + }) + expect(result).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + blockId: 'block', + kind: 'credential', + resourceId: 'credential-1', + field: 'credential', + }), + expect.objectContaining({ + blockId: 'block', + kind: 'table', + resourceId: 'table-1', + field: 'tableSelector', + }), + ]) + ) + expect(result).toHaveLength(2) + expect(JSON.stringify(result)).not.toContain('PRIVATE-API-KEY') + expect(previous.block.subBlocks.apiKey.value).toBe('PRIVATE-API-KEY') + }) + + it('reports lost bindings when a block is removed or its ID changes', () => { + const previous = { block: block({ credential: 'credential-1' }) } + expect(collectRemovedWorkflowBindings(previous, {})).toHaveLength(1) + expect( + collectRemovedWorkflowBindings(previous, { other: { ...previous.block, id: 'other' } }) + ).toHaveLength(1) + }) + + it('retains unchanged bindings and identifies replaced resource IDs', () => { + const previous = { block: block({ credential: 'credential-1', tableSelector: 'table-1' }) } + expect(collectRemovedWorkflowBindings(previous, structuredClone(previous))).toEqual([]) + expect( + collectRemovedWorkflowBindings(previous, { + block: block({ credential: 'credential-1', tableSelector: 'table-2' }), + }) + ).toEqual([expect.objectContaining({ kind: 'table', resourceId: 'table-1' })]) + }) + + describe.each([ + { selector: 'credential', manual: 'manualCredential', canonical: 'oauthCredential' }, + { selector: 'tableSelector', manual: 'manualTableId', canonical: 'tableId' }, + ])('$canonical mode transitions', ({ selector, manual, canonical }) => { + it('retains the same identifier when the manual member becomes active', () => { + const previous = { block: block({ [selector]: 'resource-1' }) } + const next = { block: block({ [selector]: 'resource-1', [manual]: 'resource-1' }) } + next.block.data = { canonicalModes: { [canonical]: 'advanced' } } + + expect(collectRemovedWorkflowBindings(previous, next)).toEqual([]) + expect(buildWorkflowReferenceManifest(next).references).toEqual([]) + }) + + it('honors automatic mode selection when the basic member is cleared', () => { + expect( + collectRemovedWorkflowBindings( + { block: block({ [selector]: 'resource-1' }) }, + { block: block({ [selector]: null, [manual]: 'resource-1' }) } + ) + ).toEqual([]) + }) + + it('does not retain an identifier from a stale dormant manual member', () => { + const next = { block: block({ [selector]: 'resource-2', [manual]: 'resource-1' }) } + next.block.data = { canonicalModes: { [canonical]: 'basic' } } + + expect( + collectRemovedWorkflowBindings({ block: block({ [selector]: 'resource-1' }) }, next) + ).toEqual([expect.objectContaining({ field: selector, resourceId: 'resource-1' })]) + }) + + it.each(['resource-2', null])( + 'does not retain a dormant selector when its active manual value is %s', + (value) => { + const next = { block: block({ [selector]: 'resource-1', [manual]: value }) } + next.block.data = { canonicalModes: { [canonical]: 'advanced' } } + + expect( + collectRemovedWorkflowBindings({ block: block({ [selector]: 'resource-1' }) }, next) + ).toEqual([expect.objectContaining({ field: selector, resourceId: 'resource-1' })]) + } + ) + + it('does not retain identifiers in condition-hidden manual fields', () => { + vi.mocked(getBlock).mockReturnValue({ + ...config, + subBlocks: config.subBlocks.map((field) => + field.id === manual + ? { ...field, condition: { field: 'operation', value: 'use-resource' } } + : field + ), + }) + const next = { block: block({ [manual]: 'resource-1', operation: 'skip-resource' }) } + next.block.data = { canonicalModes: { [canonical]: 'advanced' } } + + expect( + collectRemovedWorkflowBindings({ block: block({ [selector]: 'resource-1' }) }, next) + ).toEqual([expect.objectContaining({ field: selector, resourceId: 'resource-1' })]) + }) + + it('does not retain action bindings from the inactive surface of a trigger block', () => { + const next = { block: block({ [manual]: 'resource-1' }) } + next.block.triggerMode = true + + expect( + collectRemovedWorkflowBindings({ block: block({ [selector]: 'resource-1' }) }, next) + ).toEqual([expect.objectContaining({ field: selector, resourceId: 'resource-1' })]) + }) + }) +}) diff --git a/apps/sim/lib/workflows/editing/binding-changes.ts b/apps/sim/lib/workflows/editing/binding-changes.ts new file mode 100644 index 00000000000..4f9a91d06aa --- /dev/null +++ b/apps/sim/lib/workflows/editing/binding-changes.ts @@ -0,0 +1,87 @@ +import type { BlockState } from '@sim/workflow-types/workflow' +import { buildWorkflowReferenceManifest } from '@/lib/workflows/references/manifest' +import { createCanonicalModeGates } from '@/lib/workflows/references/remap-references' +import { getWorkflowSearchSubBlockResourceKind } from '@/lib/workflows/search-replace/resources/registry' +import { + buildCanonicalIndexForSurface, + buildSubBlockValues, + getCanonicalValues, + isSubBlockVisibleForTriggerMode, + resolveActiveCanonicalValue, +} from '@/lib/workflows/subblocks/visibility' +import { getBlock } from '@/blocks/registry' + +export interface RemovedWorkflowBinding { + blockId: string + blockName: string + field: string + valuePath: Array + kind: 'credential' | 'table' + resourceId: string +} + +/** + * Compares registered binding identifiers only. Never copies credential values or arbitrary + * sub-block content. Moving an existing binding between active modes in one block retains it. + * Manual IDs supplement retention only; the portability manifest still owns binding detection. + */ +export function collectRemovedWorkflowBindings( + previous: Record, + next: Record +): RemovedWorkflowBinding[] { + const retained = new Set() + for (const reference of buildWorkflowReferenceManifest(next).references) { + if (reference.kind !== 'credential' && reference.kind !== 'table') continue + for (const occurrence of reference.occurrences) { + retained.add(JSON.stringify([occurrence.blockId, reference.kind, reference.sourceId])) + } + } + for (const block of Object.values(next)) { + const config = getBlock(block.type) + if (!config) continue + const triggerMode = block.triggerMode === true + const subBlocks = config.subBlocks.filter((field) => + isSubBlockVisibleForTriggerMode(field, triggerMode, config) + ) + const definitions = new Map(subBlocks.map((field) => [field.id, field])) + const values = buildSubBlockValues(block.subBlocks) + const modes = block.data?.canonicalModes + const gates = createCanonicalModeGates(subBlocks, values, modes, triggerMode) + const index = buildCanonicalIndexForSurface(subBlocks, triggerMode) + for (const group of Object.values(index.groupsById)) { + if (!group.basicId) continue + const kind = getWorkflowSearchSubBlockResourceKind(definitions.get(group.basicId)) + if (kind !== 'oauth-credential' && kind !== 'table') continue + const { advancedSourceId } = getCanonicalValues(group, values) + if ( + !advancedSourceId || + !gates.isActiveManualMember(advancedSourceId) || + gates.isConditionHidden(advancedSourceId) + ) + continue + const sourceId = resolveActiveCanonicalValue(group, values, modes) + if (typeof sourceId === 'string') { + retained.add( + JSON.stringify([block.id, kind === 'oauth-credential' ? 'credential' : kind, sourceId]) + ) + } + } + } + const removed: RemovedWorkflowBinding[] = [] + for (const reference of buildWorkflowReferenceManifest(previous).references) { + if (reference.kind !== 'credential' && reference.kind !== 'table') continue + for (const occurrence of reference.occurrences) { + if (retained.has(JSON.stringify([occurrence.blockId, reference.kind, reference.sourceId]))) + continue + removed.push({ + blockId: occurrence.blockId, + blockName: previous[occurrence.blockId]?.name || occurrence.blockId, + field: occurrence.subBlockKey, + valuePath: occurrence.valuePath, + kind: reference.kind, + resourceId: reference.sourceId, + }) + } + } + return removed +} diff --git a/apps/sim/lib/workflows/editing/branch-output.test.ts b/apps/sim/lib/workflows/editing/branch-output.test.ts new file mode 100644 index 00000000000..f4b58833782 --- /dev/null +++ b/apps/sim/lib/workflows/editing/branch-output.test.ts @@ -0,0 +1,93 @@ +import type { BlockState, WorkflowState } from '@sim/workflow-types/workflow' +import { describe, expect, it } from 'vitest' +import { collectBranchDependentBlockOutputReferences } from '@/lib/workflows/editing/lint' + +function block(id: string, type: string, value = ''): BlockState { + return { + id, + type, + name: id, + enabled: true, + position: { x: 0, y: 0 }, + outputs: {}, + subBlocks: { input: { id: 'input', type: 'short-input', value } }, + } +} +function edge( + source: string, + target: string, + sourceHandle = 'source' +): WorkflowState['edges'][number] { + return { id: `${source}-${target}`, source, target, sourceHandle } +} +function graph() { + return { + blocks: { + start: block('start', 'starter'), + branch: block('branch', 'condition'), + file: block('file', 'function'), + clarify: block('clarify', 'agent'), + send: block('send', 'slack', ''), + }, + edges: [ + edge('start', 'branch'), + edge('branch', 'file', 'condition-a'), + edge('branch', 'clarify', 'condition-b'), + edge('file', 'send'), + edge('clarify', 'send'), + ], + } +} + +describe('conditional output availability', () => { + it('flags attachments produced only on the delivery branch at a shared send block', () => { + const result = collectBranchDependentBlockOutputReferences(graph()) + expect(result.issues).toEqual([ + expect.objectContaining({ + blockId: 'send', + field: 'input', + value: '', + kind: 'block-output', + reason: expect.stringContaining('condition-b'), + }), + ]) + expect(result.check.detail).toContain('Guards inside expressions') + }) + + it('accepts a consumer placed only on the producing branch', () => { + const state = graph() + state.edges = state.edges.filter( + (edge) => !(edge.source === 'clarify' && edge.target === 'send') + ) + expect(collectBranchDependentBlockOutputReferences(state).issues).toEqual([]) + }) + + it('does not apply branch warnings to ordinary parallel outgoing edges', () => { + const state = graph() + state.blocks.branch.type = 'function' + expect(collectBranchDependentBlockOutputReferences(state).issues).toEqual([]) + }) + + it('accepts a value produced before the branch and shared dynamic references', () => { + const state = graph() + state.blocks.send.subBlocks.input.value = + ' ' + expect(collectBranchDependentBlockOutputReferences(state).issues).toEqual([]) + }) + + it('uses normalized block names and groups repeated references', () => { + const state = graph() + state.blocks.file.name = 'Make File' + state.blocks.send.subBlocks.input.value = ' ' + expect(collectBranchDependentBlockOutputReferences(state).issues).toHaveLength(1) + }) + + it('reports skipped analysis for subflows without pretending they are safe', () => { + const state = graph() + state.blocks.file.type = 'loop' + expect(collectBranchDependentBlockOutputReferences(state)).toMatchObject({ + issues: [], + check: { status: 'skipped' }, + }) + }) +}) diff --git a/apps/sim/lib/workflows/editing/code-syntax.test.ts b/apps/sim/lib/workflows/editing/code-syntax.test.ts new file mode 100644 index 00000000000..3a9536e79a6 --- /dev/null +++ b/apps/sim/lib/workflows/editing/code-syntax.test.ts @@ -0,0 +1,135 @@ +import type { BlockState } from '@sim/workflow-types/workflow' +import { describe, expect, it } from 'vitest' +import { collectWorkflowCodeSyntax } from '@/lib/workflows/editing/code-syntax' + +function block(code: string, language = 'javascript'): BlockState { + return { + id: 'renderer', + type: 'function', + name: 'Contract renderer', + enabled: true, + position: { x: 0, y: 0 }, + outputs: {}, + subBlocks: { + code: { id: 'code', type: 'code', value: code }, + language: { id: 'language', type: 'dropdown', value: language }, + }, + } +} + +describe('embedded Function syntax checks', () => { + it('catches path replacements that turn a regex into invalid flags', async () => { + const report = await collectWorkflowCodeSyntax({ + renderer: block('const imports = /import\\s+from/workspace/contracts;\nreturn imports'), + }) + expect(report.issues).toEqual([ + expect.objectContaining({ + blockId: 'renderer', + language: 'javascript', + field: 'code', + message: 'Invalid regular expression flags', + line: 1, + }), + ]) + }) + + it.each([ + 'return await Promise.resolve({ ok: true })', + 'const params = 1; const environmentVariables = 2; return params + environmentVariables', + 'import path from "node:path";\nreturn path.join("files", "contracts")', + 'const value = ; return value', + 'return "{{SECRET}}" + ""', + 'const expression = /abc/{{FLAGS}}; return expression', + 'const result = /import\\s+["\'](.+)["\']/g; return result', + 'if (1 < 2 && 4 > 3) return true', + ])('accepts supported JavaScript without running it: %s', async (code) => { + expect((await collectWorkflowCodeSyntax({ renderer: block(code) })).issues).toEqual([]) + }) + + it('does not expose regex source fragments in diagnostics', async () => { + const report = await collectWorkflowCodeSyntax({ renderer: block('return /PRIVATE-SECRET[/') }) + expect(report.issues).toHaveLength(1) + expect(JSON.stringify(report)).not.toContain('PRIVATE-SECRET') + }) + + it.each([ + 'return "value"PRIVATE_TOKEN', + 'const PRIVATE_TOKEN = 1; const PRIVATE_TOKEN = 2', + 'import path from "node:path";\nreturn "value"PRIVATE_TOKEN', + 'import path from "node:path";\nconst PRIVATE_TOKEN = 1; const PRIVATE_TOKEN = 2', + ])('does not echo source tokens from native or import-parser diagnostics: %s', async (code) => { + const report = await collectWorkflowCodeSyntax({ renderer: block(code) }) + expect(report.issues).toHaveLength(1) + expect(report.issues[0]).toMatchObject({ + field: 'code', + language: 'javascript', + message: expect.stringContaining('Invalid JavaScript syntax'), + line: code.includes('\n') ? 2 : 1, + column: expect.any(Number), + }) + expect(report.check.status).toBe('complete') + expect(JSON.stringify(report)).not.toContain('PRIVATE_TOKEN') + }) + + it('reports the runtime placeholder limit without failing the lint operation', async () => { + const report = await collectWorkflowCodeSyntax({ + renderer: block(`return "${'{{KEY}}'.repeat(10001)}"`), + }) + expect(report.issues[0].message).toContain('more than 10000 variable placeholders') + }) + + it('checks reference-dense code within the supported body budget without repeated overlap scans', async () => { + const code = `/*${''.repeat(200_000)}*/return 1` + const started = performance.now() + const report = await collectWorkflowCodeSyntax({ renderer: block(code) }) + + expect(report.issues).toEqual([]) + expect(report.check.detail).toContain('1 used placeholder values') + expect(performance.now() - started).toBeLessThan(2_000) + }, 60_000) + + it('never evaluates side effects while checking code', async () => { + const key = '__workflowLintExecuted' + await collectWorkflowCodeSyntax({ + renderer: block(`globalThis.${key} = true; throw new Error('must not run')`), + }) + expect(Reflect.get(globalThis, key)).toBeUndefined() + }) + + it.each(['const value = ;', 'return /[/;', 'const value: number = 1'])( + 'reports syntax failures: %s', + async (code) => { + expect((await collectWorkflowCodeSyntax({ renderer: block(code) })).issues).toHaveLength(1) + } + ) + + it('states unsupported and disabled code coverage without misclassifying Python as JavaScript', async () => { + const report = await collectWorkflowCodeSyntax({ + python: block('return {"name": True}', 'python'), + shell: block('printf hello', 'shell'), + disabled: { ...block('bad !!!'), enabled: false }, + }) + expect(report.issues).toEqual([]) + expect(report.check).toMatchObject({ status: 'partial' }) + expect(report.check.detail).toContain('Skipped 2 non-JavaScript bodies') + expect(report.check.detail).toContain('Parsed 0') + }) + + it('marks parser-limit exhaustion as unchecked instead of failing an advisory write', async () => { + const code = `import value from "some-module"; return ${'['.repeat(20000)}0${']'.repeat(20000)}` + const report = await collectWorkflowCodeSyntax({ renderer: block(code) }) + expect(report.check.status).toBe('partial') + expect(report.check.detail).toContain('1 bodies could not be parsed') + }) + + it('reports placeholder and byte-budget limits', async () => { + const report = await collectWorkflowCodeSyntax({ + templated: block('return '), + large: block(`${' '.repeat(1024 * 1024)}return 1`), + }) + expect(report.issues).toEqual([]) + expect(report.check.status).toBe('partial') + expect(report.check.detail).toContain('1 used placeholder values') + expect(report.check.detail).toContain('1 bodies exceeding') + }) +}) diff --git a/apps/sim/lib/workflows/editing/code-syntax.ts b/apps/sim/lib/workflows/editing/code-syntax.ts new file mode 100644 index 00000000000..905b5980090 --- /dev/null +++ b/apps/sim/lib/workflows/editing/code-syntax.ts @@ -0,0 +1,204 @@ +import { Script } from 'node:vm' +import { getErrorMessage } from '@sim/utils/errors' +import { findWorkflowReferenceTokens } from '@sim/utils/workflow-references' +import type { BlockState } from '@sim/workflow-types/workflow' +import { collectCodePlaceholderOccurrences } from '@/lib/execution/code-placeholders/shared' +import { collectJavaScriptImportSegments } from '@/lib/execution/javascript-imports' +import type { WorkflowLintCheck, WorkflowLintCodeIssue } from '@/lib/workflows/editing/lint' + +const MAX_CODE_BYTES = 1024 * 1024 +const MAX_TOTAL_CODE_BYTES = 8 * MAX_CODE_BYTES + +/** + * Parses JavaScript Function bodies without executing them or resolving secrets. The native + * parser catches invalid regex flags that TypeScript's recovery parser accepts. Static imports + * are parsed and removed before checking the async body, matching the execution wrapper. + */ +export async function collectWorkflowCodeSyntax(blocks: Record): Promise<{ + issues: WorkflowLintCodeIssue[] + check: WorkflowLintCheck +}> { + const issues: WorkflowLintCodeIssue[] = [] + let checked = 0 + let unsupported = 0 + let oversized = 0 + let bytesChecked = 0 + let templated = 0 + let parserFailures = 0 + + for (const [blockId, block] of Object.entries(blocks)) { + if (block.type !== 'function' || block.enabled === false) continue + const code = block.subBlocks.code?.value + if (typeof code !== 'string' || !code.trim()) continue + const language = block.subBlocks.language?.value || 'javascript' + if (language !== 'javascript') { + unsupported++ + continue + } + const bytes = Buffer.byteLength(code) + if (bytes > MAX_CODE_BYTES || bytesChecked + bytes > MAX_TOTAL_CODE_BYTES) { + oversized++ + continue + } + bytesChecked += bytes + checked++ + let tokens: { start: number; end: number }[] + try { + tokens = [ + ...findWorkflowReferenceTokens(code).filter((token) => token.kind === 'workflow'), + ...collectCodePlaceholderOccurrences(code), + ] + } catch (error) { + issues.push( + codeIssue(blockId, block, error, getErrorMessage(error, 'Invalid variable placeholders')) + ) + continue + } + if (tokens.length) templated++ + let masked = maskRanges(code, tokens, '_') + try { + compileBody(masked) + continue + } catch (error) { + /** Most bodies need only the native parser; load TypeScript only for imports or templates. */ + if (!/\bimport\b/.test(masked) && tokens.length === 0) { + issues.push(codeIssue(blockId, block, error)) + continue + } + } + + try { + const ts = await import('@typescript/typescript6') + const parsed = ts.createSourceFile( + 'workflow-code.js', + masked, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.JS + ) + const diagnostics = Reflect.get(parsed, 'parseDiagnostics') as + | readonly import('@typescript/typescript6').Diagnostic[] + | undefined + const diagnostic = diagnostics?.[0] + if (diagnostic) { + const position = parsed.getLineAndCharacterOfPosition(diagnostic.start ?? 0) + issues.push({ + blockId, + blockName: block.name, + blockType: block.type, + field: 'code', + language: 'javascript', + message: `Invalid JavaScript syntax (TS${diagnostic.code})`, + line: position.line + 1, + column: position.character + 1, + }) + continue + } + + /** Import declarations live outside the async execution body; keep offsets for diagnostics. */ + const edits = collectJavaScriptImportSegments(parsed, ts).map(({ start, end }) => ({ + start, + end, + })) + /** Dynamic regex flags are values, not statically checkable JavaScript flags. */ + const visit = (node: import('@typescript/typescript6').Node): void => { + if (ts.isRegularExpressionLiteral(node)) { + const start = node.getStart(parsed) + const flagsStart = start + node.getText(parsed).lastIndexOf('/') + 1 + let low = 0 + let high = tokens.length + while (low < high) { + const middle = (low + high) >>> 1 + if (tokens[middle].start < flagsStart) low = middle + 1 + else high = middle + } + for ( + let index = low; + index < tokens.length && tokens[index].end <= node.getEnd(); + index++ + ) { + edits.push(tokens[index]) + } + } + ts.forEachChild(node, visit) + } + visit(parsed) + masked = maskRanges(masked, edits, ' ') + try { + compileBody(masked) + } catch (error) { + issues.push(codeIssue(blockId, block, error)) + } + } catch { + /** Excessively nested syntax can exceed parser limits; advisory lint must still return. */ + parserFailures++ + } + } + + return { + issues, + check: { + name: 'embedded-code-syntax', + status: unsupported || oversized || templated || parserFailures ? 'partial' : 'complete', + detail: `Parsed ${checked} enabled JavaScript Function bodies without execution. ${templated} used placeholder values; resolved values are not checked. Skipped ${unsupported} non-JavaScript bodies and ${oversized} bodies exceeding the 1 MiB per-body or 8 MiB total parse budget. ${parserFailures} bodies could not be parsed within parser limits; simplify deeply nested code and retry. Python, Shell, generated source, dependency availability, and runtime behavior are not validated.`, + }, + } +} + +/** Compilation only: the returned script is never run. */ +function compileBody(code: string): void { + new Script(`(async () => {\n${code}\n})`, { + filename: 'workflow-code.js', + }) +} + +function codeIssue( + blockId: string, + block: BlockState, + error: unknown, + placeholderMessage?: string +): WorkflowLintCodeIssue { + const parserMessage = getErrorMessage(error) + /** Parser messages can interpolate arbitrary source; expose only fixed syntax categories. */ + const message = + placeholderMessage ?? + (parserMessage === 'Invalid regular expression flags' + ? parserMessage + : parserMessage.startsWith('Invalid regular expression') + ? 'Invalid regular expression literal' + : 'Invalid JavaScript syntax') + const stack = error instanceof Error ? error.stack : undefined + const line = /^workflow-code\.js:(\d+)/.exec(stack ?? '')?.[1] + const caret = stack?.split('\n')[2]?.indexOf('^') + return { + blockId, + blockName: block.name, + blockType: block.type, + field: 'code', + language: 'javascript', + message, + ...(line ? { line: Math.max(1, Number(line) - 1) } : {}), + ...(caret !== undefined && caret >= 0 ? { column: caret + 1 } : {}), + } +} + +/** Preserves offsets and line breaks without copying the full body once per placeholder. */ +function maskRanges( + code: string, + ranges: { start: number; end: number }[], + character: string +): string { + const parts: string[] = [] + let cursor = 0 + for (const range of ranges.sort((left, right) => left.start - right.start)) { + if (range.end <= cursor) continue + const start = Math.max(cursor, range.start) + parts.push( + code.slice(cursor, start), + code.slice(start, range.end).replace(/[^\r\n]/g, character) + ) + cursor = range.end + } + parts.push(code.slice(cursor)) + return parts.join('') +} diff --git a/apps/sim/lib/workflows/editing/lint-report.test.ts b/apps/sim/lib/workflows/editing/lint-report.test.ts index 665c3df2c79..7de4bf131ae 100644 --- a/apps/sim/lib/workflows/editing/lint-report.test.ts +++ b/apps/sim/lib/workflows/editing/lint-report.test.ts @@ -86,7 +86,15 @@ describe('buildWorkflowLintReport notes', () => { buildWorkflowLintReport(graph, scope, { requireComplete: true }) ).rejects.toThrow('Workflow reference checks could not complete') collector.mockRejectedValueOnce(new Error('private lookup details')) - await expect(buildWorkflowLintReport(graph, scope)).resolves.toMatchObject({ notes: [] }) + const report = await buildWorkflowLintReport(graph, scope) + expect(report.notes).toEqual([]) + expect(report.checks).toContainEqual( + expect.objectContaining({ + name: kind === 'references' ? 'credential-resource-references' : 'agent-tool-references', + status: 'skipped', + }) + ) + expect(JSON.stringify(report)).not.toContain('private lookup details') } ) @@ -94,6 +102,32 @@ describe('buildWorkflowLintReport notes', () => { * `--blocks '{}' --edges '[]'` used to lint perfectly clean, so a dry run gave * no hint that applying it would erase the workflow. */ + it('reports syntax findings and explicitly distinguishes static validation from execution', async () => { + const report = await buildWorkflowLintReport( + { + blocks: { + renderer: { + ...block('renderer', 'function'), + subBlocks: { + code: { id: 'code', type: 'code', value: 'return /value/workspace/path;' }, + }, + }, + }, + edges: [], + }, + scope + ) + expect(report.codeIssues).toEqual([ + expect.objectContaining({ blockId: 'renderer', message: 'Invalid regular expression flags' }), + ]) + expect(report.checks).toContainEqual( + expect.objectContaining({ name: 'runtime-execution', status: 'skipped' }) + ) + expect(report.checks).toContainEqual( + expect.objectContaining({ name: 'embedded-code-syntax', status: 'complete' }) + ) + }) + it('notes a graph with no blocks', async () => { const report = await buildWorkflowLintReport({ blocks: {}, edges: [] } as never, scope) diff --git a/apps/sim/lib/workflows/editing/lint-report.ts b/apps/sim/lib/workflows/editing/lint-report.ts index b2a850c83c2..c13644b15ca 100644 --- a/apps/sim/lib/workflows/editing/lint-report.ts +++ b/apps/sim/lib/workflows/editing/lint-report.ts @@ -2,13 +2,16 @@ import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' import type { WorkflowState } from '@sim/workflow-types/workflow' import { getTableById } from '@/lib/table/service' +import { collectWorkflowCodeSyntax } from '@/lib/workflows/editing/code-syntax' import { + collectBranchDependentBlockOutputReferences, collectDanglingBlockOutputReferences, collectTableBlockFieldIssues, collectWorkflowFieldIssues, collectWorkflowTableIds, hasWorkflowEntryBlock, lintEditedWorkflowState, + type WorkflowLintCheck, type WorkflowLintReport, type WorkflowLintTableFieldIssue, type WorkflowLintTableSchema, @@ -117,7 +120,29 @@ export async function buildWorkflowLintReport( if (options.requireComplete && !scope.subjectUserId) { throw new Error('Workflow reference checks require a user subject') } + const checks: WorkflowLintCheck[] = [ + { + name: 'graph', + status: 'complete', + detail: 'Checked graph connections, entry blocks, and required ports.', + }, + { + name: 'fields', + status: 'complete', + detail: 'Checked required fields and active canonical modes against block definitions.', + }, + { + name: 'block-output-references', + status: 'partial', + detail: + 'Checked named blocks and statically declared first-level output keys; dynamic output shapes and runtime values are not checked.', + }, + ] + const syntax = await collectWorkflowCodeSyntax(graph.blocks) + const branches = collectBranchDependentBlockOutputReferences(graph) + checks.push(syntax.check, branches.check) const unresolvedReferences: WorkflowLintUnresolvedReference[] = [ + ...branches.issues, ...(options.tables?.unresolvedReferences ?? []), ] @@ -127,7 +152,10 @@ export async function buildWorkflowLintReport( unresolvedReferences.push(...collectDanglingBlockOutputReferences(graph)) if (scope.subjectUserId) { - for (const collect of [collectUnresolvedReferences, collectUnresolvedAgentToolReferences]) { + for (const [name, collect] of [ + ['credential-resource-references', collectUnresolvedReferences], + ['agent-tool-references', collectUnresolvedAgentToolReferences], + ] as const) { try { /** * Reported only through `lint`. These collectors are read-only, so the @@ -144,7 +172,19 @@ export async function buildWorkflowLintReport( options ) unresolvedReferences.push(...references) + checks.push({ + name, + status: 'partial', + detail: + 'Resolved static references for the acting user; dynamic references require runtime values.', + }) } catch (error) { + checks.push({ + name, + status: 'skipped', + detail: + 'Reference lookup failed. Empty findings do not establish that the references are valid; retry validation.', + }) logger.warn('Reference resolution lint failed', { workflowId: scope.workflowId, error: getErrorMessage(error), @@ -158,7 +198,14 @@ export async function buildWorkflowLintReport( } } + if (!scope.subjectUserId) { + for (const name of ['credential-resource-references', 'agent-tool-references'] as const) { + checks.push({ name, status: 'skipped', detail: REFERENCES_UNCHECKED_NOTE }) + } + } + /** Standalone diagnostics have already read tables under application authorization. */ + let tablesChecked = true let tableFieldIssues: WorkflowLintTableFieldIssue[] = options.tables?.tableFieldIssues ?? [] if (!options.tables) { try { @@ -167,6 +214,7 @@ export async function buildWorkflowLintReport( await loadTableSchemasForLint(graph.blocks, scope.workspaceId) ) } catch (error) { + tablesChecked = false logger.warn('Table field lint failed', { workflowId: scope.workflowId, error: getErrorMessage(error), @@ -179,6 +227,21 @@ export async function buildWorkflowLintReport( } } + checks.push( + { + name: 'table-fields', + status: tablesChecked ? 'partial' : 'skipped', + detail: tablesChecked + ? 'Checked literal filter/sort fields against accessible table schemas; dynamic table IDs and expressions require runtime values.' + : 'Table schema lookup failed; retry validation.', + }, + { + name: 'runtime-execution', + status: 'skipped', + detail: + 'No blocks were executed. External service access, dependency availability, resolved inputs, output values, and delivery success are not validated.', + } + ) const graphLint = lintEditedWorkflowState(graph) const notes: string[] = [...(options.tables?.notes ?? [])] @@ -198,6 +261,8 @@ export async function buildWorkflowLintReport( */ return { ...graphLint, + checks, + codeIssues: syntax.issues, fieldIssues: collectWorkflowFieldIssues(graph.blocks), unresolvedReferences, tableFieldIssues, diff --git a/apps/sim/lib/workflows/editing/lint.ts b/apps/sim/lib/workflows/editing/lint.ts index c0da8fa036f..9dc0ed62f7a 100644 --- a/apps/sim/lib/workflows/editing/lint.ts +++ b/apps/sim/lib/workflows/editing/lint.ts @@ -7,6 +7,7 @@ import { getEffectiveBlockOutputs, getResponseFormatOutputs, } from '@/lib/workflows/blocks/block-outputs' +import { validateConditionHandle, validateRouterHandle } from '@/lib/workflows/editing/validation' import { getBlock } from '@/blocks' import { isTriggerBlockType, @@ -21,7 +22,6 @@ import { type InactiveModeValue, } from '@/serializer/index' import type { WorkflowState } from '@/stores/workflows/workflow/types' -import { validateConditionHandle, validateRouterHandle } from './validation' type BlockState = { id?: string @@ -104,7 +104,32 @@ export interface WorkflowLintTableFieldIssue extends WorkflowLintBlockRef { * Aggregate lint report: the graph lint plus the config (Tier 1) and resolution * (Tier 2) checks. Returned in the edit_workflow result and written to lint.json. */ +export interface WorkflowLintCheck { + name: + | 'graph' + | 'fields' + | 'block-output-references' + | 'branch-output-references' + | 'embedded-code-syntax' + | 'credential-resource-references' + | 'agent-tool-references' + | 'table-fields' + | 'runtime-execution' + status: 'complete' | 'partial' | 'skipped' + detail: string +} + +export interface WorkflowLintCodeIssue extends WorkflowLintBlockRef { + field: string + language: 'javascript' + message: string + line?: number + column?: number +} + export interface WorkflowLintReport extends WorkflowLintResult { + checks: WorkflowLintCheck[] + codeIssues: WorkflowLintCodeIssue[] fieldIssues: WorkflowLintFieldIssue[] unresolvedReferences: WorkflowLintUnresolvedReference[] tableFieldIssues: WorkflowLintTableFieldIssue[] @@ -409,6 +434,7 @@ export function collectTableBlockFieldIssues( } type WorkflowLintIssueView = WorkflowLintResult & { + codeIssues?: WorkflowLintCodeIssue[] fieldIssues?: WorkflowLintFieldIssue[] unresolvedReferences?: WorkflowLintUnresolvedReference[] tableFieldIssues?: WorkflowLintTableFieldIssue[] @@ -420,6 +446,7 @@ export function hasWorkflowLintIssues(lint: WorkflowLintIssueView) { lint.emptyOutgoingPorts.length > 0 || lint.invalidBranchPorts.length > 0 || lint.invalidConnectionTargets.length > 0 || + (lint.codeIssues?.length ?? 0) > 0 || (lint.fieldIssues?.length ?? 0) > 0 || (lint.unresolvedReferences?.length ?? 0) > 0 || (lint.tableFieldIssues?.length ?? 0) > 0 @@ -461,6 +488,12 @@ export function formatWorkflowLintMessage(lint: WorkflowLintIssueView) { ) } + if (lint.codeIssues?.length) { + parts.push( + `Invalid embedded JavaScript: ${lint.codeIssues.map((issue) => `"${issue.blockName || issue.blockId}".${issue.field}${issue.line ? `:${issue.line}` : ''} (${issue.message})`).join('; ')}` + ) + } + const fieldIssues = lint.fieldIssues ?? [] const missing = fieldIssues.filter((issue) => issue.missingRequiredFields.length > 0) if (missing.length > 0) { @@ -728,3 +761,113 @@ export function collectDanglingBlockOutputReferences( } return findings } + +/** + * Finds references crossing mutually exclusive condition/router paths. This is advisory: + * guarded expressions may intentionally handle absent outputs. Subflows and large graphs + * are explicitly skipped rather than pretending to prove their execution ordering. + */ +export function collectBranchDependentBlockOutputReferences( + graph: Pick +): { issues: WorkflowLintUnresolvedReference[]; check: WorkflowLintCheck } { + const blocks = graph.blocks as Record + const branches = Object.entries(blocks).filter( + ([, block]) => block.type === 'condition' || block.type === 'router_v2' + ) + const check: WorkflowLintCheck = { + name: 'branch-output-references', + status: 'partial', + detail: + 'Checks explicit condition/router paths for outputs unavailable on another connected branch. Guards inside expressions, runtime routing, and subflow execution are not proven.', + } + if ( + Object.keys(blocks).length > 500 || + graph.edges.length > 5000 || + branches.length > 30 || + Object.values(blocks).some((block) => block.type === 'loop' || block.type === 'parallel') + ) { + return { + issues: [], + check: { + ...check, + status: 'skipped', + detail: + 'Branch-output analysis skipped for subflows or graphs exceeding 500 blocks, 5000 edges, or 30 branch blocks. Runtime output availability was not checked.', + }, + } + } + const outgoing = new Map() + const targetsByKey = new Map() + for (const [id, block] of Object.entries(blocks)) { + targetsByKey.set(id, id) + if (block.name) targetsByKey.set(normalizeName(block.name), id) + } + for (const edge of graph.edges) { + if (!blocks[edge.source] || !blocks[edge.target]) continue + const targets = outgoing.get(edge.source) ?? [] + targets.push(edge.target) + outgoing.set(edge.source, targets) + } + const paths = branches.flatMap(([branchId, branch]) => { + const rootsByHandle = new Map() + for (const edge of graph.edges) { + if ( + edge.source !== branchId || + !edge.sourceHandle || + edge.sourceHandle === 'error' || + !blocks[edge.target] + ) + continue + const roots = rootsByHandle.get(edge.sourceHandle) ?? [] + roots.push(edge.target) + rootsByHandle.set(edge.sourceHandle, roots) + } + if (rootsByHandle.size < 2) return [] + const reachability = [...rootsByHandle].map(([handle, roots]) => { + const reached = new Set() + const pending = [...roots] + while (pending.length) { + const id = pending.pop()! + if (id === branchId || reached.has(id)) continue + reached.add(id) + pending.push(...(outgoing.get(id) ?? [])) + } + return { handle, reached } + }) + return [{ branchId, branch, reachability }] + }) + const issues: WorkflowLintUnresolvedReference[] = [] + for (const [blockId, block] of Object.entries(blocks)) { + for (const [field, subBlock] of Object.entries(block.subBlocks ?? {})) { + const leaves: string[] = [] + collectStringLeaves(subBlock?.value, leaves) + const reported = new Set() + for (const leaf of leaves) { + for (const token of referenceCandidates(leaf, field === 'code')) { + if (!REF_TOKEN_SHAPE.test(token)) continue + const head = token.split('.')[0] ?? '' + if ((SPECIAL_REFERENCE_PREFIXES as readonly string[]).includes(head)) continue + const targetId = targetsByKey.get(head) ?? targetsByKey.get(normalizeName(head)) + if (!targetId || targetId === blockId || reported.has(token)) continue + for (const { branchId, branch, reachability } of paths) { + if (!reachability.some((path) => path.reached.has(targetId))) continue + const bypass = reachability.find( + (path) => path.reached.has(blockId) && !path.reached.has(targetId) + ) + if (!bypass) continue + issues.push({ + ...blockRef(blockId, block), + field, + value: `<${token}>`, + kind: 'block-output', + reason: `branch-dependent: "${branch.name || branchId}" can reach this block through "${bypass.handle}" without running "${blocks[targetId].name || targetId}". Guard the missing output or move the consuming block onto the producing branch.`, + }) + reported.add(token) + break + } + } + } + } + } + return { issues, check } +} diff --git a/apps/sim/lib/workflows/executor/enqueue-execution.integration.ts b/apps/sim/lib/workflows/executor/enqueue-execution.integration.ts new file mode 100644 index 00000000000..f672bb53345 --- /dev/null +++ b/apps/sim/lib/workflows/executor/enqueue-execution.integration.ts @@ -0,0 +1,233 @@ +/** Real job JSON persistence and immutable deployment reads; billing admission and block execution are fixtures. */ +import { db } from '@sim/db' +import { asyncJobs, user, workflow, workflowDeploymentVersion, workspace } from '@sim/db/schema' +import { generateId } from '@sim/utils/id' +import { eq, inArray } from 'drizzle-orm' +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' + +const boundary = vi.hoisted(() => ({ preprocess: vi.fn(), execute: vi.fn() })) +vi.mock('@/lib/core/async-jobs', () => ({ + getJobQueue: async () => queue, + /** Delay delivery so the deployment can change while the serialized job is pending. */ + shouldExecuteInline: () => false, +})) +vi.mock('@/lib/execution/preprocessing', () => ({ preprocessExecution: boundary.preprocess })) +vi.mock('@/lib/workflows/executor/execution-core', () => ({ + executeWorkflowCore: boundary.execute, + wasExecutionFinalizedByCore: () => false, +})) +vi.mock('@/lib/billing/calculations/usage-reservation', () => ({ + refreshExecutionSlotExpiry: async () => true, + releaseExecutionSlot: async () => {}, +})) +vi.mock('@/lib/logs/execution/logging-session', () => ({ + LoggingSession: class { + setTrustedExecutionCorrelation() {} + setExecutionDeadlineAt() {} + async waitForPostExecution() {} + async safeCompleteWithError() {} + projectDiagnosticError() { + return {} + } + }, +})) +vi.mock('@/lib/workflows/executor/pause-persistence', () => ({ + handlePostExecutionPauseState: async () => {}, +})) +vi.mock('@/lib/uploads/utils/user-file-base64.server', () => ({ + cleanupExecutionBase64Cache: async () => {}, +})) + +import { DatabaseJobQueue } from '@/lib/core/async-jobs/backends/database' +import { enqueueWorkflowExecution } from '@/lib/workflows/executor/enqueue-execution' +import { executeWorkflowJob, type WorkflowExecutionPayload } from '@/background/workflow-execution' +import type { ExecutionSnapshot } from '@/executor/execution/snapshot' +import type { WorkflowState } from '@/stores/workflows/workflow/types' + +const queue = new DatabaseJobQueue() +const userId = generateId() +const workspaceId = generateId() +const principal = { kind: 'personal_api_key' as const, userId, keyId: generateId() } +const jobIds: string[] = [] +let workflowId: string +let versionId: string +let entryId: string +const billingAttribution = { + actorUserId: userId, + workspaceId, + organizationId: null, + billedAccountUserId: userId, + billingEntity: { type: 'user' as const, id: userId }, + billingPeriod: { start: '2026-09-01T00:00:00.000Z', end: '2026-10-01T00:00:00.000Z' }, + payerSubscription: null, +} + +function state(name: string, variables: WorkflowState['variables']): WorkflowState { + return { + blocks: { + [entryId]: { + id: entryId, + type: 'start_trigger', + name, + enabled: true, + position: { x: 0, y: 0 }, + subBlocks: {}, + outputs: {}, + }, + }, + edges: [], + loops: {}, + parallels: {}, + variables, + } +} + +async function enqueue(deploymentVersionId: string | undefined = versionId) { + const result = await enqueueWorkflowExecution({ + requestId: generateId(), + workflowId, + principal, + userId, + billingAttribution, + workspaceId, + input: { source: 'request' }, + triggerType: 'api', + triggerBlockId: entryId, + deploymentVersionId, + executionId: generateId(), + executionTimeoutMs: 30_000, + enforceCredentialAccess: true, + }) + if (result.outcome !== 'queued') throw new Error(`Fixture enqueue failed: ${result.outcome}`) + jobIds.push(result.jobId) + /** Re-read through a fresh queue instance: the worker receives database JSON, not the original object. */ + const persisted = await new DatabaseJobQueue().getJob(result.jobId) + if (!persisted) throw new Error('Queued job was not persisted') + return persisted.payload as WorkflowExecutionPayload +} + +describe('queued workflow deployment pinning through PostgreSQL', () => { + beforeAll(async () => { + const now = new Date() + await db.insert(user).values({ + id: userId, + name: 'Queued execution fixture', + email: `${userId}@workflow.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + await db.insert(workspace).values({ + id: workspaceId, + name: 'Queued execution fixture', + ownerId: userId, + billedAccountUserId: userId, + }) + }) + + beforeEach(async () => { + workflowId = generateId() + versionId = generateId() + entryId = generateId() + await db.insert(workflow).values({ + id: workflowId, + userId, + workspaceId, + name: `Queued workflow ${workflowId}`, + lastSynced: new Date(), + createdAt: new Date(), + updatedAt: new Date(), + isDeployed: true, + variables: { source: { id: 'source', name: 'source', type: 'string', value: 'draft' } }, + }) + boundary.preprocess.mockImplementation(async () => { + const [record] = await db.select().from(workflow).where(eq(workflow.id, workflowId)) + return { success: true, actorUserId: userId, workflowRecord: record, billingAttribution } + }) + boundary.execute.mockResolvedValue({ success: true, status: 'success', output: {} }) + }) + + afterAll(async () => { + try { + if (jobIds.length) await db.delete(asyncJobs).where(inArray(asyncJobs.id, jobIds)) + await db.delete(workspace).where(eq(workspace.id, workspaceId)) + await db.delete(user).where(eq(user.id, userId)) + } finally { + await db.$client.end() + } + }) + + it.each([true, false])( + 'retains admitted state and entry after cutover, variables=%s', + async (hasVariables) => { + const variables: NonNullable = hasVariables + ? { source: { id: 'source', name: 'source', type: 'string', value: 'admitted' } } + : {} + await db.insert(workflowDeploymentVersion).values({ + id: versionId, + workflowId, + version: 1, + isActive: true, + createdBy: userId, + state: state('Admitted entry', variables), + }) + const payload = await enqueue() + await db + .update(workflowDeploymentVersion) + .set({ isActive: false }) + .where(eq(workflowDeploymentVersion.id, versionId)) + await db.insert(workflowDeploymentVersion).values({ + id: generateId(), + workflowId, + version: 2, + isActive: true, + createdBy: userId, + state: state('Replacement entry', { + source: { id: 'source', name: 'source', type: 'string', value: 'new-active' }, + }), + }) + + await executeWorkflowJob(payload) + + const snapshot: ExecutionSnapshot = boundary.execute.mock.calls[0][0].snapshot + expect(snapshot.metadata.triggerBlockId).toBe(entryId) + expect(snapshot.metadata.workflowStateOverride).toMatchObject({ + deploymentVersionId: versionId, + blocks: { [entryId]: { name: 'Admitted entry' } }, + }) + expect(snapshot.workflowVariables).toEqual(variables) + expect(snapshot.metadata.principal).toEqual(principal) + expect(payload).not.toHaveProperty('workflowStateOverride') + } + ) + + it.each(['missing', 'other-workflow'] as const)( + 'refuses a %s pinned version before execution', + async (kind) => { + if (kind === 'other-workflow') { + const foreignWorkflowId = generateId() + await db.insert(workflow).values({ + id: foreignWorkflowId, + userId, + workspaceId, + name: `Other workflow ${foreignWorkflowId}`, + lastSynced: new Date(), + createdAt: new Date(), + updatedAt: new Date(), + isDeployed: true, + }) + await db.insert(workflowDeploymentVersion).values({ + id: versionId, + workflowId: foreignWorkflowId, + version: 1, + isActive: true, + createdBy: userId, + state: state('Foreign entry', {}), + }) + } + const payload = await enqueue() + await expect(executeWorkflowJob(payload)).rejects.toThrow('was not found for workflow') + expect(boundary.execute).not.toHaveBeenCalled() + } + ) +}) diff --git a/apps/sim/lib/workflows/executor/enqueue-execution.ts b/apps/sim/lib/workflows/executor/enqueue-execution.ts index 0136fcbe08b..70d290a47be 100644 --- a/apps/sim/lib/workflows/executor/enqueue-execution.ts +++ b/apps/sim/lib/workflows/executor/enqueue-execution.ts @@ -31,6 +31,8 @@ export interface EnqueueWorkflowExecutionParams { input: unknown triggerType: CoreTriggerType triggerBlockId?: string + /** Immutable version selected while validating the deployment entry point. */ + deploymentVersionId?: string executionId: string copilotToolCallId?: string callChain?: string[] @@ -79,6 +81,7 @@ export async function enqueueWorkflowExecution( input, triggerType, triggerBlockId, + deploymentVersionId, executionId, copilotToolCallId, callChain, @@ -113,6 +116,7 @@ export async function enqueueWorkflowExecution( input, triggerType, triggerBlockId, + deploymentVersionId, executionId, requestId, correlation, diff --git a/apps/sim/lib/workflows/executor/execute-service.ts b/apps/sim/lib/workflows/executor/execute-service.ts index 5f6d7363863..1950468d131 100644 --- a/apps/sim/lib/workflows/executor/execute-service.ts +++ b/apps/sim/lib/workflows/executor/execute-service.ts @@ -16,6 +16,7 @@ import { preprocessExecution } from '@/lib/execution/preprocessing' import { LoggingSession } from '@/lib/logs/execution/logging-session' import { MAX_MCP_WORKFLOW_RESPONSE_BYTES } from '@/lib/mcp/constants' import { hydrateUserFilesWithBase64 } from '@/lib/uploads/utils/user-file-base64.server' +import { getCustomBlockRowsForWorkspace } from '@/lib/workflows/custom-blocks/operations' import { enqueueWorkflowExecution } from '@/lib/workflows/executor/enqueue-execution' import { executeWorkflow } from '@/lib/workflows/executor/execute-workflow' import { executeWorkflowCore } from '@/lib/workflows/executor/execution-core' @@ -26,6 +27,7 @@ import { releaseExecutionIdClaim, } from '@/lib/workflows/executor/execution-id-claim' import { handlePostExecutionPauseState } from '@/lib/workflows/executor/pause-persistence' +import { validateStopAfterBlock } from '@/lib/workflows/executor/stop-after-block' import { loadDeployedWorkflowState, loadWorkflowDeploymentVersionState, @@ -38,6 +40,7 @@ import { createStreamingResponse, } from '@/lib/workflows/streaming/streaming' import { workflowHasResponseBlock } from '@/lib/workflows/utils' +import { withCustomBlockOverlay } from '@/blocks/custom/server-overlay' import { ExecutionSnapshot } from '@/executor/execution/snapshot' import type { ExecutionMetadata, SerializableExecutionState } from '@/executor/execution/types' import type { BlockLog, NormalizedBlockOutput } from '@/executor/types' @@ -87,6 +90,7 @@ export interface ExecuteWorkflowServiceParams { includeFileBase64?: boolean base64MaxBytes?: number selectedOutputs?: string[] + stopAfterBlockId?: string /** MCP behavior: 413-style failure instead of large-value refs in output. */ rejectLargeInlineOutput?: boolean /** Which rate-limit bucket preprocessing debits. */ @@ -261,6 +265,7 @@ export async function executeWorkflowService( includeFileBase64 = true, base64MaxBytes, selectedOutputs = [], + stopAfterBlockId, rejectLargeInlineOutput = false, rateLimitCounter = 'sync', requestedTimeoutSeconds, @@ -283,6 +288,13 @@ export async function executeWorkflowService( statusCode: 400, }) } + if (stopAfterBlockId && mode === 'async') { + return failure({ + kind: 'precheck', + message: 'stopAfterBlockId does not support async mode', + statusCode: 400, + }) + } if (useDraftState && deploymentVersionId) { throw new Error('Manual execution cannot be pinned to a deployment version') } @@ -430,6 +442,8 @@ export async function executeWorkflowService( workspaceId, input, triggerType, + triggerBlockId, + deploymentVersionId, executionId, callChain, enforceCredentialAccess: useAuthenticatedUserAsActor, @@ -459,6 +473,7 @@ export async function executeWorkflowService( const processedInput = input let workflowVariables: Record = {} let workflowBlocks: Record = {} + let workflowStateOverride: ExecutionMetadata['workflowStateOverride'] try { const workflowData = useDraftState ? await loadWorkflowFromNormalizedTables(workflowId) @@ -486,8 +501,13 @@ export async function executeWorkflowService( ('variables' in workflowData ? (workflowData.variables as Record | undefined) : undefined) ?? - (workflow.variables as Record | null) ?? + (deploymentVersionId + ? undefined + : (workflow.variables as Record | null)) ?? {} + if (deploymentVersionId || stopAfterBlockId) { + workflowStateOverride = { ...workflowData, variables: workflowVariables } + } } else { workflowVariables = (workflow.variables as Record | null) ?? {} } @@ -513,6 +533,31 @@ export async function executeWorkflowService( }) } + if (stopAfterBlockId) { + const customBlocks = await getCustomBlockRowsForWorkspace(workspaceId) + try { + if (!workflowStateOverride) + throw new Error('No saved workflow state is available for stopAfterBlockId') + const state = workflowStateOverride + await withCustomBlockOverlay(customBlocks, async () => + validateStopAfterBlock( + { + blocks: state.blocks, + edges: state.edges, + loops: state.loops ?? {}, + parallels: state.parallels ?? {}, + }, + stopAfterBlockId, + triggerBlockId, + runFromBlock?.startBlockId + ) + ) + } catch (error) { + await releaseExecutionSlot(executionId) + return failure({ kind: 'input', message: getErrorMessage(error), statusCode: 400 }) + } + } + /** * Validated before the run starts, for the sync path as much as the stream: * a selector whose block does not exist is a caller mistake to answer with a @@ -587,6 +632,8 @@ export async function executeWorkflowService( isSecureMode: false, workflowTriggerType: triggerType, triggerBlockId, + workflowStateOverride, + stopAfterBlockId, useDraftState, runFromBlock, onStream, @@ -637,6 +684,7 @@ export async function executeWorkflowService( workflowUserId: workflow.userId, triggerType, triggerBlockId, + workflowStateOverride, useDraftState, startTime: new Date().toISOString(), isClientSession: false, @@ -689,6 +737,7 @@ export async function executeWorkflowService( base64MaxBytes, abortSignal: timeoutController.signal, runFromBlock, + stopAfterBlockId, }) await handlePostExecutionPauseState({ result, workflowId, executionId, loggingSession }) diff --git a/apps/sim/lib/workflows/executor/stop-after-block.test.ts b/apps/sim/lib/workflows/executor/stop-after-block.test.ts new file mode 100644 index 00000000000..9fba48f094a --- /dev/null +++ b/apps/sim/lib/workflows/executor/stop-after-block.test.ts @@ -0,0 +1,99 @@ +import { + blocksMock, + createBlock, + createFunctionBlock, + createStarterBlock, + toolsMetadataMock, + toolsUtilsMock, +} from '@sim/testing' +import { describe, expect, it, vi } from 'vitest' +import { validateStopAfterBlock } from '@/lib/workflows/executor/stop-after-block' +import type { WorkflowState } from '@/stores/workflows/workflow/types' + +vi.mock('@/blocks', () => blocksMock) +vi.mock('@/tools/utils', () => toolsUtilsMock) +vi.mock('@/tools/metadata', () => toolsMetadataMock) + +function state(): Pick { + return { + blocks: { + start: createStarterBlock({ id: 'start' }), + formatter: createFunctionBlock({ id: 'formatter' }), + publish: createFunctionBlock({ id: 'publish' }), + detached: createFunctionBlock({ id: 'detached' }), + }, + edges: [ + { id: 'a', source: 'start', target: 'formatter' }, + { id: 'b', source: 'formatter', target: 'publish' }, + ], + loops: {}, + parallels: {}, + } +} + +describe('stop-after target validation with the real serializer and DAG', () => { + it('accepts a reachable top-level target without mutating saved state', () => { + const graph = state() + const before = structuredClone(graph) + expect(() => validateStopAfterBlock(graph, 'formatter', 'start')).not.toThrow() + expect(graph).toEqual(before) + }) + + it('rejects missing, disabled and unreachable targets', () => { + const graph = state() + expect(() => validateStopAfterBlock(graph, 'missing', 'start')).toThrow('enabled block') + expect(() => validateStopAfterBlock(graph, 'detached', 'start')).toThrow('not reachable') + graph.blocks.formatter.enabled = false + expect(() => validateStopAfterBlock(graph, 'formatter', 'start')).toThrow('enabled block') + }) + + it('requires partial-run stops to be in the rerun set, including disconnected partial runs', () => { + const graph = state() + expect(() => validateStopAfterBlock(graph, 'formatter', undefined, 'publish')).toThrow( + 'not reachable' + ) + expect(() => validateStopAfterBlock(graph, 'publish', undefined, 'formatter')).not.toThrow() + expect(() => validateStopAfterBlock(graph, 'detached', undefined, 'detached')).not.toThrow() + }) + + it('requires the resolved entry instead of selecting another trigger by graph order', () => { + const graph = state() + graph.blocks = { + webhook: createBlock({ id: 'webhook', type: 'webhook' }), + ...graph.blocks, + } + graph.edges.push({ id: 'c', source: 'webhook', target: 'detached' }) + + expect(() => validateStopAfterBlock(graph, 'formatter')).toThrow('resolved trigger') + expect(() => validateStopAfterBlock(graph, 'detached')).toThrow('resolved trigger') + expect(() => validateStopAfterBlock(graph, 'formatter', 'start')).not.toThrow() + expect(() => validateStopAfterBlock(graph, 'detached', 'start')).toThrow('not reachable') + expect(() => validateStopAfterBlock(graph, 'detached', 'webhook')).not.toThrow() + }) + + it.each(['loop', 'parallel'] as const)( + 'allows the %s container and rejects its interior', + (kind) => { + const graph = state() + graph.blocks.container = createBlock({ id: 'container', type: kind }) + graph.blocks.formatter.data = { parentId: 'container', extent: 'parent' } + graph.edges = [ + { id: 'a', source: 'start', target: 'container' }, + { id: 'b', source: 'container', target: 'formatter', sourceHandle: `${kind}-start-source` }, + { id: 'c', source: 'container', target: 'publish', sourceHandle: `${kind}-end-source` }, + ] + if (kind === 'loop') + graph.loops = { + container: { id: 'container', nodes: ['formatter'], iterations: 2, loopType: 'for' }, + } + else + graph.parallels = { + container: { id: 'container', nodes: ['formatter'], count: 2, parallelType: 'count' }, + } + expect(() => validateStopAfterBlock(graph, 'container', 'start')).not.toThrow() + expect(() => validateStopAfterBlock(graph, 'formatter', 'start')).toThrow( + /inside a loop or parallel|not reachable/ + ) + } + ) +}) diff --git a/apps/sim/lib/workflows/executor/stop-after-block.ts b/apps/sim/lib/workflows/executor/stop-after-block.ts new file mode 100644 index 00000000000..4a450420386 --- /dev/null +++ b/apps/sim/lib/workflows/executor/stop-after-block.ts @@ -0,0 +1,55 @@ +import { mergeSubblockStateWithValues } from '@sim/workflow-persistence/subblocks' +import { DAGBuilder } from '@/executor/dag/builder' +import { + computeExecutionSets, + resolveContainerToSentinelStart, +} from '@/executor/utils/run-from-block' +import { Serializer } from '@/serializer' +import type { WorkflowState } from '@/stores/workflows/workflow/types' + +/** Checks the stop target against the caller's resolved entry, never a DAG-selected fallback. */ +export function validateStopAfterBlock( + state: Pick, + blockId: string, + triggerBlockId?: string, + fromBlockId?: string +): void { + if (!triggerBlockId && !fromBlockId) { + throw new Error('stopAfterBlockId requires a resolved trigger or partial-run starting block.') + } + const block = state.blocks[blockId] + if (!block || block.enabled === false) { + throw new Error( + `stopAfterBlockId "${blockId}" must name an enabled block in the selected workflow state.` + ) + } + const serialized = new Serializer().serializeWorkflow( + mergeSubblockStateWithValues(state.blocks), + state.edges, + state.loops, + state.parallels, + true + ) + const dag = new DAGBuilder().build(serialized, { + triggerBlockId, + includeAllBlocks: Boolean(fromBlockId), + }) + const sentinelId = resolveContainerToSentinelStart(blockId, dag) + const nodeId = sentinelId ?? blockId + const node = dag.nodes.get(nodeId) + if (!node || (fromBlockId && !computeExecutionSets(dag, fromBlockId).dirtySet.has(nodeId))) { + throw new Error(`stopAfterBlockId "${blockId}" is not reachable from the selected entry point.`) + } + if ( + node.metadata.isLoopNode || + node.metadata.isParallelBranch || + [...dag.loopConfigs].some(([id, config]) => id !== blockId && config.nodes.includes(blockId)) || + [...dag.parallelConfigs].some( + ([id, config]) => id !== blockId && config.nodes.includes(blockId) + ) + ) { + throw new Error( + `stopAfterBlockId "${blockId}" is inside a loop or parallel. Choose its top-level container to stop after all iterations complete.` + ) + } +} diff --git a/apps/sim/lib/workflows/operations/export-workflow.test.ts b/apps/sim/lib/workflows/operations/export-workflow.test.ts index 2efccf9a654..67969812f7b 100644 --- a/apps/sim/lib/workflows/operations/export-workflow.test.ts +++ b/apps/sim/lib/workflows/operations/export-workflow.test.ts @@ -69,7 +69,10 @@ vi.mock('@/blocks/registry', () => ({ }, })) +import { v2ExportWorkflowContract } from '@/lib/api/contracts/v2/workflows' import { buildWorkflowExportPayload } from '@/lib/workflows/operations/export-workflow' +import { parseWorkflowJson } from '@/lib/workflows/operations/import-export' +import { resolveImportedMetadata } from '@/lib/workflows/operations/import-workflow' import { buildWorkflowImportPlan } from '@/lib/workflows/references/import-plan' /** @@ -404,4 +407,28 @@ describe('buildWorkflowExportPayload with includeWorkspaceBindings', () => { expect(sharing?.state.blocks.lookup.subBlocks.credential.value).toBeNull() expect(sameWorkspace?.state.blocks.lookup.subBlocks.credential.value).toBeNull() }) + it.each([false, true])( + 'round trips the diagnostic export envelope with references=%s', + async (includeReferences) => { + const payload = await buildWorkflowExportPayload(record, { + includeReferences, + includeWorkspaceBindings: true, + }) + const response = v2ExportWorkflowContract.response.schema.parse({ + data: { + ...payload, + representation: 'portable-export', + warnings: ['Portable export; use state get for in-place edits.'], + workflow: { ...payload!.workflow, folderPath: '/' }, + }, + }) + const parsed = parseWorkflowJson(JSON.stringify(response)) + expect(parsed.errors).toEqual([]) + const imported = Object.values(parsed.data!.blocks).find((block) => block.name === 'Lookup')! + expect(imported.subBlocks.tableSelector.value).toBe('tbl_239e870374c14d4a89923175a7b10648') + expect(imported.subBlocks.credential.value).toBeNull() + expect(resolveImportedMetadata(response)).toMatchObject({ name: record.name }) + expect(response.data.referenceManifest !== undefined).toBe(includeReferences) + } + ) }) diff --git a/apps/sim/lib/workflows/persistence/utils.test.ts b/apps/sim/lib/workflows/persistence/utils.test.ts index 4883e9f0efa..898c7262310 100644 --- a/apps/sim/lib/workflows/persistence/utils.test.ts +++ b/apps/sim/lib/workflows/persistence/utils.test.ts @@ -311,6 +311,37 @@ describe('Database Helpers', () => { }) describe('loadWorkflowFromNormalizedTables', () => { + it.each([false, true])( + 'normalizes legacy blocks with persistMigrations=%s', + async (persistMigrations) => { + queueLoadFixtures({ + blocks: [ + toDbBlock( + createStarterBlock({ + id: 'start', + subBlocks: legacySubBlocks({ + _removed_oldSecret: { + id: '_removed_oldSecret', + type: 'short-input', + value: 'old', + }, + }), + }), + mockWorkflowId + ), + ], + }) + const result = await dbHelpers.loadWorkflowFromNormalizedTables(mockWorkflowId, undefined, { + persistMigrations, + }) + expect(result?.blocks.start.subBlocks).not.toHaveProperty('_removed_oldSecret') + await Promise.resolve() + expect(dbChainMockFns.update).toHaveBeenCalledTimes(persistMigrations ? 1 : 0) + expect(dbChainMockFns.insert).not.toHaveBeenCalled() + expect(dbChainMockFns.transaction).not.toHaveBeenCalled() + } + ) + it.each(['for', 'forEach', 'while', 'doWhile'] as const)( 'preserves valid block counts and expressions for %s loops even when subflow counts differ', async (loopType) => { @@ -805,21 +836,6 @@ describe('Database Helpers', () => { expect(mockSanitizeAgentToolsInBlocks).toHaveBeenCalledTimes(2) }) - it('loads an admitted immutable deployment version even after a later cutover', async () => { - const state = buildDeployedState() - queueTableRows(schemaMock.workflowDeploymentVersion, [{ id: 'dv-admitted', state }]) - - const result = await dbHelpers.loadWorkflowDeploymentVersionState( - 'wf-admitted', - 'dv-admitted', - 'workspace-1' - ) - - expect(result.deploymentVersionId).toBe('dv-admitted') - expect(result.blocks).toEqual(state.blocks) - expect(dbChainMockFns.where).toHaveBeenCalledTimes(1) - }) - it('invalidateDeployedStateCache(id) forces a rebuild on the next call', async () => { queueActiveVersion('dv-inv', buildDeployedState()) queueActiveVersion('dv-inv', buildDeployedState()) diff --git a/apps/sim/lib/workflows/persistence/utils.ts b/apps/sim/lib/workflows/persistence/utils.ts index aeece86a6b7..76d3eee9516 100644 --- a/apps/sim/lib/workflows/persistence/utils.ts +++ b/apps/sim/lib/workflows/persistence/utils.ts @@ -558,7 +558,8 @@ async function migrateCredentialIds( */ export async function loadWorkflowFromNormalizedTables( workflowId: string, - externalTx?: DbOrTx + externalTx?: DbOrTx, + options: { persistMigrations?: boolean } = {} ): Promise { const raw = await loadWorkflowFromNormalizedTablesRaw(workflowId, externalTx) if (!raw) return null @@ -569,7 +570,7 @@ export async function loadWorkflowFromNormalizedTables( externalTx ?? db ) - if (migrated) { + if (migrated && options.persistMigrations !== false) { // Deliberate fire-and-forget persistence on the global pool: it must not // join (or block) a read transaction this load may be running inside, so // it escapes the transaction context instead of tripping the wire. @@ -612,7 +613,7 @@ export async function loadWorkflowDeploymentSnapshot( ): Promise { const loadSnapshot = async (tx: DbOrTx) => { const [normalizedData, [workflowRecord]] = await Promise.all([ - loadWorkflowFromNormalizedTables(workflowId, tx), + loadWorkflowFromNormalizedTables(workflowId, tx, { persistMigrations: false }), tx .select({ variables: workflow.variables }) .from(workflow) diff --git a/apps/sim/lib/workflows/queries.ts b/apps/sim/lib/workflows/queries.ts index f989b3e4d49..13f3bccfe3e 100644 --- a/apps/sim/lib/workflows/queries.ts +++ b/apps/sim/lib/workflows/queries.ts @@ -122,13 +122,14 @@ export async function listWorkspaceWorkflows(input: ListWorkspaceWorkflowsInput) /** * Loads one consistent workflow record + normalized definition snapshot. Both * the editor route and public metadata route derive their own response from - * this read rather than issuing independent block/workflow queries. + * this read rather than issuing independent block/workflow queries. Legacy + * blocks are normalized in memory; reads never schedule migration writes. */ export async function loadWorkflowReadSnapshot(workflowId: string, workspaceId: string) { return db.transaction(async (tx) => { await tx.execute(sql`SET TRANSACTION ISOLATION LEVEL REPEATABLE READ`) const [normalizedData, [workflowRecord]] = await Promise.all([ - loadWorkflowFromNormalizedTables(workflowId, tx), + loadWorkflowFromNormalizedTables(workflowId, tx, { persistMigrations: false }), tx .select() .from(workflow) diff --git a/apps/sim/lib/workflows/triggers/deployment-entry.test.ts b/apps/sim/lib/workflows/triggers/deployment-entry.test.ts new file mode 100644 index 00000000000..c53bfc2a51f --- /dev/null +++ b/apps/sim/lib/workflows/triggers/deployment-entry.test.ts @@ -0,0 +1,65 @@ +import { createBlock } from '@sim/testing' +import { describe, expect, it } from 'vitest' +import { resolveDeploymentTriggerBlockId } from '@/lib/workflows/triggers/deployment-entry' +import type { BlockState } from '@/stores/workflows/workflow/types' + +function blocks(...types: string[]): Record { + return Object.fromEntries( + types.map((type, index) => [`block-${index}`, createBlock({ id: `block-${index}`, type })]) + ) +} + +describe('deployed workflow entry selection', () => { + it.each([ + 'schedule', + 'starter', + 'start_trigger', + 'api_trigger', + 'manual_trigger', + 'chat_trigger', + ])('resolves the sole enabled %s entry', (type) => { + expect(resolveDeploymentTriggerBlockId(blocks(type, 'function'))).toBe('block-0') + }) + + it('preserves an unambiguous API entry in a mixed deployment', () => { + expect(resolveDeploymentTriggerBlockId(blocks('schedule', 'api_trigger', 'chat_trigger'))).toBe( + 'block-1' + ) + }) + + it('allows an explicit Schedule entry and rejects non-trigger selections', () => { + const graph = blocks('schedule', 'api_trigger', 'function') + expect(resolveDeploymentTriggerBlockId(graph, 'block-0')).toBe('block-0') + expect(() => resolveDeploymentTriggerBlockId(graph, 'block-2')).toThrow('Available triggers:') + expect(() => resolveDeploymentTriggerBlockId(graph, 'draft-only')).toThrow('active deployment') + }) + + it.each([ + { types: ['api_trigger', 'api_trigger'], expected: 'block-0' }, + { types: ['input_trigger', 'api_trigger', 'start_trigger'], expected: 'block-2' }, + { types: ['starter', 'input_trigger', 'api_trigger'], expected: 'block-2' }, + ])('preserves the existing default API entry for $types', ({ types, expected }) => { + expect(resolveDeploymentTriggerBlockId(blocks(...types))).toBe(expected) + }) + + it('allows explicit selection to override the default API entry', () => { + expect(resolveDeploymentTriggerBlockId(blocks('api_trigger', 'api_trigger'), 'block-1')).toBe( + 'block-1' + ) + }) + + it('rejects ambiguous non-API entries with an actionable selector', () => { + expect(() => resolveDeploymentTriggerBlockId(blocks('schedule', 'schedule'))).toThrow( + 'Set run.entry' + ) + }) + + it('excludes disabled triggers and reports no runnable deployment', () => { + const graph = blocks('schedule', 'function') + graph['block-0'].enabled = false + expect(() => resolveDeploymentTriggerBlockId(graph)).toThrow('no enabled runnable trigger') + expect(() => resolveDeploymentTriggerBlockId(graph, 'block-0')).toThrow( + 'not an enabled trigger' + ) + }) +}) diff --git a/apps/sim/lib/workflows/triggers/deployment-entry.ts b/apps/sim/lib/workflows/triggers/deployment-entry.ts new file mode 100644 index 00000000000..9717b2eeffa --- /dev/null +++ b/apps/sim/lib/workflows/triggers/deployment-entry.ts @@ -0,0 +1,37 @@ +import { OrchestrationError } from '@/lib/core/orchestration/types' +import { resolveStartCandidates } from '@/lib/workflows/triggers/triggers' +import type { BlockState } from '@/stores/workflows/workflow/types' + +/** Selects from the deployed graph, preserving the executor's existing API entry priority. */ +export function resolveDeploymentTriggerBlockId( + blocks: Record, + requestedBlockId?: string +): string { + const api = resolveStartCandidates(blocks, { execution: 'api' }) + const candidates = [ + ...new Map( + [ + ...resolveStartCandidates(blocks, { execution: 'manual' }), + ...resolveStartCandidates(blocks, { execution: 'chat' }), + ].map((candidate) => [candidate.blockId, candidate]) + ).values(), + ] + const available = candidates + .map(({ blockId, block }) => `${blockId} (${block.name || block.type})`) + .join(', ') + if (requestedBlockId) { + if (candidates.some(({ blockId }) => blockId === requestedBlockId)) return requestedBlockId + throw new OrchestrationError( + 'validation', + `run.entry.blockId "${requestedBlockId}" is not an enabled trigger in the active deployment. Available triggers: ${available || 'none'}.` + ) + } + if (api.length > 0) return api[0].blockId + if (candidates.length === 1) return candidates[0].blockId + throw new OrchestrationError( + 'validation', + candidates.length === 0 + ? 'The active deployment has no enabled runnable trigger. Add a trigger and redeploy before running.' + : `The active deployment has multiple runnable entry points. Set run.entry to {"type":"trigger","blockId":""} to choose one. Available triggers: ${available}.` + ) +} diff --git a/apps/sim/lib/workspaces/__integration__/http-cli.integration.ts b/apps/sim/lib/workspaces/__integration__/http-cli.integration.ts index 90d4df66033..50da84d9f90 100644 --- a/apps/sim/lib/workspaces/__integration__/http-cli.integration.ts +++ b/apps/sim/lib/workspaces/__integration__/http-cli.integration.ts @@ -9,6 +9,7 @@ import { permissions, user, workflow, + workflowBlocks, workspace, workspaceOperationReceipt, } from '@sim/db/schema' @@ -17,6 +18,7 @@ import { eq } from 'drizzle-orm' import { NextRequest } from 'next/server' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { hashApiKey } from '@/lib/api-key/crypto' +import { POST as workflowOperations } from '@/app/api/v2/workflows/[workflowId]/operations/route' import { POST as importPreview } from '@/app/api/v2/workflows/import/preview/route' import { POST as importApply } from '@/app/api/v2/workflows/import/route' import { POST as forkPreview } from '@/app/api/v2/workspaces/[workspaceId]/fork/preview/route' @@ -160,8 +162,12 @@ describe('v2 and CLI workflow protocol against PostgreSQL', () => { const path = new URL(request.url).pathname const match = path.match(/^\/api\/v2\/workspaces\/([^/]+)\/(.*)$/) const context = { params: Promise.resolve({ workspaceId: match?.[1] ?? workspaceId }) } - const response = - path === '/api/v2/workflows/import/preview' + const workflowMatch = path.match(/^\/api\/v2\/workflows\/([^/]+)\/operations$/) + const response = workflowMatch + ? await workflowOperations(request, { + params: Promise.resolve({ workflowId: workflowMatch[1] }), + }) + : path === '/api/v2/workflows/import/preview' ? await importPreview(request, { params: Promise.resolve({}) }) : path === '/api/v2/workflows/import' ? await importApply(request, { params: Promise.resolve({}) }) @@ -310,6 +316,66 @@ describe('v2 and CLI workflow protocol against PostgreSQL', () => { expect(requestCount).toBe(before) }) + it('previews and commits enablement-only CLI edits without moving or rewriting the block', async () => { + const workflowId = generateId() + const blockId = generateId() + const now = new Date() + await db.insert(workflow).values({ + id: workflowId, + userId, + workspaceId, + name: `Enablement ${workflowId}`, + lastSynced: now, + createdAt: now, + updatedAt: now, + }) + const fields = { + positionX: '123', + positionY: '456', + subBlocks: { + code: { id: 'code', type: 'code', value: 'return 42' }, + }, + } + await db.insert(workflowBlocks).values({ + id: blockId, + workflowId, + type: 'function', + name: 'Existing function', + enabled: true, + ...fields, + outputs: {}, + data: {}, + }) + const read = async () => { + const [row] = await db + .select({ + enabled: workflowBlocks.enabled, + positionX: workflowBlocks.positionX, + positionY: workflowBlocks.positionY, + subBlocks: workflowBlocks.subBlocks, + }) + .from(workflowBlocks) + .where(eq(workflowBlocks.id, blockId)) + return row + } + const before = await read() + const args = [ + 'workflows', + 'operations', + 'apply', + workflowId, + '--atomic', + '--set-block-enabled', + JSON.stringify([{ block_id: blockId, enabled: false }]), + ] + const preview = await cli([...args, '--dry-run']) + expect(preview.code, preview.stderr).toBe(0) + expect(await read()).toEqual(before) + const saved = await cli([...args, '--yes']) + expect(saved.code, saved.stderr).toBe(0) + expect(await read()).toEqual({ ...before, enabled: false }) + }) + it('creates a draft fork through the CLI and follows its operation receipt', async () => { const preview = await cli(['workspaces', 'fork-preview', '--name', 'CLI fork fixture']) expect(preview.code, preview.stderr).toBe(0) diff --git a/apps/sim/next.config.ts b/apps/sim/next.config.ts index 55521e16dce..e12d78822a1 100644 --- a/apps/sim/next.config.ts +++ b/apps/sim/next.config.ts @@ -92,6 +92,9 @@ const nextConfig: NextConfig = { output: isTruthy(env.DOCKER_BUILD) ? 'standalone' : undefined, serverExternalPackages: [ '@1password/sdk', + /** These Node credential providers produce colliding chunks in Turbopack 16.3.x. */ + '@aws-sdk/credential-provider-login', + '@aws-sdk/credential-provider-web-identity', 'ws', 'isolated-vm', '@e2b/code-interpreter', diff --git a/apps/sim/package.json b/apps/sim/package.json index 412424982f3..b2a787c4484 100644 --- a/apps/sim/package.json +++ b/apps/sim/package.json @@ -212,7 +212,7 @@ "mssql": "12.7.0", "mysql2": "3.24.2", "neo4j-driver": "6.0.1", - "next": "16.3.4", + "next": "16.3.6", "next-mdx-remote": "^6.0.0", "next-themes": "^0.4.6", "nodemailer": "9.1.1", @@ -261,7 +261,7 @@ "zustand": "^5.0.13" }, "devDependencies": { - "@next/env": "16.3.4", + "@next/env": "16.3.6", "@sim/testing": "workspace:*", "@sim/tsconfig": "workspace:*", "@tailwindcss/postcss": "^4.3.3", diff --git a/apps/sim/providers/anthropic/core.request.test.ts b/apps/sim/providers/anthropic/core.request.test.ts index 99fec3560c2..c2ac6664320 100644 --- a/apps/sim/providers/anthropic/core.request.test.ts +++ b/apps/sim/providers/anthropic/core.request.test.ts @@ -16,6 +16,60 @@ describe('executeAnthropicProviderRequest request identity and usage', () => { mockExecuteTool.mockReset() }) + it.each([ + ['anthropic', false], + ['anthropic', true], + ['azure-anthropic', false], + ['azure-anthropic', true], + ] as const)( + 'preserves authoritative tool success for %s responses when success=%s', + async (providerId, success) => { + mockExecuteTool.mockResolvedValue( + success + ? { success: true, output: { error: true, message: 'An error record returned as data' } } + : { success: false, error: 'Search credits exhausted', output: {} } + ) + const create = vi + .fn() + .mockResolvedValueOnce({ + content: [{ type: 'tool_use', id: 'search-1', name: 'exa_search', input: {} }], + stop_reason: 'tool_use', + usage: { input_tokens: 2, output_tokens: 2 }, + }) + .mockResolvedValueOnce({ + content: [{ type: 'text', text: 'Handled tool result' }], + stop_reason: 'end_turn', + usage: { input_tokens: 2, output_tokens: 2 }, + }) + const result = (await executeAnthropicProviderRequest( + { + model: 'claude-sonnet-4-5', + apiKey: 'test-key', + stream: false, + maxTokens: 1024, + messages: [{ role: 'user', content: 'Research' }], + tools: [ + { + id: 'exa_search', + description: 'Search', + params: {}, + parameters: { type: 'object', properties: {}, required: [] }, + }, + ], + }, + { + providerId, + providerLabel: providerId, + createClient: () => ({ messages: { create } }) as never, + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + } + )) as ProviderResponse + + expect(result.toolCalls).toHaveLength(1) + expect(result.toolCalls![0].success).toBe(success) + } + ) + it('keeps registry identity while sending the resolved wire model and aggregating cache usage', async () => { const create = vi.fn().mockResolvedValue({ id: 'msg-test', diff --git a/apps/sim/providers/anthropic/core.ts b/apps/sim/providers/anthropic/core.ts index 0f84ef8c615..0f4a479fe22 100644 --- a/apps/sim/providers/anthropic/core.ts +++ b/apps/sim/providers/anthropic/core.ts @@ -968,6 +968,7 @@ export async function executeAnthropicProviderRequest( endTime: tc.endTime, duration: tc.duration, result: tc.result as Record | undefined, + success: tc.success, })) : undefined, toolResults: toolResults.length > 0 ? toolResults : undefined, diff --git a/apps/sim/providers/bedrock/index.test.ts b/apps/sim/providers/bedrock/index.test.ts index 7eb86a77de9..65ff659cc94 100644 --- a/apps/sim/providers/bedrock/index.test.ts +++ b/apps/sim/providers/bedrock/index.test.ts @@ -85,7 +85,9 @@ import type { StreamingExecution } from '@/executor/types' import { bedrockProvider } from '@/providers/bedrock/index' import { clearProviderClientCacheForTests } from '@/providers/client-cache' import { getModelCapabilities, isKnownModelId } from '@/providers/models' +import type { ProviderResponse } from '@/providers/types' import { prepareToolsWithUsageControl } from '@/providers/utils' +import { executeTool } from '@/tools' describe('bedrockProvider credential handling', () => { beforeEach(() => { @@ -103,6 +105,48 @@ describe('bedrockProvider credential handling', () => { messages: [{ role: 'user' as const, content: 'Hello' }], } + it.each([false, true])( + 'preserves authoritative tool success=%s in its response', + async (success) => { + vi.mocked(executeTool).mockResolvedValueOnce( + success + ? { success: true, output: { error: true, message: 'An error record returned as data' } } + : { success: false, error: 'Search credits exhausted', output: {} } + ) + mockSend + .mockResolvedValueOnce({ + output: { + message: { + content: [{ toolUse: { toolUseId: 'search-1', name: 'exa_search', input: {} } }], + }, + }, + stopReason: 'tool_use', + usage: { inputTokens: 1, outputTokens: 1 }, + }) + .mockResolvedValueOnce({ + output: { message: { content: [{ text: 'Handled tool result' }] } }, + stopReason: 'end_turn', + usage: { inputTokens: 1, outputTokens: 1 }, + }) + + const result = (await bedrockProvider.executeRequest({ + ...baseRequest, + stream: false, + tools: [ + { + id: 'exa_search', + description: 'Search', + params: {}, + parameters: { type: 'object', properties: {}, required: [] }, + }, + ], + })) as ProviderResponse + + expect(result.toolCalls).toHaveLength(1) + expect(result.toolCalls![0].success).toBe(success) + } + ) + it('preserves system-only instructions while supplying the required user message', async () => { await bedrockProvider.executeRequest({ ...baseRequest, diff --git a/apps/sim/providers/bedrock/index.ts b/apps/sim/providers/bedrock/index.ts index 46e4cf2fe0d..b1167f4f9d8 100644 --- a/apps/sim/providers/bedrock/index.ts +++ b/apps/sim/providers/bedrock/index.ts @@ -1033,6 +1033,7 @@ export const bedrockProvider: ProviderConfig = { endTime: tc.endTime, duration: tc.duration, result: tc.result, + success: tc.success, })) : undefined, toolResults: toolResults.length > 0 ? toolResults : undefined, diff --git a/apps/sim/tools/file/compress.ts b/apps/sim/tools/file/compress.ts index e4c3a93769d..fd86b9f41a4 100644 --- a/apps/sim/tools/file/compress.ts +++ b/apps/sim/tools/file/compress.ts @@ -6,6 +6,8 @@ interface FileCompressParams { folderPaths?: string[] includeSubfolders?: boolean archiveName?: string + folderPath?: string + onConflict?: 'rename' | 'error' workspaceId?: string } @@ -52,6 +54,20 @@ export const fileCompressTool: InternalToolConfig ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() })) +vi.mock('@sim/logger', () => ({ createLogger: () => logger })) + import { fileFetchTool, fileParserTool, fileParserV3Tool } from '@/tools/file/parser' describe('fileParserTool', () => { + it('preserves authenticated fetch inputs without logging headers or signed URLs', () => { + const fileUrl = 'https://example.com/report.pdf?signature=private-url-token' + const headers = { Authorization: 'Bearer private-header-token' } + expect(fileFetchTool.operation.input({ fileUrl, headers })).toMatchObject({ + filePath: fileUrl, + headers, + }) + const logged = JSON.stringify([ + ...logger.info.mock.calls, + ...logger.warn.mock.calls, + ...logger.error.mock.calls, + ]) + expect(logged).not.toContain('private-url-token') + expect(logged).not.toContain('private-header-token') + }) + + it('does not log supplied headers when the file path is missing', () => { + expect(() => + fileFetchTool.operation.input({ + fileUrl: '', + headers: { Authorization: 'Bearer private-header-token' }, + }) + ).toThrow('Missing required parameter: filePath') + const logged = JSON.stringify([ + ...logger.info.mock.calls, + ...logger.warn.mock.calls, + ...logger.error.mock.calls, + ]) + expect(logged).not.toContain('private-header-token') + }) + it('maps the public File Fetch URL to the internal parser path', () => { expect( fileFetchTool.operation.input({ diff --git a/apps/sim/tools/file/parser.ts b/apps/sim/tools/file/parser.ts index 743b4b388bb..1f6d6426cd7 100644 --- a/apps/sim/tools/file/parser.ts +++ b/apps/sim/tools/file/parser.ts @@ -199,8 +199,6 @@ export const fileParserTool: InternalToolConfig { - logger.info('Request parameters received by tool body:', params) - if (!params) { logger.error('Tool body received no parameters') throw new Error('No parameters provided to tool body') @@ -234,7 +232,6 @@ export const fileParserTool: InternalToolConfig file array > single file object > legacy files array // 1. Check for direct filePath (URL or single path from upload) if (params.filePath) { - logger.info('Tool body found direct filePath:', params.filePath) determinedFilePath = params.filePath } // 2. Check for file upload (array) @@ -275,11 +272,10 @@ export const fileParserTool: InternalToolConfig.', + 'Source code in the selected language. Read permitted workspace secrets with {{NAME}}, for example const token = {{SERVICE_API_KEY}}; do not use process.env.NAME for workspace secrets. JavaScript runs as an async function body and returns a result with return. Python runs as a module and returns an optional result through __sim_result__; legacy snippets with a top-level return remain supported. Shell runs as Bash and can emit a typed result with __SIM_RESULT__=.', }, language: { type: 'string', @@ -184,14 +185,16 @@ To return a file from a Function sandbox, write it to ${SANDBOX_OUTPUT_DIR}. In type: 'string', required: false, visibility: 'user-only', - description: 'Whether this code can read all workspace secrets or only selected ones', + description: + 'Secret access: all workspace secrets or selected names only. Read secrets with {{NAME}} placeholders, not process.env.NAME.', }, mountedSecrets: { type: 'array', items: { type: 'string' }, required: false, visibility: 'user-only', - description: 'Secret names this code can read when secretScope is "selected"', + description: + 'Case-sensitive names this code can read when secretScope is "selected". Example: ["SERVICE_API_KEY"] permits {{SERVICE_API_KEY}}; an empty list permits no workspace secrets.', }, envVars: { type: 'object', diff --git a/apps/sim/tools/generated/tool-metadata.ts b/apps/sim/tools/generated/tool-metadata.ts index 0a1c7bd206e..192b26f0c43 100644 --- a/apps/sim/tools/generated/tool-metadata.ts +++ b/apps/sim/tools/generated/tool-metadata.ts @@ -3,7 +3,7 @@ /** Serializable metadata for every built-in tool, keyed by tool id. */ const toolMetadata: Record = 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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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)"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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)"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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)"}},"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"}},"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"}},"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"}},"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)"}},"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)"}},"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)"}},"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)"}},"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)"}},"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)"}},"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"}},"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"}},"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."}},"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"}},"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."}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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 number of records to return (default: all records)"},"filterFormula":{"type":"string","required":false,"visibility":"user-or-llm","description":"Formula to filter records (e.g., \\"({Field Name} = \'Value\')\\")"}},"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"},"airweave_search":{"id":"airweave_search","name":"Airweave Search","description":"Search your synced data collections using Airweave. Supports semantic search with hybrid, neural, or keyword retrieval strategies. Optionally generate AI-powered answers from search results.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Airweave API Key for authentication"},"collectionId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The readable ID of the collection to search"},"query":{"type":"string","required":true,"visibility":"user-or-llm","description":"The search query text"},"limit":{"type":"number","required":false,"visibility":"user-only","description":"Maximum number of results to return (default: 100)"},"retrievalStrategy":{"type":"string","required":false,"visibility":"user-or-llm","description":"Retrieval strategy: hybrid (default), neural, or keyword"},"expandQuery":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Generate query variations to improve recall"},"rerank":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Reorder results for improved relevance using LLM"},"generateAnswer":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Generate a natural-language answer to the query"}},"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"}},"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)"}},"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"}},"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"}},"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."}},"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"}},"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"}},"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"}},"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"}},"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\\"."}},"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"}},"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"}},"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)"}},"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)"}},"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"}},"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)"}},"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"},"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: 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 (max 1000)"},"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\\""}},"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: 100, 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\\""}},"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\\""}},"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\\""}},"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\\""}},"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\\""}},"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\\""}},"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\\""}},"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: \\"bracket\\", \\"rolling\\", or \\"n-day\\" (default: n-day)"},"retentionBrackets":{"type":"string","required":false,"visibility":"user-or-llm","description":"Required when Retention Mode is \\"bracket\\". Day ranges, e.g. [[0,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\\""}},"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\\""}},"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\\""}},"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":{"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)"}},"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\\""}},"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\\""}},"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\\""}},"hostedApiKey":"none"},"apify_run_actor_async":{"id":"apify_run_actor_async","name":"APIFY Run Actor (Async)","description":"Run an APIFY actor asynchronously with polling for long-running tasks","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\\""}},"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\\""}},"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\\""}},"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":{"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)"}},"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":{"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."}},"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":{"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"}},"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":{"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)"}},"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":{"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"}},"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":{"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"}},"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":{"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"}},"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":{"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"}},"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":{"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)"}},"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":{"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"}},"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":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"}},"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":{"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"}},"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":{"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\\")"}},"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":{"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)"}},"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":{"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"}},"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":{"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\\"])"}},"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":{"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\\")"}},"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":{"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)"}},"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":{"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)"}},"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":{"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)"}},"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":{"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)"}},"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":{"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"}},"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":{"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)"}},"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":{"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"}},"hostedApiKey":"none"},"apollo_task_search":{"id":"apollo_task_search","name":"Apollo Search Tasks","description":"Search for tasks in Apollo","version":"1.0.0","params":{"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)"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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"}},"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 (required when not using taskGid)"},"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 (default: 50)"}},"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":"Text to search for in task names"},"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"}},"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"}},"hostedApiKey":"none"},"ashby_anonymize_candidate":{"id":"ashby_anonymize_candidate","name":"Ashby Anonymize Candidate","description":"Strips personally identifiable information from a candidate in Ashby. This does not delete the candidate - the record and its applications remain, with the PII removed. Ashby exposes no candidate deletion endpoint; true deletion is UI-only, restricted by role, and limited to a 10-day window. 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"}},"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."}},"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."}},"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"}},"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"}},"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: , , , ,