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
2 changes: 1 addition & 1 deletion apps/docs/content/docs/cli/reference.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -8865,7 +8865,7 @@ sim workflows source find <block> [options]

</CommandTable>

Prints each block the name matches, read from the directory alone (no request is made): its declaration in workflow.ts with line numbers, its function file, the wiring statements of its incoming and outgoing edges, and every block that reads its outputs (a param, a branch, or a function file's $ref), each as file:line. &lt;block&gt; is a block name (Security Score), its key (securityscore) or its identifier (securityScore); with no exact match, every block whose name contains it is printed (at most 20). Run it from a workflow source directory, or pass --dir.
Prints each block the name matches, read from the directory alone (no request is made): its declaration in workflow.ts with line numbers, its function file, the wiring statements of its incoming and outgoing edges, and every block that reads its outputs (a param, a branch, or a function file's $ref), each as file:line. &lt;block&gt; is a block name (Security Score), its key (securityscore) or its identifier (securityScore); with no exact match, every block whose name contains it is printed (at most 20). Run it from a workflow source directory, or pass --dir. When the source does not compile, readers are left out (JSON output carries compiles: false).

Exit codes: 0 printed; 1 no block matches (the closest name is suggested), or the directory is not a workflow source directory.

Expand Down
2 changes: 1 addition & 1 deletion apps/docs/content/docs/cli/workflows.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1597,7 +1597,7 @@ sim workflows source find <block> [options]

</CommandTable>

Prints each block the name matches, read from the directory alone (no request is made): its declaration in workflow.ts with line numbers, its function file, the wiring statements of its incoming and outgoing edges, and every block that reads its outputs (a param, a branch, or a function file's $ref), each as file:line. &lt;block&gt; is a block name (Security Score), its key (securityscore) or its identifier (securityScore); with no exact match, every block whose name contains it is printed (at most 20). Run it from a workflow source directory, or pass --dir.
Prints each block the name matches, read from the directory alone (no request is made): its declaration in workflow.ts with line numbers, its function file, the wiring statements of its incoming and outgoing edges, and every block that reads its outputs (a param, a branch, or a function file's $ref), each as file:line. &lt;block&gt; is a block name (Security Score), its key (securityscore) or its identifier (securityScore); with no exact match, every block whose name contains it is printed (at most 20). Run it from a workflow source directory, or pass --dir. When the source does not compile, readers are left out (JSON output carries compiles: false).

Exit codes: 0 printed; 1 no block matches (the closest name is suggested), or the directory is not a workflow source directory.

Expand Down
14 changes: 14 additions & 0 deletions apps/sim/executor/variables/resolver.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { StartBlockPath } from '@/lib/workflows/triggers/triggers'
import { AgentBlock } from '@/blocks/blocks/agent'
import { ResponseBlock } from '@/blocks/blocks/response'
import { TableV2Block } from '@/blocks/blocks/table_v2'
import { WorkflowInputBlock } from '@/blocks/blocks/workflow_input'
import { getBlock } from '@/blocks/registry'
import type { BlockConfig } from '@/blocks/types'
import { BlockType } from '@/executor/constants'
Expand Down Expand Up @@ -1296,6 +1297,7 @@ describe('VariableResolver JSON text inputs', () => {
[BlockType.AGENT]: AgentBlock,
[BlockType.RESPONSE]: ResponseBlock,
table_v2: TableV2Block,
[BlockType.WORKFLOW_INPUT]: WorkflowInputBlock,
}

beforeEach(() => {
Expand Down Expand Up @@ -1452,6 +1454,18 @@ describe('VariableResolver JSON text inputs', () => {
expect(JSON.parse(resolved.data)).toEqual({ body: awkwardText })
})

it('escapes references in a child workflow input mapping stored as JSON text', async () => {
const { resolve } = createJsonResolver(BlockType.WORKFLOW_INPUT, {
workflowId: 'child',
inputMapping: '{"summary": "<producer.text>", "record": "<producer.record>"}',
})
const resolved = await resolve()
expect(JSON.parse(resolved.inputMapping)).toEqual({
summary: awkwardText,
record: JSON.stringify({ name: 'Ada "the first"', tags: ['x', 'y'] }),
})
})

it('leaves quoted references in non-JSON fields raw', async () => {
const { resolve } = createJsonResolver(BlockType.AGENT, {
userPrompt: '{"note": "<producer.text>"}',
Expand Down
16 changes: 10 additions & 6 deletions apps/sim/executor/variables/resolver.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createLogger } from '@sim/logger'
import { toError } from '@sim/utils/errors'
import { JSON_TEXT_CONTAINER_TYPES } from '@sim/workflow-code/json-text'
import { isUserFileWithMetadata } from '@/lib/core/utils/user-file'
import { mergeLargeValueKeys } from '@/lib/execution/payloads/access-keys'
import { isLargeArrayManifest } from '@/lib/execution/payloads/large-array-manifest-metadata'
Expand Down Expand Up @@ -322,16 +323,19 @@ interface TemplateResolutionOptions {
jsonText?: boolean
}

/** Whether `key` is a block input the editor stores as JSON text (a JSON code field). */
function isJsonCodeInput(block: SerializedBlock | undefined, key: string): boolean {
/**
* Whether `key` is a block input that may hold JSON text: a JSON code field, or a container field
* (`JSON_TEXT_CONTAINER_TYPES`) whose runtime parses text and objects alike.
*/
function isJsonTextInput(block: SerializedBlock | undefined, key: string): boolean {
const blockType = block?.metadata?.id
if (!blockType) return false
return (
getBlock(blockType)?.subBlocks.some(
(subBlock) =>
subBlock.type === 'code' &&
subBlock.language === 'json' &&
(subBlock.id === key || subBlock.canonicalParamId === key)
(subBlock.id === key || subBlock.canonicalParamId === key) &&
((subBlock.type === 'code' && subBlock.language === 'json') ||
JSON_TEXT_CONTAINER_TYPES.has(subBlock.type))
) ?? false
)
}
Expand Down Expand Up @@ -516,7 +520,7 @@ export class VariableResolver {
resolved[key] = await this.resolveValue(ctx, currentNodeId, value, undefined, block, {
allowLargeValueRefs: this.canResolveInputToLargeValueRef(block, key),
inputPath: [key],
jsonText: typeof value === 'string' && isJSONString(value) && isJsonCodeInput(block, key),
jsonText: typeof value === 'string' && isJSONString(value) && isJsonTextInput(block, key),
})
}
return resolved
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/lib/workflows/canonical/subblock-value.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { JSON_TEXT_CONTAINER_TYPES, parseJsonContainer } from '@sim/workflow-code'
import { JSON_TEXT_CONTAINER_TYPES, parseJsonContainer } from '@sim/workflow-code/json-text'
import {
normalizedStringify,
sanitizeInputFormat,
Expand Down
23 changes: 23 additions & 0 deletions apps/sim/lib/workflows/code/api-built-source.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,3 +168,26 @@ describe('a child workflow call whose input mapping the operations route stored
expect(typeCheckAgainstSdk(workDir, 'edited', [file])).toBe('')
}, 120_000)
})

describe('a child workflow call whose input mapping is one whole reference', () => {
it('stores an object written over the reference natively, not as JSON text', () => {
const stored = builtWorkflow()
const call = createBlockFromParams('call-block', {
type: 'workflow_input',
name: 'Record Audit',
inputs: { workflowId: 'child-workflow', inputMapping: '<start.input>' },
})
stored.blocks[call.id] = { ...call, position: { x: 800, y: 0 } }
const written = getThenApply(stored, (text) =>
text.replace(
'inputMapping: start.input,',
"inputMapping: { ticketId: start.input, source: 'api' },"
)
)
expect(written.errors).toEqual([])
expect(written.state.blocks['call-block']?.subBlocks.inputMapping?.value).toEqual({
ticketId: '<start.input>',
source: 'api',
})
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ beforeEach(() => {
writeFileSync(join(dir, 'workflow.ts'), WORKFLOW_TS)
writeFileSync(
join(dir, 'functions/score.js'),
"const s = 1\nreturn $ref.fetchpolicy.data\nconst tag = '<fetchpolicy.status>'\n"
"const s = 1\nreturn $ref.fetchpolicy.data ?? $ref.fetchpolicy.status\nconst tag = '<fetchpolicy.status>'\n"
)
writeFileSync(join(dir, 'functions/audit.py'), 'import json\nprint(<fetchpolicy.data>)\n')
vi.stubEnv('SIM_CONFIG_DIR', join(dir, 'config'))
Expand Down Expand Up @@ -128,4 +128,30 @@ describe('sim workflows source find', () => {
message: expect.stringContaining('Did you mean Fetch Policy?'),
})
})

it('says the source does not compile instead of only that no block matches', async () => {
writeFileSync(
join(dir, 'workflow.ts'),
WORKFLOW_TS.replace("api('Fetch Policy', {", "api('Fetch Policy', {{")
)
await expect(find('Fetch Policy')).rejects.toMatchObject({
code: 'BLOCK_UNKNOWN',
message: expect.stringContaining('does not compile'),
})
})

it('reads a wiring statement the printer wrapped as one statement', async () => {
const wrapped = WORKFLOW_TS.replace('fetchPolicy.to(audit)', 'fetchPolicy.to(\n audit,\n )')
writeFileSync(join(dir, 'workflow.ts'), wrapped)
await find('Audit')
const [block] = stdoutJson().blocks
expect(block.incoming).toMatchObject([
{ block: 'Fetch Policy', statement: 'fetchPolicy.to(audit)' },
])
})

it('refuses an empty name rather than matching every block', async () => {
await expect(find(' ')).rejects.toMatchObject({ code: 'BLOCK_UNKNOWN' })
await expect(find('.')).rejects.toMatchObject({ code: 'BLOCK_UNKNOWN' })
})
})
47 changes: 41 additions & 6 deletions packages/sim-cli/src/commands/protocol/workflow-source-find.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
fromCodeFile,
LineIndex,
referencedHeads,
type SourceSpan,
type StoredEdgeRef,
} from '@sim/workflow-code'
import { SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits'
Expand All @@ -35,6 +36,7 @@ incoming and outgoing edges, and every block that reads its outputs (a param, a
function file's $ref), each as file:line. <block> is a block name (Security Score), its key
(securityscore) or its identifier (securityScore); with no exact match, every block whose name
contains it is printed (at most ${MAX_FOUND}). Run it from a workflow source directory, or pass --dir.
When the source does not compile, readers are left out (JSON output carries compiles: false).

Exit codes: 0 printed; 1 no block matches (the closest name is suggested), or the
directory is not a workflow source directory.`
Expand Down Expand Up @@ -132,7 +134,11 @@ function blockFields(block: CanonicalBlock): Array<{ field: string; texts: strin
*/
function readersByKey(index: SourceIndex): Map<BlockKey, Reader[]> {
const readers = new Map<BlockKey, Reader[]>()
const seen = new Set<string>()
const add = (key: BlockKey, reader: Reader) => {
const id = JSON.stringify([key, reader.file, reader.line, reader.block, reader.field])
if (seen.has(id)) return
seen.add(id)
const list = readers.get(key)
if (list) list.push(reader)
else readers.set(key, [reader])
Expand Down Expand Up @@ -184,14 +190,38 @@ function matchBlocks(index: SourceIndex, query: string): BlockKey[] {
.filter((key) => key.includes(normalized) || index.nameOf(key).toLowerCase().includes(needle))
}

/** The refusal for a query no block matches, naming the closest block. */
/**
* The refusal for a query no block matches, naming the closest block, and saying so when the
* source does not compile (a parse failure names no blocks at all).
*/
function unknownBlock(index: SourceIndex, query: string): CliUsageError {
const names = index
.keys()
.map((key) => index.nameOf(key))
.sort(compareStrings)
const hint = didYouMean(query, names) ?? `It has ${names.length} blocks.`
return new CliUsageError(`No block is named ${query}. ${hint}`, { code: 'BLOCK_UNKNOWN' })
const compileNote =
index.compiled.workflow === null
? ' The source does not compile: run `sim workflows source check`.'
: ''
return new CliUsageError(`No block is named ${query}. ${hint}${compileNote}`, {
code: 'BLOCK_UNKNOWN',
})
}

/**
* A wiring statement's text on one line, so a fan-out the printer wrapped reads whole. Only the
* line breaks are rewritten, so a raw handle's text is printed as written.
*/
function statementText(index: SourceIndex, span: SourceSpan): string {
const lines = index.linesOf(span.file)?.lines.slice(span.line - 1, span.endLine) ?? []
return lines
.map((line) => line.trim())
.reduce((joined, line) => {
if (joined === '') return line
if (line.startsWith(')')) return `${joined.replace(/,$/, '')}${line}`
return joined.endsWith('(') ? `${joined}${line}` : `${joined} ${line}`
}, '')
}

function describeBlock(
Expand All @@ -209,9 +239,7 @@ function describeBlock(
port: ref.port,
file: written?.file ?? SOURCE_ENTRY_FILE,
line: written?.line ?? span?.line ?? 0,
statement: written
? (index.linesOf(written.file)?.lines[written.line - 1]?.trim() ?? '')
: '',
statement: written ? statementText(index, written) : '',
}
}
const ends = (side: 'from' | 'to', other: 'from' | 'to') =>
Expand Down Expand Up @@ -273,6 +301,9 @@ export function attachWorkflowSourceFind(source: Command): void {
await assertSourceDirKind(options.dir, 'workflow')
const catalog = await lookupCatalog(options.dir, profile)
const { compiled, files } = await compileWorkflowDir(options.dir, catalog)
if (normalizeWorkflowBlockName(query) === '') {
throw new CliUsageError('Name a block.', { code: 'BLOCK_UNKNOWN' })
}
const index = new SourceIndex(compiled, files)
const keys = matchBlocks(index, query)
if (keys.length === 0) throw unknownBlock(index, query)
Expand All @@ -283,7 +314,11 @@ export function attachWorkflowSourceFind(source: Command): void {
.sort(byLine)
const more = keys.length - found.length
if (isMachine(profile.output)) {
printProtocolResult(profile.output, { blocks: found, ...(more > 0 ? { more } : {}) })
printProtocolResult(profile.output, {
blocks: found,
compiles: compiled.workflow !== null,
...(more > 0 ? { more } : {}),
})
return
}
if (compiled.workflow === null) {
Expand Down
4 changes: 4 additions & 0 deletions packages/workflow-code/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@
"types": "./src/diagnostics/codes.ts",
"default": "./src/diagnostics/codes.ts"
},
"./json-text": {
"types": "./src/json-text.ts",
"default": "./src/json-text.ts"
},
"./code-files/references": {
"types": "./src/code-files/references.ts",
"default": "./src/code-files/references.ts"
Expand Down
15 changes: 2 additions & 13 deletions packages/workflow-code/src/canonicalize/params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import { isConditionClause } from '../catalog/conditions'
import type { CatalogBlock, CatalogCondition, CatalogSubBlock } from '../catalog/types'
import { declarationsOf } from '../catalog/view'
import { diagnostic } from '../diagnostics/factory'
import { JSON_TEXT_CONTAINER_TYPES, parseJsonContainer } from '../json-text'
import type { BlockKey, CanonicalParam, SubBlockId, Value } from '../model'
import { parseJsonContainer, setOwn } from '../records'
import { setOwn } from '../records'
import { structuredCodec } from '../structured'
import type { CanonContext } from './context'
import { liftTools } from './tools'
Expand Down Expand Up @@ -60,18 +61,6 @@ function holdsJsonText(declaration: CatalogSubBlock): boolean {
return declaration.structured !== undefined || declaration.storage === 'json-string'
}

/**
* Field types whose runtime reads JSON text and the container it encodes alike: the workflow
* handler and the tool runners parse a child workflow's `inputMapping` either way, and the
* operations route stores either. Canonicalize decodes the text so it prints as the object source
* can type, and deploy-change detection takes the two encodings as one value. Any other native
* container field stays as stored, since its runtime reads only one form.
*/
export const JSON_TEXT_CONTAINER_TYPES: ReadonlySet<string> = new Set([
'input-mapping',
'workflow-input-mapper',
])

/** A field of a {@link JSON_TEXT_CONTAINER_TYPES} type; text that does not parse stays a value. */
function holdsNativeContainer(declaration: CatalogSubBlock): boolean {
return JSON_TEXT_CONTAINER_TYPES.has(declaration.type)
Expand Down
3 changes: 2 additions & 1 deletion packages/workflow-code/src/canonicalize/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ import { mcpBinding, mcpToolId } from '../agent-tools'
import { type CanonicalModeOverrides, scopeCanonicalModesForTool } from '../catalog/canonical-index'
import type { BlockCatalog, CatalogSubBlock } from '../catalog/types'
import { catalogBlock } from '../catalog/view'
import { parseJsonContainer } from '../json-text'
import { type BlockKey, type CanonicalTool, isUsageControl, type Json, type Value } from '../model'
import { parseJsonContainer, setOwn } from '../records'
import { setOwn } from '../records'
import type { CanonContext } from './context'
import { toolModes } from './modes'
import { liftResourceId, liftResourceValue, toJson, toValue } from './values'
Expand Down
4 changes: 2 additions & 2 deletions packages/workflow-code/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ export { decodeAnchor, encodeAnchor } from './anchors'
export { babelErrorShape, babelMessage } from './babel'
export { type CanonicalizeResult, canonicalize, canonicalizeUnderLock } from './canonicalize'
export { toolModes } from './canonicalize/modes'
export { JSON_TEXT_CONTAINER_TYPES } from './canonicalize/params'
export {
builderProducedOutputs,
executableInactiveParams,
Expand Down Expand Up @@ -89,6 +88,7 @@ export { executableView } from './equivalence/executable'
export { sha256Hex, stableStringify } from './hash'
export { readsIterationOutOfScope, type ScopeNode } from './iteration-scope'
export { type ChildResultFields, parseJsonField } from './json-fields'
export { parseJsonContainer } from './json-text'
export {
type DefinedField,
fieldNames,
Expand Down Expand Up @@ -131,7 +131,7 @@ export type {
export { isResourceKind } from './model'
export { assignIdentifiers, printWorkflow, referencedHeads } from './print'
export { hasSuspiciousCharacter, printKey, printNumber, quoteString } from './print/strings'
export { getOwn, invertRecord, parseJsonContainer, setOrDelete, setOwn } from './records'
export { getOwn, invertRecord, setOrDelete, setOwn } from './records'
export {
calledWorkflowKey,
calledWorkflowKeys,
Expand Down
3 changes: 2 additions & 1 deletion packages/workflow-code/src/json-fields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import type { BlockCatalog, CatalogOutput } from './catalog/types'
import { catalogBlock } from './catalog/view'
import { ENV_VAR_NAME, parseStoredPath, type RefSegment } from './code-files/ref-path'
import { referencedResultKind } from './compile/function-returns'
import { parseJsonContainer } from './json-text'
import {
type BlockKey,
type CanonicalBlock,
Expand All @@ -33,7 +34,7 @@ import {
isSimNode,
type Value,
} from './model'
import { getOwn, parseJsonContainer, setOwn } from './records'
import { getOwn, setOwn } from './records'

/** A reference at a leaf of a JSON field: the stored token, and whether the text quotes it. */
export class JsonRef {
Expand Down
33 changes: 33 additions & 0 deletions packages/workflow-code/src/json-text.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* JSON-text decoding shared by canonicalize, the app's deploy-change detection and the executor.
* Dependency-free so client bundles and the executor can import it without the compiler.
*/

/**
* Field types whose runtime reads JSON text and the container it encodes alike: the workflow
* handler and the tool runners parse a child workflow's `inputMapping` either way, and the
* operations route stores either. Canonicalize decodes the text so it prints as the object source
* can type, deploy-change detection takes the two encodings as one value, and the executor
* escapes a reference spliced into the text's string literals. Any other native
* container field stays as stored, since its runtime reads only one form.
*/
export const JSON_TEXT_CONTAINER_TYPES: ReadonlySet<string> = new Set([
'input-mapping',
'workflow-input-mapper',
])

/**
* JSON text that holds an object or array, decoded; `undefined` for blank text, text that does not
* parse, and a scalar, which callers keep as the text it is.
*/
export function parseJsonContainer(text: string): Record<string, unknown> | unknown[] | undefined {
if (text.trim() === '') return undefined
try {
const parsed: unknown = JSON.parse(text)
return typeof parsed === 'object' && parsed !== null
? (parsed as Record<string, unknown> | unknown[])
: undefined
} catch {
return undefined
}
}
Loading
Loading