Skip to content

Commit e34fbba

Browse files
authored
fix(workflow-code): agent-facing semantics copy for guardrails failures, loop results, and params --full (#10543)
* fix(workflow-code): agent-facing semantics copy for guardrails failures, loop results, and params --full - guardrails block, docs and previews: a failed check leaves through the error port, so handle it there (onError in workflow code), not with a Condition on passed - loop/parallel results typed Json[][] with the per-iteration wording in core.d.ts, cookbook, primer and json-fields - source params JSON brief names the --full lookup as next * fix(sim-cli): keep the typed workspace and options in the params --full next step
1 parent 428f30e commit e34fbba

13 files changed

Lines changed: 150 additions & 101 deletions

File tree

‎apps/docs/components/workflow-preview/examples.ts‎

Lines changed: 46 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -1445,14 +1445,28 @@ const GUARDRAILS_START = {
14451445
position: { x: 0, y: 0 },
14461446
} as const
14471447

1448-
const GUARDRAILS_GATE = {
1449-
id: 'condition',
1450-
name: 'Condition',
1451-
type: 'condition',
1452-
typeLabel: 'Condition',
1453-
bgColor: '#FF752F',
1454-
position: { x: 640, y: 0 },
1455-
} as const
1448+
/** A Function block in a guardrails example: the passing path (top) or the error path (bottom). */
1449+
function guardrailsFunction(id: string, name: string, code: string, path: 'pass' | 'error') {
1450+
return {
1451+
id,
1452+
name,
1453+
type: 'function',
1454+
typeLabel: 'Function',
1455+
sentence: ['Run', { subBlockId: 'Code', noun: 'code' }],
1456+
bgColor: '#FF402F',
1457+
position: { x: 640, y: path === 'pass' ? -60 : 140 },
1458+
rows: [{ title: 'Code', value: code }],
1459+
}
1460+
}
1461+
1462+
/** A guardrails example's edges: the check passes to `passId`, and fails through its error port to `errorId`. */
1463+
function guardrailsEdges(passId: string, errorId: string): PreviewWorkflow['edges'] {
1464+
return [
1465+
{ id: 'start-guardrails', source: 'start', target: 'guardrails' },
1466+
{ id: `guardrails-${passId}`, source: 'guardrails', target: passId },
1467+
{ id: `guardrails-${errorId}`, source: 'guardrails', target: errorId, sourceHandle: 'error' },
1468+
]
1469+
}
14561470

14571471
/** Guardrails example: validate JSON before parsing it. */
14581472
export const GUARDRAILS_JSON_WORKFLOW: PreviewWorkflow = {
@@ -1473,46 +1487,15 @@ export const GUARDRAILS_JSON_WORKFLOW: PreviewWorkflow = {
14731487
{ title: 'Validation', value: 'Valid JSON' },
14741488
],
14751489
},
1476-
{
1477-
...GUARDRAILS_GATE,
1478-
rows: [],
1479-
branches: [
1480-
{ id: 'condition-if', label: 'If', value: '<guardrails.passed>' },
1481-
{ id: 'condition-else', label: 'else' },
1482-
],
1483-
},
1484-
{
1485-
id: 'parse',
1486-
name: 'Parse',
1487-
type: 'function',
1488-
typeLabel: 'Function',
1489-
sentence: ['Run', { subBlockId: 'Code', noun: 'code' }],
1490-
bgColor: '#FF402F',
1491-
position: { x: 960, y: -60 },
1492-
rows: [{ title: 'Code', value: 'return JSON.parse(<agent.content>);' }],
1493-
},
1494-
{
1495-
id: 'reject',
1496-
name: 'Reject',
1497-
type: 'function',
1498-
typeLabel: 'Function',
1499-
sentence: ['Run', { subBlockId: 'Code', noun: 'code' }],
1500-
bgColor: '#FF402F',
1501-
position: { x: 960, y: 140 },
1502-
rows: [{ title: 'Code', value: 'return { valid: false, error: <guardrails.error> };' }],
1503-
},
1504-
],
1505-
edges: [
1506-
{ id: 'start-guardrails', source: 'start', target: 'guardrails' },
1507-
{ id: 'guardrails-condition', source: 'guardrails', target: 'condition' },
1508-
{ id: 'condition-parse', source: 'condition', target: 'parse', sourceHandle: 'condition-if' },
1509-
{
1510-
id: 'condition-reject',
1511-
source: 'condition',
1512-
target: 'reject',
1513-
sourceHandle: 'condition-else',
1514-
},
1490+
guardrailsFunction('parse', 'Parse', 'return JSON.parse(<agent.content>);', 'pass'),
1491+
guardrailsFunction(
1492+
'reject',
1493+
'Reject',
1494+
'return { valid: false, error: <guardrails.error> };',
1495+
'error'
1496+
),
15151497
],
1498+
edges: guardrailsEdges('parse', 'reject'),
15161499
}
15171500

15181501
/** Guardrails example: check an answer is grounded in the knowledge base. */
@@ -1541,19 +1524,15 @@ export const GUARDRAILS_HALLUCINATION_WORKFLOW: PreviewWorkflow = {
15411524
{ title: 'Model', value: 'claude-sonnet-5-5' },
15421525
],
15431526
},
1544-
{
1545-
...GUARDRAILS_GATE,
1546-
rows: [],
1547-
branches: [
1548-
{ id: 'condition-if', label: 'If', value: '<guardrails.score> >= 3' },
1549-
{ id: 'condition-else', label: 'else' },
1550-
],
1551-
},
1552-
],
1553-
edges: [
1554-
{ id: 'start-guardrails', source: 'start', target: 'guardrails' },
1555-
{ id: 'guardrails-condition', source: 'guardrails', target: 'condition' },
1527+
guardrailsFunction('answer', 'Answer', 'return <agent.content>;', 'pass'),
1528+
guardrailsFunction(
1529+
'flag',
1530+
'Flag',
1531+
'return { grounded: false, score: <guardrails.score>, reason: <guardrails.error> };',
1532+
'error'
1533+
),
15561534
],
1535+
edges: guardrailsEdges('answer', 'flag'),
15571536
}
15581537

15591538
/** Guardrails example: block user input that contains PII. */
@@ -1586,19 +1565,15 @@ export const GUARDRAILS_PII_WORKFLOW: PreviewWorkflow = {
15861565
{ title: 'Action', value: 'Block Request' },
15871566
],
15881567
},
1589-
{
1590-
...GUARDRAILS_GATE,
1591-
rows: [],
1592-
branches: [
1593-
{ id: 'condition-if', label: 'If', value: '<guardrails.passed>' },
1594-
{ id: 'condition-else', label: 'else' },
1595-
],
1596-
},
1597-
],
1598-
edges: [
1599-
{ id: 'start-guardrails', source: 'start', target: 'guardrails' },
1600-
{ id: 'guardrails-condition', source: 'guardrails', target: 'condition' },
1568+
guardrailsFunction('process', 'Process', 'return <start.input>;', 'pass'),
1569+
guardrailsFunction(
1570+
'reject',
1571+
'Reject',
1572+
'return { rejected: true, found: <guardrails.detectedEntities> };',
1573+
'error'
1574+
),
16011575
],
1576+
edges: guardrailsEdges('process', 'reject'),
16021577
}
16031578

16041579
/** HITL example: a human approves AI content before it ships. */

‎apps/docs/content/docs/workflows/blocks/guardrails.mdx‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,23 +6,27 @@ description: Validate JSON, match a pattern, assess grounding, or detect PII.
66
import { Callout } from '@/components/ui/callout'
77
import { BlockPreview, WorkflowPreview, GUARDRAILS_JSON_WORKFLOW, GUARDRAILS_HALLUCINATION_WORKFLOW, GUARDRAILS_PII_WORKFLOW } from '@/components/workflow-preview'
88

9-
The **Guardrails block** checks content and returns a result. Each block runs one validation type; chain blocks for multiple checks. Validation alone does not choose the next path—connect a Condition to act on it.
9+
The **Guardrails block** checks content. Each block runs one validation type; chain blocks for multiple checks. A passing check continues along the normal output. A failed check leaves through the block's **error port**, so connect the error port to handle it.
10+
11+
<Callout type="warn">
12+
Do not branch on `<guardrails.passed>` with a Condition. A failed check never reaches the Condition, and with nothing on the error port the run completes without output. In workflow code, wire the failure with `onError`: `check.onError(reject)`.
13+
</Callout>
1014

1115
<BlockPreview type="guardrails" />
1216

1317
## Validate before parsing
1418

1519
<WorkflowPreview workflow={GUARDRAILS_JSON_WORKFLOW} />
1620

17-
Select **Valid JSON**, check `<agent.content>`, and branch on `<guardrails.passed>` before parsing it in Function. This checks JSON syntax, not a schema's required fields or types.
21+
Select **Valid JSON** and check `<agent.content>`. Valid JSON continues to the Function that parses it; invalid JSON takes the error port to **Reject**, which reads the parse error as `<guardrails.error>`. This checks JSON syntax, not a schema's required fields or types.
1822

1923
## Configuration
2024

2125
Set **Content to Validate** to text or an earlier output, then select **Validation Type**.
2226

2327
### Valid JSON
2428

25-
Passes when the content parses as JSON. Invalid content returns `passed: false` and a parse error. Use a Function after this check if you also need schema validation.
29+
Passes when the content parses as JSON. Invalid content fails the check with a parse error in `error`. Use a Function after this check if you also need schema validation.
2630

2731
### Regex match
2832

@@ -32,7 +36,7 @@ Enter **Regex Pattern**, for example an email pattern:
3236
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
3337
```
3438

35-
Patterns use RE2's linear-time engine. Lookahead, lookbehind, and backreferences are unsupported and fail validation. To require that content does not contain a pattern, match the pattern and invert `passed` in a Condition.
39+
Patterns use RE2's linear-time engine. Lookahead, lookbehind, and backreferences are unsupported and fail validation. To require that content does not contain a pattern, use a Condition or Function instead: a Regex Match that fails always takes the error port.
3640

3741
### Hallucination check
3842

@@ -71,8 +75,8 @@ The picker groups these regional identifiers. Availability depends on the select
7175

7276
| Action | Result when PII is found |
7377
| --- | --- |
74-
| **Block Request** (default) | `passed: false`, detected entities, and an error summary |
75-
| **Mask PII** | Replaced text in `maskedText`; `passed: true` when masking succeeds |
78+
| **Block Request** (default) | Fails the check through the error port, with the detected entities and an error summary |
79+
| **Mask PII** | Passes, with replaced text in `maskedText` |
7680

7781
With no PII found, Mask returns the original text. Read `detectedEntities` to distinguish no detection from successful masking.
7882

@@ -84,10 +88,10 @@ Use `<guardrails.maskedText>` downstream in Mask mode. The original content is s
8488

8589
| Reference | Value |
8690
| --- | --- |
87-
| `<guardrails.passed>` | Validation outcome; for Mask, whether masking succeeded |
91+
| `<guardrails.passed>` | `true` after a passing check; a failed check takes the error port instead |
8892
| `<guardrails.validationType>` | Check that ran |
8993
| `<guardrails.input>` | Original checked content |
90-
| `<guardrails.error>` | Failure message, when present |
94+
| `<guardrails.error>` | Why the check failed, for the block on the error port |
9195
| `<guardrails.score>` / `<guardrails.reasoning>` | Grounding score and explanation for Hallucination Check |
9296
| `<guardrails.detectedEntities>` | PII entities with type, location, detected text, and confidence |
9397
| `<guardrails.maskedText>` | Masked text in Mask mode |
@@ -96,16 +100,17 @@ Use `<guardrails.maskedText>` downstream in Mask mode. The original content is s
96100

97101
<WorkflowPreview workflow={GUARDRAILS_HALLUCINATION_WORKFLOW} />
98102

99-
Use `passed` for the configured threshold, or `score` for an explicit downstream comparison. Hallucination checks run synchronously; choose the model and chunk count according to the latency your workflow allows.
103+
A score below **Confidence** fails the check through the error port, where `<guardrails.score>` and `<guardrails.error>` say why. A grounded answer continues along the normal output. Hallucination checks run synchronously; choose the model and chunk count according to the latency your workflow allows.
100104

101105
## Block PII in input
102106

103107
<WorkflowPreview workflow={GUARDRAILS_PII_WORKFLOW} />
104108

105-
Branch on `passed` to process clean input or reject detected PII. Selecting only the types relevant to your task keeps the check focused.
109+
Clean input continues along the normal output; detected PII takes the error port to **Reject**. Selecting only the types relevant to your task keeps the check focused.
106110

107111
## Related docs
108112

113+
- [Connections and error paths](/workflows/connections)
109114
- [Condition](/workflows/blocks/condition)
110115
- [Function](/workflows/blocks/function)
111116
- [Credentials and execution-log protection](/platform/credentials)

‎apps/sim/blocks/blocks/guardrails.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,10 @@ export const GuardrailsBlock: BlockConfig = {
3131
- Use regex validation for format checking (emails, phone numbers, URLs, etc.)
3232
- Use hallucination check to validate LLM outputs against knowledge base content
3333
- Use PII detection to block or mask sensitive personal information
34-
- Access validation result with <guardrails.passed> (true/false)
34+
- A failed check leaves through the error port, not the normal output: connect the error port to handle it (in workflow code, check.onError(handler)); the handler reads why as <guardrails.error>
35+
- Do not branch on <guardrails.passed> with a Condition: on a failed check the Condition never runs, and the run ends with no output
3536
- For hallucination check, access <guardrails.score> (0-10 confidence) and <guardrails.reasoning>
3637
- For PII detection, access <guardrails.detectedEntities> and <guardrails.maskedText>
37-
- Chain with Condition block to handle validation failures
3838
`,
3939
docsLink: 'https://docs.sim.ai/workflows/blocks/guardrails',
4040
category: 'blocks',
@@ -309,7 +309,8 @@ Return ONLY the regex pattern - no explanations, no quotes, no forward slashes,
309309
},
310310
passed: {
311311
type: 'boolean',
312-
description: 'Whether validation passed (true/false)',
312+
description:
313+
'Whether validation passed. A failed check leaves through the error port, so the normal output only sees true',
313314
},
314315
score: {
315316
type: 'number',
@@ -326,7 +327,8 @@ Return ONLY the regex pattern - no explanations, no quotes, no forward slashes,
326327
},
327328
error: {
328329
type: 'string',
329-
description: 'Error message if validation failed',
330+
description:
331+
'Why validation failed, read by the block connected to the error port (onError in workflow code)',
330332
},
331333
},
332334
}

‎packages/sim-cli/src/commands/protocol/source-primer.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ function sharedRules(extra: { renames?: string; patterns?: string; debug?: strin
6161
- **References**: \`${SOURCE_ENTRY_FILE}\` reads \`x.content\`, text as \`\` t\`…\` \`\`, env as \`env.NAME\`. A function file (\`codeFile('./functions/x.js')\`) reads \`$ref.<key>.<path>\` (key: display name lowercased, no spaces or dots), \`$ref.loop.currentItem\` / \`.index\` in a body (\`parallel\` too), \`$env.NAME\`; \`.py\`/\`.sh\` files \`<key.path>\`, \`{{NAME}}\`. A block that never ran reads \`null\` (\`''\` in text).
6262
${PATTERNS_HEADING} (\`.sim/examples/\`, indexed atop \`cookbook.ts\`; any builder: \`${PARAMS_COMMAND} <builder>\`):
6363
- Condition: keys test in order, first true wins, \`else: true\` last; wire \`route.high.to(alert)\`.
64-
- Loop: \`const each = loop.forEach('Each Order', { collection: recent.rows }, (p) => {\`; inside, \`p.currentItem.data.orderId\` and \`p.index\`; after, \`each.results\`.
64+
- Loop: \`const each = loop.forEach('Each Order', { collection: recent.rows }, (p) => {\`; inside \`p.currentItem.data.orderId\`, \`p.index\`; after \`each.results[i][0]\`.
6565
- Failure: \`lookup.onError(failed)\`; \`failed\` reads its message as \`lookup.error\` (any block; a Function's adds the line: \`.errorMessage\` doesn't).
6666
- Retry: an \`api\` block resends with \`retries: 3\`, \`retryDelayMs: 500\`; any block's Retry on fail: 3rd argument, \`{ retry: { enabled: true, maxTries: 3, waitBetweenTriesMs: 2000 } }\`.
6767
- Child: \`const enrich = runWorkflow('Enrich Lead', {\` with \`workflowId: childWorkflow('enrich-lead')\`, \`inputMapping: { email: start.email }\`; read \`enrich.result.data.<field>\`.

‎packages/sim-cli/src/commands/protocol/workflow-source-params.test.ts‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,49 @@ describe('sim workflows source params', () => {
180180
await params('table.upsertRow', '--full')
181181
const full = stdoutJson() as { builder: { params: { common: unknown[] } } }
182182
expect(full.builder.params.common.length).toBeGreaterThan(brief.builder.required.length)
183-
expect(JSON.stringify(full).length).toBeGreaterThan(JSON.stringify(brief).length * 2)
183+
expect(JSON.stringify(full.builder).length).toBeGreaterThan(
184+
JSON.stringify(brief.builder).length * 2
185+
)
186+
})
187+
188+
it('names the --full lookup in the JSON brief as typed, and that lookup types the optional params', async () => {
189+
cacheCatalogText(join(dir, 'config'), WORKSPACE_ID, FIXTURE_TEXT)
190+
writeBase()
191+
/** The CLI from its root, so a printed command line runs as typed. */
192+
const sim = async (...argv: string[]) => {
193+
const root = new Command('sim').option('--workspace <id>')
194+
const source = root.command('workflows').command('source')
195+
attachWorkflowSourceParams(source)
196+
source.commands.forEach((command) => command.exitOverride())
197+
await root.parseAsync(['node', 'sim', ...argv])
198+
}
199+
200+
await sim(
201+
'--workspace',
202+
WORKSPACE_ID,
203+
'workflows',
204+
'source',
205+
'params',
206+
'slack.tool.sendMessage',
207+
'--dir',
208+
dir
209+
)
210+
const { builder, next } = stdoutJson() as {
211+
builder: { optional: string[] }
212+
next?: { command: string; reason: string }
213+
}
214+
const words = (next?.command ?? '').split(' ').map((word) => word.replace(/^'(.*)'$/, '$1'))
215+
expect(words.slice(0, 3)).toEqual(['sim', '--workspace', WORKSPACE_ID])
216+
expect(words).toContain('--full')
217+
218+
vi.mocked(console.log).mockClear()
219+
await sim(...words.slice(1))
220+
const full = stdoutJson() as {
221+
builder: { key: string; params: { common: Array<{ key: string; type: string }> } }
222+
}
223+
expect(full.builder.key).toBe('slack.sendMessage')
224+
const typed = full.builder.params.common.map((param) => param.key)
225+
expect(builder.optional.every((key) => typed.includes(key))).toBe(true)
184226
})
185227

186228
it('keeps the call signature of a builder whose required params core.d.ts types', async () => {

‎packages/sim-cli/src/commands/protocol/workflow-source-params.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
} from '@sim/workflow-sdk/codegen'
88
import type { Command } from 'commander'
99
import { printLine } from '#sim-cli/output/io'
10+
import { typedCommandLine } from '#sim-cli/runtime/run-next'
1011
import { isMachineFormat, type ResolvedProfile } from '../../config/index'
1112
import { actingProfileFrom } from '../../context'
1213
import { CliUsageError, SourceDirError } from './local-errors'
@@ -72,8 +73,19 @@ export function attachWorkflowSourceParams(source: Command): void {
7273
switch (found.kind) {
7374
case 'builder':
7475
if (machine) {
75-
const builder = options.full ? found.reference : compactBuilder(found.reference)
76-
printProtocolResult(profile.output, { builder })
76+
printProtocolResult(
77+
profile.output,
78+
options.full
79+
? { builder: found.reference }
80+
: {
81+
builder: compactBuilder(found.reference),
82+
next: {
83+
command: `${typedCommandLine(command, [found.reference.key])} --full`,
84+
reason:
85+
"Every param's type, enum, default and doc: the brief names the optional ones only.",
86+
},
87+
}
88+
)
7789
} else {
7890
printLine(
7991
(options.full ? renderBuilderReference : renderCompactBuilder)(found.reference)

‎packages/workflow-code/src/json-fields.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ export function refValueKind(
229229
}
230230
const block = scope.block(head.name)
231231
if (!block || segments.length === 0) return 'untyped'
232-
// A loop or parallel's `results` is the array of every iteration's output.
232+
// A loop or parallel's `results` holds one list per iteration, of its body blocks' outputs.
233233
if (block.subflow) {
234234
const [first] = segments
235235
return segments.length === 1 && first?.kind === 'name' && first.name === 'results'

‎packages/workflow-sdk/cookbook/examples/agents.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,10 +66,10 @@ export default workflow(
6666
inputMapping: { email: start.email },
6767
})
6868

69-
// Parallel: one branch per item, run at once. p.currentItem is the item and p.index its
70-
// position; each.results lists every branch's output once all finish. (loop.forEach is the
71-
// sequential form.) In a function code file inside the body, the same values are
72-
// $ref.parallel.currentItem and $ref.parallel.index.
69+
// Parallel: one branch per item, run at once (loop.forEach is the sequential form).
70+
// p.currentItem is the item and p.index its position; once all finish, each.results[i] lists
71+
// branch i's body-block outputs (one block: each.results[i][0]). In a function code file
72+
// inside the body, the same values are $ref.parallel.currentItem and $ref.parallel.index.
7373
const each = parallel.collection('Each Domain', { collection: start.domains }, (p) => {
7474
const brief = agent('Company Brief', {
7575
model: 'claude-sonnet-4-6',

‎packages/workflow-sdk/cookbook/examples/cookbook.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -138,8 +138,8 @@ export default workflow('Cookbook', { description: 'One example of each common b
138138
else: true,
139139
})
140140

141-
// Loop over a list: p.currentItem is one element and p.index its position; the loop's results
142-
// is the list of iteration outputs. In js`` code a reference is the value itself, not text
141+
// Loop over a list: p.currentItem is one element and p.index its position; each.results[i] is
142+
// iteration i's body-block outputs (one block: [i][0]). In js`` code a reference is the value itself, not text
143143
// spliced in: write it where an expression goes, never inside quotes ('${x}' would give the
144144
// JSON, quotes included). A function code file (code: codeFile('./functions/line.js')) reads
145145
// other blocks as $ref.<block key>.<path> ($ref.recentorders.rows) and, inside the loop body,

‎packages/workflow-sdk/src/codegen/cookbook-text.generated.ts‎

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

0 commit comments

Comments
 (0)