Skip to content

Commit 1bdc20a

Browse files
authored
fix(workflow-code): keep js template escapes verbatim, add table agent tool form, pin create fingerprint (#10528)
* fix(workflow-code): keep js template escapes verbatim, add table/knowledge/file agent tool forms, pin create fingerprint - js/py/sh/json/md tagged templates now store the raw text written between the backticks (only \` and \${ are escapes), so js`/\s+/` stores /\s+/ instead of silently dropping the backslash. The printer writes code back so compile reads exactly the stored text, using ${'...'} for what raw text cannot hold. - The catalog marks the built-in blocks the agent tool picker offers (agentTool), so table.tool.queryRows(...), knowledge.tool.search(...) and file.tool.read(...) compile and print instead of requiring raw(). - A source write now prints its answer with the workspace's resource keys for any resource the source wrote by id, so the returned fingerprint matches the next read and a pinned deploy (create --deploy no longer fails with a draft-changed conflict). * fix(workflow-code): read verbatim tags through the file's SDK imports in the character check A cooked t imported as js skipped the NUL/lone-surrogate check while compile still read it cooked. Also documents that agentTool marks hidden legacy versions. * docs(workflow-sdk): show a table operation as an agent tool in the agents cookbook
1 parent c2d0e6b commit 1bdc20a

32 files changed

Lines changed: 603 additions & 102 deletions

File tree

‎apps/docs/content/docs/workflows/code/syntax.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,8 @@ The optional third argument holds what belongs to the block, not to its settings
160160
| `` json`…` `` | JSON text kept as written |
161161
| `` md`…` `` | Markdown, such as a note's content |
162162

163+
Code and markup (`js`, `py`, `sh`, `json`, `md`) are stored exactly as written between the backticks, like `String.raw`: `` js`/\s+/.test(x)` `` stores `/\s+/.test(x)`. Only `` \` `` and `\${` are escapes, for a backtick and a literal `${` in the code. A `t` template is text and reads like a JavaScript string, so `\n` in it is a newline.
164+
163165
### Resource helpers
164166

165167
A key is the resource's stable key in the workspace; `.sim/sdk/workspace.d.ts` lists them. A key with no live resource is `E_MAT_UNKNOWN_RESOURCE` on apply.

‎apps/docs/openapi-v2-resources.json‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32073,6 +32073,11 @@
3207332073
"description": "At most one per workflow.",
3207432074
"type": "boolean"
3207532075
},
32076+
"agentTool": {
32077+
"description": "A built-in block the agent tool picker offers beside integrations, so its operations have an agent-tool form.",
32078+
"type": "boolean",
32079+
"const": true
32080+
},
3207632081
"subBlocks": {
3207732082
"type": "array",
3207832083
"items": {

‎apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,6 @@ import {
6868
import type { StoredTool } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/types'
6969
import {
7070
isAgentToolBlock,
71-
isCoreAgentToolBlock,
7271
isCustomToolAlreadySelected,
7372
isMcpToolAlreadySelected,
7473
isWorkflowAlreadySelected,
@@ -81,6 +80,7 @@ import {
8180
useActiveSearchTarget,
8281
} from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/providers/active-search-target-provider'
8382
import { getAllBlocks, getBlock } from '@/blocks'
83+
import { isCoreAgentToolBlock } from '@/blocks/agent-tools'
8484
import { isCustomBlockType } from '@/blocks/custom/build-config'
8585
import { useCustomBlockOverlayVersion } from '@/blocks/custom/client-overlay'
8686
import { getTileIconColorClass } from '@/blocks/icon-color'

‎apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/utils.ts‎

Lines changed: 1 addition & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,9 @@
1-
import { stripVersionSuffix } from '@sim/utils/string'
21
import type { StoredTool } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/types'
2+
import { isCoreAgentToolBlock } from '@/blocks/agent-tools'
33
import type { BlockConfig } from '@/blocks/types'
44
import { resolveModelProviderId } from '@/blocks/utils'
55
import { supportsToolUsageControl } from '@/providers/models'
66

7-
/**
8-
* Core blocks the agent tool picker offers even though they are not
9-
* `category: 'tools'`. Stored as BASE types and matched after stripping the
10-
* `_vN` suffix, so a new version never has to be re-listed here.
11-
*/
12-
const CORE_AGENT_TOOL_TYPES = new Set([
13-
'api',
14-
'webhook_request',
15-
'workflow',
16-
'workflow_input',
17-
'knowledge',
18-
'function',
19-
'table',
20-
'file',
21-
])
22-
237
/**
248
* Checks whether a registered block should appear in the agent tool picker.
259
*
@@ -35,14 +19,6 @@ export function isAgentToolBlock(
3519
return isCoreAgentToolBlock(block)
3620
}
3721

38-
/**
39-
* Checks whether a block is one of the platform's core agent tools, which the
40-
* picker lists under "Built-in Tools" rather than "Integrations".
41-
*/
42-
export function isCoreAgentToolBlock(block: Pick<BlockConfig, 'type'>): boolean {
43-
return CORE_AGENT_TOOL_TYPES.has(stripVersionSuffix(block.type))
44-
}
45-
4622
/**
4723
* Checks if an MCP tool is already selected.
4824
*/

‎apps/sim/blocks/agent-tools.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { stripVersionSuffix } from '@sim/utils/string'
2+
import type { BlockConfig } from '@/blocks/types'
3+
4+
/**
5+
* Core blocks the agent tool picker offers even though they are not
6+
* `category: 'tools'`. Stored as BASE types and matched after stripping the
7+
* `_vN` suffix, so a new version never has to be re-listed here.
8+
*/
9+
const CORE_AGENT_TOOL_TYPES = new Set([
10+
'api',
11+
'webhook_request',
12+
'workflow',
13+
'workflow_input',
14+
'knowledge',
15+
'function',
16+
'table',
17+
'file',
18+
])
19+
20+
/**
21+
* Checks whether a block is one of the platform's core agent tools, which the
22+
* picker lists under "Built-in Tools" rather than "Integrations" and the
23+
* workflow source catalog marks `agentTool`.
24+
*/
25+
export function isCoreAgentToolBlock(block: Pick<BlockConfig, 'type'>): boolean {
26+
return CORE_AGENT_TOOL_TYPES.has(stripVersionSuffix(block.type))
27+
}

‎apps/sim/lib/api/contracts/v2/source-catalog.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,12 @@ const catalogBlockSchema = z
318318
.optional()
319319
.describe('Trigger mode support.'),
320320
singleInstance: z.boolean().optional().describe('At most one per workflow.'),
321+
agentTool: z
322+
.literal(true)
323+
.optional()
324+
.describe(
325+
'A built-in block the agent tool picker offers beside integrations, so its operations have an agent-tool form.'
326+
),
321327
subBlocks: z
322328
.array(z.union([catalogSubBlockSchema, sharedSubBlockRefSchema, triggerSubBlocksRefSchema]))
323329
.describe('Configuration fields in declared order, inline or by reference.'),

‎apps/sim/lib/workflows/application/apply-workflow-source.integration.ts‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ import {
5757
createWorkflowFromSource,
5858
planWorkflowSource,
5959
} from '@/lib/workflows/application/apply-workflow-source'
60+
import { deployWorkflow } from '@/lib/workflows/application/deployments'
6061
import { readWorkflowSource } from '@/lib/workflows/application/read-workflow-source'
6162
import { WorkflowSourceRejectedError } from '@/lib/workflows/application/source-error'
6263
import {
@@ -356,6 +357,70 @@ export default workflow('Each item', {}, () => {
356357
expect(result.diff.noop).toBe(true)
357358
})
358359

360+
check(
361+
'a create naming tables by id answers with the fingerprint its next read and a pinned deploy see',
362+
async () => {
363+
const tableNamed = async (keyed: boolean) => {
364+
const name = `tool_rows_${generateId().slice(0, 8)}`
365+
const created = await createTableUseCase.execute({
366+
principal,
367+
input: { workspaceId, name, schema: { columns: [{ name: 'email', type: 'string' }] } },
368+
})
369+
if (keyed) {
370+
await claimResourceKey({
371+
workspaceId,
372+
kind: 'table',
373+
key: name,
374+
resourceId: created.table.id,
375+
origin: 'adopted',
376+
createdBy: ownerId,
377+
})
378+
}
379+
return created.table.id
380+
}
381+
const keyed = await tableNamed(true)
382+
const unkeyed = await tableNamed(false)
383+
const tableTool = (tableId: string) =>
384+
`raw({ type: 'table_v2', toolId: 'table_query_rows', operation: 'query_rows', modes: {}, params: { tableId: '${tableId}' } })`
385+
const created = await withPermissionGroupScope(() =>
386+
createWorkflowFromSource.execute({
387+
principal,
388+
input: {
389+
workspaceId,
390+
name: `Source create ${generateId()}`,
391+
files: {
392+
'workflow.ts': `// @sim-sdk 1
393+
import { agent, raw, trigger, workflow } from '@sim/workflow-sdk'
394+
395+
export default workflow('Table tools ${generateId().slice(0, 8)}', {}, () => {
396+
const start = trigger.start('Start', { inputFormat: { q: 'string' } })
397+
const lookup = agent('Lookup', {
398+
model: 'claude-sonnet-4-5',
399+
messages: [{ role: 'user', content: start.q }],
400+
tools: [${tableTool(keyed)}, ${tableTool(unkeyed)}],
401+
})
402+
start.to(lookup)
403+
})
404+
`,
405+
},
406+
},
407+
})
408+
)
409+
expect(created.applied).toBe(true)
410+
411+
const deployed = await deployWorkflow.execute({
412+
principal,
413+
input: {
414+
workflowId: created.workflowId,
415+
requestId: generateId(),
416+
expectedDraftFingerprint: created.base.fingerprint,
417+
},
418+
})
419+
expect(deployed.success).toBe(true)
420+
expect((await getSource(created.workflowId)).base.fingerprint).toBe(created.base.fingerprint)
421+
}
422+
)
423+
359424
check('create keeps the function file name the source wrote', async () => {
360425
const created = await withPermissionGroupScope(() =>
361426
createWorkflowFromSource.execute({

‎apps/sim/lib/workflows/application/source-pipeline/commit.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ export async function commitSource(
8787
target.kind === 'new' ? 'Created workflow from source' : 'Applied workflow source',
8888
logContext
8989
)
90-
return shapeOutcome(frame, printWritten(planned, committed.state), {
90+
return shapeOutcome(frame, await printWritten(planned, committed.state, { allocate: true }), {
9191
applied: true,
9292
wroteSourceMeta: true,
9393
diff: plan.diff,

‎apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ import { loadAvailableResourceKeys, loadResourceKeyResolver } from '@/lib/workfl
3636
* `primary`, falling back to `fallback` for a key, id or name it does not resolve. Whether an id
3737
* is built in is `primary`'s answer alone.
3838
*/
39-
function withFallback(
39+
export function withFallback(
4040
primary: ResourceKeyResolver,
4141
fallback: Pick<ResourceKeyResolver, 'toKey' | 'toId' | 'nameOf'>
4242
): ResourceKeyResolver {

‎apps/sim/lib/workflows/application/source-pipeline/outcome.ts‎

Lines changed: 54 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,24 @@
11
import type { Principal } from '@sim/auth/principal'
22
import { createLogger } from '@sim/logger'
3-
import type {
4-
BlockCatalog,
5-
CanonicalizeResult,
6-
SourceBase,
7-
WorkflowLockV1,
8-
WorkflowSourceMetaV1,
3+
import {
4+
type BlockCatalog,
5+
type CanonicalizeResult,
6+
canonicalize,
7+
type ResourceKeyResolver,
8+
type SourceBase,
9+
type WorkflowLockV1,
10+
type WorkflowSourceMetaV1,
911
} from '@sim/workflow-code'
1012
import type { WorkflowState } from '@sim/workflow-types/workflow'
1113
import { withCatalogBlockScope } from '@/lib/catalog/application/context'
1214
import { previewSourceCommit } from '@/lib/workflows/application/source-commit'
1315
import { emptyDiffSummary, type SourceDiffSummary } from '@/lib/workflows/application/source-diff'
1416
import type { WorkflowSourceDiagnostic } from '@/lib/workflows/application/source-error'
17+
import { withFallback } from '@/lib/workflows/application/source-pipeline/evaluate/resolve'
1518
import { type CommitTarget, targetIds } from '@/lib/workflows/application/source-pipeline/load'
1619
import type { PlannedSource, RefusedSource } from '@/lib/workflows/application/source-pipeline/plan'
1720
import { type PrintedSource, printStoredSource } from '@/lib/workflows/code/print-stored'
21+
import { loadResourceKeyResolver, type ResourceReferences } from '@/lib/workflows/code/resources'
1822
import {
1923
type DeploymentDrift,
2024
readDeploymentDrift,
@@ -102,7 +106,10 @@ export function printPlanned(
102106
{ plan, loaded }: Pick<PlannedSource, 'plan' | 'loaded'>,
103107
state: WorkflowState,
104108
sourceMeta: WorkflowSourceMetaV1 | null,
105-
lockless?: CanonicalizeResult
109+
{
110+
lockless,
111+
resources = plan.resources,
112+
}: { lockless?: CanonicalizeResult; resources?: ResourceKeyResolver } = {}
106113
): PrintedSource {
107114
/** The function files the submission named, kept so a write never renames the author's. */
108115
const codeFiles: Record<string, string> = {}
@@ -113,7 +120,7 @@ export function printPlanned(
113120
state,
114121
meta: plan.meta,
115122
catalog: loaded.catalog,
116-
resources: plan.resources,
123+
resources,
117124
sourceMeta,
118125
functionCode: plan.functionCode,
119126
identity: plan.identity,
@@ -123,16 +130,46 @@ export function printPlanned(
123130
})
124131
}
125132

126-
/** Prints the blocks and edges a write stores with the plan's variables and source meta. */
127-
export function printWritten(
133+
/**
134+
* Prints the blocks and edges a write stores, or a dry run would, with the plan's variables and
135+
* source meta, as the next read prints them. The plan's resolver knows the resources the source
136+
* named by key; one the source wrote by id (a `raw()` tool's literal `tableId`) resolves through
137+
* the workspace's resource keys, allocating a missing key when `allocate` (a commit) as that read
138+
* does. With the plan's resolver alone such a resource would print, and fingerprint, unlike every
139+
* later read and a pinned deploy's draft check.
140+
*/
141+
export async function printWritten(
128142
planned: Pick<PlannedSource, 'plan' | 'loaded'>,
129-
written: Omit<WorkflowState, 'variables'>
130-
): PrintedSource {
131-
return printPlanned(
132-
planned,
133-
{ ...written, variables: planned.plan.storedVariables },
134-
planned.plan.sourceMeta
143+
written: Omit<WorkflowState, 'variables'>,
144+
{ allocate }: { allocate: boolean }
145+
): Promise<PrintedSource> {
146+
const { plan, loaded } = planned
147+
const state = { ...written, variables: plan.storedVariables }
148+
const unresolved: ResourceReferences['ids'] = []
149+
const recording: ResourceKeyResolver = {
150+
toKey(kind, id) {
151+
const key = plan.resources.toKey(kind, id)
152+
if (key === null) unresolved.push({ kind, id })
153+
return key
154+
},
155+
toId: (kind, key) => plan.resources.toId(kind, key),
156+
nameOf: (kind, id) => plan.resources.nameOf?.(kind, id) ?? null,
157+
isBuiltin: plan.resources.isBuiltin,
158+
}
159+
const lockless = canonicalize(state, {
160+
catalog: loaded.catalog,
161+
meta: plan.meta,
162+
resources: recording,
163+
})
164+
if (unresolved.length === 0) return printPlanned(planned, state, plan.sourceMeta, { lockless })
165+
const byId = await loadResourceKeyResolver(
166+
loaded.scope.workspaceId,
167+
{ ids: unresolved },
168+
{ actorUserId: loaded.scope.subjectUserId, allocate }
135169
)
170+
return printPlanned(planned, state, plan.sourceMeta, {
171+
resources: withFallback(plan.resources, byId),
172+
})
136173
}
137174

138175
/**
@@ -177,7 +214,7 @@ export async function previewSource(
177214
workspaceId: loaded.scope.workspaceId,
178215
principalKind: principal.kind,
179216
})
180-
return shapeOutcome(frame, printWritten(planned, preview.state), {
217+
return shapeOutcome(frame, await printWritten(planned, preview.state, { allocate: false }), {
181218
applied: false,
182219
...(isNew
183220
? UNDEPLOYED

0 commit comments

Comments
 (0)