Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions .github/workflows/workflow-code-corpus.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
name: workflow-code-corpus

# The workflow-code corpus suites over the whole generated corpus. The PR test job samples a few
# cases per block type (`corpusSubjects`) to stay inside its budget, so a property that fails only
# on an unsampled case never shows there. This runs every case nightly, and on a change to itself.

on:
pull_request:
paths:
- '.github/workflows/workflow-code-corpus.yml'
schedule:
- cron: '17 8 * * *'
workflow_dispatch:

permissions:
contents: read

concurrency:
group: workflow-code-corpus-${{ github.ref }}
cancel-in-progress: true

jobs:
corpus:
name: corpus (full)
runs-on: ${{ (vars.CI_PROVIDER == '' || vars.CI_PROVIDER == 'blacksmith') && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-latest' }}
timeout-minutes: 60
steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6

- name: Setup workspace
uses: ./.github/actions/setup
with:
provider: ${{ vars.CI_PROVIDER }}

- name: Run the corpus suites over every case
working-directory: apps/sim
env:
ROUNDTRIP_CORPUS_FULL: '1'
NODE_OPTIONS: '--no-warnings --max-old-space-size=8192'
NEXT_PUBLIC_APP_URL: 'https://www.sim.ai'
DATABASE_URL: 'postgresql://postgres:postgres@localhost:5432/simstudio'
ENCRYPTION_KEY: '0000000000000000000000000000000000000000000000000000000000000000' # dummy key for CI only
run: bunx vitest run lib/workflows/code/corpus/

4 changes: 2 additions & 2 deletions apps/docs/content/docs/workflows/code/diagnostics.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ Reading and writing `workflow.ts`.
| `E_UNKNOWN_BUILDER` | A builder path the catalog does not have, a bare builder-shaped call (`apii('Name', …)`) nothing binds, or a namespace the SDK lacks or the file did not import; `hint` names the builder a common other name stands for (`http.request` → `api`), then prefers a synonymous verb (`postMessage` → `sendMessage`), then the closest path, then the namespace's builders. |
| `E_UNKNOWN_PARAM` | A param the block does not have; the hint has a did-you-mean, or for block meta written there (`retry`, `disabled`, `locked`, `errorPort`) the third argument that takes it. |
| `E_FIXED_PARAM` | A param the builder already pins. |
| `W_FIELD_NOT_APPLICABLE` | A param not visible under the block's values; apply keeps the stored value and the written-back source drops it. |
| `W_FIELD_NOT_APPLICABLE` | A param not visible under the block's values, or a basic-only field on a block with `advancedMode`; apply keeps the stored value and the written-back source drops it. |
| `W_REQUIRED_MISSING` | A required field left empty, including `todo()`; not repeated for a field an `E_UNKNOWN_PARAM` did-you-mean names, or one written with a value that failed to compile. |
| `W_UNKNOWN_OPTION` | A dropdown value none of its options names; `hint` lists them. |
| `E_UNKNOWN_OPERATION` | An `operation` the block does not offer; `hint` lists them. A retired one the stored block holds is `W_UNKNOWN_OPTION`. |
Expand All @@ -80,7 +80,7 @@ Reading and writing `workflow.ts`.
| `W_VALUE_KIND` | A value whose JSON type differs from the field's. |
| `W_OUT_OF_RANGE` | A literal slider value outside the catalog `min`/`max`, off its `step`, or fractional where it takes whole numbers; kept as written, and the executor forwards it unclamped. |
| `W_TABLE_FILTER_SHAPE` | A literal table filter the runtime refuses: the legacy `$` operator grammar, or predicate and builder rows mixed. |
| `W_LITERAL_SECRET` | A password field (an API key, a token) holding literal text instead of an env reference, or any field holding a detected credential (a token format, an `Authorization` header, a credential-named property or query parameter); get prints it as `stored()`. For a literal token in a credential field, the hint says `credential('<key>')`. |
| `W_LITERAL_SECRET` | A password field (an API key, a token) holding literal text instead of an env reference, or any field or workflow variable holding a detected credential (a token format, an `Authorization` header, a credential-named property or query parameter); get prints it as `stored()`. A value Sim minted at creation (a webhook token) is not reported. For a literal token in a credential field, the hint says `credential('<key>')`. |
| `W_SUBFLOW_COUNT` | A loop or parallel count, or a parallel batch size, the runtime replaces or clamps. |
| `W_UNKNOWN_OUTPUT_PATH` | A ref path the block's outputs do not have; the hint has a did-you-mean or lists the outputs. |
| `W_OUTPUT_PATH_UNDECLARED` | A path the block does not declare that the run still accepts: an undeclared `inputFormat` input, or `x.error` with no error edge. Never refused. |
Expand Down
9 changes: 5 additions & 4 deletions apps/docs/content/docs/workflows/code/syntax.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ How to read it:
- Each `const` is a block. `agent`, `condition`, `table.insertRow`, and `slack.sendMessage` are the blocks you know from the workflow builder, with the same settings.
- `classify.category` is a typed reference to another block's output, the same as `<classify.category>` in the builder. `t` writes text with references in it; `js` writes code.
- `table('tickets')` and `credential('support-slack')` name workspace resources by a stable key. Renaming the table in Sim keeps the key.
- `env.TICKETS_WEBHOOK_TOKEN` reads an environment variable. Secret values are never printed: a key pasted into a password field prints as `stored()`, which keeps the saved value.
- `env.TICKETS_WEBHOOK_TOKEN` reads an environment variable. A key pasted into a password field, or a value that looks like a credential, prints as `stored()`, which keeps the saved value.
- `.to()` connects blocks, `byCategory.billing` is one branch of the condition, and `.onError()` follows the error path. `notify` has three incoming edges and runs once, after the branch that was taken.
- A webhook answers its caller as soon as the request is accepted and runs the workflow in the background, so the caller never sees a `response` block's output. `responseMode: 'custom'` sets that fixed answer (here `202` with `{ "ok": true }`; without it, `200` with `{ "message": "Webhook processed" }`). To answer with values the run computes, start the workflow with `trigger.start` and call it through the API; a `response` block then sets what the caller receives.

Expand All @@ -110,7 +110,7 @@ export default workflow('Name', { description: '…', variables: { /* … */ } }
- Line 1 is `// @sim-sdk N`. Without it the file is refused with `E_SDK_HEADER`; a number other than the one the server reads is `E_SDK_MAJOR`.
- Imports are named imports from `'@sim/workflow-sdk'` only. Aliases are allowed.
- The file has exactly one `export default workflow(name, options?, body)` (`E_WORKFLOW_EXPORT`). `options` is `{ description?, variables? }`. `body` is `() => { … }` or `({ vars }) => { … }`.
- Variables are `variables: { <key>: { name?, type, value } }`. `type` is `string`, `number`, `boolean`, `object`, `array` or `plain`, and both `type` and `value` are required; `value` is plain JSON. The key is the variable's key: lowercased, with spaces and dots removed. `name` is written only when it differs, and must normalize to the key (`E_VARIABLE_NAME_MISMATCH`). Read one as `vars.<key>`.
- Variables are `variables: { <key>: { name?, type, value } }`. `type` is `string`, `number`, `boolean`, `object`, `array` or `plain`, and both `type` and `value` are required; `value` is plain JSON, or `stored()` for a value that looks like a credential. The key is the variable's key: lowercased, with spaces and dots removed. `name` is written only when it differs, and must normalize to the key (`E_VARIABLE_NAME_MISMATCH`). Read one as `vars.<key>`.
- The body holds block declarations and wiring statements. Helpers, loops, conditionals and imports of your own have no stored form and are refused. Use `loop`, `parallel`, `condition` and `runWorkflow` blocks instead.

## Blocks
Expand All @@ -124,8 +124,9 @@ export default workflow('Name', { description: '…', variables: { /* … */ } }

- A param is a setting of the block, named as `sim workflows source params <builder>` lists it. For a setting the builder shows as a basic or advanced pair, you write the shared name, not either member. Writing a member by its own name is `E_UNKNOWN_PARAM`, and the hint names the right one.
- An omitted param is the default the workflow builder fills in, so a block with no params is stored like one made in the builder. `null` for a whole param stores it as absent.
- A value Sim creates with the block, such as a webhook token, is kept when the source leaves it out. Write `null` to clear it; on a new block, `null` creates the block without one.
- A param the builder already fixes, such as `operation`, is `E_FIXED_PARAM`.
- A param that is not visible under the block's other settings is `W_FIELD_NOT_APPLICABLE`. It never runs, so the apply keeps the stored value and the next `get` leaves the line out.
- A param that is not visible under the block's other settings is `W_FIELD_NOT_APPLICABLE`, as is a basic-only field on a block with `advancedMode: true`. It never runs, so the apply keeps the stored value and the next `get` leaves the line out.
- A required field left empty, or written as `todo()`, is `W_REQUIRED_MISSING`. A value of the wrong JSON type is `W_VALUE_KIND`; it is never converted.

### Selecting a resource or typing an ID
Expand Down Expand Up @@ -186,7 +187,7 @@ In a workspace directory, `sim workspaces source check` reports a key the direct

### Secrets and `stored()`

A secret is never printed. A literal value in a password field prints as `stored()`, which compiles to the value the stored workflow already holds for the same block and param. A new block, another block type or an empty field has nothing stored: `stored()` there is `E_STORED_VALUE_MISSING`. To set a secret, write `env.NAME` and keep the value in the workspace's environment variables. A literal key in the file is `W_LITERAL_SECRET`.
A literal value in a password field prints as `stored()`, and so does any param, tool param or variable value that looks like a credential: a known token format, an `Authorization` header or a credential-named property. `stored()` compiles to the value the stored workflow already holds for the same block and param, or for a variable, the same variable. A secret that matches none of these patterns outside a password field prints as written. A new block, another block type or an empty field has nothing stored: `stored()` there is `E_STORED_VALUE_MISSING`. To set a secret, write `env.NAME` and keep the value in the workspace's environment variables. A literal key in the file is `W_LITERAL_SECRET`.

### References

Expand Down
79 changes: 76 additions & 3 deletions apps/sim/lib/workflows/code/hand-written.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,12 +105,16 @@ function applyTwice(text: string) {
}

/** One stored block canonicalized, printed and compiled back against what it continues. */
function printAndCompile(type: string, values: Record<string, unknown>) {
function printAndCompile(
type: string,
values: Record<string, unknown>,
options: { advancedMode?: boolean } = {}
) {
const subBlocks = Object.fromEntries(
Object.entries(values).map(([id, value]) => [id, { id, type: 'short-input', value }])
)
const state: WorkflowState = {
blocks: { b1: createBlock({ id: 'b1', type, name: 'Block', subBlocks } as never) },
blocks: { b1: createBlock({ id: 'b1', type, name: 'Block', subBlocks, ...options } as never) },
edges: [],
loops: {},
parallels: {},
Expand All @@ -122,7 +126,12 @@ function printAndCompile(type: string, values: Record<string, unknown>) {
}).workflow
const text = printWorkflow({ workflow: canonical, catalog, options: { functionCode: 'inline' } })
.files[0].text
return { text, diagnostics: compile(text, canonical).diagnostics }
return { text, canonical, diagnostics: compile(text, canonical).diagnostics }
}

/** The params a compile's diagnostics of `code` name. */
function paramsOf(diagnostics: ReadonlyArray<{ code: string; param?: string }>, code: string) {
return diagnostics.filter((d) => d.code === code).map((d) => d.param)
}

describe('hand-written source over the real catalog', () => {
Expand Down Expand Up @@ -234,6 +243,70 @@ export default workflow('Chat', {}, () => {
expect(compile(text).diagnostics).toEqual([])
}, 120_000)

it('treats a basic-only field as never running on a block in advanced mode', () => {
const { text, canonical, diagnostics } = printAndCompile(
'sailpoint_v2',
{ operation: 'sailpoint_search_aggregate', aggregationType: 'SAILPOINT' },
{ advancedMode: true }
)
expect(text).not.toContain('aggregations:')
expect(paramsOf(diagnostics, 'W_REQUIRED_MISSING')).not.toContain('aggregations')
const written = text.replace(
"aggregationType: 'SAILPOINT',",
"aggregationType: 'SAILPOINT',\n aggregations: { name: 'department' },"
)
expect(written).not.toBe(text)
expect(paramsOf(compile(written, canonical).diagnostics, 'W_FIELD_NOT_APPLICABLE')).toEqual([
'aggregations',
])
}, 120_000)

it('keeps a credential in a workflow variable out of the file and compiles it back', () => {
const key = ['sk-proj-', 'abcdefghijklmnopqrstuvwxyz', '123456'].join('')
const text = `${HEADER}import { trigger, workflow } from '@sim/workflow-sdk'
export default workflow('Keys', { variables: { apiKey: { type: 'string', value: '${key}' } } }, () => {
trigger.start('Start', {})
})
`
const run = applyTwice(text)
expect(run.first.diagnostics.map((d) => d.code)).toEqual(['W_LITERAL_SECRET'])
expect(run.readBack).not.toContain(key)
expect(run.readBack).toContain('value: stored()')
const again = compile(run.readBack, run.canonical)
expect(again.diagnostics.filter((d) => d.severity === 'error')).toEqual([])
expect(again.workflow?.variables).toEqual(run.canonical.variables)
expect(compile(run.readBack).diagnostics.map((d) => d.code)).toContain('E_STORED_VALUE_MISSING')
const offline = (variables: Record<string, string>) =>
compileWorkflow({
entry: { path: 'workflow.ts', text: run.readBack },
files: new Map(),
catalog,
sdkMajor: catalog.sdkMajor,
storedUnread: { version: 1, blocks: {}, variables },
}).diagnostics.filter((d) => d.code === 'E_STORED_VALUE_MISSING')
expect(offline({ apikey: 'var-1' })).toEqual([])
expect(offline({ other: 'var-1' })).toHaveLength(1)
}, 120_000)

it('never warns about the webhook token Sim mints, on apply or read-back', () => {
const text = `${HEADER}import { trigger, workflow } from '@sim/workflow-sdk'
export default workflow('Hook', {}, () => {
trigger.webhook('Hook', {})
})
`
const run = applyTwice(text)
expect(run.readBack).toContain('token: stored()')
const printed = printWorkflow({
workflow: run.canonical,
catalog,
options: { functionCode: 'inline' },
})
expect(paramsOf(printed.diagnostics, 'W_LITERAL_SECRET')).toEqual([])
expect(paramsOf(compile(run.readBack, run.canonical).diagnostics, 'W_LITERAL_SECRET')).toEqual(
[]
)
}, 120_000)

it('reads a stored uploaded file back as source that type-checks and compiles clean', () => {
const file = { name: 'a.txt', path: '/api/files/serve/a.txt', size: 3, type: 'text/plain' }
const { text, diagnostics } = printAndCompile('agent', {
Expand Down
6 changes: 4 additions & 2 deletions packages/workflow-code/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -426,7 +426,7 @@ as written (`table_v2`'s filter builder).

## Secrets

A secret is never printed. `secrets.ts` holds the one predicate print and compile share
A detected secret is never printed. `secrets.ts` holds the one predicate print and compile share
(`holdsSecret`): literal text in a `password` subBlock, or in any other field a high-confidence
credential (`holdsDetectedSecret`): a known token format (`sk-…`, `ghp_…`, `xoxb-…`, `AKIA…`, a
JWT, a private key, `Bearer <token>`), a credential header row (`Authorization`, `X-Api-Key`), a
Expand All @@ -437,7 +437,9 @@ credential-named property, code assignment or URL query parameter (`api_key`, `c

Such a param (block params, agent tool params and MCP tool arguments alike) prints as `stored()`,
meaning "keep the stored value", with `W_LITERAL_SECRET`; compile warns the same way where source
writes one literally. A custom tool snapshot's code has no `stored()` form, so a credential there
writes one literally. A workflow variable value holding a detected credential does the same, its
`stored()` resolved by variable key. A value creation mints (`mintsFreshValue`, a webhook token)
prints as `stored()` without the warning: Sim wrote it, not the source. A custom tool snapshot's code has no `stored()` form, so a credential there
only warns. Compile resolves `stored()` to the value `CompileInput.stored` (the stored workflow,
canonicalized under the submitted lock) holds for the same block key, type and param, a pair's
members and mode included, so a get followed by an unchanged apply keeps the value. A new block,
Expand Down
12 changes: 11 additions & 1 deletion packages/workflow-code/src/catalog/activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -254,10 +254,20 @@ function serializes(subBlock: CatalogSubBlock, inputs: ActivityInputs): boolean
}

if (subBlock.mode === 'advanced' && !advancedMode) return isNonEmptyValue(values[subBlock.id])
if (subBlock.mode === 'basic' && advancedMode) return false
if (basicOnlyHidden(subBlock, advancedMode)) return false
return conditionHolds(subBlock, values)
}

/**
* Whether the block's `advancedMode` keeps a standalone field (one outside any `canonicalParamId`
* group) from ever running: the serializer never sends a basic-only field from a block in advanced
* mode, whatever it holds. Compile and print ask here before treating such a field as applicable
* or required, so neither asks for a value the run would drop.
*/
export function basicOnlyHidden(subBlock: CatalogSubBlock, advancedMode: boolean): boolean {
return advancedMode && subBlock.mode === 'basic' && subBlock.canonicalParamId === undefined
}

/**
* Whether a stored param is inactive: stored, but neither forwarded by the serializer nor read by
* deploy (`deployReadIds`) under the block's current values. Mirrors the include rule in
Expand Down
4 changes: 3 additions & 1 deletion packages/workflow-code/src/catalog/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@ export function subBlockEditorDefault(subBlock: CatalogSubBlock): EditorDefault
* state it, and a block created from source keeps the value `MaterializeHooks.initBlock` computed,
* exactly as a canvas-created block does.
*/
export function mintsFreshValue(subBlock: CatalogSubBlock): boolean {
export function mintsFreshValue(
subBlock: Pick<CatalogSubBlock, 'hidden' | 'readOnly' | 'valueDefault'>
): boolean {
if (subBlock.hidden || subBlock.readOnly) return false
const thunk = subBlock.valueDefault
return thunk !== undefined && 'computed' in thunk && thunk.initial === undefined
Expand Down
Loading
Loading