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: 2 additions & 0 deletions apps/docs/content/docs/workflows/code/syntax.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,8 @@ The optional third argument holds what belongs to the block, not to its settings
| `` json`…` `` | JSON text kept as written |
| `` md`…` `` | Markdown, such as a note's content |

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.

### Resource helpers

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.
Expand Down
5 changes: 5 additions & 0 deletions apps/docs/openapi-v2-resources.json
Original file line number Diff line number Diff line change
Expand Up @@ -32073,6 +32073,11 @@
"description": "At most one per workflow.",
"type": "boolean"
},
"agentTool": {
"description": "A built-in block the agent tool picker offers beside integrations, so its operations have an agent-tool form.",
"type": "boolean",
"const": true
},
"subBlocks": {
"type": "array",
"items": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ import {
import type { StoredTool } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/types'
import {
isAgentToolBlock,
isCoreAgentToolBlock,
isCustomToolAlreadySelected,
isMcpToolAlreadySelected,
isWorkflowAlreadySelected,
Expand All @@ -81,6 +80,7 @@ import {
useActiveSearchTarget,
} from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/providers/active-search-target-provider'
import { getAllBlocks, getBlock } from '@/blocks'
import { isCoreAgentToolBlock } from '@/blocks/agent-tools'
import { isCustomBlockType } from '@/blocks/custom/build-config'
import { useCustomBlockOverlayVersion } from '@/blocks/custom/client-overlay'
import { getTileIconColorClass } from '@/blocks/icon-color'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,25 +1,9 @@
import { stripVersionSuffix } from '@sim/utils/string'
import type { StoredTool } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/types'
import { isCoreAgentToolBlock } from '@/blocks/agent-tools'
import type { BlockConfig } from '@/blocks/types'
import { resolveModelProviderId } from '@/blocks/utils'
import { supportsToolUsageControl } from '@/providers/models'

/**
* Core blocks the agent tool picker offers even though they are not
* `category: 'tools'`. Stored as BASE types and matched after stripping the
* `_vN` suffix, so a new version never has to be re-listed here.
*/
const CORE_AGENT_TOOL_TYPES = new Set([
'api',
'webhook_request',
'workflow',
'workflow_input',
'knowledge',
'function',
'table',
'file',
])

/**
* Checks whether a registered block should appear in the agent tool picker.
*
Expand All @@ -35,14 +19,6 @@ export function isAgentToolBlock(
return isCoreAgentToolBlock(block)
}

/**
* Checks whether a block is one of the platform's core agent tools, which the
* picker lists under "Built-in Tools" rather than "Integrations".
*/
export function isCoreAgentToolBlock(block: Pick<BlockConfig, 'type'>): boolean {
return CORE_AGENT_TOOL_TYPES.has(stripVersionSuffix(block.type))
}

/**
* Checks if an MCP tool is already selected.
*/
Expand Down
27 changes: 27 additions & 0 deletions apps/sim/blocks/agent-tools.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { stripVersionSuffix } from '@sim/utils/string'
import type { BlockConfig } from '@/blocks/types'

/**
* Core blocks the agent tool picker offers even though they are not
* `category: 'tools'`. Stored as BASE types and matched after stripping the
* `_vN` suffix, so a new version never has to be re-listed here.
*/
const CORE_AGENT_TOOL_TYPES = new Set([
'api',
'webhook_request',
'workflow',
'workflow_input',
'knowledge',
'function',
'table',
'file',
])

/**
* Checks whether a block is one of the platform's core agent tools, which the
* picker lists under "Built-in Tools" rather than "Integrations" and the
* workflow source catalog marks `agentTool`.
*/
export function isCoreAgentToolBlock(block: Pick<BlockConfig, 'type'>): boolean {
return CORE_AGENT_TOOL_TYPES.has(stripVersionSuffix(block.type))
}
6 changes: 6 additions & 0 deletions apps/sim/lib/api/contracts/v2/source-catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,12 @@ const catalogBlockSchema = z
.optional()
.describe('Trigger mode support.'),
singleInstance: z.boolean().optional().describe('At most one per workflow.'),
agentTool: z
.literal(true)
.optional()
.describe(
'A built-in block the agent tool picker offers beside integrations, so its operations have an agent-tool form.'
),
subBlocks: z
.array(z.union([catalogSubBlockSchema, sharedSubBlockRefSchema, triggerSubBlocksRefSchema]))
.describe('Configuration fields in declared order, inline or by reference.'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ import {
createWorkflowFromSource,
planWorkflowSource,
} from '@/lib/workflows/application/apply-workflow-source'
import { deployWorkflow } from '@/lib/workflows/application/deployments'
import { readWorkflowSource } from '@/lib/workflows/application/read-workflow-source'
import { WorkflowSourceRejectedError } from '@/lib/workflows/application/source-error'
import {
Expand Down Expand Up @@ -356,6 +357,70 @@ export default workflow('Each item', {}, () => {
expect(result.diff.noop).toBe(true)
})

check(
'a create naming tables by id answers with the fingerprint its next read and a pinned deploy see',
async () => {
const tableNamed = async (keyed: boolean) => {
const name = `tool_rows_${generateId().slice(0, 8)}`
const created = await createTableUseCase.execute({
principal,
input: { workspaceId, name, schema: { columns: [{ name: 'email', type: 'string' }] } },
})
if (keyed) {
await claimResourceKey({
workspaceId,
kind: 'table',
key: name,
resourceId: created.table.id,
origin: 'adopted',
createdBy: ownerId,
})
}
return created.table.id
}
const keyed = await tableNamed(true)
const unkeyed = await tableNamed(false)
const tableTool = (tableId: string) =>
`raw({ type: 'table_v2', toolId: 'table_query_rows', operation: 'query_rows', modes: {}, params: { tableId: '${tableId}' } })`
const created = await withPermissionGroupScope(() =>
createWorkflowFromSource.execute({
principal,
input: {
workspaceId,
name: `Source create ${generateId()}`,
files: {
'workflow.ts': `// @sim-sdk 1
import { agent, raw, trigger, workflow } from '@sim/workflow-sdk'

export default workflow('Table tools ${generateId().slice(0, 8)}', {}, () => {
const start = trigger.start('Start', { inputFormat: { q: 'string' } })
const lookup = agent('Lookup', {
model: 'claude-sonnet-4-5',
messages: [{ role: 'user', content: start.q }],
tools: [${tableTool(keyed)}, ${tableTool(unkeyed)}],
})
start.to(lookup)
})
`,
},
},
})
)
expect(created.applied).toBe(true)

const deployed = await deployWorkflow.execute({
principal,
input: {
workflowId: created.workflowId,
requestId: generateId(),
expectedDraftFingerprint: created.base.fingerprint,
},
})
expect(deployed.success).toBe(true)
expect((await getSource(created.workflowId)).base.fingerprint).toBe(created.base.fingerprint)
}
)

check('create keeps the function file name the source wrote', async () => {
const created = await withPermissionGroupScope(() =>
createWorkflowFromSource.execute({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export async function commitSource(
target.kind === 'new' ? 'Created workflow from source' : 'Applied workflow source',
logContext
)
return shapeOutcome(frame, printWritten(planned, committed.state), {
return shapeOutcome(frame, await printWritten(planned, committed.state, { allocate: true }), {
applied: true,
wroteSourceMeta: true,
diff: plan.diff,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import { loadAvailableResourceKeys, loadResourceKeyResolver } from '@/lib/workfl
* `primary`, falling back to `fallback` for a key, id or name it does not resolve. Whether an id
* is built in is `primary`'s answer alone.
*/
function withFallback(
export function withFallback(
primary: ResourceKeyResolver,
fallback: Pick<ResourceKeyResolver, 'toKey' | 'toId' | 'nameOf'>
): ResourceKeyResolver {
Expand Down
71 changes: 54 additions & 17 deletions apps/sim/lib/workflows/application/source-pipeline/outcome.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,24 @@
import type { Principal } from '@sim/auth/principal'
import { createLogger } from '@sim/logger'
import type {
BlockCatalog,
CanonicalizeResult,
SourceBase,
WorkflowLockV1,
WorkflowSourceMetaV1,
import {
type BlockCatalog,
type CanonicalizeResult,
canonicalize,
type ResourceKeyResolver,
type SourceBase,
type WorkflowLockV1,
type WorkflowSourceMetaV1,
} from '@sim/workflow-code'
import type { WorkflowState } from '@sim/workflow-types/workflow'
import { withCatalogBlockScope } from '@/lib/catalog/application/context'
import { previewSourceCommit } from '@/lib/workflows/application/source-commit'
import { emptyDiffSummary, type SourceDiffSummary } from '@/lib/workflows/application/source-diff'
import type { WorkflowSourceDiagnostic } from '@/lib/workflows/application/source-error'
import { withFallback } from '@/lib/workflows/application/source-pipeline/evaluate/resolve'
import { type CommitTarget, targetIds } from '@/lib/workflows/application/source-pipeline/load'
import type { PlannedSource, RefusedSource } from '@/lib/workflows/application/source-pipeline/plan'
import { type PrintedSource, printStoredSource } from '@/lib/workflows/code/print-stored'
import { loadResourceKeyResolver, type ResourceReferences } from '@/lib/workflows/code/resources'
import {
type DeploymentDrift,
readDeploymentDrift,
Expand Down Expand Up @@ -102,7 +106,10 @@ export function printPlanned(
{ plan, loaded }: Pick<PlannedSource, 'plan' | 'loaded'>,
state: WorkflowState,
sourceMeta: WorkflowSourceMetaV1 | null,
lockless?: CanonicalizeResult
{
lockless,
resources = plan.resources,
}: { lockless?: CanonicalizeResult; resources?: ResourceKeyResolver } = {}
): PrintedSource {
/** The function files the submission named, kept so a write never renames the author's. */
const codeFiles: Record<string, string> = {}
Expand All @@ -113,7 +120,7 @@ export function printPlanned(
state,
meta: plan.meta,
catalog: loaded.catalog,
resources: plan.resources,
resources,
sourceMeta,
functionCode: plan.functionCode,
identity: plan.identity,
Expand All @@ -123,16 +130,46 @@ export function printPlanned(
})
}

/** Prints the blocks and edges a write stores with the plan's variables and source meta. */
export function printWritten(
/**
* Prints the blocks and edges a write stores, or a dry run would, with the plan's variables and
* source meta, as the next read prints them. The plan's resolver knows the resources the source
* named by key; one the source wrote by id (a `raw()` tool's literal `tableId`) resolves through
* the workspace's resource keys, allocating a missing key when `allocate` (a commit) as that read
* does. With the plan's resolver alone such a resource would print, and fingerprint, unlike every
* later read and a pinned deploy's draft check.
*/
export async function printWritten(
planned: Pick<PlannedSource, 'plan' | 'loaded'>,
written: Omit<WorkflowState, 'variables'>
): PrintedSource {
return printPlanned(
planned,
{ ...written, variables: planned.plan.storedVariables },
planned.plan.sourceMeta
written: Omit<WorkflowState, 'variables'>,
{ allocate }: { allocate: boolean }
): Promise<PrintedSource> {
const { plan, loaded } = planned
const state = { ...written, variables: plan.storedVariables }
const unresolved: ResourceReferences['ids'] = []
const recording: ResourceKeyResolver = {
toKey(kind, id) {
const key = plan.resources.toKey(kind, id)
if (key === null) unresolved.push({ kind, id })
return key
},
toId: (kind, key) => plan.resources.toId(kind, key),
nameOf: (kind, id) => plan.resources.nameOf?.(kind, id) ?? null,
isBuiltin: plan.resources.isBuiltin,
}
const lockless = canonicalize(state, {
catalog: loaded.catalog,
meta: plan.meta,
resources: recording,
})
if (unresolved.length === 0) return printPlanned(planned, state, plan.sourceMeta, { lockless })
const byId = await loadResourceKeyResolver(
loaded.scope.workspaceId,
{ ids: unresolved },
{ actorUserId: loaded.scope.subjectUserId, allocate }
)
return printPlanned(planned, state, plan.sourceMeta, {
resources: withFallback(plan.resources, byId),
})
}

/**
Expand Down Expand Up @@ -177,7 +214,7 @@ export async function previewSource(
workspaceId: loaded.scope.workspaceId,
principalKind: principal.kind,
})
return shapeOutcome(frame, printWritten(planned, preview.state), {
return shapeOutcome(frame, await printWritten(planned, preview.state, { allocate: false }), {
applied: false,
...(isNew
? UNDEPLOYED
Expand Down
4 changes: 2 additions & 2 deletions apps/sim/lib/workflows/application/source-pipeline/plan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -336,10 +336,10 @@ function printNoop(planned: PlannedSource): NonNullable<PlannedSource['noop']> {
workflow: { ...storedCanonical.canonical.workflow, meta: plan.meta },
}
: storedCanonical.canonical
const printed = printPlanned(planned, stored.state, plan.sourceMeta, lockless)
const printed = printPlanned(planned, stored.state, plan.sourceMeta, { lockless })
const before = isEqual(plan.sourceMeta, storedSourceMeta)
? printed
: printPlanned(planned, stored.state, storedSourceMeta, lockless)
: printPlanned(planned, stored.state, storedSourceMeta, { lockless })
return {
printed,
sourceMetaChanged: !isEqual(printed.files, before.files) || !isEqual(printed.lock, before.lock),
Expand Down
3 changes: 3 additions & 0 deletions apps/sim/lib/workflows/code/catalog/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { operationOptions } from '@/lib/workflows/code/catalog/sdk-names'
import { deriveValueShape } from '@/lib/workflows/code/catalog/value-kind'
import { TRIGGER_TYPES } from '@/lib/workflows/triggers/types'
import { accessIdEffect, blockEffect } from '@/blocks/access-effect'
import { isCoreAgentToolBlock } from '@/blocks/agent-tools'
import type { BlockConfig, SubBlockConfig } from '@/blocks/types'
import {
isHumanInTheLoopBlock,
Expand Down Expand Up @@ -660,6 +661,8 @@ export function projectBlock(block: BlockConfig): CatalogBlock {
}
}
assign(projected, 'singleInstance', block.singleInstance)
// Hidden legacy versions too: an agent tool stored from one still prints through its builder.
if (block.category !== 'tools' && isCoreAgentToolBlock(block)) projected.agentTool = true
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
const dynamicOutputs = projectDynamicOutputs(block)
if (dynamicOutputs) projected.dynamicOutputs = dynamicOutputs
if (block.errorOutputs) projected.errorOutputs = Object.keys(block.errorOutputs)
Expand Down
Loading
Loading