From 5c70cc48679b3587f48972ddeb93afc048f16ab5 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 22:07:48 -0800 Subject: [PATCH 1/5] fix(workflow-code): name workspace files by path in file() references file('/') now resolves the workspace file at that path and writes the object the editor's file picker stores (storage key and file id), a stored workspace file prints back as file(''), and the source resources manifest and workspace.d.ts list file paths. --- apps/docs/content/docs/cli/reference.mdx | 2 +- apps/docs/content/docs/cli/workflows.mdx | 2 +- .../content/docs/workflows/code/directory.mdx | 2 +- .../content/docs/workflows/code/syntax.mdx | 4 +- apps/docs/openapi-v2-workflows.json | 10 ++ .../workflows/source/resources/route.test.ts | 1 + .../contracts/v2/openapi/source-resources.ts | 1 + .../lib/api/contracts/v2/source-resources.ts | 5 + .../contexts/workspace/file-manager.ts | 9 -- .../read-source-resources.integration.ts | 26 ++++ .../application/read-source-resources.ts | 26 +++- .../source-pipeline/evaluate/resolve.ts | 16 ++- apps/sim/lib/workflows/code/resources.ts | 101 ++++++++++++- .../application/create-workspace-file.ts | 4 - .../write-workspace-file-by-path.ts | 8 +- .../workspace-files/folder-display-path.ts | 18 +++ .../application/files.integration.ts | 133 +++++++++--------- .../application/kinds/files/adapter.ts | 89 ++---------- apps/sim/lib/workspaces/resource-keys.ts | 21 +-- .../src/commands/protocol/source-tree.ts | 8 +- packages/sim-cli/src/contract/commands.ts | 2 +- packages/sim-cli/src/generated/v2-api.ts | 1 + .../workflow-code/src/canonicalize/params.ts | 4 +- .../workflow-code/src/canonicalize/tools.ts | 6 +- .../workflow-code/src/canonicalize/values.ts | 25 ++++ packages/workflow-code/src/catalog/types.ts | 3 +- packages/workflow-code/src/compile/SYNTAX.md | 2 +- .../workflow-code/src/materialize/values.ts | 7 +- packages/workflow-code/src/model.ts | 13 +- .../src/codegen/core-text.generated.ts | 2 +- .../workflow-sdk/src/codegen/map-subblock.ts | 3 +- .../codegen/workspace-declarations.test.ts | 28 +++- .../workflow-sdk/src/codegen/workspace.ts | 7 +- packages/workflow-sdk/src/core.d.ts | 21 ++- packages/workspace-code/DESIGN.md | 7 +- packages/workspace-code/src/specs.ts | 5 +- 36 files changed, 392 insertions(+), 230 deletions(-) diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 7a79c0a3ed7..d8a99890152 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8604,7 +8604,7 @@ API request and response schemas: [getSourceCatalog](/api-reference/catalog/getS ### sim workflows source resources -List the tables, knowledge bases, credentials, workflows, skills, custom tools, MCP servers and env names source can name +List the tables, knowledge bases, credentials, workflows, skills, custom tools, MCP servers, files and env names source can name ```bash sim workflows source resources diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 1ba505bb7d7..4a54c467df6 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1636,7 +1636,7 @@ Prints a builder in brief (an example call, the required params with types, the Exit codes: 0 printed; 1 no builder or namespace of that name (the closest one is named), or no cached catalog (run a get once). -### List the tables, knowledge bases, credentials, workflows, skills, custom tools, MCP servers and env names source can name +### List the tables, knowledge bases, credentials, workflows, skills, custom tools, MCP servers, files and env names source can name ```bash sim workflows source resources diff --git a/apps/docs/content/docs/workflows/code/directory.mdx b/apps/docs/content/docs/workflows/code/directory.mdx index 3bd416acb86..bb5bfddf416 100644 --- a/apps/docs/content/docs/workflows/code/directory.mdx +++ b/apps/docs/content/docs/workflows/code/directory.mdx @@ -61,7 +61,7 @@ A resource's key is its file or folder name, and a workflow names it by that key - `mcp/.ts`: `export default defineMcpServer({ name?, url, headers?, auth?, timeout?, retries?, enabled? })`. A credential header holds `env.NAME` or `'Bearer {{NAME}}'`, never a literal secret; `stored()` keeps the value the server holds. A new host or path in `url` replaces the server; a new query string updates it in place. A workflow: `mcp('').tool('')`. - `tables/.ts`: `export default defineTable({ name, description?, folder?, columns: { … } })` with `column.string()`, `column.number()`, `column.select({ options: [...] })`, … from `@sim/workflow-sdk/workspace`. Rows stay out of source unless `rows` opts in: `{ mode: 'managed', key: '' }` keeps the rows equal to `tables/.rows.jsonl` (one JSON object per line, keyed by column key), `{ mode: 'seed' }` writes them once into a new table. A workflow: `table('')`. - `knowledge//knowledge.ts` (`defineKnowledgeBase({ name, description?, folder?, chunking?, embeddingModel? })`) and `knowledge//docs/`, one file per document, flat. A workflow: `knowledgeBase('')`. Connector-synced documents are never part of source. -- `files/`: every file is one workspace file at that folder path; no declaration. +- `files/`: every file is one workspace file at that folder path; no declaration. A workflow: `file('')` (the path under `files/`), as a file-upload field's value. - `workflows//`: one workflow each, exactly a `sim workflows source get --dir` directory (`workflow.ts`, `functions/*`, `.sim/lock.json`, `.sim/base.json`). - `deployments/.ts`: `defineDeployment({ live: 'draft' | 'pinned', api?: { public? }, chat? })` deploys `workflows//`, so its schedule, webhook, API and chat triggers run. `live: 'draft'` publishes the draft whenever it differs from the live version; `'pinned'` never redeploys and says when the draft differs. A chat password is `env.NAME` (or `stored()` to keep the stored one); chat outputs name a block by its name. Removing the file undeploys the workflow (needs `--allow-delete`). Deploying needs workspace admin, never a workspace API key. MCP publishing is not part of source. diff --git a/apps/docs/content/docs/workflows/code/syntax.mdx b/apps/docs/content/docs/workflows/code/syntax.mdx index 49a81eabd26..132d37f5110 100644 --- a/apps/docs/content/docs/workflows/code/syntax.mdx +++ b/apps/docs/content/docs/workflows/code/syntax.mdx @@ -165,14 +165,14 @@ The optional third argument holds what belongs to the block, not to its settings ### 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. +A key is the resource's stable key in the workspace; `.sim/sdk/workspace.d.ts` lists them. A file's key is its folder path and name, so the same source names the file at that path in any workspace it is applied to. A key with no live resource is `E_MAT_UNKNOWN_RESOURCE` on apply. | Form | Stands for | | --- | --- | | `credential('key')` | A saved credential | | `table('key')` | A workspace table | | `knowledgeBase('key')` | A knowledge base | -| `file('path')` | A workspace file | +| `file('folder/name.pdf')` | A workspace file, by its folder path and name; a file field's value, or an item of a multi-file field's list | | `folder('key')` | A workspace folder | | `childWorkflow('key')` | A workflow, for `runWorkflow`; `.asTool()` in a `tools` list | | `customTool('key')` | A custom tool, in a `tools` list | diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 42186dcc29a..f31a6dcd6be 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -6887,6 +6887,7 @@ "tools": ["create_issue", "list_issues"] } ], + "files": ["contracts/acme.pdf"], "env": ["CRM_KEY"], "truncated": false } @@ -23925,6 +23926,13 @@ }, "description": "MCP servers, oldest first." }, + "files": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Workspace files by folder path and name (`docs/report.pdf`), as `file(path)` names them, oldest upload first." + }, "env": { "type": "array", "items": { @@ -23946,6 +23954,7 @@ "skills", "customTools", "mcpServers", + "files", "env", "truncated" ], @@ -24029,6 +24038,7 @@ "tools": ["create_issue", "list_issues"] } ], + "files": ["contracts/acme.pdf"], "env": ["CRM_KEY"], "truncated": false } diff --git a/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/resources/route.test.ts b/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/resources/route.test.ts index b9ed2d1ee11..67ac3bd3dba 100644 --- a/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/resources/route.test.ts +++ b/apps/sim/app/api/v2/workspaces/[workspaceId]/workflows/source/resources/route.test.ts @@ -62,6 +62,7 @@ const manifest = { skills: [{ key: 'triage', id: 'skl_1', name: 'Triage' }], customTools: [{ key: 'lookup-order', id: 'ctl_1', name: 'Lookup order' }], mcpServers: [{ key: 'github', id: 'mcp-1', name: 'GitHub', tools: ['create_issue'] }], + files: ['contracts/acme.pdf'], env: ['CRM_KEY'], truncated: false, } diff --git a/apps/sim/lib/api/contracts/v2/openapi/source-resources.ts b/apps/sim/lib/api/contracts/v2/openapi/source-resources.ts index 32e839a6206..eb72d86972b 100644 --- a/apps/sim/lib/api/contracts/v2/openapi/source-resources.ts +++ b/apps/sim/lib/api/contracts/v2/openapi/source-resources.ts @@ -40,6 +40,7 @@ const SOURCE_RESOURCES_EXAMPLE = { mcpServers: [ { key: 'github', id: 'mcp-1a2b3c4d', name: 'GitHub', tools: ['create_issue', 'list_issues'] }, ], + files: ['contracts/acme.pdf'], env: ['CRM_KEY'], truncated: false, } diff --git a/apps/sim/lib/api/contracts/v2/source-resources.ts b/apps/sim/lib/api/contracts/v2/source-resources.ts index eafef6dfeab..6d1f79072ba 100644 --- a/apps/sim/lib/api/contracts/v2/source-resources.ts +++ b/apps/sim/lib/api/contracts/v2/source-resources.ts @@ -108,6 +108,11 @@ const sourceResourcesSchema = z .describe('An MCP server the workspace consumes: `mcp(key)`.') ) .describe('MCP servers, oldest first.'), + files: z + .array(z.string()) + .describe( + 'Workspace files by folder path and name (`docs/report.pdf`), as `file(path)` names them, oldest upload first.' + ), env: z .array(z.string()) .describe( diff --git a/apps/sim/lib/uploads/contexts/workspace/file-manager.ts b/apps/sim/lib/uploads/contexts/workspace/file-manager.ts index 13ccdb132d7..044f04498e8 100644 --- a/apps/sim/lib/uploads/contexts/workspace/file-manager.ts +++ b/apps/sim/lib/uploads/contexts/workspace/file-manager.ts @@ -767,9 +767,6 @@ export async function commitFileCreateInTx( return inserted } -/** Writes that commit with a new workspace file: run in its create transaction, given its id. */ -export type WorkspaceFileCreateHook = (tx: DbTransaction, fileId: string) => Promise - /** * Upload a file to workspace-scoped storage */ @@ -785,11 +782,6 @@ export async function uploadWorkspaceFile( exactName?: boolean secretProvenance?: WorkspaceFileSecretProvenance notifyWorkspaceChange?: boolean - /** - * Runs inside the create's transaction once the file row is inserted, so what it writes - * commits or rolls back with the file. - */ - withinCreate?: WorkspaceFileCreateHook } ): Promise { logger.info(`Uploading workspace file: ${fileName} for workspace ${workspaceId}`) @@ -867,7 +859,6 @@ export async function uploadWorkspaceFile( secretProvenance: options?.secretProvenance, }) const usage = await accounting.mutation.applyDelta(effectiveBuffer.length) - await options?.withinCreate?.(tx, inserted.id) return { inserted, updatedUsage: usage, billing: accounting.billing } }) diff --git a/apps/sim/lib/workflows/application/read-source-resources.integration.ts b/apps/sim/lib/workflows/application/read-source-resources.integration.ts index 1f343161659..6cf11046140 100644 --- a/apps/sim/lib/workflows/application/read-source-resources.integration.ts +++ b/apps/sim/lib/workflows/application/read-source-resources.integration.ts @@ -24,6 +24,7 @@ import { userTableDefinitions, workspace, workspaceEnvironment, + workspaceFiles, } from '@sim/db/schema' import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' import { @@ -204,6 +205,16 @@ describe('source resources manifest', () => { createdBy: tokenOwnerId, }, ]) + await db.insert(workspaceFiles).values({ + id: generateId(), + key: `workspace/${workspaceId}/plan.md`, + userId: adminId, + workspaceId, + context: 'workspace', + originalName: 'plan.md', + contentType: 'text/markdown', + sizeBytes: 7, + }) await db.insert(workspaceEnvironment).values({ id: generateId(), workspaceId, @@ -494,6 +505,21 @@ describe('source resources manifest', () => { expect(manifest.tables.map((table) => table.name)).toEqual(['leads']) }) + it('lists workspace files by path, and omits them when the caller’s group hides the Files tab', async () => { + const visible = await readSourceResources.execute({ + principal: session(readerId), + input: { workspaceId }, + }) + expect(visible.files).toEqual(['plan.md']) + await withholdInGroup({ hideFilesTab: true }) + const manifest = await readSourceResources.execute({ + principal: session(readerId), + input: { workspaceId }, + }) + expect(manifest.files).toEqual([]) + expect(manifest.tables.map((table) => table.name)).toEqual(['leads']) + }) + it('omits env names for a workspace API key, which the secrets listing denies', async () => { const manifest = await readSourceResources.execute({ principal: workspaceKey(), diff --git a/apps/sim/lib/workflows/application/read-source-resources.ts b/apps/sim/lib/workflows/application/read-source-resources.ts index a985ca1b2f0..0634a28123c 100644 --- a/apps/sim/lib/workflows/application/read-source-resources.ts +++ b/apps/sim/lib/workflows/application/read-source-resources.ts @@ -31,7 +31,11 @@ import type { StaticPermissionGroupCapability } from '@/lib/permission-groups/ca import { isWorkspaceCapabilityWithheld } from '@/lib/permission-groups/capability-assertions' import { isColumnType } from '@/lib/table/column-types' import { workflowOperations } from '@/lib/workflows/application/operations' -import { loadEnvNames, loadVisibleCredentials } from '@/lib/workflows/code/resources' +import { + loadEnvNames, + loadVisibleCredentials, + loadWorkspaceFilePaths, +} from '@/lib/workflows/code/resources' import { extractInputFieldsFromBlocks } from '@/lib/workflows/input-format' import { INPUT_DEFINITION_TRIGGER_TYPES } from '@/lib/workflows/triggers/input-definition-triggers' import { resolveActiveWorkspaceApplicationContext } from '@/lib/workspaces/application/context' @@ -162,9 +166,9 @@ async function loadWorkflowInputs( * Which manifest sections the caller may see, by the gates the editor's own pickers apply: env * names follow the env-var autocomplete (the workspace environment read, `secrets.manage`, and * like `secrets.list` never a workspace API key), credentials follow the credential selector - * (`integrations.manage`), and skills, custom tools, MCP servers, tables and knowledge bases - * follow their own lists (`skills.use`, `custom_tools.use`, `mcp_tools.use`, `tables.use`, - * `knowledge.use`). A withheld section is listed empty rather than refusing the whole manifest, + * (`integrations.manage`), and skills, custom tools, MCP servers, tables, knowledge bases and + * files follow their own lists (`skills.use`, `custom_tools.use`, `mcp_tools.use`, `tables.use`, + * `knowledge.use`, `files.use`). A withheld section is listed empty rather than refusing the whole manifest, * so a member restricted from one still gets the workflows and the rest. */ async function visibleSections(principal: Principal, context: WorkspaceAuthorizationContext) { @@ -185,6 +189,7 @@ async function visibleSections(principal: Principal, context: WorkspaceAuthoriza // permission-group-enforced: mcp_tools.use — omits the MCP servers section, as the MCP server list refuses // permission-group-enforced: tables.use — omits the tables section, as the table list refuses // permission-group-enforced: knowledge.use — omits the knowledge bases section, as the knowledge base list refuses + // permission-group-enforced: files.use — omits the files section, as the file list refuses const [ secretsWithheld, integrationsWithheld, @@ -193,6 +198,7 @@ async function visibleSections(principal: Principal, context: WorkspaceAuthoriza mcpWithheld, tablesWithheld, knowledgeWithheld, + filesWithheld, ] = await Promise.all([ withheld('secrets.manage'), withheld('integrations.manage'), @@ -201,6 +207,7 @@ async function visibleSections(principal: Principal, context: WorkspaceAuthoriza withheld('mcp_tools.use'), withheld('tables.use'), withheld('knowledge.use'), + withheld('files.use'), ]) return { tables: !tablesWithheld, @@ -210,6 +217,7 @@ async function visibleSections(principal: Principal, context: WorkspaceAuthoriza skills: !skillsWithheld, customTools: !customToolsWithheld, mcpServers: !mcpWithheld, + files: !filesWithheld, } } @@ -223,8 +231,8 @@ function capped(rows: T[]): { rows: T[]; truncated: boolean } { * The workspace resources a workflow file can name, by the keys source uses for them: tables * with their columns, knowledge bases, saved credentials with their provider, workflows with * the inputs their start block declares, workspace skills and custom tools, MCP servers with the - * tool names they list (best effort, see `loadMcpToolNames`), and env variable names (never - * values). Credentials are the ones the caller's credential listing shows, and every section is + * tool names they list (best effort, see `loadMcpToolNames`), workspace files by path, and env + * variable names (never values). Credentials are the ones the caller's credential listing shows, and every section is * omitted where the editor's own pickers or the resource's own list would withhold it (see * `visibleSections`). The CLI writes it as * `workspace.d.ts`, so `table('tickets')`, `skill('triage')` and `env.X` type-check. @@ -256,6 +264,7 @@ export const readSourceResources = defineAuthorizedWorkspaceUseCase({ skillRows, customToolRows, mcpServerRows, + filePaths, env, ] = await Promise.all([ visible.tables @@ -316,6 +325,7 @@ export const readSourceResources = defineAuthorizedWorkspaceUseCase({ .orderBy(asc(mcpServers.createdAt), asc(mcpServers.id)) .limit(PAGE) : [], + visible.files ? loadWorkspaceFilePaths(workspaceId, PAGE) : [], visible.env ? loadEnvNames(workspaceId, userId, access) : [], ]) @@ -326,6 +336,7 @@ export const readSourceResources = defineAuthorizedWorkspaceUseCase({ const skills = capped(skillRows) const tools = capped(customToolRows) const servers = capped(mcpServerRows) + const files = capped(filePaths) const refs: ResourceIdRef[] = [ ...tables.rows.map((row) => ({ kind: 'table' as const, id: row.id })), @@ -375,8 +386,9 @@ export const readSourceResources = defineAuthorizedWorkspaceUseCase({ const names = mcpTools.get(server.id) return names ? { ...server, tools: names } : server }), + files: files.rows, env, - truncated: [tables, kbs, credentials, workflows, skills, tools, servers].some( + truncated: [tables, kbs, credentials, workflows, skills, tools, servers, files].some( (section) => section.truncated ), } diff --git a/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts b/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts index ff5b4337f17..b80a4466f88 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts @@ -38,19 +38,22 @@ import { loadAvailableResourceKeys, loadResourceKeyResolver } from '@/lib/workfl */ export function withFallback( primary: ResourceKeyResolver, - fallback: Pick + fallback: Pick ): ResourceKeyResolver { return { toKey: (kind, id) => primary.toKey(kind, id) ?? fallback.toKey(kind, id), toId: (kind, key) => primary.toId(kind, key) ?? fallback.toId(kind, key), nameOf: (kind, id) => primary.nameOf?.(kind, id) ?? fallback.nameOf?.(kind, id) ?? null, isBuiltin: primary.isBuiltin, + uploadOf: (path) => primary.uploadOf?.(path) ?? fallback.uploadOf?.(path) ?? null, } } /** * `resources`, falling back to `pending` for a key, id or name it does not resolve; a resource the - * apply moves to a new key (`moved`) is named by that key first. + * apply moves to a new key (`moved`) is named by that key first. A file the apply has yet to create + * uploads as its stand-in id, name and path: a plan resolving it is planned again once the file is + * written (`planForCommit`), so the stand-in is never stored. */ function withPendingResources( resources: ResourceKeyResolver, @@ -59,11 +62,16 @@ function withPendingResources( if (pending.length === 0) return resources const byId = (kind: ResourceKind, id: string) => pending.find((entry) => entry.kind === kind && entry.id === id) + const byKey = (kind: ResourceKind, key: string) => + pending.find((entry) => entry.kind === kind && entry.key === key) const resolver = withFallback(resources, { toKey: (kind, id) => byId(kind, id)?.key ?? null, - toId: (kind, key) => - pending.find((entry) => entry.kind === kind && entry.key === key)?.id ?? null, + toId: (kind, key) => byKey(kind, key)?.id ?? null, nameOf: (kind, id) => byId(kind, id)?.name ?? null, + uploadOf: (path) => { + const file = byKey('file', path) + return file ? { name: file.name ?? path, path, id: file.id } : null + }, }) const moved = pending.filter((entry) => entry.moved) if (moved.length === 0) return resolver diff --git a/apps/sim/lib/workflows/code/resources.ts b/apps/sim/lib/workflows/code/resources.ts index 6e4f452296f..e7c3c21cf09 100644 --- a/apps/sim/lib/workflows/code/resources.ts +++ b/apps/sim/lib/workflows/code/resources.ts @@ -1,12 +1,18 @@ import { db } from '@sim/db' import { credential, credentialMember, skill } from '@sim/db/schema' import { compareStrings } from '@sim/utils/string' -import type { ResourceKeyResolver, ResourceKind } from '@sim/workflow-code' +import type { Json, ResourceKeyResolver, ResourceKind } from '@sim/workflow-code' import { and, asc, eq, inArray, notInArray } from 'drizzle-orm' import { SHARED_CREDENTIAL_TYPES } from '@/lib/credentials/access' import { credentialAccessClause, credentialMembershipJoin } from '@/lib/credentials/queries' import { getWorkspaceEnvironmentVariableNames } from '@/lib/environment/utils' +import { + lookupActiveWorkspaceFiles, + queryWorkspaceFiles, + type WorkspaceFileRecord, +} from '@/lib/uploads/contexts/workspace/file-manager' import { isBuiltinSkillId } from '@/lib/workflows/skills/builtin-skills' +import { workspaceFileSourcePath } from '@/lib/workspace-files/folder-display-path' import { checkWorkspaceAccess, type WorkspaceAccess } from '@/lib/workspaces/permissions/utils' import { listLiveKeys, @@ -32,6 +38,10 @@ import { * see (see `loadVisibleCredentials`) resolves in neither direction for them: its id stays * `unresolved` (printed verbatim, so an unchanged re-apply keeps the binding), no key is allocated * from its name, and naming its key is an unknown resource, as for one that does not exist. + * + * A workspace file has no persisted key: `file('docs/a.pdf')` names it by its folder path and + * name, as the workspace directory's `files/` does, so the same source names the file at that path + * in whichever workspace it is applied to. */ /** Env-secret credential types, which a `credential(...)` never names. */ @@ -127,6 +137,42 @@ async function loadSkillNames(workspaceId: string, ids: string[]): Promise refs.flatMap((ref) => (ref.kind === 'credential' ? [ref.id] : [])) +/** + * The live workspace files `references` name: by the id or storage key a stored file-upload + * object carries (`stored`) and by source path (`paths`), each file under its source path. + */ +async function loadReferencedFiles( + workspaceId: string, + stored: string[], + paths: string[] +): Promise> { + const byPath = new Map() + if (stored.length === 0 && paths.length === 0) return byPath + const { files } = await lookupActiveWorkspaceFiles(workspaceId, { + ids: stored, + keys: stored, + references: paths, + }) + for (const file of files) { + const path = workspaceFileSourcePath(file) + if (path !== null) byPath.set(path, file) + } + return byPath +} + +/** What a file-upload field stores for a workspace file, as the editor's workspace file picker writes it. */ +function uploadedFile(file: WorkspaceFileRecord): Json { + return { + name: file.name, + path: file.path, + key: file.key, + size: file.size, + type: file.type, + id: file.id, + ...(file.folderPath ? { folderPath: file.folderPath } : {}), + } +} + /** The `(kind, id)` and `(kind, key)` pairs a canonicalize pass asks a resolver about. */ export interface ResourceReferences { ids: ResourceIdRef[] @@ -157,11 +203,21 @@ export async function loadResourceKeyResolver( options: LoadResourceKeyResolverOptions ): Promise { const actorUserId = options.actorUserId ?? undefined - const idRefs = references.ids ?? [] - const [hiddenRefIds, boundIdsByKey] = await Promise.all([ + const idRefs = (references.ids ?? []).filter((ref) => ref.kind !== 'file') + const keyRefs = (references.keys ?? []).filter((ref) => ref.kind !== 'file') + const storedFiles = (references.ids ?? []).flatMap((ref) => (ref.kind === 'file' ? [ref.id] : [])) + const filePaths = (references.keys ?? []).flatMap((ref) => (ref.kind === 'file' ? [ref.key] : [])) + const [hiddenRefIds, boundIdsByKey, filesByPath] = await Promise.all([ hiddenCredentialIds(workspaceId, actorUserId, credentialIdsOf(idRefs)), - resolveIds(workspaceId, references.keys ?? []), + resolveIds(workspaceId, keyRefs), + loadReferencedFiles(workspaceId, storedFiles, filePaths), ]) + const filePathByStored = new Map( + [...filesByPath].flatMap(([path, file]) => [ + [file.id, path], + [file.key, path], + ]) + ) const [keysById, idsByKey] = await Promise.all([ resolveKeys( workspaceId, @@ -182,10 +238,20 @@ export async function loadResourceKeyResolver( const lookup = (map: ResourceKeyMap, kind: ResourceKind, value: string) => map.get(kind)?.get(value) ?? null return { - toKey: (kind, id) => lookup(keysById, kind, id) ?? lookup(keysByIdFromKeys, kind, id), - toId: (kind, key) => lookup(idsByKey, kind, key) ?? lookup(idsByKeyFromIds, kind, key), + toKey: (kind, id) => + kind === 'file' + ? (filePathByStored.get(id) ?? null) + : (lookup(keysById, kind, id) ?? lookup(keysByIdFromKeys, kind, id)), + toId: (kind, key) => + kind === 'file' + ? (filesByPath.get(key)?.id ?? null) + : (lookup(idsByKey, kind, key) ?? lookup(idsByKeyFromIds, kind, key)), nameOf: (kind, id) => (kind === 'skill' ? (skillNames.get(id) ?? null) : null), isBuiltin: (kind, id) => kind === 'skill' && isBuiltinSkillId(id), + uploadOf: (path) => { + const file = filesByPath.get(path) + return file ? uploadedFile(file) : null + }, } } @@ -204,6 +270,9 @@ export async function loadAvailableResourceKeys( const userId = actorUserId ?? undefined const entries = await Promise.all( [...new Set(kinds)].map(async (kind) => { + if (kind === 'file') { + return [kind, await loadWorkspaceFilePaths(workspaceId, AVAILABLE_KEYS_LIMIT)] as const + } const rows = await listLiveKeys(workspaceId, kind, { limit: AVAILABLE_KEYS_LIMIT }) if (kind !== 'credential') return [kind, rows.map((row) => row.key)] as const const hidden = await hiddenCredentialIds( @@ -217,6 +286,26 @@ export async function loadAvailableResourceKeys( return new Map(entries) } +/** + * The source paths (`file('')`) of up to `limit` of the workspace's live files, oldest upload + * first; a file no slash-separated path names is left out. + */ +export async function loadWorkspaceFilePaths( + workspaceId: string, + limit: number +): Promise { + const { files } = await queryWorkspaceFiles(workspaceId, { + scope: 'active', + sortBy: 'uploadedAt', + sortOrder: 'asc', + limit, + }) + return files.flatMap((file) => { + const path = workspaceFileSourcePath(file) + return path === null ? [] : [path] + }) +} + /** `idsByKey` without the credential keys bound to a credential `userId` cannot see. */ async function withoutHiddenCredentials( workspaceId: string, diff --git a/apps/sim/lib/workspace-files/application/create-workspace-file.ts b/apps/sim/lib/workspace-files/application/create-workspace-file.ts index f56dc2a259f..25f63343d67 100644 --- a/apps/sim/lib/workspace-files/application/create-workspace-file.ts +++ b/apps/sim/lib/workspace-files/application/create-workspace-file.ts @@ -10,7 +10,6 @@ import { uploadWorkspaceFile, type WorkspaceFileRecord, } from '@/lib/uploads/contexts/workspace' -import type { WorkspaceFileCreateHook } from '@/lib/uploads/contexts/workspace/file-manager' import type { WorkspaceFileSecretProvenance } from '@/lib/uploads/contexts/workspace/file-secret-provenance' import { EXACT_EMPTY_WORKSPACE_FILE_SECRET_PROVENANCE } from '@/lib/uploads/contexts/workspace/file-secret-provenance' import { defineAuthorizedWorkspaceFileUseCase } from '@/lib/workspace-files/application/authorized-workspace-file-use-case' @@ -39,8 +38,6 @@ export interface CreateWorkspaceFileBufferInput extends Omit { content: Buffer notifyWorkspaceChange?: boolean - /** Writes that commit with the file, in its create transaction. In-process only. */ - withinCreate?: WorkspaceFileCreateHook } async function resolveCreateWorkspaceFileContext(workspaceId: string) { @@ -78,7 +75,6 @@ export async function createAuthorizedWorkspaceFile({ exactName: input.exactName, secretProvenance: input.secretProvenance ?? EXACT_EMPTY_WORKSPACE_FILE_SECRET_PROVENANCE, notifyWorkspaceChange: input.notifyWorkspaceChange, - ...(input.withinCreate ? { withinCreate: input.withinCreate } : {}), } ) } catch (error) { diff --git a/apps/sim/lib/workspace-files/application/write-workspace-file-by-path.ts b/apps/sim/lib/workspace-files/application/write-workspace-file-by-path.ts index 87cac2d17ca..529eda610b7 100644 --- a/apps/sim/lib/workspace-files/application/write-workspace-file-by-path.ts +++ b/apps/sim/lib/workspace-files/application/write-workspace-file-by-path.ts @@ -1,10 +1,7 @@ import { type Principal, resolvePrincipalAttribution } from '@sim/auth/principal' import { OrchestrationError } from '@/lib/core/orchestration/types' import { ensureWorkspaceFileFolderPath } from '@/lib/uploads/contexts/workspace/file-folder-manager' -import { - loadActiveWorkspaceContext, - type WorkspaceFileCreateHook, -} from '@/lib/uploads/contexts/workspace/file-manager' +import { loadActiveWorkspaceContext } from '@/lib/uploads/contexts/workspace/file-manager' import type { WorkspaceFileSecretProvenance } from '@/lib/uploads/contexts/workspace/file-secret-provenance' import { encodeVfsPathSegments, encodeVfsSegment } from '@/lib/vfs/path' import { @@ -26,8 +23,6 @@ export interface WriteWorkspaceFileBufferByPathInput { exactName?: boolean syncLiveDoc?: boolean secretProvenance?: WorkspaceFileSecretProvenance - /** A create's writes that commit with the file, in its transaction. In-process only. */ - withinCreate?: WorkspaceFileCreateHook } export interface WriteWorkspaceFileByPathResult { @@ -91,7 +86,6 @@ async function executeCreateBuffer({ folderId, exactName: input.exactName ?? true, secretProvenance: input.secretProvenance, - ...(input.withinCreate ? { withinCreate: input.withinCreate } : {}), }, }) return toResult(result.file, 'create') diff --git a/apps/sim/lib/workspace-files/folder-display-path.ts b/apps/sim/lib/workspace-files/folder-display-path.ts index de842935b80..cc1fe052cb6 100644 --- a/apps/sim/lib/workspace-files/folder-display-path.ts +++ b/apps/sim/lib/workspace-files/folder-display-path.ts @@ -99,3 +99,21 @@ export function toWorkspaceFileFolderPathView(folder: { updatedAt: folder.updatedAt.toISOString(), } } + +/** + * A workspace file's path as workspace source names it (`files/`, `file('')`): its + * folder names, then its name. `null` when its folder path cannot be read or a name in it holds a + * slash, since no slash-separated path then names the file. + */ +export function workspaceFileSourcePath(file: { + folderPath?: string | null + name: string +}): string | null { + let segments: string[] + try { + segments = [...parseWorkspaceFileFolderDisplayPath(file.folderPath ?? ''), file.name] + } catch { + return null + } + return segments.some((segment) => segment.includes('/')) ? null : segments.join('/') +} diff --git a/apps/sim/lib/workspace-source/application/files.integration.ts b/apps/sim/lib/workspace-source/application/files.integration.ts index 7c6dc1da5f7..4343bbc3145 100644 --- a/apps/sim/lib/workspace-source/application/files.integration.ts +++ b/apps/sim/lib/workspace-source/application/files.integration.ts @@ -19,7 +19,6 @@ import { user, workspaceFiles, workspaceFileVersion, - workspaceResourceKey, workspaceSourceStagedBlob, } from '@sim/db/schema' import { sha256Hex } from '@sim/security/hash' @@ -61,7 +60,6 @@ import { findMissingSourceBlobs } from '@/lib/workspace-source/application/stage import { blobManifest, codes, - failKeyClaims, type ManifestBlob, refusal, sourceChecks, @@ -70,7 +68,6 @@ import { stageBlobsAs, } from '@/lib/workspace-source/application/workspace-source.test-helpers' import { WorkspaceSourceBusyError } from '@/lib/workspace-source/lease/store' -import { claimResourceKey } from '@/lib/workspaces/resource-keys' /** Local object storage the suite's uploads land in, under a temp directory. */ let storageRoot = '' @@ -212,6 +209,28 @@ async function setUp(workspaceId: string) { return get(workspaceId) } +/** The file a workflow's file block reads, as its file picker (`readFile`) stores it. */ +async function storedFileInput(workflowId: string): Promise { + const stored = await loadWorkflowFromNormalizedTables(workflowId) + const block = Object.values(stored?.blocks ?? {}).find((entry) => 'readFile' in entry.subBlocks) + return block?.subBlocks.readFile?.value +} + +/** A workflow whose file block reads `reference` (source text, e.g. `file('a.txt')`). */ +function fileReader(reference: string): string { + return `// @sim-sdk 1 +import { file, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('Path reader', {}, () => { + const start = trigger.start('Start', { inputFormat: {} }) + const read = file.read('Read', { readFileInput: ${reference}, folderIncludeSubfolders: true }) + start.to(read) +}) +` +} + +const workflowsOnly = sourceRunner(['workflow'], owner) + function fileId(base: WorkspaceBaseV1, key: string): string { const id = base.resources[`file:${key}`]?.id if (!id) throw new Error(`The base has no file ${key}`) @@ -935,7 +954,7 @@ import { file, trigger, workflow } from '@sim/workflow-sdk' export default workflow('Reader', {}, () => { const start = trigger.start('Start', { inputFormat: {${extra}} }) const read = file.read('Read', { - readFileInput: { name: 'contract.pdf', path: 'contract.pdf', key: file('contract-pdf') }, + readFileInput: file('contract.pdf'), folderIncludeSubfolders: true, }) start.to(read) @@ -966,8 +985,15 @@ export default workflow('Reader', {}, () => { const fileRow = second.base.resources['file:contract.pdf']?.id const workflowRow = second.base.resources['workflow:reader']?.id if (!fileRow || !workflowRow) throw new Error('The apply wrote nothing') - const stored = await loadWorkflowFromNormalizedTables(workflowRow) - expect(JSON.stringify(stored?.blocks)).toContain(fileRow) + const [created] = await db + .select({ key: workspaceFiles.key }) + .from(workspaceFiles) + .where(eq(workspaceFiles.id, fileRow)) + expect(await storedFileInput(workflowRow)).toMatchObject({ + id: fileRow, + key: created?.key, + name: 'contract.pdf', + }) // An edited workflow that still names the file refuses its delete. const read = await withFiles.get(workspaceId) @@ -990,69 +1016,48 @@ export default workflow('Reader', {}, () => { } ) check( - 'nine creates of one name each claim a free key, past a key a live file already holds', + 'a workflow names a workspace file by its folder path, prints it back so, and resolves it in another workspace by the same path', async () => { const workspaceId = await newWorkspace() - const holder = await uploadInUi(workspaceId, '', 'holder.txt', 'holds a key') - // The ninth key a plan would offer `data.csv`, held by a file the Files tab uploaded. - await claimResourceKey({ - workspaceId, - kind: 'file', - key: 'data-csv-9', - resourceId: holder.id, - origin: 'adopted', - createdBy: ownerId, + const stored = await uploadInUi(workspaceId, 'moved', 'a.txt', 'first workspace') + const text = { 'workflows/path-reader/workflow.ts': fileReader("file('moved/a.txt')") } + + const applied = await workflowsOnly.apply(workspaceId, { files: text }) + expect(applied.failed).toBeUndefined() + const workflowId = applied.base.resources['workflow:path-reader']?.id + if (!workflowId) throw new Error('The apply wrote no workflow') + expect(await storedFileInput(workflowId)).toMatchObject({ + id: stored.id, + key: stored.key, + name: 'a.txt', + size: stored.size, }) - const files = Object.fromEntries( - 'abcdefghi' - .split('') - .map((folder) => [`files/${folder}/data.csv`, Buffer.from(`rows of ${folder}`)]) + const printed = (await workflowsOnly.get(workspaceId)).files[ + 'workflows/path-reader/workflow.ts' + ] + expect(printed).toContain("readFileInput: file('moved/a.txt')") + + const unknown = await refusal( + workflowsOnly.apply(workspaceId, { + files: { 'workflows/lost/workflow.ts': fileReader("file('nowhere/a.txt')") }, + }) ) - - const created = await apply(workspaceId, files) - - expect(created.failed).toBeUndefined() - const keys = await db - .select({ key: workspaceResourceKey.key, resourceId: workspaceResourceKey.resourceId }) - .from(workspaceResourceKey) - .where( - and( - eq(workspaceResourceKey.workspaceId, workspaceId), - eq(workspaceResourceKey.kind, 'file') - ) - ) - const createdIds = Object.keys(files).map((blobPath) => - fileId(created.base, blobPath.slice('files/'.length)) + const missing = unknown.diagnostics.find( + (finding) => finding.code === 'E_MAT_UNKNOWN_RESOURCE' ) - expect(keys.filter((row) => createdIds.includes(row.resourceId))).toHaveLength(9) - expect(keys.find((row) => row.key === 'data-csv-9')?.resourceId).toBe(holder.id) - } - ) - - check( - 'a file create whose key claim fails leaves no file behind, so applying again creates and keys it', - async () => { - const workspaceId = await newWorkspace() - const files = { 'files/claim-crash.pdf': Buffer.from('%PDF-1.4 a claim') } - const restore = await failKeyClaims('claim-crash-pdf') - const crashed = await apply(workspaceId, files).finally(restore) - - expect(crashed.failed).toMatchObject({ kind: 'file', key: 'claim-crash.pdf' }) - expect(await storedFiles(workspaceId)).toEqual([]) - - const again = await apply(workspaceId, files) - expect(again.failed).toBeUndefined() - const [binding] = await db - .select({ resourceId: workspaceResourceKey.resourceId }) - .from(workspaceResourceKey) - .where( - and( - eq(workspaceResourceKey.workspaceId, workspaceId), - eq(workspaceResourceKey.kind, 'file'), - eq(workspaceResourceKey.key, 'claim-crash-pdf') - ) - ) - expect(binding?.resourceId).toBe(fileId(again.base, 'claim-crash.pdf')) + expect(missing?.message).toContain('nowhere/a.txt') + expect(missing?.hint).toContain('moved/a.txt') + + const target = await newWorkspace() + const own = await uploadInUi(target, 'moved', 'a.txt', 'second workspace') + if (printed === undefined) throw new Error('The get printed no workflow') + const promoted = await workflowsOnly.apply(target, { + files: { 'workflows/path-reader/workflow.ts': printed }, + }) + expect(promoted.failed).toBeUndefined() + const targetWorkflowId = promoted.base.resources['workflow:path-reader']?.id + if (!targetWorkflowId) throw new Error('The apply wrote no workflow') + expect(await storedFileInput(targetWorkflowId)).toMatchObject({ id: own.id, key: own.key }) } ) diff --git a/apps/sim/lib/workspace-source/application/kinds/files/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/files/adapter.ts index ce428f6bd8d..ab0c76c5b8a 100644 --- a/apps/sim/lib/workspace-source/application/kinds/files/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/files/adapter.ts @@ -26,7 +26,6 @@ import { } from '@sim/workspace-code/kinds/files' import { WORKSPACE_SOURCE_LIMITS } from '@sim/workspace-code/limits' import { OrchestrationError } from '@/lib/core/orchestration/types' -import type { DbTransaction } from '@/lib/db/types' import type { WorkspaceFileRecord } from '@/lib/uploads/contexts/workspace' import { resolveEffectiveMimeType } from '@/lib/uploads/utils/file' import { encodeVfsPathSegments, normalizeDisplaySegment } from '@/lib/vfs/path' @@ -70,12 +69,6 @@ import type { StoredResource, StoredSet, } from '@/lib/workspace-source/application/types' -import { - claimResourceKey, - nextFreeKey, - resolveIds, - resourceKeyBase, -} from '@/lib/workspaces/resource-keys' const logger = createLogger('WorkspaceSourceFiles') @@ -97,17 +90,11 @@ interface StoredFileState { type StoredFile = StoredResource /** - * What a write carries out: for an update or delete, the content revision the plan saw (the - * write refuses a file that moved past it); for a create, the resource key it claims. + * What an update or delete carries out: the content revision the plan saw (the write refuses a + * file that moved past it). */ export interface FilePlan { rev?: string - /** - * The key a workflow names the created file by (`file('report-pdf')`), as a get would first - * allocate it from the file's name: the create claims it, so a workflow this apply writes - * after it resolves the file, as the dry run did through the create's pending entry. - */ - resourceKey?: string } type FileChange = PlannedChange<'file'> @@ -415,67 +402,17 @@ function refuseCollisions( } } -/** Keys past those a plan's creates of one key base take, checked for files holding them live. */ -const KEY_CANDIDATES = 8 - /** - * Gives each create (one without findings) the resource key a get would first allocate it, so a - * workflow of the same apply can name the file: a pending entry under that key, and the key the - * create claims once written. A key a live file holds already is skipped, as allocation skips it. + * Gives each create (one without findings) a pending entry under its path, so a workflow of the + * same apply naming it (`file('')`) dry-runs; the workflow resolves the written file by the + * same path once the create runs. */ -async function keyCreates(ctx: PlanContext, files: FileChange[]): Promise { - const creates = files.filter( - (change) => change.action === 'create' && change.diagnostics.length === 0 - ) - if (creates.length === 0) return - const bases = creates.map((change) => - resourceKeyBase('file', change.key.slice(change.key.lastIndexOf('/') + 1)) - ) - const sharing = new Map() - for (const base of bases) sharing.set(base, (sharing.get(base) ?? 0) + 1) - // Every key the creates of a base could take: one each, plus as many as live files may hold. - const candidates = [...sharing].flatMap(([base, creates]) => { - const keys = new Set() - while (keys.size < creates + KEY_CANDIDATES) keys.add(nextFreeKey(base, keys)) - return [...keys] - }) - const live = ( - await resolveIds( - ctx.workspace.workspaceId, - candidates.map((key) => ({ kind: 'file' as const, key })) - ) - ).get('file') - const taken = new Set(live?.keys() ?? []) - creates.forEach((change, index) => { - const resourceKey = nextFreeKey(bases[index], taken) - taken.add(resourceKey) +function pendCreates(files: FileChange[]): void { + for (const change of files) { + if (change.action !== 'create' || change.diagnostics.length > 0) continue const name = change.key.slice(change.key.lastIndexOf('/') + 1) - change.detail = { resourceKey } - change.pending = { kind: 'file', key: resourceKey, id: generateId(), placeholder: true, name } - }) -} - -/** - * Binds `resourceKey` to a file this apply creates, inside the create's transaction `tx`, so a - * claim that fails undoes the create rather than leaving a file no later apply keys. A key another - * live file took since the plan refuses the create (`E_NAME_TAKEN`); applying again picks a free - * key. - */ -async function claimFileKey( - ctx: SourceContext, - resourceKey: string, - fileId: string, - tx: DbTransaction -): Promise { - await claimResourceKey({ - workspaceId: ctx.workspace.workspaceId, - kind: 'file', - key: resourceKey, - resourceId: fileId, - origin: 'created', - createdBy: ctx.createdBy, - tx, - }) + change.pending = { kind: 'file', key: change.key, id: generateId(), placeholder: true, name } + } } /** @@ -569,7 +506,7 @@ export const fileAdapter: KindAdapter<'file', StoredFileState> = { const files = [...desired].map(([key, decl]) => planFile(key, decl, stored, ctx, byId)) const deletes = planDeletes(desired, stored, ctx, files) refuseCollisions(files, stored, deletes) - await keyCreates(ctx, files) + pendCreates(files) return [...files, ...deletes] }, @@ -609,7 +546,6 @@ export const fileAdapter: KindAdapter<'file', StoredFileState> = { const { content, sha256, stored } = await contentOf(change, ctx) if (change.action === 'create') { const segments = change.key.split('/') - const resourceKey = change.detail?.resourceKey const created = await createWorkspaceFileBufferByPath.execute({ principal, input: { @@ -619,9 +555,6 @@ export const fileAdapter: KindAdapter<'file', StoredFileState> = { contentType: resolveEffectiveMimeType(undefined, segments[segments.length - 1] ?? ''), mode: 'create', exactName: true, - ...(resourceKey - ? { withinCreate: (tx, fileId) => claimFileKey(ctx, resourceKey, fileId, tx) } - : {}), }, }) stored() diff --git a/apps/sim/lib/workspaces/resource-keys.ts b/apps/sim/lib/workspaces/resource-keys.ts index 160c1c0a5c6..49074a63002 100644 --- a/apps/sim/lib/workspaces/resource-keys.ts +++ b/apps/sim/lib/workspaces/resource-keys.ts @@ -8,7 +8,6 @@ import { skill, userTableDefinitions, workflow, - workspaceFiles, workspaceResourceKey, } from '@sim/db/schema' import { createLogger } from '@sim/logger' @@ -18,7 +17,6 @@ import type { ResourceKind } from '@sim/workflow-code' import { and, asc, eq, inArray, isNull, like, or } from 'drizzle-orm' import { OrchestrationError } from '@/lib/core/orchestration/types' import type { DbOrTx, DbTransaction } from '@/lib/db/types' -import { fileOwnerCondition } from '@/lib/workspace-files/ownership-query' /** * Persisted resource keys (`workspace_resource_key`): the only mapping between a workflow @@ -71,7 +69,8 @@ type LiveResourceLoader = ( /** * Reads the live resources among `ids` in one workspace: archived, deleted and foreign rows are * left out. Every kind is listed, so a new one fails to compile until it has a loader; `null` - * marks a kind with no workspace table to check, whose keys never resolve. + * marks a kind with no workspace table to check, or one source names by something else (a file, + * by its path), whose keys never resolve. */ const LIVE_RESOURCE_LOADERS: Record = { 'knowledge-document': null, @@ -144,21 +143,7 @@ const LIVE_RESOURCE_LOADERS: Record = { .select({ id: credential.id, name: credential.displayName, createdAt: credential.createdAt }) .from(credential) .where(and(eq(credential.workspaceId, workspaceId), inArray(credential.id, ids))), - file: (executor, workspaceId, ids) => - executor - .select({ - id: workspaceFiles.id, - name: workspaceFiles.originalName, - createdAt: workspaceFiles.uploadedAt, - }) - .from(workspaceFiles) - .where( - and( - fileOwnerCondition({ entityType: 'workspace', entityId: workspaceId }), - inArray(workspaceFiles.id, ids), - isNull(workspaceFiles.deletedAt) - ) - ), + file: null, 'file-folder': (executor, workspaceId, ids) => executor .select({ id: folder.id, name: folder.name, createdAt: folder.createdAt }) diff --git a/packages/sim-cli/src/commands/protocol/source-tree.ts b/packages/sim-cli/src/commands/protocol/source-tree.ts index db7e01f5789..c38bf266ce5 100644 --- a/packages/sim-cli/src/commands/protocol/source-tree.ts +++ b/packages/sim-cli/src/commands/protocol/source-tree.ts @@ -264,6 +264,7 @@ function workspaceManifestFrom({ skills, customTools, mcpServers, + files, env, }: GetSourceResourcesResponse['data']): WorkspaceManifest { return { @@ -288,6 +289,7 @@ function workspaceManifestFrom({ mcpServers: Object.fromEntries( mcpServers.map((server) => [server.key, server.tools ? { tools: server.tools } : {}]) ), + files, env, } } @@ -304,6 +306,7 @@ export type LocalDeclarations = Pick< | 'customTools' | 'mcpServerDeclarations' | 'workflows' + | 'files' > /** `workspace.d.ts`, and the stored manifest it was generated from (`null` when none was read). */ @@ -315,7 +318,7 @@ export interface WorkspaceTypes { /** * `workspace.d.ts` for the `stored` resources with what a workspace directory declares typed too: * its tables, secrets and credentials from their declarations, and its knowledge base, skill, - * custom tool and workflow keys beside the stored ones. A workflow the directory declares only by + * custom tool, file and workflow keys beside the stored ones. A workflow the directory declares only by * its key (no `inputs`) keeps its stored inputs, so a parent's `inputMapping` stays checked; a * declared `inputs` wins. `null` without either. */ @@ -330,7 +333,7 @@ function workspaceTypesFrom( ) return declared ? { text: generateWorkspaceTypes(local).text, stored: null } : null } - const both = (key: 'knowledgeBases' | 'skills' | 'customTools') => [ + const both = (key: 'knowledgeBases' | 'skills' | 'customTools' | 'files') => [ ...(stored[key] ?? []), ...(local[key] ?? []), ] @@ -346,6 +349,7 @@ function workspaceTypesFrom( knowledgeBases: both('knowledgeBases'), skills: both('skills'), customTools: both('customTools'), + files: both('files'), workflows: Object.fromEntries([ ...Object.entries(stored.workflows ?? {}), ...Object.entries(local.workflows ?? {}).filter( diff --git a/packages/sim-cli/src/contract/commands.ts b/packages/sim-cli/src/contract/commands.ts index 7ab0bd4ce07..8c1bb46427c 100644 --- a/packages/sim-cli/src/contract/commands.ts +++ b/packages/sim-cli/src/contract/commands.ts @@ -751,7 +751,7 @@ export const CLI_CONTRACT: CliContract = { command: 'workflows source resources', profileWorkspacePath: true, describe: - 'List the tables, knowledge bases, credentials, workflows, skills, custom tools, MCP servers and env names source can name', + 'List the tables, knowledge bases, credentials, workflows, skills, custom tools, MCP servers, files and env names source can name', }, replaceWorkflowState: { command: 'workflows state replace', diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index d3a6f923281..4b85405cd3f 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -9812,6 +9812,7 @@ export type GetSourceResourcesResponse = { name: string tools?: Array }> + files: Array env: Array truncated: boolean } diff --git a/packages/workflow-code/src/canonicalize/params.ts b/packages/workflow-code/src/canonicalize/params.ts index c9b750aef19..c592623f00a 100644 --- a/packages/workflow-code/src/canonicalize/params.ts +++ b/packages/workflow-code/src/canonicalize/params.ts @@ -11,7 +11,7 @@ import { setOwn } from '../records' import { structuredCodec } from '../structured' import type { CanonContext } from './context' import { liftTools } from './tools' -import { liftResourceValue, toValue } from './values' +import { liftResourceValue, liftUploadValue, toValue } from './values' /** * Server-owned trigger runtime ids (triggers/constants.ts @@ -233,6 +233,8 @@ export function canonicalParams(inputs: ParamInputs, context: CanonContext): Par location, declaration.multiple ) ?? toValue(decoded, context) + } else if (declaration?.valueKind === 'upload') { + value = liftUploadValue(decoded, context) ?? toValue(decoded, context) } else { value = toValue(decoded, context) } diff --git a/packages/workflow-code/src/canonicalize/tools.ts b/packages/workflow-code/src/canonicalize/tools.ts index 5cb2b64ce49..dbef74fae3e 100644 --- a/packages/workflow-code/src/canonicalize/tools.ts +++ b/packages/workflow-code/src/canonicalize/tools.ts @@ -8,7 +8,7 @@ import { type BlockKey, type CanonicalTool, isUsageControl, type Json, type Valu import { setOwn } from '../records' import type { CanonContext } from './context' import { toolModes } from './modes' -import { liftResourceId, liftResourceValue, toJson, toValue } from './values' +import { liftResourceId, liftResourceValue, liftUploadValue, toJson, toValue } from './values' export type ToolParamShape = 'string' | 'number' | 'boolean' | 'json' @@ -93,7 +93,9 @@ function liftTool( const lifted = subBlock?.valueKind === 'resource' && subBlock.resourceKind ? liftResourceValue(subBlock.resourceKind, decoded, context, location, subBlock.multiple) - : undefined + : subBlock?.valueKind === 'upload' + ? liftUploadValue(decoded, context) + : undefined setOwn(params, key, lifted ?? toValue(decoded, context)) } const binding = mcpBinding(type, rawParams) diff --git a/packages/workflow-code/src/canonicalize/values.ts b/packages/workflow-code/src/canonicalize/values.ts index f0afc08450d..12a192ab31f 100644 --- a/packages/workflow-code/src/canonicalize/values.ts +++ b/packages/workflow-code/src/canonicalize/values.ts @@ -150,3 +150,28 @@ export function liftResourceValue( } return undefined } + +/** + * The `file` node for a stored file-upload object that names a live workspace file: by its `id`, + * or by its storage `key` when it was stored without one. `undefined` for any other file (one + * uploaded in place), which stays a verbatim object. + */ +function liftUploadedFile(file: unknown, context: CanonContext): ResourceNode | undefined { + if (!isRecordLike(file)) return undefined + const stored = typeof file.id === 'string' ? file.id : file.key + if (typeof stored !== 'string' || stored === '') return undefined + const key = context.resources?.toKey('file', stored) ?? null + return key === null ? undefined : { $sim: 'resource', kind: 'file', key } +} + +/** + * The resource-site form of a file-upload value (`ResourceNode`'s `files` encoding): each stored + * file naming a live workspace file becomes a `file` node, and the others stay verbatim objects. + * `undefined` when no file lifts, so the value stays as stored. + */ +export function liftUploadValue(value: unknown, context: CanonContext): Value | undefined { + if (!Array.isArray(value)) return liftUploadedFile(value, context) + const lifted = value.map((file) => liftUploadedFile(file, context)) + if (lifted.every((node) => node === undefined)) return undefined + return value.map((file, index) => lifted[index] ?? toValue(file, context)) +} diff --git a/packages/workflow-code/src/catalog/types.ts b/packages/workflow-code/src/catalog/types.ts index ef8878e962b..6f3ef82d606 100644 --- a/packages/workflow-code/src/catalog/types.ts +++ b/packages/workflow-code/src/catalog/types.ts @@ -52,7 +52,8 @@ export type CatalogCondition = SubBlockConditionClause | OpaqueMarker * - `resource`: a workspace resource by key (`resourceKind` says which). Selector-kind, so a pair * member of this kind is the basic member. * - `picked`: an opaque provider id from a remote selector (`picked('C0123')`); basic. - * - `upload`: a workspace file (`file('path')`); basic. + * - `upload`: a file-upload value: a workspace file by folder path and name (`file('docs/a.pdf')`), + * or a file uploaded in place, kept as its stored object; basic. * - `none`: display-only or server-managed (text, schedule-info, webhook-config, modal); never * written in source. */ diff --git a/packages/workflow-code/src/compile/SYNTAX.md b/packages/workflow-code/src/compile/SYNTAX.md index 24343120274..4a623503c99 100644 --- a/packages/workflow-code/src/compile/SYNTAX.md +++ b/packages/workflow-code/src/compile/SYNTAX.md @@ -161,7 +161,7 @@ round-trip such a block but never introduce one; renaming the block retires the | `credential('key')` | A saved credential (`credential`) | | `table('key')` | A workspace table (`table`); the table block's operations live on `table.*` | | `knowledgeBase('key')` | A knowledge base (`knowledge-base`) | -| `file('path')` | A workspace file (`file`); the file block's operations live on `file.*` | +| `file('folder/name.pdf')` | A workspace file by folder path and name (`file`), as a file-upload field's value or list item; the file block's operations live on `file.*` | | `folder('key')` | A workspace folder (`file-folder`) | | `childWorkflow('key')` | A workflow, for `runWorkflow` and similar (`workflow`); `.asTool()` in a `tools` list | | `customTool('key', { usageControl?, usageControlExpression? })` | A custom tool; in a `tools` list, the picker's reference | diff --git a/packages/workflow-code/src/materialize/values.ts b/packages/workflow-code/src/materialize/values.ts index 93b581a5090..e0789c31411 100644 --- a/packages/workflow-code/src/materialize/values.ts +++ b/packages/workflow-code/src/materialize/values.ts @@ -130,8 +130,11 @@ function unliftNode(node: SimNode, context: MaterializeContext, location: ValueL return node.key } case 'resource': { - const id = context.resources?.toId(node.kind, node.key) ?? null - if (id !== null) return id + const resolved = + node.kind === 'file' + ? (context.resources?.uploadOf?.(node.key) ?? null) + : (context.resources?.toId(node.kind, node.key) ?? null) + if (resolved !== null) return resolved const hint = availableKeysHint(node.kind, context.resources?.keysOf?.(node.kind), node.key) context.diagnostics.push( diagnostic('E_MAT_UNKNOWN_RESOURCE', `No ${node.kind} "${node.key}" in this workspace`, { diff --git a/packages/workflow-code/src/model.ts b/packages/workflow-code/src/model.ts index 93893b41fe0..1242434943c 100644 --- a/packages/workflow-code/src/model.ts +++ b/packages/workflow-code/src/model.ts @@ -86,8 +86,11 @@ export interface VarNode { * A workspace resource lifted from its internal id to its stable key. Where an id sits inside a * larger stored shape, only the id is replaced and the shape is kept: * - scalar or array encoding: the string, or each array element, becomes a node; - * - `files` encoding (file-upload objects carrying `key`): each object stays an object and its - * `key` field becomes `{ $sim: 'resource', kind: 'file', key }`; + * - `files` encoding (file-upload objects): a stored file whose `id` (or, stored without one, + * storage `key`) names a live workspace file becomes the `file` node itself, keyed by the file's + * folder path and name, so it prints `file('docs/a.pdf')` as the SDK types it. Materialize + * writes a new one as {@link ResourceKeyResolver.uploadOf} gives it; any other file (one + * uploaded in place) stays a verbatim object. * - `csv` encoding (several ids in one comma-joined string): see {@link CsvNode}. * - `skills` encoding (agent `skill-input` entries `{ skillId, name }`): an entry whose skill * resolves becomes the `skill` node itself, so it prints `skill('key')` as the SDK types it. @@ -127,6 +130,12 @@ export interface ResourceKeyResolver { * finding lists them with a did-you-mean. `undefined` when not loaded. */ keysOf?(kind: ResourceKind): readonly string[] | undefined + /** + * The object a file-upload field stores for the workspace file at `path` (its folder path and + * name, the `file` key), as the editor stores a file picked from the workspace; `null` when the + * workspace holds no file there. + */ + uploadOf?(path: string): Json | null } /** diff --git a/packages/workflow-sdk/src/codegen/core-text.generated.ts b/packages/workflow-sdk/src/codegen/core-text.generated.ts index 9e9ef9311be..ee991739b35 100644 --- a/packages/workflow-sdk/src/codegen/core-text.generated.ts +++ b/packages/workflow-sdk/src/codegen/core-text.generated.ts @@ -1,4 +1,4 @@ // Generated by scripts/generate-embedded-text.ts from src/core.d.ts; do not edit. /** The text of `core.d.ts`, the workflow SDK authoring declarations. */ -export const CORE_DTS = "/**\n * The authoring surface for Sim workflows written as TypeScript.\n *\n * Nothing declared here runs. `@sim/workflow-code` compiles a workflow file statically, and every\n * runtime export of this package throws `SimSdkNotExecutable`. These declarations exist so an\n * editor, `tsc` (the type-check command `sim` prints) or an agent can check a workflow file before\n * the compiler sees it.\n *\n * Block builders (`slack.sendMessage`, `agent`, `trigger.gmail.poller`, ...) are not declared here:\n * they are generated from the block catalog into `blocks/{type}.d.ts`, which augment this module.\n * The generic `block(type, name, params)` covers any stored type without a builder.\n *\n * Every workflow file starts with the SDK header line, before any import:\n *\n * ```ts\n * // @sim-sdk 1\n * import { agent, trigger, workflow } from \u0027@sim/workflow-sdk\u0027\n * ```\n *\n * The number is the SDK major version the file is written against. A file without the header is\n * refused with `E_SDK_HEADER`, and one written for a newer major than the server supports with\n * `E_SDK_MAJOR`.\n */\n\n/** Plain JSON. */\nexport type Json = null | boolean | number | string | Json[] | { [key: string]: Json }\n\ndeclare const REF: unique symbol\ndeclare const TEMPLATE: unique symbol\ndeclare const ENV: unique symbol\ndeclare const RESOURCE: unique symbol\ndeclare const TOOL: unique symbol\ndeclare const NODE: unique symbol\ndeclare const CODE_FILE: unique symbol\ndeclare const RAW: unique symbol\ndeclare const UNTYPED: unique symbol\n\n/** Any reference, whatever it points at. */\nexport interface AnyRef {\n readonly [REF]: unknown\n}\n\n/** Marks a reference into untyped JSON, which any param accepts: its value is known only at run time. */\ninterface Untyped {\n readonly [UNTYPED]: true\n}\n\n/**\n * A reference into untyped JSON, where any path is allowed at any depth. An interface rather than\n * `Ref`, which TypeScript stops resolving after one step (`a.b.c` failed at `c`).\n */\ninterface UntypedRef extends Untyped {\n readonly [REF]: Json\n readonly [key: string]: UntypedRef\n}\n\ntype RefPaths = [Json] extends [T]\n ? Untyped & { readonly [key: string]: UntypedRef }\n : T extends readonly (infer E)[]\n ? { readonly [index: number]: Ref; readonly length: Ref }\n : T extends object\n ? { readonly [K in keyof T]-?: Ref }\n : unknown\n\n/**\n * A typed reference to a block output, compiled to ``.\n * Paths map exactly: `.seg`, `[\u0027seg\u0027]` and `[n]`. Untyped JSON allows any path.\n */\nexport type Ref = { readonly [REF]: T } & RefPaths\n\n/** Text with references in it, written with one of the tags below. */\nexport type Template = string & { readonly [TEMPLATE]: true }\n\n/** A workspace environment variable, compiled to `{{NAME}}`. */\nexport interface EnvRef {\n readonly [ENV]: string\n}\n\n/**\n * What a reference must hold to fill a param of type `T`. A param taking some strings takes any\n * string (an option id computed at run time); `null` (an output a step left empty) fits anywhere.\n */\ntype RefValue = [Extract] extends [never] ? T | null : T | string | null\n\n/**\n * A reference that fits a param of type `T`: one whose value has that type, or one into untyped\n * JSON. A whole block is not a value: reference one of its outputs.\n */\nexport type RefTo = ({ readonly [REF]: RefValue } | (AnyRef & Untyped)) & {\n readonly [NODE]?: never\n}\n\n/** A param value: a literal, a reference of a fitting type, a template or an environment variable. */\nexport type Value = T | RefTo | Template | EnvRef\n\n/** JSON whose leaves may be references, templates or environment variables. */\nexport type JsonWithRefs =\n | null\n | boolean\n | number\n | string\n | AnyRef\n | Template\n | EnvRef\n | JsonWithRefs[]\n | { [key: string]: JsonWithRefs }\n\n/** A literal union that still accepts any other string (option ids read from values). */\nexport type LiteralUnion = T | (string & {})\n\n/** A `time-input` value, `HH:MM`. */\nexport type TimeString = `${number}:${number}`\n\n/** A reference written into text: any output or variable, but not a whole block. */\ntype InterpolatedRef = AnyRef & { readonly [NODE]?: never }\n\ntype Interpolation = InterpolatedRef | EnvRef | VarRef | string | number | boolean\n\n/** Text with interpolated references: `` t`New ${cls.category} ticket` ``. */\nexport declare function t(strings: TemplateStringsArray, ...values: Interpolation[]): Template\n/**\n * JavaScript code (condition expressions, inline function code), kept exactly as written: like\n * `String.raw`, `` js`/\\s+/` `` is `/\\s+/`. Only `` \\` `` and `\\${` are escapes, for a backtick\n * and a literal `${`. So are `py`, `sh`, `json` and `md`; `t` text reads like a JS string.\n */\nexport declare const js: typeof t\n/** Python code, kept exactly as written (see {@link js}). */\nexport declare const py: typeof t\n/** Shell code, kept exactly as written (see {@link js}). */\nexport declare const sh: typeof t\n/**\n * JSON text kept verbatim, for bodies an object literal cannot reproduce byte for byte. In a JSON\n * field an object literal is the usual form: a bare reference keeps its value\u0027s type (`n: score.value`\n * is a number), and a template is text.\n */\nexport declare const json: typeof t\n/** Markdown text (note content). */\nexport declare const md: typeof t\n\n/** A reference with a non-canonical spelling, such as `ref(\u0027Classify.content\u0027)`. */\nexport declare function ref(path: string): Ref\n\n/** A stored value outside the generated type (a legacy option id, say), kept verbatim. */\nexport declare function raw(value: unknown): T & { readonly [RAW]: true }\n\n/** A required value that is still missing; compiles to absent, so canvas drafts type-check. */\nexport declare function todo(): never\n\n/**\n * Keeps the value the stored workflow holds for this param, without showing it: the printer writes\n * it for a secret pasted into a password field or a value that looks like a credential. Valid only\n * on a param of a block the stored workflow already has (same name and type) and holds a value\n * for, or as the `value` of a variable the stored workflow declares; anything else is\n * `E_STORED_VALUE_MISSING`.\n */\nexport declare function stored(): never\n\n/** Function code kept in a file next to the workflow (`.js`, `.py` or `.sh`), stored verbatim. */\nexport interface CodeFileRef {\n readonly [CODE_FILE]: string\n}\nexport declare function codeFile(path: `./${string}`): CodeFileRef\n\n/**\n * Environment variable names known to the workspace. `workspace.d.ts` adds one member per name;\n * until it exists `env` accepts any name.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceEnv {}\n\nexport declare const env: keyof WorkspaceEnv extends never\n ? { readonly [name: string]: EnvRef }\n : { readonly [K in keyof WorkspaceEnv]: EnvRef }\n\n/**\n * Workspace resources by stable key, filled in by the generated `workspace.d.ts`. Each map\u0027s\n * values describe the resource: a table\u0027s row type, a credential\u0027s provider, a workflow\u0027s inputs.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceTables {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceKnowledgeBases {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCredentials {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceWorkflows {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceSkills {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCustomTools {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceMcpServers {}\n\ntype KeyOf = keyof M extends never ? string : Extract\n\nexport type TableKey = KeyOf\nexport type KnowledgeBaseKey = KeyOf\nexport type CredentialKey = KeyOf\nexport type WorkflowKey = KeyOf\nexport type SkillKey = KeyOf\nexport type CustomToolKey = KeyOf\nexport type McpServerKey = KeyOf\n/**\n * The tool names of MCP server `K`, as `workspace.d.ts` records them from the server\u0027s last\n * listing; any name for a server it could not list or does not know.\n */\nexport type McpToolName = K extends keyof WorkspaceMcpServers\n ? WorkspaceMcpServers[K] extends { tools: infer T extends string }\n ? T\n : string\n : string\n\n/** A workspace resource by stable key, compiled to the resource\u0027s internal id. */\nexport interface ResourceRef {\n readonly [RESOURCE]: Kind\n readonly key: Key\n}\n\n/** A saved credential: `credential(\u0027support-slack\u0027)`. */\nexport type CredentialRef = ResourceRef<\u0027credential\u0027, Key>\n\n/**\n * Keys of the saved credentials for one of `Providers`, as `workspace.d.ts` records each\n * credential\u0027s provider; any key until it exists.\n */\nexport type CredentialKeyFor = keyof WorkspaceCredentials extends never\n ? string\n : {\n [K in Extract]: WorkspaceCredentials[K] extends {\n provider: Providers\n }\n ? K\n : never\n }[Extract]\nexport declare function credential(key: K): CredentialRef\n\n/**\n * The other form a credential field takes beside `credential(\u0027key\u0027)`: a credential id produced at\n * run time by a reference, a template or an environment variable, stored in the field\u0027s advanced\n * twin (`manualCredential`). Literal text is not one, so a pasted token never type-checks; a\n * literal id the stored workflow already holds prints as `raw(\u0027…\u0027)`.\n */\nexport type CredentialIdValue = RefTo | Template | EnvRef\n\n/** The columns of a workspace table, or loose JSON when `workspace.d.ts` does not know it. */\nexport type TableColumns = K extends keyof WorkspaceTables\n ? WorkspaceTables[K]\n : { [column: string]: Json }\n/**\n * One row as the table blocks output it: the row id, and its cells keyed by column name under\n * `data` (`row.data.status`). Times are ISO strings.\n */\nexport interface TableRow {\n id: string\n data: TableColumns\n position: number\n createdAt: string\n updatedAt: string\n}\n/**\n * A value written to a field of type `T` (a table cell, a child workflow input): a JSON or JSON\n * array field takes JSON with references in it, and `null` leaves the field empty.\n */\ntype FieldValue = [Json] extends [T]\n ? JsonWithRefs\n : [Json[]] extends [T]\n ? JsonWithRefs\n : Value | null\n\n/** The columns of table `K` every row must hold: those whose cell type does not admit `null`. */\ntype RequiredColumns = {\n [C in keyof WorkspaceTables[K]]-?: null extends WorkspaceTables[K][C] ? never : C\n}[keyof WorkspaceTables[K]]\n\n/**\n * A whole row, as an insert, an upsert or a batch insert writes it, each value checked against\n * its column\u0027s type. A required column must be present and not `null`: the table refuses a row\n * without it (`Missing required field`), and an upsert checks the whole row before it looks for a\n * match.\n */\nexport type TableData = K extends keyof WorkspaceTables\n ? { [C in RequiredColumns]-?: Exclude, null> } & {\n [C in Exclude>]?: FieldValue<\n WorkspaceTables[K][C]\n >\n }\n : { [column: string]: JsonWithRefs }\n\n/**\n * The cells an update writes, each checked against its column\u0027s type. Every column is optional:\n * an update merges these cells over the stored row.\n */\nexport type TableDataPatch = K extends keyof WorkspaceTables\n ? { [C in keyof WorkspaceTables[K]]?: FieldValue }\n : { [column: string]: JsonWithRefs }\n\n/** A workspace table: `table(\u0027leads\u0027)`. Table block operations live on `table.*`. */\nexport type TableRef = ResourceRef<\u0027table\u0027, Key>\nexport declare function table(key: K): TableRef\n\n/** A knowledge base: `knowledgeBase(\u0027docs\u0027)`. */\nexport type KnowledgeBaseRef = ResourceRef<\u0027knowledge-base\u0027, Key>\nexport declare function knowledgeBase(key: K): KnowledgeBaseRef\n\n/** A workspace skill: `skill(\u0027triage\u0027)`. */\nexport type SkillRef = ResourceRef<\u0027skill\u0027, Key>\nexport declare function skill(key: K): SkillRef\n\n/** A workspace folder: `folder(\u0027reports\u0027)`. */\nexport type FolderRef = ResourceRef<\u0027file-folder\u0027>\nexport declare function folder(key: string): FolderRef\n\n/** A workspace file: `file(\u0027contracts/acme.pdf\u0027)`. File block operations live on `file.*`. */\nexport type FileRef = ResourceRef<\u0027file\u0027>\nexport declare function file(path: string): FileRef\n\n/**\n * A file a file-upload field holds, as the editor stores it: one uploaded in place, or a workspace\n * file chosen by `key` (written `file(\u0027path\u0027)` when the workspace resolves it).\n */\nexport interface UploadedFile {\n name: string\n path: string\n size?: number\n type?: string\n key?: string | FileRef\n id?: string\n folderPath?: string\n}\n\n/** A file produced at run time (`file` / `file[]` outputs). */\nexport interface SimFile {\n id: string\n name: string\n url: string\n size: number\n type: string\n key: string\n}\n\n// Agent tools\n\n/** One entry of an agent\u0027s `tools` list. */\nexport interface Tool {\n readonly [TOOL]: true\n}\n\n/** How the model may use a tool, and the stored tool fields a print carries. */\nexport interface ToolOpts {\n usageControl?: \u0027auto\u0027 | \u0027force\u0027 | \u0027none\u0027\n usageControlExpression?: string\n title?: string\n /** The stored operation, when the method does not pin it. */\n operation?: string\n toolId?: string\n /** Pair modes of the tool\u0027s params, which pick the member the agent reads. */\n modes?: Record\n customTool?: JsonWithRefs\n operationPolicy?: Json\n /** Unknown stored tool keys, kept verbatim. */\n extra?: Json\n}\n\n/**\n * A workspace custom tool by key, as an agent tool: `customTool(\u0027lookup-order\u0027)`. A stored tool\n * whose definition was copied into the workflow (and may have drifted from the workspace tool)\n * prints as `raw(tool)` instead.\n */\nexport declare function customTool(key: K, options?: ToolUsage): Tool\n\n/** How the model may use a tool the SDK writes by name (`customTool`, `mcp().tool`, `asTool`). */\nexport type ToolUsage = Pick\n\n/** An MCP tool\u0027s arguments and the editor\u0027s snapshot of its server. */\nexport interface McpToolOpts extends ToolUsage {\n /** Argument values the workflow fixes; the model fills in the rest. */\n args?: Record\n /**\n * What the editor saved about the server and the tool\u0027s input schema when the tool was picked.\n * Shown in the editor; never run.\n */\n snapshot?: { serverName?: string; serverUrl?: string; schema?: Json }\n}\n\n/** An MCP server by key: `mcp(\u0027linear\u0027)`. */\nexport interface McpServerRef extends ResourceRef<\u0027mcp-server\u0027, Key> {\n /** One of the server\u0027s tools, as an agent tool: `mcp(\u0027linear\u0027).tool(\u0027create_issue\u0027)`. */\n tool(name: McpToolName, options?: McpToolOpts): Tool\n}\nexport declare function mcp(key: K): McpServerRef\n\n// Graph\n\n/** Block-level fields (`BlockState`), written as the third builder argument. */\nexport interface BlockMeta {\n /**\n * A legacy key the display name cannot carry (a `name~n` collision key or a reserved name such\n * as `Loop`). Printed only for such a stored block; apply accepts it only for a key the stored\n * workflow already has, so it can never introduce one.\n */\n key?: string\n /** Stored as `enabled: false`. */\n disabled?: true\n /** Locked: apply refuses any change to this block. */\n locked?: true\n /** Exposes the error port without an `onError` edge. */\n errorPort?: boolean\n /** The block-level advanced toggle (`advancedMode`). */\n advancedMode?: boolean\n /**\n * Runs the block as its trigger (`triggerMode`). Trigger builders (`trigger.gmail.poller`) set\n * it themselves; write it on any other builder only for a block stored in trigger mode.\n */\n triggerMode?: boolean\n /** The stored retry policy, written whole. */\n retry?: BlockRetryConfig\n /**\n * Per branch key of a condition or router, the row\u0027s display `title` and any stored fields the\n * SDK has no syntax for (`extra`, plain JSON). `title: null` keeps a row stored with no title,\n * which the executor never takes for `else`.\n */\n branches?: Record }>\n /**\n * Stored params that run but have no SDK syntax: a schema-agnostic custom block\u0027s inputs, the\n * agent\u0027s legacy prompt fields, a container\u0027s stored params. Values the block keeps but never\n * runs are not written; apply keeps them from the stored workflow.\n */\n extra?: Record\n /**\n * A loop or parallel\u0027s `block.data` subflow keys the loader could not read as config, kept\n * verbatim (plain JSON).\n */\n subflowData?: Record\n}\n\n/** A block\u0027s retry policy, field for field the stored `BlockRetryConfig`. */\nexport interface BlockRetryConfig {\n /** Absent config and `false` mean the same thing: the block runs once. */\n enabled: boolean\n /** Total tries including the first. */\n maxTries: number\n /** Delay between tries. */\n waitBetweenTriesMs: number\n}\n\n/** Anything an edge can point at. */\nexport type Target = Node | Group\n\n/** A block or container in the graph. */\nexport interface Node {\n readonly [NODE]: true\n /** Wires this node\u0027s default port to each target. Returns the target, or a group of them. */\n to(...targets: T): T extends [infer One] ? One : Group\n /** Wires this node\u0027s error port to each target. */\n onError(...targets: Target[]): void\n}\n\n/** Several nodes; `.to()` wires every member (fan-in). */\nexport interface Group {\n to(...targets: Target[]): Group\n}\n\n/**\n * What a block outputs when it fails and an error edge leaves it (`x.onError(y)` runs `y` with\n * `x.error`): the failure message `error` on every block, plus the error outputs `E` its catalog\n * entry declares (a Function\u0027s `errorMessage`, the thrown message without its line and code). A\n * check refuses each on a block without an error edge, which fails the run instead. An output the\n * block declares under the same name keeps its declared type.\n */\ntype ErrorOutputs = {\n readonly [K in \u0027error\u0027 | E as [O] extends [Record] ? never : K]: Ref\n}\n\n/** A block: a node whose outputs can be referenced, and its error outputs after an `onError` edge. */\nexport type Block = Node & Ref & ErrorOutputs\n\n/** The named ports of a condition or router. */\nexport type Branches = { readonly [P in K]: Node }\n\n/** Trigger builders (`trigger.start`, `trigger.gmail.poller`, ...), generated from the catalog. */\nexport declare namespace trigger {}\n\n/** Builders for hidden legacy block versions (`legacy.slack.send`), generated from the catalog. */\nexport declare namespace legacy {}\n\n/** A raw edge from a handle the SDK has no name for (a legacy or unknown port). */\nexport declare function edge(from: Node, handle: string, to: Target): void\n\n/** Any stored block type without a builder (legacy, unknown or custom), with untyped outputs. */\nexport declare function block(\n type: string,\n name: string,\n params: Record,\n meta?: BlockMeta\n): Block\n\n// Workflow and variables\n\nexport type VariableType = \u0027string\u0027 | \u0027number\u0027 | \u0027boolean\u0027 | \u0027object\u0027 | \u0027array\u0027 | \u0027plain\u0027\n\n/** A workflow variable declared in `workflow(name, { variables })`: its type and initial value. */\nexport interface VariableDeclaration {\n /**\n * The display name, written only when it differs from the key. It must normalize to the key\n * (lowercased, spaces and dots removed), as `\u0027Total Count\u0027` does to `totalcount`.\n */\n name?: string\n type: VariableType\n value: Json\n}\n\n/** The variables a workflow declares, by name. */\nexport type VariableDeclarations = Record\n\ndeclare const VAR: unique symbol\n\n/** A workflow variable, compiled to ``. */\nexport interface VarRef {\n readonly [VAR]: string\n}\n\ntype VariableValue = T extends \u0027number\u0027\n ? number\n : T extends \u0027boolean\u0027\n ? boolean\n : T extends \u0027string\u0027 | \u0027plain\u0027\n ? string\n : Json\n\n/** `vars` in the workflow body: one typed reference per declared variable. */\nexport type VarRefs = {\n readonly [K in keyof V]: VarRef & Ref>\n}\n\n/**\n * Workflow variables by name, untyped. Prefer the `vars` the `workflow()` body receives, which is\n * typed from the declared variables.\n */\nexport declare const vars: { readonly [name: string]: VarRef & Ref }\n\ndeclare const WORKFLOW_DEF: unique symbol\n\n/** The default export of a workflow file. */\nexport interface WorkflowDef {\n readonly [WORKFLOW_DEF]: true\n}\n\n/** A child workflow by key, for `runWorkflow` or as an agent tool. */\nexport interface WorkflowRef extends ResourceRef<\u0027workflow\u0027, Key> {\n /**\n * The workflow as an agent tool, as the editor\u0027s tool picker adds it:\n * `childWorkflow(\u0027enrich-lead\u0027).asTool()`. A tool with fixed inputs is written `raw(tool)`.\n */\n asTool(options?: ToolUsage): Tool\n}\n\n/**\n * Declares a workflow. The body wires blocks; it never runs. With no description or variables the\n * options may be left out: `workflow(\u0027Name\u0027, () => { ... })`.\n */\nexport declare function workflow>(\n name: string,\n options: { description?: string; variables?: V },\n body: (scope: { vars: VarRefs }) => void\n): WorkflowDef\nexport declare function workflow(\n name: string,\n body: (scope: { vars: VarRefs> }) => void\n): WorkflowDef\n/** A child workflow by key: `childWorkflow(\u0027enrich-lead\u0027)`. */\nexport declare function childWorkflow(key: K): WorkflowRef\n\n// Containers\n\ntype ItemOf = C extends { readonly [REF]: readonly (infer E)[] }\n ? E\n : C extends readonly (infer E)[]\n ? E\n : Json\n\n/** Inside a loop or parallel body. As a node it is the container\u0027s start port: `p.to(first)`. */\nexport interface SubflowScope extends Node {\n readonly index: Ref\n readonly currentItem: Ref\n readonly items: Ref\n}\n\n/**\n * A container\u0027s outputs, plus its iteration fields by name (`outer.index`), which a block inside\n * the container reads (in a nested container too: an outer loop\u0027s index or item). Outside the\n * container only `results` resolves: check reports `W_REF_OUT_OF_SCOPE` on `outer.index` there.\n */\nexport interface SubflowOutput {\n /**\n * One entry per iteration (a parallel: per branch), each the list of outputs of the body blocks\n * that ran in it, in the order they finished. With one block in the body its output is\n * `results[i][0]`; in code, `results.flat()` lists every output.\n */\n results: Json[][]\n index: number\n currentItem: Json\n items: Json[]\n}\n\n/** A loop or parallel container. Its `.to()` wires the port taken after it finishes. */\nexport type Container = Block\n\ntype Collection = AnyRef | Template | Json[] | string\n\n/**\n * A loop container: `forEach` over a list, `for` a count, `while` or `doWhile` a condition. The\n * body callback declares the blocks each iteration runs and wires the first from the scope\n * (`p.to(first)`), which reads the iteration as `p.currentItem` and `p.index` (a code file:\n * `$ref.loop.currentItem`). After it, `each.results[i]` lists iteration `i`\u0027s body-block outputs\n * (one block: `each.results[i][0]`), and `each.to(next)` wires what runs once all finish.\n * @example const each = loop.forEach(\u0027Each Order\u0027, { collection: orders.rows }, (p) => { const line = fn(\u0027Line\u0027, { code: js`return ${p.currentItem.data.id}` }); p.to(line) })\n */\nexport declare const loop: {\n for(\n name: string,\n params: { count?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n forEach(\n name: string,\n params: { collection: C },\n body: (scope: SubflowScope>) => void,\n meta?: BlockMeta\n ): Container\n while(\n name: string,\n params: { condition: Template | string },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n doWhile(\n name: string,\n params: { condition?: Template | string; count?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n}\n\nexport declare const parallel: {\n /** A parallel with no stored type, which the loader runs as `count`. */\n (\n name: string,\n params: { count?: number; collection?: Collection; batchSize?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n count(\n name: string,\n params: { count: number; batchSize?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n collection(\n name: string,\n params: { collection: C; batchSize?: number },\n body: (scope: SubflowScope>) => void,\n meta?: BlockMeta\n ): Container\n}\n\n// Blocks with a source form of their own\n\n/**\n * Params and outputs of the blocks below, generated from the catalog. Each entry is\n * `{ params; output }`, with `errorOutputs` when the block declares any; without generated types\n * the params are loose.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface SpecialBuilderTypes {}\n\ntype SpecialParams = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { params: infer P }\n ? P\n : never\n : Record\n\ntype SpecialOutput = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { output: infer O }\n ? O\n : never\n : Json\n\n/** The error outputs a special builder\u0027s block declares; a builder whose block has any passes them. */\ntype SpecialErrorOutputs = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { errorOutputs: infer E extends string }\n ? E\n : never\n : never\n\n/** A condition expression, or `true` for the `else` branch. */\nexport type BranchExpression = Template | string | true\n\ndeclare const ONLY_ELSE: unique symbol\n\n/** What a branch other than `else` written as `true` must be, which no value is: the error names it. */\ninterface OnlyElseMayBeTrue {\n readonly [ONLY_ELSE]: true\n}\n\n/**\n * A condition\u0027s branches: every key holds an expression, and only `else` may be `true`. Another\n * branch written as `true` is checked against {@link OnlyElseMayBeTrue}, so the error names that\n * branch alone.\n */\ntype ConditionBranches = {\n [K in keyof B]: K extends \u0027else\u0027\n ? BranchExpression\n : B[K] extends true\n ? OnlyElseMayBeTrue\n : Template | string\n}\n\n/**\n * Keys of a condition written with no rows (`condition(\u0027Name\u0027, {})`, the source form of rows\n * that were never persisted): the implicit `if` and `else` ports stay addressable.\n */\ntype ConditionKeys = keyof B extends never ? \u0027if\u0027 | \u0027else\u0027 : Extract\ntype RouterKeys = keyof R extends never ? \u0027route0\u0027 : Extract\n\n/**\n * A condition: named branches tested in order, top to bottom; the first whose expression holds\n * runs, and `else` (last, written `true`) runs when none does. Wire each as `x..to(block)`.\n * @example condition(\u0027Route\u0027, { big: js`${order.total} >= 500`, small: js`${order.total} < 50`, else: true })\n */\nexport declare function condition>(\n name: string,\n branches: B & ConditionBranches,\n meta?: BlockMeta\n): Block> & Branches>\n\n/** A router: named routes described for the model. */\nexport declare function router>(\n name: string,\n params: SpecialParams<\u0027router\u0027> & { routes: R },\n meta?: BlockMeta\n): Block> & Branches>\n\n/** A function block. `code` is inline (`` js`...` ``) or a code file (`codeFile(\u0027./functions/x.js\u0027)`). */\nexport declare function fn(\n name: string,\n params: SpecialParams<\u0027fn\u0027> & { code: Template | CodeFileRef | string },\n meta?: BlockMeta\n): Block, SpecialErrorOutputs<\u0027fn\u0027>>\n\n/**\n * The inputs of a child workflow by key, each checked against the input its start block\n * declares when `workspace.d.ts` knows the workflow; loose JSON otherwise.\n */\nexport type WorkflowInputMapping = K extends keyof WorkspaceWorkflows\n ? WorkspaceWorkflows[K] extends { inputs: infer I }\n ? { [N in keyof I]?: FieldValue }\n : InputMapping\n : InputMapping\n\n/**\n * Runs a child workflow. A `childWorkflow(\u0027key\u0027)` checks `inputMapping` against its inputs. Its\n * `result` is the child\u0027s output: its first response block\u0027s `{ data, status, headers }` (a body\n * field is `result.data.field`), else the output of the last block it ran.\n */\nexport declare function runWorkflow(\n name: string,\n params: Omit, \u0027workflowId\u0027 | \u0027inputMapping\u0027> & {\n workflowId: WorkflowRef | Exclude[\u0027workflowId\u0027], WorkflowRef>\n inputMapping?: WorkflowInputMapping\n },\n meta?: BlockMeta\n): Block>\n\n/**\n * Pauses for a person; the form in `inputFormat` types `submission`. A resumed block also holds\n * each form field at its top level (the runtime copies the submission up, over any output of the\n * same name), so `approval.approved` and `approval.submission.approved` both read it.\n */\nexport declare function human>(\n name: string,\n params: SpecialParams<\u0027human\u0027> & { inputFormat?: F },\n meta?: BlockMeta\n): Block<\n Omit, \u0027submission\u0027 | keyof F> & {\n submission: InputFieldsOutput\n } & InputFieldsOutput\n>\n\n/**\n * A response\u0027s body, status and headers: the editor\u0027s JSON mode, `body` standing for\n * `{ dataMode: \u0027json\u0027, data }`. An object or array `body` is JSON whose references keep their\n * types; a template or reference is the body text as written.\n */\nexport interface ResponseBody {\n body: JsonWithRefs\n /** HTTP status; 200 when omitted. A template or reference must produce a number. */\n status?: number | RefTo | Template | EnvRef\n /** Response headers by name. */\n headers?: Record>\n}\n\n/**\n * Ends the workflow with an API response: `response(\u0027Reply\u0027, { body: { ok: true }, status: 201 })`\n * (`body` is short for `dataMode: \u0027json\u0027` with `data`), or the block\u0027s own params (`dataMode`,\n * `builderData`, ...) when the body is built field by field.\n */\nexport declare function response(\n name: string,\n params: ResponseBody,\n meta?: BlockMeta\n): Block>\nexport declare function response(\n name: string,\n params: SpecialParams<\u0027response\u0027>,\n meta?: BlockMeta\n): Block>\n\n/** Assigns workflow variables. */\nexport declare function setVariables(\n name: string,\n params: SpecialParams<\u0027setVariables\u0027>,\n meta?: BlockMeta\n): Block>\n\ndeclare const ANNOTATION: unique symbol\n\n/** A canvas note: no edges, no outputs. */\nexport interface Annotation {\n readonly [ANNOTATION]: true\n}\nexport declare function note(\n name: string,\n params: SpecialParams<\u0027note\u0027>,\n meta?: BlockMeta\n): Annotation\n\n// Structured param shapes\n\n/** Type names an input-format field may declare. */\nexport type InputFieldType = \u0027string\u0027 | \u0027number\u0027 | \u0027boolean\u0027 | \u0027object\u0027 | \u0027array\u0027 | \u0027file[]\u0027\n\n/** A structured input field: its type plus a default value, description or required flag. */\nexport interface InputFieldSpec {\n type: InputFieldType\n value?: JsonWithRefs\n description?: string\n required?: boolean\n}\n\n/** `input-format` fields by name: `{ subject: \u0027string\u0027, amount: { type: \u0027number\u0027, value: 0 } }`. */\nexport type InputFields = Record\n\ntype InputFieldValue = T extends \u0027string\u0027\n ? string\n : T extends \u0027number\u0027\n ? number\n : T extends \u0027boolean\u0027\n ? boolean\n : T extends \u0027array\u0027\n ? Json[]\n : T extends \u0027file[]\u0027\n ? SimFile[]\n : Json\n\n/** The outputs an `input-format` declares. */\nexport type InputFieldsOutput = {\n [K in keyof F]: F[K] extends { type: infer T } ? InputFieldValue : InputFieldValue\n}\n\n/**\n * One `response-format` field as the editor\u0027s builder stores it. An `object` or `array` field\u0027s\n * `value` may hold nested fields. A response is usually written with `body` instead.\n */\nexport interface ResponseField {\n id?: string\n name: string\n type: string\n value?: JsonWithRefs\n collapsed?: boolean\n}\n\n/** `response-format` fields: `[{ name: \u0027ok\u0027, type: \u0027boolean\u0027, value: true }]`. */\nexport type ResponseFields = ResponseField[]\n\n/** An agent message. */\nexport interface Message {\n role: \u0027system\u0027 | \u0027user\u0027 | \u0027assistant\u0027\n content: Value\n}\n\n/** One `variables-input` assignment, with any other stored keys kept. */\nexport interface VariableAssignment {\n variableId: VarRef\n value?: JsonWithRefs\n [key: string]: JsonWithRefs | VarRef | undefined\n}\n\n/** Child workflow inputs by name (`input-mapping`, `workflow-input-mapper`). */\nexport type InputMapping = Record\n\n/** An operator a table filter condition or builder rule can use. */\nexport type FilterOperator = LiteralUnion<\n | \u0027eq\u0027\n | \u0027ne\u0027\n | \u0027gt\u0027\n | \u0027gte\u0027\n | \u0027lt\u0027\n | \u0027lte\u0027\n | \u0027in\u0027\n | \u0027nin\u0027\n | \u0027like\u0027\n | \u0027ilike\u0027\n | \u0027nlike\u0027\n | \u0027nilike\u0027\n | \u0027contains\u0027\n | \u0027ncontains\u0027\n | \u0027startsWith\u0027\n | \u0027endsWith\u0027\n | \u0027isNull\u0027\n | \u0027isNotNull\u0027\n | \u0027isEmpty\u0027\n | \u0027isNotEmpty\u0027\n>\n\n/** One row of the editor\u0027s filter builder, as it stores it. */\nexport interface FilterRule {\n id?: string\n /** How this row joins the rows before it; `and` when omitted. */\n logicalOperator?: \u0027and\u0027 | \u0027or\u0027\n column: string\n operator: FilterOperator\n value: Value\n collapsed?: boolean\n}\n\n/** A filter-builder value: the editor\u0027s rows, `[{ column: \u0027status\u0027, operator: \u0027eq\u0027, value: \u0027new\u0027 }]`. */\nexport type Filter = FilterRule[]\n\n/** One table filter condition: `{ field: \u0027status\u0027, op: \u0027eq\u0027, value: \u0027new\u0027 }`. */\nexport interface TableCondition {\n field: string\n op: FilterOperator\n value?: JsonWithRefs\n}\n\n/**\n * A table predicate: a condition, or an `all` (and) / `any` (or) group of predicates. The\n * `{ status: { $eq: \u0027new\u0027 } }` operator-object grammar is not one: the runtime refuses it.\n */\nexport type TablePredicate = TableCondition | { all: TablePredicate[] } | { any: TablePredicate[] }\n\n/** A table sort by column: `{ createdAt: \u0027desc\u0027 }`. */\nexport type Sort =\n | Record\n | Array<{ column: string; direction: \u0027asc\u0027 | \u0027desc\u0027 }>\n\n/** One knowledge tag filter. */\nexport interface TagFilter {\n tagName: string\n tagValue: Value\n [key: string]: JsonWithRefs\n}\n\n/** One document tag. */\nexport interface DocumentTag {\n tagName: string\n value: Value\n [key: string]: JsonWithRefs\n}\n\n/** One `eval-input` metric. */\nexport interface EvalMetric {\n name: string\n description?: string\n range?: { min: number; max: number }\n [key: string]: JsonWithRefs | undefined\n}\n\n/** One `model-fallback-list` entry. */\nexport interface ModelFallback {\n model: LiteralUnion\n [key: string]: JsonWithRefs\n}\n\n/**\n * Model ids, generated into `models.d.ts` (which adds one member per model). Kept apart from the\n * block files so a model-list change touches one file.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface ModelIds {}\nexport type Model = Extract\n\n/** A JSON Schema `responseFormat`, or `{ name, strict, schema }` around one. */\nexport type ResponseFormat = JsonWithRefs\n\ntype Depth = [never, 0, 1, 2, 3, 4]\n\ntype FromSchema = [D] extends [never]\n ? Json\n : S extends { enum: readonly (infer E)[] }\n ? E\n : S extends { type: \u0027object\u0027; properties: infer P }\n ? { [K in keyof P]: FromSchema }\n : S extends { type: \u0027array\u0027; items: infer I }\n ? FromSchema[]\n : S extends { type: \u0027string\u0027 }\n ? string\n : S extends { type: \u0027number\u0027 | \u0027integer\u0027 }\n ? number\n : S extends { type: \u0027boolean\u0027 }\n ? boolean\n : Json\n\n/**\n * The outputs a literal `responseFormat` adds, read from its JSON Schema with recursion capped at\n * depth 4. A template or reference adds untyped JSON.\n */\nexport type ResponseFormatOutput = [RF] extends [undefined]\n ? unknown\n : RF extends { schema: infer S }\n ? FromSchema\n : RF extends { type: \u0027object\u0027; properties: object }\n ? FromSchema\n : { [key: string]: Json }\n" +export const CORE_DTS = "/**\n * The authoring surface for Sim workflows written as TypeScript.\n *\n * Nothing declared here runs. `@sim/workflow-code` compiles a workflow file statically, and every\n * runtime export of this package throws `SimSdkNotExecutable`. These declarations exist so an\n * editor, `tsc` (the type-check command `sim` prints) or an agent can check a workflow file before\n * the compiler sees it.\n *\n * Block builders (`slack.sendMessage`, `agent`, `trigger.gmail.poller`, ...) are not declared here:\n * they are generated from the block catalog into `blocks/{type}.d.ts`, which augment this module.\n * The generic `block(type, name, params)` covers any stored type without a builder.\n *\n * Every workflow file starts with the SDK header line, before any import:\n *\n * ```ts\n * // @sim-sdk 1\n * import { agent, trigger, workflow } from \u0027@sim/workflow-sdk\u0027\n * ```\n *\n * The number is the SDK major version the file is written against. A file without the header is\n * refused with `E_SDK_HEADER`, and one written for a newer major than the server supports with\n * `E_SDK_MAJOR`.\n */\n\n/** Plain JSON. */\nexport type Json = null | boolean | number | string | Json[] | { [key: string]: Json }\n\ndeclare const REF: unique symbol\ndeclare const TEMPLATE: unique symbol\ndeclare const ENV: unique symbol\ndeclare const RESOURCE: unique symbol\ndeclare const TOOL: unique symbol\ndeclare const NODE: unique symbol\ndeclare const CODE_FILE: unique symbol\ndeclare const RAW: unique symbol\ndeclare const UNTYPED: unique symbol\n\n/** Any reference, whatever it points at. */\nexport interface AnyRef {\n readonly [REF]: unknown\n}\n\n/** Marks a reference into untyped JSON, which any param accepts: its value is known only at run time. */\ninterface Untyped {\n readonly [UNTYPED]: true\n}\n\n/**\n * A reference into untyped JSON, where any path is allowed at any depth. An interface rather than\n * `Ref`, which TypeScript stops resolving after one step (`a.b.c` failed at `c`).\n */\ninterface UntypedRef extends Untyped {\n readonly [REF]: Json\n readonly [key: string]: UntypedRef\n}\n\ntype RefPaths = [Json] extends [T]\n ? Untyped & { readonly [key: string]: UntypedRef }\n : T extends readonly (infer E)[]\n ? { readonly [index: number]: Ref; readonly length: Ref }\n : T extends object\n ? { readonly [K in keyof T]-?: Ref }\n : unknown\n\n/**\n * A typed reference to a block output, compiled to ``.\n * Paths map exactly: `.seg`, `[\u0027seg\u0027]` and `[n]`. Untyped JSON allows any path.\n */\nexport type Ref = { readonly [REF]: T } & RefPaths\n\n/** Text with references in it, written with one of the tags below. */\nexport type Template = string & { readonly [TEMPLATE]: true }\n\n/** A workspace environment variable, compiled to `{{NAME}}`. */\nexport interface EnvRef {\n readonly [ENV]: string\n}\n\n/**\n * What a reference must hold to fill a param of type `T`. A param taking some strings takes any\n * string (an option id computed at run time); `null` (an output a step left empty) fits anywhere.\n */\ntype RefValue = [Extract] extends [never] ? T | null : T | string | null\n\n/**\n * A reference that fits a param of type `T`: one whose value has that type, or one into untyped\n * JSON. A whole block is not a value: reference one of its outputs.\n */\nexport type RefTo = ({ readonly [REF]: RefValue } | (AnyRef & Untyped)) & {\n readonly [NODE]?: never\n}\n\n/** A param value: a literal, a reference of a fitting type, a template or an environment variable. */\nexport type Value = T | RefTo | Template | EnvRef\n\n/** JSON whose leaves may be references, templates or environment variables. */\nexport type JsonWithRefs =\n | null\n | boolean\n | number\n | string\n | AnyRef\n | Template\n | EnvRef\n | JsonWithRefs[]\n | { [key: string]: JsonWithRefs }\n\n/** A literal union that still accepts any other string (option ids read from values). */\nexport type LiteralUnion = T | (string & {})\n\n/** A `time-input` value, `HH:MM`. */\nexport type TimeString = `${number}:${number}`\n\n/** A reference written into text: any output or variable, but not a whole block. */\ntype InterpolatedRef = AnyRef & { readonly [NODE]?: never }\n\ntype Interpolation = InterpolatedRef | EnvRef | VarRef | string | number | boolean\n\n/** Text with interpolated references: `` t`New ${cls.category} ticket` ``. */\nexport declare function t(strings: TemplateStringsArray, ...values: Interpolation[]): Template\n/**\n * JavaScript code (condition expressions, inline function code), kept exactly as written: like\n * `String.raw`, `` js`/\\s+/` `` is `/\\s+/`. Only `` \\` `` and `\\${` are escapes, for a backtick\n * and a literal `${`. So are `py`, `sh`, `json` and `md`; `t` text reads like a JS string.\n */\nexport declare const js: typeof t\n/** Python code, kept exactly as written (see {@link js}). */\nexport declare const py: typeof t\n/** Shell code, kept exactly as written (see {@link js}). */\nexport declare const sh: typeof t\n/**\n * JSON text kept verbatim, for bodies an object literal cannot reproduce byte for byte. In a JSON\n * field an object literal is the usual form: a bare reference keeps its value\u0027s type (`n: score.value`\n * is a number), and a template is text.\n */\nexport declare const json: typeof t\n/** Markdown text (note content). */\nexport declare const md: typeof t\n\n/** A reference with a non-canonical spelling, such as `ref(\u0027Classify.content\u0027)`. */\nexport declare function ref(path: string): Ref\n\n/** A stored value outside the generated type (a legacy option id, say), kept verbatim. */\nexport declare function raw(value: unknown): T & { readonly [RAW]: true }\n\n/** A required value that is still missing; compiles to absent, so canvas drafts type-check. */\nexport declare function todo(): never\n\n/**\n * Keeps the value the stored workflow holds for this param, without showing it: the printer writes\n * it for a secret pasted into a password field or a value that looks like a credential. Valid only\n * on a param of a block the stored workflow already has (same name and type) and holds a value\n * for, or as the `value` of a variable the stored workflow declares; anything else is\n * `E_STORED_VALUE_MISSING`.\n */\nexport declare function stored(): never\n\n/** Function code kept in a file next to the workflow (`.js`, `.py` or `.sh`), stored verbatim. */\nexport interface CodeFileRef {\n readonly [CODE_FILE]: string\n}\nexport declare function codeFile(path: `./${string}`): CodeFileRef\n\n/**\n * Environment variable names known to the workspace. `workspace.d.ts` adds one member per name;\n * until it exists `env` accepts any name.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceEnv {}\n\nexport declare const env: keyof WorkspaceEnv extends never\n ? { readonly [name: string]: EnvRef }\n : { readonly [K in keyof WorkspaceEnv]: EnvRef }\n\n/**\n * Workspace resources by stable key, filled in by the generated `workspace.d.ts`. Each map\u0027s\n * values describe the resource: a table\u0027s row type, a credential\u0027s provider, a workflow\u0027s inputs.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceTables {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceKnowledgeBases {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCredentials {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceWorkflows {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceSkills {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCustomTools {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceMcpServers {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceFiles {}\n\ntype KeyOf = keyof M extends never ? string : Extract\n\nexport type TableKey = KeyOf\nexport type KnowledgeBaseKey = KeyOf\nexport type CredentialKey = KeyOf\nexport type WorkflowKey = KeyOf\nexport type SkillKey = KeyOf\nexport type CustomToolKey = KeyOf\nexport type McpServerKey = KeyOf\n/** A workspace file\u0027s folder path and name (`docs/report.pdf`), as `files/` in a workspace directory holds it. */\nexport type FileKey = KeyOf\n/**\n * The tool names of MCP server `K`, as `workspace.d.ts` records them from the server\u0027s last\n * listing; any name for a server it could not list or does not know.\n */\nexport type McpToolName = K extends keyof WorkspaceMcpServers\n ? WorkspaceMcpServers[K] extends { tools: infer T extends string }\n ? T\n : string\n : string\n\n/** A workspace resource by stable key, compiled to the resource\u0027s internal id. */\nexport interface ResourceRef {\n readonly [RESOURCE]: Kind\n readonly key: Key\n}\n\n/** A saved credential: `credential(\u0027support-slack\u0027)`. */\nexport type CredentialRef = ResourceRef<\u0027credential\u0027, Key>\n\n/**\n * Keys of the saved credentials for one of `Providers`, as `workspace.d.ts` records each\n * credential\u0027s provider; any key until it exists.\n */\nexport type CredentialKeyFor = keyof WorkspaceCredentials extends never\n ? string\n : {\n [K in Extract]: WorkspaceCredentials[K] extends {\n provider: Providers\n }\n ? K\n : never\n }[Extract]\nexport declare function credential(key: K): CredentialRef\n\n/**\n * The other form a credential field takes beside `credential(\u0027key\u0027)`: a credential id produced at\n * run time by a reference, a template or an environment variable, stored in the field\u0027s advanced\n * twin (`manualCredential`). Literal text is not one, so a pasted token never type-checks; a\n * literal id the stored workflow already holds prints as `raw(\u0027…\u0027)`.\n */\nexport type CredentialIdValue = RefTo | Template | EnvRef\n\n/** The columns of a workspace table, or loose JSON when `workspace.d.ts` does not know it. */\nexport type TableColumns = K extends keyof WorkspaceTables\n ? WorkspaceTables[K]\n : { [column: string]: Json }\n/**\n * One row as the table blocks output it: the row id, and its cells keyed by column name under\n * `data` (`row.data.status`). Times are ISO strings.\n */\nexport interface TableRow {\n id: string\n data: TableColumns\n position: number\n createdAt: string\n updatedAt: string\n}\n/**\n * A value written to a field of type `T` (a table cell, a child workflow input): a JSON or JSON\n * array field takes JSON with references in it, and `null` leaves the field empty.\n */\ntype FieldValue = [Json] extends [T]\n ? JsonWithRefs\n : [Json[]] extends [T]\n ? JsonWithRefs\n : Value | null\n\n/** The columns of table `K` every row must hold: those whose cell type does not admit `null`. */\ntype RequiredColumns = {\n [C in keyof WorkspaceTables[K]]-?: null extends WorkspaceTables[K][C] ? never : C\n}[keyof WorkspaceTables[K]]\n\n/**\n * A whole row, as an insert, an upsert or a batch insert writes it, each value checked against\n * its column\u0027s type. A required column must be present and not `null`: the table refuses a row\n * without it (`Missing required field`), and an upsert checks the whole row before it looks for a\n * match.\n */\nexport type TableData = K extends keyof WorkspaceTables\n ? { [C in RequiredColumns]-?: Exclude, null> } & {\n [C in Exclude>]?: FieldValue<\n WorkspaceTables[K][C]\n >\n }\n : { [column: string]: JsonWithRefs }\n\n/**\n * The cells an update writes, each checked against its column\u0027s type. Every column is optional:\n * an update merges these cells over the stored row.\n */\nexport type TableDataPatch = K extends keyof WorkspaceTables\n ? { [C in keyof WorkspaceTables[K]]?: FieldValue }\n : { [column: string]: JsonWithRefs }\n\n/** A workspace table: `table(\u0027leads\u0027)`. Table block operations live on `table.*`. */\nexport type TableRef = ResourceRef<\u0027table\u0027, Key>\nexport declare function table(key: K): TableRef\n\n/** A knowledge base: `knowledgeBase(\u0027docs\u0027)`. */\nexport type KnowledgeBaseRef = ResourceRef<\u0027knowledge-base\u0027, Key>\nexport declare function knowledgeBase(key: K): KnowledgeBaseRef\n\n/** A workspace skill: `skill(\u0027triage\u0027)`. */\nexport type SkillRef = ResourceRef<\u0027skill\u0027, Key>\nexport declare function skill(key: K): SkillRef\n\n/** A workspace folder: `folder(\u0027reports\u0027)`. */\nexport type FolderRef = ResourceRef<\u0027file-folder\u0027>\nexport declare function folder(key: string): FolderRef\n\n/**\n * A workspace file by its folder path and name: `file(\u0027contracts/acme.pdf\u0027)`, written as a\n * file-upload field\u0027s value (or one item of a multi-file field\u0027s list); the same source names the\n * file at that path in whichever workspace it is applied to. File block operations live on\n * `file.*`.\n */\nexport type FileRef = ResourceRef<\u0027file\u0027, Key>\nexport declare function file(path: K): FileRef\n\n/**\n * A file a file-upload field holds, as the editor stores it, for a file that is not a workspace\n * file (one uploaded in place); a workspace file is written `file(\u0027/\u0027)`.\n */\nexport interface UploadedFile {\n name: string\n path: string\n size?: number\n type?: string\n key?: string\n id?: string\n folderPath?: string\n}\n\n/** A file produced at run time (`file` / `file[]` outputs). */\nexport interface SimFile {\n id: string\n name: string\n url: string\n size: number\n type: string\n key: string\n}\n\n// Agent tools\n\n/** One entry of an agent\u0027s `tools` list. */\nexport interface Tool {\n readonly [TOOL]: true\n}\n\n/** How the model may use a tool, and the stored tool fields a print carries. */\nexport interface ToolOpts {\n usageControl?: \u0027auto\u0027 | \u0027force\u0027 | \u0027none\u0027\n usageControlExpression?: string\n title?: string\n /** The stored operation, when the method does not pin it. */\n operation?: string\n toolId?: string\n /** Pair modes of the tool\u0027s params, which pick the member the agent reads. */\n modes?: Record\n customTool?: JsonWithRefs\n operationPolicy?: Json\n /** Unknown stored tool keys, kept verbatim. */\n extra?: Json\n}\n\n/**\n * A workspace custom tool by key, as an agent tool: `customTool(\u0027lookup-order\u0027)`. A stored tool\n * whose definition was copied into the workflow (and may have drifted from the workspace tool)\n * prints as `raw(tool)` instead.\n */\nexport declare function customTool(key: K, options?: ToolUsage): Tool\n\n/** How the model may use a tool the SDK writes by name (`customTool`, `mcp().tool`, `asTool`). */\nexport type ToolUsage = Pick\n\n/** An MCP tool\u0027s arguments and the editor\u0027s snapshot of its server. */\nexport interface McpToolOpts extends ToolUsage {\n /** Argument values the workflow fixes; the model fills in the rest. */\n args?: Record\n /**\n * What the editor saved about the server and the tool\u0027s input schema when the tool was picked.\n * Shown in the editor; never run.\n */\n snapshot?: { serverName?: string; serverUrl?: string; schema?: Json }\n}\n\n/** An MCP server by key: `mcp(\u0027linear\u0027)`. */\nexport interface McpServerRef extends ResourceRef<\u0027mcp-server\u0027, Key> {\n /** One of the server\u0027s tools, as an agent tool: `mcp(\u0027linear\u0027).tool(\u0027create_issue\u0027)`. */\n tool(name: McpToolName, options?: McpToolOpts): Tool\n}\nexport declare function mcp(key: K): McpServerRef\n\n// Graph\n\n/** Block-level fields (`BlockState`), written as the third builder argument. */\nexport interface BlockMeta {\n /**\n * A legacy key the display name cannot carry (a `name~n` collision key or a reserved name such\n * as `Loop`). Printed only for such a stored block; apply accepts it only for a key the stored\n * workflow already has, so it can never introduce one.\n */\n key?: string\n /** Stored as `enabled: false`. */\n disabled?: true\n /** Locked: apply refuses any change to this block. */\n locked?: true\n /** Exposes the error port without an `onError` edge. */\n errorPort?: boolean\n /** The block-level advanced toggle (`advancedMode`). */\n advancedMode?: boolean\n /**\n * Runs the block as its trigger (`triggerMode`). Trigger builders (`trigger.gmail.poller`) set\n * it themselves; write it on any other builder only for a block stored in trigger mode.\n */\n triggerMode?: boolean\n /** The stored retry policy, written whole. */\n retry?: BlockRetryConfig\n /**\n * Per branch key of a condition or router, the row\u0027s display `title` and any stored fields the\n * SDK has no syntax for (`extra`, plain JSON). `title: null` keeps a row stored with no title,\n * which the executor never takes for `else`.\n */\n branches?: Record }>\n /**\n * Stored params that run but have no SDK syntax: a schema-agnostic custom block\u0027s inputs, the\n * agent\u0027s legacy prompt fields, a container\u0027s stored params. Values the block keeps but never\n * runs are not written; apply keeps them from the stored workflow.\n */\n extra?: Record\n /**\n * A loop or parallel\u0027s `block.data` subflow keys the loader could not read as config, kept\n * verbatim (plain JSON).\n */\n subflowData?: Record\n}\n\n/** A block\u0027s retry policy, field for field the stored `BlockRetryConfig`. */\nexport interface BlockRetryConfig {\n /** Absent config and `false` mean the same thing: the block runs once. */\n enabled: boolean\n /** Total tries including the first. */\n maxTries: number\n /** Delay between tries. */\n waitBetweenTriesMs: number\n}\n\n/** Anything an edge can point at. */\nexport type Target = Node | Group\n\n/** A block or container in the graph. */\nexport interface Node {\n readonly [NODE]: true\n /** Wires this node\u0027s default port to each target. Returns the target, or a group of them. */\n to(...targets: T): T extends [infer One] ? One : Group\n /** Wires this node\u0027s error port to each target. */\n onError(...targets: Target[]): void\n}\n\n/** Several nodes; `.to()` wires every member (fan-in). */\nexport interface Group {\n to(...targets: Target[]): Group\n}\n\n/**\n * What a block outputs when it fails and an error edge leaves it (`x.onError(y)` runs `y` with\n * `x.error`): the failure message `error` on every block, plus the error outputs `E` its catalog\n * entry declares (a Function\u0027s `errorMessage`, the thrown message without its line and code). A\n * check refuses each on a block without an error edge, which fails the run instead. An output the\n * block declares under the same name keeps its declared type.\n */\ntype ErrorOutputs = {\n readonly [K in \u0027error\u0027 | E as [O] extends [Record] ? never : K]: Ref\n}\n\n/** A block: a node whose outputs can be referenced, and its error outputs after an `onError` edge. */\nexport type Block = Node & Ref & ErrorOutputs\n\n/** The named ports of a condition or router. */\nexport type Branches = { readonly [P in K]: Node }\n\n/** Trigger builders (`trigger.start`, `trigger.gmail.poller`, ...), generated from the catalog. */\nexport declare namespace trigger {}\n\n/** Builders for hidden legacy block versions (`legacy.slack.send`), generated from the catalog. */\nexport declare namespace legacy {}\n\n/** A raw edge from a handle the SDK has no name for (a legacy or unknown port). */\nexport declare function edge(from: Node, handle: string, to: Target): void\n\n/** Any stored block type without a builder (legacy, unknown or custom), with untyped outputs. */\nexport declare function block(\n type: string,\n name: string,\n params: Record,\n meta?: BlockMeta\n): Block\n\n// Workflow and variables\n\nexport type VariableType = \u0027string\u0027 | \u0027number\u0027 | \u0027boolean\u0027 | \u0027object\u0027 | \u0027array\u0027 | \u0027plain\u0027\n\n/** A workflow variable declared in `workflow(name, { variables })`: its type and initial value. */\nexport interface VariableDeclaration {\n /**\n * The display name, written only when it differs from the key. It must normalize to the key\n * (lowercased, spaces and dots removed), as `\u0027Total Count\u0027` does to `totalcount`.\n */\n name?: string\n type: VariableType\n value: Json\n}\n\n/** The variables a workflow declares, by name. */\nexport type VariableDeclarations = Record\n\ndeclare const VAR: unique symbol\n\n/** A workflow variable, compiled to ``. */\nexport interface VarRef {\n readonly [VAR]: string\n}\n\ntype VariableValue = T extends \u0027number\u0027\n ? number\n : T extends \u0027boolean\u0027\n ? boolean\n : T extends \u0027string\u0027 | \u0027plain\u0027\n ? string\n : Json\n\n/** `vars` in the workflow body: one typed reference per declared variable. */\nexport type VarRefs = {\n readonly [K in keyof V]: VarRef & Ref>\n}\n\n/**\n * Workflow variables by name, untyped. Prefer the `vars` the `workflow()` body receives, which is\n * typed from the declared variables.\n */\nexport declare const vars: { readonly [name: string]: VarRef & Ref }\n\ndeclare const WORKFLOW_DEF: unique symbol\n\n/** The default export of a workflow file. */\nexport interface WorkflowDef {\n readonly [WORKFLOW_DEF]: true\n}\n\n/** A child workflow by key, for `runWorkflow` or as an agent tool. */\nexport interface WorkflowRef extends ResourceRef<\u0027workflow\u0027, Key> {\n /**\n * The workflow as an agent tool, as the editor\u0027s tool picker adds it:\n * `childWorkflow(\u0027enrich-lead\u0027).asTool()`. A tool with fixed inputs is written `raw(tool)`.\n */\n asTool(options?: ToolUsage): Tool\n}\n\n/**\n * Declares a workflow. The body wires blocks; it never runs. With no description or variables the\n * options may be left out: `workflow(\u0027Name\u0027, () => { ... })`.\n */\nexport declare function workflow>(\n name: string,\n options: { description?: string; variables?: V },\n body: (scope: { vars: VarRefs }) => void\n): WorkflowDef\nexport declare function workflow(\n name: string,\n body: (scope: { vars: VarRefs> }) => void\n): WorkflowDef\n/** A child workflow by key: `childWorkflow(\u0027enrich-lead\u0027)`. */\nexport declare function childWorkflow(key: K): WorkflowRef\n\n// Containers\n\ntype ItemOf = C extends { readonly [REF]: readonly (infer E)[] }\n ? E\n : C extends readonly (infer E)[]\n ? E\n : Json\n\n/** Inside a loop or parallel body. As a node it is the container\u0027s start port: `p.to(first)`. */\nexport interface SubflowScope extends Node {\n readonly index: Ref\n readonly currentItem: Ref\n readonly items: Ref\n}\n\n/**\n * A container\u0027s outputs, plus its iteration fields by name (`outer.index`), which a block inside\n * the container reads (in a nested container too: an outer loop\u0027s index or item). Outside the\n * container only `results` resolves: check reports `W_REF_OUT_OF_SCOPE` on `outer.index` there.\n */\nexport interface SubflowOutput {\n results: Json[]\n index: number\n currentItem: Json\n items: Json[]\n}\n\n/** A loop or parallel container. Its `.to()` wires the port taken after it finishes. */\nexport type Container = Block\n\ntype Collection = AnyRef | Template | Json[] | string\n\n/**\n * A loop container: `forEach` over a list, `for` a count, `while` or `doWhile` a condition. The\n * body callback declares the blocks each iteration runs and wires the first from the scope\n * (`p.to(first)`), which reads the iteration as `p.currentItem` and `p.index` (a code file:\n * `$ref.loop.currentItem`). After it, `each.results` lists every iteration\u0027s output, and\n * `each.to(next)` wires what runs once all finish.\n * @example const each = loop.forEach(\u0027Each Order\u0027, { collection: orders.rows }, (p) => { const line = fn(\u0027Line\u0027, { code: js`return ${p.currentItem.data.id}` }); p.to(line) })\n */\nexport declare const loop: {\n for(\n name: string,\n params: { count?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n forEach(\n name: string,\n params: { collection: C },\n body: (scope: SubflowScope>) => void,\n meta?: BlockMeta\n ): Container\n while(\n name: string,\n params: { condition: Template | string },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n doWhile(\n name: string,\n params: { condition?: Template | string; count?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n}\n\nexport declare const parallel: {\n /** A parallel with no stored type, which the loader runs as `count`. */\n (\n name: string,\n params: { count?: number; collection?: Collection; batchSize?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n count(\n name: string,\n params: { count: number; batchSize?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n collection(\n name: string,\n params: { collection: C; batchSize?: number },\n body: (scope: SubflowScope>) => void,\n meta?: BlockMeta\n ): Container\n}\n\n// Blocks with a source form of their own\n\n/**\n * Params and outputs of the blocks below, generated from the catalog. Each entry is\n * `{ params; output }`, with `errorOutputs` when the block declares any; without generated types\n * the params are loose.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface SpecialBuilderTypes {}\n\ntype SpecialParams = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { params: infer P }\n ? P\n : never\n : Record\n\ntype SpecialOutput = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { output: infer O }\n ? O\n : never\n : Json\n\n/** The error outputs a special builder\u0027s block declares; a builder whose block has any passes them. */\ntype SpecialErrorOutputs = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { errorOutputs: infer E extends string }\n ? E\n : never\n : never\n\n/** A condition expression, or `true` for the `else` branch. */\nexport type BranchExpression = Template | string | true\n\ndeclare const ONLY_ELSE: unique symbol\n\n/** What a branch other than `else` written as `true` must be, which no value is: the error names it. */\ninterface OnlyElseMayBeTrue {\n readonly [ONLY_ELSE]: true\n}\n\n/**\n * A condition\u0027s branches: every key holds an expression, and only `else` may be `true`. Another\n * branch written as `true` is checked against {@link OnlyElseMayBeTrue}, so the error names that\n * branch alone.\n */\ntype ConditionBranches = {\n [K in keyof B]: K extends \u0027else\u0027\n ? BranchExpression\n : B[K] extends true\n ? OnlyElseMayBeTrue\n : Template | string\n}\n\n/**\n * Keys of a condition written with no rows (`condition(\u0027Name\u0027, {})`, the source form of rows\n * that were never persisted): the implicit `if` and `else` ports stay addressable.\n */\ntype ConditionKeys = keyof B extends never ? \u0027if\u0027 | \u0027else\u0027 : Extract\ntype RouterKeys = keyof R extends never ? \u0027route0\u0027 : Extract\n\n/**\n * A condition: named branches tested in order, top to bottom; the first whose expression holds\n * runs, and `else` (last, written `true`) runs when none does. Wire each as `x..to(block)`.\n * @example condition(\u0027Route\u0027, { big: js`${order.total} >= 500`, small: js`${order.total} < 50`, else: true })\n */\nexport declare function condition>(\n name: string,\n branches: B & ConditionBranches,\n meta?: BlockMeta\n): Block> & Branches>\n\n/** A router: named routes described for the model. */\nexport declare function router>(\n name: string,\n params: SpecialParams<\u0027router\u0027> & { routes: R },\n meta?: BlockMeta\n): Block> & Branches>\n\n/** A function block. `code` is inline (`` js`...` ``) or a code file (`codeFile(\u0027./functions/x.js\u0027)`). */\nexport declare function fn(\n name: string,\n params: SpecialParams<\u0027fn\u0027> & { code: Template | CodeFileRef | string },\n meta?: BlockMeta\n): Block, SpecialErrorOutputs<\u0027fn\u0027>>\n\n/**\n * The inputs of a child workflow by key, each checked against the input its start block\n * declares when `workspace.d.ts` knows the workflow; loose JSON otherwise.\n */\nexport type WorkflowInputMapping = K extends keyof WorkspaceWorkflows\n ? WorkspaceWorkflows[K] extends { inputs: infer I }\n ? { [N in keyof I]?: FieldValue }\n : InputMapping\n : InputMapping\n\n/**\n * Runs a child workflow. A `childWorkflow(\u0027key\u0027)` checks `inputMapping` against its inputs. Its\n * `result` is the child\u0027s output: its first response block\u0027s `{ data, status, headers }` (a body\n * field is `result.data.field`), else the output of the last block it ran.\n */\nexport declare function runWorkflow(\n name: string,\n params: Omit, \u0027workflowId\u0027 | \u0027inputMapping\u0027> & {\n workflowId: WorkflowRef | Exclude[\u0027workflowId\u0027], WorkflowRef>\n inputMapping?: WorkflowInputMapping\n },\n meta?: BlockMeta\n): Block>\n\n/**\n * Pauses for a person; the form in `inputFormat` types `submission`. A resumed block also holds\n * each form field at its top level (the runtime copies the submission up, over any output of the\n * same name), so `approval.approved` and `approval.submission.approved` both read it.\n */\nexport declare function human>(\n name: string,\n params: SpecialParams<\u0027human\u0027> & { inputFormat?: F },\n meta?: BlockMeta\n): Block<\n Omit, \u0027submission\u0027 | keyof F> & {\n submission: InputFieldsOutput\n } & InputFieldsOutput\n>\n\n/**\n * A response\u0027s body, status and headers: the editor\u0027s JSON mode, `body` standing for\n * `{ dataMode: \u0027json\u0027, data }`. An object or array `body` is JSON whose references keep their\n * types; a template or reference is the body text as written.\n */\nexport interface ResponseBody {\n body: JsonWithRefs\n /** HTTP status; 200 when omitted. A template or reference must produce a number. */\n status?: number | RefTo | Template | EnvRef\n /** Response headers by name. */\n headers?: Record>\n}\n\n/**\n * Ends the workflow with an API response: `response(\u0027Reply\u0027, { body: { ok: true }, status: 201 })`\n * (`body` is short for `dataMode: \u0027json\u0027` with `data`), or the block\u0027s own params (`dataMode`,\n * `builderData`, ...) when the body is built field by field.\n */\nexport declare function response(\n name: string,\n params: ResponseBody,\n meta?: BlockMeta\n): Block>\nexport declare function response(\n name: string,\n params: SpecialParams<\u0027response\u0027>,\n meta?: BlockMeta\n): Block>\n\n/** Assigns workflow variables. */\nexport declare function setVariables(\n name: string,\n params: SpecialParams<\u0027setVariables\u0027>,\n meta?: BlockMeta\n): Block>\n\ndeclare const ANNOTATION: unique symbol\n\n/** A canvas note: no edges, no outputs. */\nexport interface Annotation {\n readonly [ANNOTATION]: true\n}\nexport declare function note(\n name: string,\n params: SpecialParams<\u0027note\u0027>,\n meta?: BlockMeta\n): Annotation\n\n// Structured param shapes\n\n/** Type names an input-format field may declare. */\nexport type InputFieldType = \u0027string\u0027 | \u0027number\u0027 | \u0027boolean\u0027 | \u0027object\u0027 | \u0027array\u0027 | \u0027file[]\u0027\n\n/** A structured input field: its type plus a default value, description or required flag. */\nexport interface InputFieldSpec {\n type: InputFieldType\n value?: JsonWithRefs\n description?: string\n required?: boolean\n}\n\n/** `input-format` fields by name: `{ subject: \u0027string\u0027, amount: { type: \u0027number\u0027, value: 0 } }`. */\nexport type InputFields = Record\n\ntype InputFieldValue = T extends \u0027string\u0027\n ? string\n : T extends \u0027number\u0027\n ? number\n : T extends \u0027boolean\u0027\n ? boolean\n : T extends \u0027array\u0027\n ? Json[]\n : T extends \u0027file[]\u0027\n ? SimFile[]\n : Json\n\n/** The outputs an `input-format` declares. */\nexport type InputFieldsOutput = {\n [K in keyof F]: F[K] extends { type: infer T } ? InputFieldValue : InputFieldValue\n}\n\n/**\n * One `response-format` field as the editor\u0027s builder stores it. An `object` or `array` field\u0027s\n * `value` may hold nested fields. A response is usually written with `body` instead.\n */\nexport interface ResponseField {\n id?: string\n name: string\n type: string\n value?: JsonWithRefs\n collapsed?: boolean\n}\n\n/** `response-format` fields: `[{ name: \u0027ok\u0027, type: \u0027boolean\u0027, value: true }]`. */\nexport type ResponseFields = ResponseField[]\n\n/** An agent message. */\nexport interface Message {\n role: \u0027system\u0027 | \u0027user\u0027 | \u0027assistant\u0027\n content: Value\n}\n\n/** One `variables-input` assignment, with any other stored keys kept. */\nexport interface VariableAssignment {\n variableId: VarRef\n value?: JsonWithRefs\n [key: string]: JsonWithRefs | VarRef | undefined\n}\n\n/** Child workflow inputs by name (`input-mapping`, `workflow-input-mapper`). */\nexport type InputMapping = Record\n\n/** An operator a table filter condition or builder rule can use. */\nexport type FilterOperator = LiteralUnion<\n | \u0027eq\u0027\n | \u0027ne\u0027\n | \u0027gt\u0027\n | \u0027gte\u0027\n | \u0027lt\u0027\n | \u0027lte\u0027\n | \u0027in\u0027\n | \u0027nin\u0027\n | \u0027like\u0027\n | \u0027ilike\u0027\n | \u0027nlike\u0027\n | \u0027nilike\u0027\n | \u0027contains\u0027\n | \u0027ncontains\u0027\n | \u0027startsWith\u0027\n | \u0027endsWith\u0027\n | \u0027isNull\u0027\n | \u0027isNotNull\u0027\n | \u0027isEmpty\u0027\n | \u0027isNotEmpty\u0027\n>\n\n/** One row of the editor\u0027s filter builder, as it stores it. */\nexport interface FilterRule {\n id?: string\n /** How this row joins the rows before it; `and` when omitted. */\n logicalOperator?: \u0027and\u0027 | \u0027or\u0027\n column: string\n operator: FilterOperator\n value: Value\n collapsed?: boolean\n}\n\n/** A filter-builder value: the editor\u0027s rows, `[{ column: \u0027status\u0027, operator: \u0027eq\u0027, value: \u0027new\u0027 }]`. */\nexport type Filter = FilterRule[]\n\n/** One table filter condition: `{ field: \u0027status\u0027, op: \u0027eq\u0027, value: \u0027new\u0027 }`. */\nexport interface TableCondition {\n field: string\n op: FilterOperator\n value?: JsonWithRefs\n}\n\n/**\n * A table predicate: a condition, or an `all` (and) / `any` (or) group of predicates. The\n * `{ status: { $eq: \u0027new\u0027 } }` operator-object grammar is not one: the runtime refuses it.\n */\nexport type TablePredicate = TableCondition | { all: TablePredicate[] } | { any: TablePredicate[] }\n\n/** A table sort by column: `{ createdAt: \u0027desc\u0027 }`. */\nexport type Sort =\n | Record\n | Array<{ column: string; direction: \u0027asc\u0027 | \u0027desc\u0027 }>\n\n/** One knowledge tag filter. */\nexport interface TagFilter {\n tagName: string\n tagValue: Value\n [key: string]: JsonWithRefs\n}\n\n/** One document tag. */\nexport interface DocumentTag {\n tagName: string\n value: Value\n [key: string]: JsonWithRefs\n}\n\n/** One `eval-input` metric. */\nexport interface EvalMetric {\n name: string\n description?: string\n range?: { min: number; max: number }\n [key: string]: JsonWithRefs | undefined\n}\n\n/** One `model-fallback-list` entry. */\nexport interface ModelFallback {\n model: LiteralUnion\n [key: string]: JsonWithRefs\n}\n\n/**\n * Model ids, generated into `models.d.ts` (which adds one member per model). Kept apart from the\n * block files so a model-list change touches one file.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface ModelIds {}\nexport type Model = Extract\n\n/** A JSON Schema `responseFormat`, or `{ name, strict, schema }` around one. */\nexport type ResponseFormat = JsonWithRefs\n\ntype Depth = [never, 0, 1, 2, 3, 4]\n\ntype FromSchema = [D] extends [never]\n ? Json\n : S extends { enum: readonly (infer E)[] }\n ? E\n : S extends { type: \u0027object\u0027; properties: infer P }\n ? { [K in keyof P]: FromSchema }\n : S extends { type: \u0027array\u0027; items: infer I }\n ? FromSchema[]\n : S extends { type: \u0027string\u0027 }\n ? string\n : S extends { type: \u0027number\u0027 | \u0027integer\u0027 }\n ? number\n : S extends { type: \u0027boolean\u0027 }\n ? boolean\n : Json\n\n/**\n * The outputs a literal `responseFormat` adds, read from its JSON Schema with recursion capped at\n * depth 4. A template or reference adds untyped JSON.\n */\nexport type ResponseFormatOutput = [RF] extends [undefined]\n ? unknown\n : RF extends { schema: infer S }\n ? FromSchema\n : RF extends { type: \u0027object\u0027; properties: object }\n ? FromSchema\n : { [key: string]: Json }\n" diff --git a/packages/workflow-sdk/src/codegen/map-subblock.ts b/packages/workflow-sdk/src/codegen/map-subblock.ts index 75d710911d4..c84f9063ece 100644 --- a/packages/workflow-sdk/src/codegen/map-subblock.ts +++ b/packages/workflow-sdk/src/codegen/map-subblock.ts @@ -146,7 +146,8 @@ export function mapSubBlock(subBlock: CatalogSubBlock): MappedType | null { case 'workflow-selector': return { type: 'WorkflowRef', doc } case 'file-upload': { - const uploaded = subBlock.multiple ? 'UploadedFile | UploadedFile[]' : 'UploadedFile' + const one = 'FileRef | UploadedFile' + const uploaded = subBlock.multiple ? `${one} | Array<${one}>` : one return { type: `${uploaded} | RefTo`, doc } } case 'tool-input': diff --git a/packages/workflow-sdk/src/codegen/workspace-declarations.test.ts b/packages/workflow-sdk/src/codegen/workspace-declarations.test.ts index 71e9d277e25..7207535f11e 100644 --- a/packages/workflow-sdk/src/codegen/workspace-declarations.test.ts +++ b/packages/workflow-sdk/src/codegen/workspace-declarations.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest' -import { typecheckSdkDirectory } from '../../test/typecheck-project' +import { loadFixtureCatalog, typecheckSdkDirectory } from '../../test/typecheck-project' +import { generateSdkTypes } from './generate' import { generateWorkspaceTypes } from './workspace' /** The modules a workspace directory declares, as the CLI lays it out. */ @@ -79,6 +80,31 @@ export default defineKnowledgeBase({ expect(output).not.toContain('knowledge/good/knowledge.ts') }, 120_000) + it('type a workspace file by its path where a file-upload field takes one', () => { + const slack = generateSdkTypes(loadFixtureCatalog()).find( + (generated) => generated.path === 'blocks/slack_v2.d.ts' + ) + if (!slack) throw new Error('The fixture catalog has no slack_v2 block') + const output = typecheckSdkDirectory( + { + '.sim/sdk/workspace.d.ts': generateWorkspaceTypes({ files: ['moved/a.txt'] }).text, + '.sim/sdk/blocks/slack_v2.d.ts': slack.text, + 'workflows/w/check.ts': `import { credential, file, slack } from '@sim/workflow-sdk' +export const send = slack.sendMessage('Send', { + credential: credential('slack'), + channel: 'C0SUPPORT', + text: 'report', + files: [file('moved/a.txt')], +}) +export const unknown = file('moved/b.txt') +`, + }, + ['workflows/*/*.ts'] + ) + expect(output).toContain(`'"moved/b.txt"' is not assignable`) + expect(output.split('\n').filter((line) => line.includes('error TS'))).toHaveLength(1) + }, 120_000) + it('type MCP tool names per server, any name for a server it could not list', () => { const output = typecheckSdkDirectory( { diff --git a/packages/workflow-sdk/src/codegen/workspace.ts b/packages/workflow-sdk/src/codegen/workspace.ts index 2a1582e8b5e..07f14f15cc9 100644 --- a/packages/workflow-sdk/src/codegen/workspace.ts +++ b/packages/workflow-sdk/src/codegen/workspace.ts @@ -1,8 +1,8 @@ /** * `generateWorkspaceTypes(manifest)`: one `workspace.d.ts` that narrows the SDK to a workspace's * resources. It fills the `Workspace*` interfaces `core.d.ts` declares, so `table('leads')` types - * its rows, a misspelled `knowledgeBase('dosc')`, `skill('tirage')`, `mcp('github').tool('crate_issue')` - * or `env.STRIPE_KYE` is an error, and so on. + * its rows, a misspelled `knowledgeBase('dosc')`, `skill('tirage')`, `mcp('github').tool('crate_issue')`, + * `file('docs/plna.md')` or `env.STRIPE_KYE` is an error, and so on. * Written by `sim workflows source get --dir` from the workspace source resources; without it * every key is a plain string. */ @@ -84,6 +84,8 @@ export interface WorkspaceManifest { * the stored ones; one not stored yet takes any tool name until it is applied and read again. */ mcpServerDeclarations?: string[] + /** Workspace files by their folder path and name (`docs/report.pdf`), for `file('')`. */ + files?: string[] /** Environment variable names (never values). */ env?: string[] } @@ -248,6 +250,7 @@ export const generateWorkspaceTypes: GenerateWorkspaceTypesFn = (manifest) => { ...interfaceBlock('WorkspaceSkills', keyMembers(manifest.skills)), ...interfaceBlock('WorkspaceCustomTools', keyMembers(manifest.customTools)), ...interfaceBlock('WorkspaceMcpServers', mcpServers), + ...interfaceBlock('WorkspaceFiles', keyMembers(manifest.files)), ...interfaceBlock( 'WorkspaceEnv', env, diff --git a/packages/workflow-sdk/src/core.d.ts b/packages/workflow-sdk/src/core.d.ts index e78c54bb623..577a19ded5b 100644 --- a/packages/workflow-sdk/src/core.d.ts +++ b/packages/workflow-sdk/src/core.d.ts @@ -190,6 +190,8 @@ export interface WorkspaceSkills {} export interface WorkspaceCustomTools {} // biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment export interface WorkspaceMcpServers {} +// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment +export interface WorkspaceFiles {} type KeyOf = keyof M extends never ? string : Extract @@ -200,6 +202,8 @@ export type WorkflowKey = KeyOf export type SkillKey = KeyOf export type CustomToolKey = KeyOf export type McpServerKey = KeyOf +/** A workspace file's folder path and name (`docs/report.pdf`), as `files/` in a workspace directory holds it. */ +export type FileKey = KeyOf /** * The tool names of MCP server `K`, as `workspace.d.ts` records them from the server's last * listing; any name for a server it could not list or does not know. @@ -310,20 +314,25 @@ export declare function skill(key: K): SkillRef export type FolderRef = ResourceRef<'file-folder'> export declare function folder(key: string): FolderRef -/** A workspace file: `file('contracts/acme.pdf')`. File block operations live on `file.*`. */ -export type FileRef = ResourceRef<'file'> -export declare function file(path: string): FileRef +/** + * A workspace file by its folder path and name: `file('contracts/acme.pdf')`, written as a + * file-upload field's value (or one item of a multi-file field's list); the same source names the + * file at that path in whichever workspace it is applied to. File block operations live on + * `file.*`. + */ +export type FileRef = ResourceRef<'file', Key> +export declare function file(path: K): FileRef /** - * A file a file-upload field holds, as the editor stores it: one uploaded in place, or a workspace - * file chosen by `key` (written `file('path')` when the workspace resolves it). + * A file a file-upload field holds, as the editor stores it, for a file that is not a workspace + * file (one uploaded in place); a workspace file is written `file('/')`. */ export interface UploadedFile { name: string path: string size?: number type?: string - key?: string | FileRef + key?: string id?: string folderPath?: string } diff --git a/packages/workspace-code/DESIGN.md b/packages/workspace-code/DESIGN.md index 2e490ca2123..6ae18748a57 100644 --- a/packages/workspace-code/DESIGN.md +++ b/packages/workspace-code/DESIGN.md @@ -77,9 +77,10 @@ deleted. A workflow folder is the exception: its `.sim/base.json` names the work folder moves the workflow's key (`renamedFrom`, an update with `fields: ['key']` even when nothing else changed), and its deployment's with it. The plan refuses the rename while a deployment file or a declared workflow still names the old key (`E_WORKFLOW_RENAMED_IN_USE`), and the workflows it -writes print the new key. A workflow still names a workspace file by its resource key (`file('report-pdf')`), not -its path: a file an apply creates claims the key a get would first allocate it, so a workflow of -the same apply resolves it. +writes print the new key. A workspace file has no key row: a workflow names it by its path under +`files/` (`file('docs/report.pdf')`), the key the directory gives it, so a workflow of the same +apply resolves a file that apply creates, and a promotion resolves the target's file at the same +path. A table's column keys persist with the table too: every table write records each declared column whose key is not its name in `metadata.sourceColumnKeys` (column id → key), and a read prints a diff --git a/packages/workspace-code/src/specs.ts b/packages/workspace-code/src/specs.ts index c2f0d9f3763..a2f977d57c8 100644 --- a/packages/workspace-code/src/specs.ts +++ b/packages/workspace-code/src/specs.ts @@ -42,6 +42,7 @@ interface WorkspaceKindSpec { | 'skills' | 'mcpServerDeclarations' | 'workflows' + | 'files' | null /** The kind's entry in the directory's agent guide: its files, and how a workflow names one. */ guide: string @@ -110,8 +111,8 @@ export const WORKSPACE_KIND_SPECS: { readonly [K in WorkspaceKind]: WorkspaceKin keyShape: 'path', resourceKind: null, typeChecked: [], - manifestKey: null, - guide: `\`${KIND_DIRS.file}/\`: every file is one workspace file at that folder path; no declaration.`, + manifestKey: 'files', + guide: `\`${KIND_DIRS.file}/\`: every file is one workspace file at that folder path; no declaration. A workflow: \`file('')\` (the path under \`${KIND_DIRS.file}/\`), as a file-upload field's value.`, }, workflow: { noun: 'workflow', From 2358fd4d7127df8067acf2b4cb070d7eaf4d1514 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 22:30:23 -0800 Subject: [PATCH 2/5] fix(workflow-code): resolve file() paths as written and keep them from withheld callers --- .../application/read-source-resources.ts | 5 +- .../source-pipeline/evaluate/resolve.ts | 16 +++- apps/sim/lib/workflows/code/resources.ts | 5 +- .../application/files.integration.ts | 81 ++++++++++++++----- 4 files changed, 83 insertions(+), 24 deletions(-) diff --git a/apps/sim/lib/workflows/application/read-source-resources.ts b/apps/sim/lib/workflows/application/read-source-resources.ts index 0634a28123c..93d10401382 100644 --- a/apps/sim/lib/workflows/application/read-source-resources.ts +++ b/apps/sim/lib/workflows/application/read-source-resources.ts @@ -237,8 +237,9 @@ function capped(rows: T[]): { rows: T[]; truncated: boolean } { * `visibleSections`). The CLI writes it as * `workspace.d.ts`, so `table('tickets')`, `skill('triage')` and `env.X` type-check. * - * Every listed resource gets its key here (`resolveKeys` allocates one for a resource no source - * has named yet), so a key an agent reads from the manifest resolves on apply. That allocation is + * Every listed resource but a file (named by its path) gets its key here (`resolveKeys` allocates + * one for a resource no source has named yet), so a key an agent reads from the manifest resolves + * on apply. That allocation is * idempotent identity bookkeeping, not a change to any resource, which is why a read-role caller * (Copilot included) may cause it. Not audited, like the other catalog reads. */ diff --git a/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts b/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts index b80a4466f88..918ce67f183 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts @@ -18,6 +18,7 @@ import { } from '@sim/workflow-code' import { diagnostic } from '@sim/workflow-code/diagnostics' import { and, inArray, ne } from 'drizzle-orm' +import { isWorkspaceCapabilityWithheld } from '@/lib/permission-groups/capability-assertions' import { resolvePermissionGroupConfig } from '@/lib/permission-groups/config-scope.server' import type { WorkflowSourceDiagnostic } from '@/lib/workflows/application/source-error' import { createLocator, hasErrors } from '@/lib/workflows/application/source-locate' @@ -266,9 +267,22 @@ export async function resolveSubmission( let materialized = materializeWith(lock) if (materialized.diagnostics.some((d) => d.code === 'E_MAT_UNKNOWN_RESOURCE')) { // Only on a miss: list the keys the source could have named, for the finding's did-you-mean. - const missingKinds = compiledKeys + let missingKinds = compiledKeys .filter(({ kind, key }) => resources.toId(kind, key) === null) .map(({ kind }) => kind) + // As in the source resources manifest, file paths stay unlisted when the caller's group + // withholds Files. + if ( + missingKinds.includes('file') && + (await isWorkspaceCapabilityWithheld( + scope.subjectUserId, + scope.workspaceId, + 'files.use', + scope.workspaceOrganizationId + )) + ) { + missingKinds = missingKinds.filter((kind) => kind !== 'file') + } if (missingKinds.length > 0) { const available = await loadAvailableResourceKeys( scope.workspaceId, diff --git a/apps/sim/lib/workflows/code/resources.ts b/apps/sim/lib/workflows/code/resources.ts index e7c3c21cf09..41fb7216680 100644 --- a/apps/sim/lib/workflows/code/resources.ts +++ b/apps/sim/lib/workflows/code/resources.ts @@ -11,6 +11,7 @@ import { queryWorkspaceFiles, type WorkspaceFileRecord, } from '@/lib/uploads/contexts/workspace/file-manager' +import { encodeVfsPathSegments } from '@/lib/vfs/path' import { isBuiltinSkillId } from '@/lib/workflows/skills/builtin-skills' import { workspaceFileSourcePath } from '@/lib/workspace-files/folder-display-path' import { checkWorkspaceAccess, type WorkspaceAccess } from '@/lib/workspaces/permissions/utils' @@ -148,10 +149,12 @@ async function loadReferencedFiles( ): Promise> { const byPath = new Map() if (stored.length === 0 && paths.length === 0) return byPath + // A reference is read as a VFS path (`files/` prefix stripped, segments percent-decoded), so + // each path is spelled in that form to resolve its folder and file names exactly as written. const { files } = await lookupActiveWorkspaceFiles(workspaceId, { ids: stored, keys: stored, - references: paths, + references: paths.map((path) => `files/${encodeVfsPathSegments(path.split('/'))}`), }) for (const file of files) { const path = workspaceFileSourcePath(file) diff --git a/apps/sim/lib/workspace-source/application/files.integration.ts b/apps/sim/lib/workspace-source/application/files.integration.ts index 4343bbc3145..abdd1f4e91f 100644 --- a/apps/sim/lib/workspace-source/application/files.integration.ts +++ b/apps/sim/lib/workspace-source/application/files.integration.ts @@ -231,6 +231,30 @@ export default workflow('Path reader', {}, () => { const workflowsOnly = sourceRunner(['workflow'], owner) +/** Puts the `blocked` member in a permission group that withholds Files in `workspaceId`. */ +async function withholdFilesFromBlocked(workspaceId: string) { + const groupId = generateId() + await db.insert(permissionGroup).values({ + id: groupId, + organizationId, + name: `No files ${groupId}`, + createdBy: ownerId, + config: { hideFilesTab: true }, + }) + await db.insert(permissionGroupWorkspace).values({ + id: generateId(), + permissionGroupId: groupId, + workspaceId, + organizationId, + }) + await db.insert(permissionGroupMember).values({ + id: generateId(), + permissionGroupId: groupId, + organizationId, + userId: blockedId, + }) +} + function fileId(base: WorkspaceBaseV1, key: string): string { const id = base.resources[`file:${key}`]?.id if (!id) throw new Error(`The base has no file ${key}`) @@ -415,26 +439,7 @@ describe('workspace source files', () => { 'a member whose permission group withholds Files is refused before anything is written', async () => { const workspaceId = await newWorkspace() - const groupId = generateId() - await db.insert(permissionGroup).values({ - id: groupId, - organizationId, - name: `No files ${groupId}`, - createdBy: ownerId, - config: { hideFilesTab: true }, - }) - await db.insert(permissionGroupWorkspace).values({ - id: generateId(), - permissionGroupId: groupId, - workspaceId, - organizationId, - }) - await db.insert(permissionGroupMember).values({ - id: generateId(), - permissionGroupId: groupId, - organizationId, - userId: blockedId, - }) + await withholdFilesFromBlocked(workspaceId) const refused = await refusal(apply(workspaceId, STARTER, { principal: blocked })) @@ -1061,6 +1066,42 @@ export default workflow('Reader', {}, () => { } ) + check( + 'a file path resolves as written, percent signs and a top-level files folder included', + async () => { + const workspaceId = await newWorkspace() + const stored = await uploadInUi(workspaceId, 'files', 'a%20b.txt', 'literal name') + const applied = await workflowsOnly.apply(workspaceId, { + files: { 'workflows/path-reader/workflow.ts': fileReader("file('files/a%20b.txt')") }, + }) + expect(applied.failed).toBeUndefined() + const workflowId = applied.base.resources['workflow:path-reader']?.id + if (!workflowId) throw new Error('The apply wrote no workflow') + expect(await storedFileInput(workflowId)).toMatchObject({ id: stored.id, key: stored.key }) + } + ) + + check( + 'an unknown file path lists no workspace files to a member whose permission group withholds Files', + async () => { + const workspaceId = await newWorkspace() + await uploadInUi(workspaceId, 'moved', 'a.txt', 'hidden from the member') + await withholdFilesFromBlocked(workspaceId) + + const unknown = await refusal( + workflowsOnly.apply(workspaceId, { + files: { 'workflows/lost/workflow.ts': fileReader("file('nowhere/a.txt')") }, + principal: blocked, + }) + ) + const missing = unknown.diagnostics.find( + (finding) => finding.code === 'E_MAT_UNKNOWN_RESOURCE' + ) + expect(missing?.message).toContain('nowhere/a.txt') + expect(JSON.stringify(unknown.diagnostics)).not.toContain('moved/a.txt') + } + ) + check( 'a declared file the server can no longer hand to source since the get refuses only a directory that changes it', async () => { From 21372f023c635cf0ff763f643dcc28284765b3ee Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 22:36:11 -0800 Subject: [PATCH 3/5] fix(workflow-code): report a malformed file() path as an unknown file --- apps/sim/lib/workflows/code/resources.ts | 23 +++++++++++++++---- .../application/files.integration.ts | 6 +++++ 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/apps/sim/lib/workflows/code/resources.ts b/apps/sim/lib/workflows/code/resources.ts index 41fb7216680..2b890effe98 100644 --- a/apps/sim/lib/workflows/code/resources.ts +++ b/apps/sim/lib/workflows/code/resources.ts @@ -11,7 +11,7 @@ import { queryWorkspaceFiles, type WorkspaceFileRecord, } from '@/lib/uploads/contexts/workspace/file-manager' -import { encodeVfsPathSegments } from '@/lib/vfs/path' +import { encodeVfsPathSegments, VfsPathError } from '@/lib/vfs/path' import { isBuiltinSkillId } from '@/lib/workflows/skills/builtin-skills' import { workspaceFileSourcePath } from '@/lib/workspace-files/folder-display-path' import { checkWorkspaceAccess, type WorkspaceAccess } from '@/lib/workspaces/permissions/utils' @@ -138,6 +138,20 @@ async function loadSkillNames(workspaceId: string, ids: string[]): Promise refs.flatMap((ref) => (ref.kind === 'credential' ? [ref.id] : [])) +/** + * `path` in the VFS form a file reference is read in (`files/` prefix stripped, segments + * percent-decoded), so its folder and file names resolve exactly as written; `null` for a path + * with an empty or dot segment, which names no file. + */ +function vfsReference(path: string): string | null { + try { + return `files/${encodeVfsPathSegments(path.split('/'))}` + } catch (error) { + if (error instanceof VfsPathError) return null + throw error + } +} + /** * The live workspace files `references` name: by the id or storage key a stored file-upload * object carries (`stored`) and by source path (`paths`), each file under its source path. @@ -149,12 +163,13 @@ async function loadReferencedFiles( ): Promise> { const byPath = new Map() if (stored.length === 0 && paths.length === 0) return byPath - // A reference is read as a VFS path (`files/` prefix stripped, segments percent-decoded), so - // each path is spelled in that form to resolve its folder and file names exactly as written. const { files } = await lookupActiveWorkspaceFiles(workspaceId, { ids: stored, keys: stored, - references: paths.map((path) => `files/${encodeVfsPathSegments(path.split('/'))}`), + references: paths.flatMap((path) => { + const reference = vfsReference(path) + return reference === null ? [] : [reference] + }), }) for (const file of files) { const path = workspaceFileSourcePath(file) diff --git a/apps/sim/lib/workspace-source/application/files.integration.ts b/apps/sim/lib/workspace-source/application/files.integration.ts index abdd1f4e91f..d57e04d8fe5 100644 --- a/apps/sim/lib/workspace-source/application/files.integration.ts +++ b/apps/sim/lib/workspace-source/application/files.integration.ts @@ -1052,6 +1052,12 @@ export default workflow('Reader', {}, () => { ) expect(missing?.message).toContain('nowhere/a.txt') expect(missing?.hint).toContain('moved/a.txt') + const malformed = await refusal( + workflowsOnly.apply(workspaceId, { + files: { 'workflows/lost/workflow.ts': fileReader("file('moved//a.txt')") }, + }) + ) + expect(codes(malformed.diagnostics)).toContain('E_MAT_UNKNOWN_RESOURCE') const target = await newWorkspace() const own = await uploadInUi(target, 'moved', 'a.txt', 'second workspace') From ea5282c6dd20ee11b8b399fae080243b00e8a7d2 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 23:48:36 -0800 Subject: [PATCH 4/5] fix(workflow-code): gate file() paths on files.use, match names as written, and report truncation exactly - a path the stored workflow does not already hold resolves only for a caller whose group allows Files; any other caller gets the unknown-file finding a missing path gets - resolve file() paths by exact name and folder path instead of the VFS reference parser, so files named content or meta.json inside a folder resolve - read file pages until the manifest cap is filled so files no path names cannot hide a truncated list - document the quoted file('docs/report.pdf') form in the manifest description --- apps/docs/openapi-v2-workflows.json | 2 +- .../lib/api/contracts/v2/source-resources.ts | 2 +- .../contexts/workspace/file-manager.ts | 18 +++-- .../read-source-resources.integration.ts | 33 ++++++++ .../application/read-source-resources.ts | 9 ++- .../source-pipeline/evaluate/resolve.ts | 24 +++--- apps/sim/lib/workflows/code/resources.ts | 61 +++++++------- .../application/files.integration.ts | 79 ++++++++++++++++++- 8 files changed, 172 insertions(+), 56 deletions(-) diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index f31a6dcd6be..5dc0b2eb411 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -23931,7 +23931,7 @@ "items": { "type": "string" }, - "description": "Workspace files by folder path and name (`docs/report.pdf`), as `file(path)` names them, oldest upload first." + "description": "Workspace files by folder path and name (`docs/report.pdf`), each named in source as `file('docs/report.pdf')`, oldest upload first." }, "env": { "type": "array", diff --git a/apps/sim/lib/api/contracts/v2/source-resources.ts b/apps/sim/lib/api/contracts/v2/source-resources.ts index 6d1f79072ba..375727c2e11 100644 --- a/apps/sim/lib/api/contracts/v2/source-resources.ts +++ b/apps/sim/lib/api/contracts/v2/source-resources.ts @@ -111,7 +111,7 @@ const sourceResourcesSchema = z files: z .array(z.string()) .describe( - 'Workspace files by folder path and name (`docs/report.pdf`), as `file(path)` names them, oldest upload first.' + "Workspace files by folder path and name (`docs/report.pdf`), each named in source as `file('docs/report.pdf')`, oldest upload first." ), env: z .array(z.string()) diff --git a/apps/sim/lib/uploads/contexts/workspace/file-manager.ts b/apps/sim/lib/uploads/contexts/workspace/file-manager.ts index 044f04498e8..9b15fe62d04 100644 --- a/apps/sim/lib/uploads/contexts/workspace/file-manager.ts +++ b/apps/sim/lib/uploads/contexts/workspace/file-manager.ts @@ -2486,23 +2486,30 @@ async function listWorkspaceFileCandidates( } /** - * Live workspace files by id, by storage key, and by reference (resolved as + * Live workspace files by id, by storage key, by exact name in any folder (`names`, taken as + * written rather than as a VFS path), and by reference (resolved as * {@link findListedWorkspaceFiles} resolves it), from one read and one folder-path hydration. * `files` holds each match once, oldest upload first. Another workspace's ids and keys, deleted * files, chat uploads, and owned files never match. */ export async function lookupActiveWorkspaceFiles( workspaceId: string, - lookup: { ids: readonly string[]; keys: readonly string[]; references: readonly string[] } + lookup: { + ids: readonly string[] + keys: readonly string[] + names?: readonly string[] + references: readonly string[] + } ): Promise<{ files: WorkspaceFileRecord[]; references: Map }> { - if (lookup.ids.length + lookup.keys.length + lookup.references.length === 0) { + const names = new Set(lookup.names) + if (lookup.ids.length + lookup.keys.length + names.size + lookup.references.length === 0) { return { files: [], references: new Map() } } const byReference = referenceCandidates(lookup.references) const candidates = await listWorkspaceFileCandidates(workspaceId, { ids: [...lookup.ids, ...byReference.ids], keys: lookup.keys, - leafNames: byReference.leafNames, + leafNames: [...byReference.leafNames, ...[...names].map(normalizeDisplaySegment)], }) const references = resolveListedReferences(candidates, lookup.references) const ids = new Set(lookup.ids) @@ -2510,7 +2517,8 @@ export async function lookupActiveWorkspaceFiles( const resolved = new Set([...references.values()].map((file) => file?.id)) return { files: candidates.filter( - (file) => ids.has(file.id) || keys.has(file.key) || resolved.has(file.id) + (file) => + ids.has(file.id) || keys.has(file.key) || names.has(file.name) || resolved.has(file.id) ), references, } diff --git a/apps/sim/lib/workflows/application/read-source-resources.integration.ts b/apps/sim/lib/workflows/application/read-source-resources.integration.ts index 6cf11046140..04f606946d9 100644 --- a/apps/sim/lib/workflows/application/read-source-resources.integration.ts +++ b/apps/sim/lib/workflows/application/read-source-resources.integration.ts @@ -35,6 +35,7 @@ import { featureFlagsMock, featureFlagsMockFns } from '@sim/testing/mocks/featur import { generateId } from '@sim/utils/id' import { eq, inArray } from 'drizzle-orm' import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' +import { MAX_MANIFEST_RESOURCES_PER_KIND } from '@/lib/api/contracts/v2/source-resources' import { readSourceResources } from '@/lib/workflows/application/read-source-resources' vi.mock('@/lib/core/config/feature-flags', () => featureFlagsMock) @@ -528,4 +529,36 @@ describe('source resources manifest', () => { expect(manifest.env).toEqual([]) }) }) + + it('marks the files section truncated when a file no path names sits among the first page', async () => { + const before = Date.now() - 60 * 60 * 1000 + const rows = Array.from({ length: MAX_MANIFEST_RESOURCES_PER_KIND + 1 }, (_, index) => ({ + id: generateId(), + key: `workspace/${workspaceId}/bulk-${index}`, + userId: adminId, + workspaceId, + context: 'workspace', + originalName: index === 0 ? 'a/b.txt' : `bulk-${index}.txt`, + contentType: 'text/plain', + sizeBytes: 1, + uploadedAt: new Date(before + index), + })) + await db.insert(workspaceFiles).values(rows) + try { + const manifest = await readSourceResources.execute({ + principal: session(adminId), + input: { workspaceId }, + }) + expect(manifest.files).toHaveLength(MAX_MANIFEST_RESOURCES_PER_KIND) + expect(manifest.files).not.toContain('plan.md') + expect(manifest.truncated).toBe(true) + } finally { + await db.delete(workspaceFiles).where( + inArray( + workspaceFiles.id, + rows.map((row) => row.id) + ) + ) + } + }) }) diff --git a/apps/sim/lib/workflows/application/read-source-resources.ts b/apps/sim/lib/workflows/application/read-source-resources.ts index 93d10401382..4439c08fd97 100644 --- a/apps/sim/lib/workflows/application/read-source-resources.ts +++ b/apps/sim/lib/workflows/application/read-source-resources.ts @@ -265,7 +265,7 @@ export const readSourceResources = defineAuthorizedWorkspaceUseCase({ skillRows, customToolRows, mcpServerRows, - filePaths, + files, env, ] = await Promise.all([ visible.tables @@ -326,7 +326,9 @@ export const readSourceResources = defineAuthorizedWorkspaceUseCase({ .orderBy(asc(mcpServers.createdAt), asc(mcpServers.id)) .limit(PAGE) : [], - visible.files ? loadWorkspaceFilePaths(workspaceId, PAGE) : [], + visible.files + ? loadWorkspaceFilePaths(workspaceId, MAX_MANIFEST_RESOURCES_PER_KIND) + : { paths: [], truncated: false }, visible.env ? loadEnvNames(workspaceId, userId, access) : [], ]) @@ -337,7 +339,6 @@ export const readSourceResources = defineAuthorizedWorkspaceUseCase({ const skills = capped(skillRows) const tools = capped(customToolRows) const servers = capped(mcpServerRows) - const files = capped(filePaths) const refs: ResourceIdRef[] = [ ...tables.rows.map((row) => ({ kind: 'table' as const, id: row.id })), @@ -387,7 +388,7 @@ export const readSourceResources = defineAuthorizedWorkspaceUseCase({ const names = mcpTools.get(server.id) return names ? { ...server, tools: names } : server }), - files: files.rows, + files: files.paths, env, truncated: [tables, kbs, credentials, workflows, skills, tools, servers, files].some( (section) => section.truncated diff --git a/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts b/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts index 918ce67f183..892c56d8cd0 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/evaluate/resolve.ts @@ -189,7 +189,19 @@ export async function resolveSubmission( collectResourceKeys(block, compiledKeys, span) } const storedResources = resources - const newKeys = compiledKeys.filter(({ kind, key }) => storedResources.toId(kind, key) === null) + let filesWithheld: Promise | undefined + // permission-group-enforced: files.use — a path the stored workflow does not hold names a file only for a caller the file list serves; for any other it names no file + const isFilesWithheld = () => + (filesWithheld ??= isWorkspaceCapabilityWithheld( + scope.subjectUserId, + scope.workspaceId, + 'files.use', + scope.workspaceOrganizationId + )) + let newKeys = compiledKeys.filter(({ kind, key }) => storedResources.toId(kind, key) === null) + if (newKeys.some(({ kind }) => kind === 'file') && (await isFilesWithheld())) { + newKeys = newKeys.filter(({ kind }) => kind !== 'file') + } if (newKeys.length > 0) { const extra = await loadResourceKeyResolver( scope.workspaceId, @@ -272,15 +284,7 @@ export async function resolveSubmission( .map(({ kind }) => kind) // As in the source resources manifest, file paths stay unlisted when the caller's group // withholds Files. - if ( - missingKinds.includes('file') && - (await isWorkspaceCapabilityWithheld( - scope.subjectUserId, - scope.workspaceId, - 'files.use', - scope.workspaceOrganizationId - )) - ) { + if (missingKinds.includes('file') && (await isFilesWithheld())) { missingKinds = missingKinds.filter((kind) => kind !== 'file') } if (missingKinds.length > 0) { diff --git a/apps/sim/lib/workflows/code/resources.ts b/apps/sim/lib/workflows/code/resources.ts index 2b890effe98..20634ee2154 100644 --- a/apps/sim/lib/workflows/code/resources.ts +++ b/apps/sim/lib/workflows/code/resources.ts @@ -8,10 +8,10 @@ import { credentialAccessClause, credentialMembershipJoin } from '@/lib/credenti import { getWorkspaceEnvironmentVariableNames } from '@/lib/environment/utils' import { lookupActiveWorkspaceFiles, + type QueryWorkspaceFilesOptions, queryWorkspaceFiles, type WorkspaceFileRecord, } from '@/lib/uploads/contexts/workspace/file-manager' -import { encodeVfsPathSegments, VfsPathError } from '@/lib/vfs/path' import { isBuiltinSkillId } from '@/lib/workflows/skills/builtin-skills' import { workspaceFileSourcePath } from '@/lib/workspace-files/folder-display-path' import { checkWorkspaceAccess, type WorkspaceAccess } from '@/lib/workspaces/permissions/utils' @@ -138,20 +138,6 @@ async function loadSkillNames(workspaceId: string, ids: string[]): Promise refs.flatMap((ref) => (ref.kind === 'credential' ? [ref.id] : [])) -/** - * `path` in the VFS form a file reference is read in (`files/` prefix stripped, segments - * percent-decoded), so its folder and file names resolve exactly as written; `null` for a path - * with an empty or dot segment, which names no file. - */ -function vfsReference(path: string): string | null { - try { - return `files/${encodeVfsPathSegments(path.split('/'))}` - } catch (error) { - if (error instanceof VfsPathError) return null - throw error - } -} - /** * The live workspace files `references` name: by the id or storage key a stored file-upload * object carries (`stored`) and by source path (`paths`), each file under its source path. @@ -163,13 +149,13 @@ async function loadReferencedFiles( ): Promise> { const byPath = new Map() if (stored.length === 0 && paths.length === 0) return byPath + // A path is matched as written, never read as a VFS path: `docs/content` names a file + // called `content`, not the folder `docs`. const { files } = await lookupActiveWorkspaceFiles(workspaceId, { ids: stored, keys: stored, - references: paths.flatMap((path) => { - const reference = vfsReference(path) - return reference === null ? [] : [reference] - }), + names: paths.flatMap((path) => path.split('/').at(-1) || []), + references: [], }) for (const file of files) { const path = workspaceFileSourcePath(file) @@ -289,7 +275,8 @@ export async function loadAvailableResourceKeys( const entries = await Promise.all( [...new Set(kinds)].map(async (kind) => { if (kind === 'file') { - return [kind, await loadWorkspaceFilePaths(workspaceId, AVAILABLE_KEYS_LIMIT)] as const + const { paths } = await loadWorkspaceFilePaths(workspaceId, AVAILABLE_KEYS_LIMIT) + return [kind, paths] as const } const rows = await listLiveKeys(workspaceId, kind, { limit: AVAILABLE_KEYS_LIMIT }) if (kind !== 'credential') return [kind, rows.map((row) => row.key)] as const @@ -306,22 +293,32 @@ export async function loadAvailableResourceKeys( /** * The source paths (`file('')`) of up to `limit` of the workspace's live files, oldest upload - * first; a file no slash-separated path names is left out. + * first, and whether more follow; a file no slash-separated path names is left out, so pages are + * read until `limit` paths are found or none remain. */ export async function loadWorkspaceFilePaths( workspaceId: string, limit: number -): Promise { - const { files } = await queryWorkspaceFiles(workspaceId, { - scope: 'active', - sortBy: 'uploadedAt', - sortOrder: 'asc', - limit, - }) - return files.flatMap((file) => { - const path = workspaceFileSourcePath(file) - return path === null ? [] : [path] - }) +): Promise<{ paths: string[]; truncated: boolean }> { + const paths: string[] = [] + let after: QueryWorkspaceFilesOptions['after'] + for (;;) { + const page = await queryWorkspaceFiles(workspaceId, { + scope: 'active', + sortBy: 'uploadedAt', + sortOrder: 'asc', + limit: limit + 1 - paths.length, + after, + }) + for (const file of page.files) { + const path = workspaceFileSourcePath(file) + if (path !== null) paths.push(path) + } + if (paths.length > limit || page.nextKeys === null) { + return { paths: paths.slice(0, limit), truncated: paths.length > limit } + } + after = page.nextKeys + } } /** `idsByKey` without the credential keys bound to a credential `userId` cannot see. */ diff --git a/apps/sim/lib/workspace-source/application/files.integration.ts b/apps/sim/lib/workspace-source/application/files.integration.ts index d57e04d8fe5..748a2ae8162 100644 --- a/apps/sim/lib/workspace-source/application/files.integration.ts +++ b/apps/sim/lib/workspace-source/application/files.integration.ts @@ -216,12 +216,12 @@ async function storedFileInput(workflowId: string): Promise { return block?.subBlocks.readFile?.value } -/** A workflow whose file block reads `reference` (source text, e.g. `file('a.txt')`). */ -function fileReader(reference: string): string { +/** A workflow named `name` whose file block reads `reference` (source text, e.g. `file('a.txt')`). */ +function fileReader(reference: string, name = 'Path reader'): string { return `// @sim-sdk 1 import { file, trigger, workflow } from '@sim/workflow-sdk' -export default workflow('Path reader', {}, () => { +export default workflow('${name}', {}, () => { const start = trigger.start('Start', { inputFormat: {} }) const read = file.read('Read', { readFileInput: ${reference}, folderIncludeSubfolders: true }) start.to(read) @@ -1108,6 +1108,79 @@ export default workflow('Reader', {}, () => { } ) + check( + 'a member whose permission group withholds Files names no file by path, as for a missing one, yet keeps the file a workflow holds', + async () => { + const workspaceId = await newWorkspace() + const held = await uploadInUi(workspaceId, 'moved', 'a.txt', 'held by the workflow') + await uploadInUi(workspaceId, 'moved', 'b.txt', 'withheld from the member') + const applied = await workflowsOnly.apply(workspaceId, { + files: { 'workflows/path-reader/workflow.ts': fileReader("file('moved/a.txt')") }, + }) + if (applied.failed) throw new Error('The owner could not name the file') + const workflowId = applied.base.resources['workflow:path-reader']?.id + if (!workflowId) throw new Error('The apply wrote no workflow') + await withholdFilesFromBlocked(workspaceId) + + const refusedAs = async (path: string) => { + const refused = await refusal( + workflowsOnly.apply(workspaceId, { + files: { 'workflows/lost/workflow.ts': fileReader(`file('${path}')`, 'Lost') }, + principal: blocked, + }) + ) + const errors = refused.diagnostics.flatMap(({ severity, code, message, hint }) => + severity === 'error' ? [{ code, message: message.replace(path, ''), hint }] : [] + ) + expect(errors.map((finding) => finding.code)).toEqual(['E_MAT_UNKNOWN_RESOURCE']) + return errors + } + expect(await refusedAs('moved/b.txt')).toEqual(await refusedAs('moved/c.txt')) + + const read = await workflowsOnly.get(workspaceId, blocked) + const printed = read.files['workflows/path-reader/workflow.ts'] + if (printed === undefined) throw new Error('The get printed no workflow') + const kept = await workflowsOnly.apply(workspaceId, { + files: { + ...read.files, + 'workflows/path-reader/workflow.ts': printed.replace("'Read'", "'Read held file'"), + }, + base: read.base, + principal: blocked, + }) + expect(kept.failed).toBeUndefined() + expect(summary(kept.applied)).toEqual(['update path-reader']) + expect(await storedFileInput(workflowId)).toMatchObject({ id: held.id, key: held.key }) + } + ) + + check( + 'a file path names a file called content or meta.json, and a folder called content, as written', + async () => { + const workspaceId = await newWorkspace() + const named = [ + ['docs', 'content'], + ['docs', 'meta.json'], + ['content', 'a.txt'], + ['', 'content'], + ] as const + for (const [index, [folderPath, name]] of named.entries()) { + const stored = await uploadInUi(workspaceId, folderPath, name, `${folderPath}/${name}`) + const path = folderPath ? `${folderPath}/${name}` : name + const source = `workflows/reader-${index}/workflow.ts` + const applied = await workflowsOnly.apply(workspaceId, { + files: { [source]: fileReader(`file('${path}')`, `Reader ${index}`) }, + }) + expect(applied.failed).toBeUndefined() + const workflowId = applied.base.resources[`workflow:reader-${index}`]?.id + if (!workflowId) throw new Error(`The apply naming ${path} wrote no workflow`) + expect(await storedFileInput(workflowId)).toMatchObject({ id: stored.id, key: stored.key }) + const printed = (await workflowsOnly.get(workspaceId)).files[source] + expect(printed).toContain(`readFileInput: file('${path}')`) + } + } + ) + check( 'a declared file the server can no longer hand to source since the get refuses only a directory that changes it', async () => { From be37ecfaf394d075784b0679884e07c64f44f8b3 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 1 Dec 2026 00:05:13 -0800 Subject: [PATCH 5/5] chore(workflow-sdk): regenerate core text after rebase --- packages/workflow-sdk/src/codegen/core-text.generated.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/workflow-sdk/src/codegen/core-text.generated.ts b/packages/workflow-sdk/src/codegen/core-text.generated.ts index ee991739b35..61bfe13e78c 100644 --- a/packages/workflow-sdk/src/codegen/core-text.generated.ts +++ b/packages/workflow-sdk/src/codegen/core-text.generated.ts @@ -1,4 +1,4 @@ // Generated by scripts/generate-embedded-text.ts from src/core.d.ts; do not edit. /** The text of `core.d.ts`, the workflow SDK authoring declarations. */ -export const CORE_DTS = "/**\n * The authoring surface for Sim workflows written as TypeScript.\n *\n * Nothing declared here runs. `@sim/workflow-code` compiles a workflow file statically, and every\n * runtime export of this package throws `SimSdkNotExecutable`. These declarations exist so an\n * editor, `tsc` (the type-check command `sim` prints) or an agent can check a workflow file before\n * the compiler sees it.\n *\n * Block builders (`slack.sendMessage`, `agent`, `trigger.gmail.poller`, ...) are not declared here:\n * they are generated from the block catalog into `blocks/{type}.d.ts`, which augment this module.\n * The generic `block(type, name, params)` covers any stored type without a builder.\n *\n * Every workflow file starts with the SDK header line, before any import:\n *\n * ```ts\n * // @sim-sdk 1\n * import { agent, trigger, workflow } from \u0027@sim/workflow-sdk\u0027\n * ```\n *\n * The number is the SDK major version the file is written against. A file without the header is\n * refused with `E_SDK_HEADER`, and one written for a newer major than the server supports with\n * `E_SDK_MAJOR`.\n */\n\n/** Plain JSON. */\nexport type Json = null | boolean | number | string | Json[] | { [key: string]: Json }\n\ndeclare const REF: unique symbol\ndeclare const TEMPLATE: unique symbol\ndeclare const ENV: unique symbol\ndeclare const RESOURCE: unique symbol\ndeclare const TOOL: unique symbol\ndeclare const NODE: unique symbol\ndeclare const CODE_FILE: unique symbol\ndeclare const RAW: unique symbol\ndeclare const UNTYPED: unique symbol\n\n/** Any reference, whatever it points at. */\nexport interface AnyRef {\n readonly [REF]: unknown\n}\n\n/** Marks a reference into untyped JSON, which any param accepts: its value is known only at run time. */\ninterface Untyped {\n readonly [UNTYPED]: true\n}\n\n/**\n * A reference into untyped JSON, where any path is allowed at any depth. An interface rather than\n * `Ref`, which TypeScript stops resolving after one step (`a.b.c` failed at `c`).\n */\ninterface UntypedRef extends Untyped {\n readonly [REF]: Json\n readonly [key: string]: UntypedRef\n}\n\ntype RefPaths = [Json] extends [T]\n ? Untyped & { readonly [key: string]: UntypedRef }\n : T extends readonly (infer E)[]\n ? { readonly [index: number]: Ref; readonly length: Ref }\n : T extends object\n ? { readonly [K in keyof T]-?: Ref }\n : unknown\n\n/**\n * A typed reference to a block output, compiled to ``.\n * Paths map exactly: `.seg`, `[\u0027seg\u0027]` and `[n]`. Untyped JSON allows any path.\n */\nexport type Ref = { readonly [REF]: T } & RefPaths\n\n/** Text with references in it, written with one of the tags below. */\nexport type Template = string & { readonly [TEMPLATE]: true }\n\n/** A workspace environment variable, compiled to `{{NAME}}`. */\nexport interface EnvRef {\n readonly [ENV]: string\n}\n\n/**\n * What a reference must hold to fill a param of type `T`. A param taking some strings takes any\n * string (an option id computed at run time); `null` (an output a step left empty) fits anywhere.\n */\ntype RefValue = [Extract] extends [never] ? T | null : T | string | null\n\n/**\n * A reference that fits a param of type `T`: one whose value has that type, or one into untyped\n * JSON. A whole block is not a value: reference one of its outputs.\n */\nexport type RefTo = ({ readonly [REF]: RefValue } | (AnyRef & Untyped)) & {\n readonly [NODE]?: never\n}\n\n/** A param value: a literal, a reference of a fitting type, a template or an environment variable. */\nexport type Value = T | RefTo | Template | EnvRef\n\n/** JSON whose leaves may be references, templates or environment variables. */\nexport type JsonWithRefs =\n | null\n | boolean\n | number\n | string\n | AnyRef\n | Template\n | EnvRef\n | JsonWithRefs[]\n | { [key: string]: JsonWithRefs }\n\n/** A literal union that still accepts any other string (option ids read from values). */\nexport type LiteralUnion = T | (string & {})\n\n/** A `time-input` value, `HH:MM`. */\nexport type TimeString = `${number}:${number}`\n\n/** A reference written into text: any output or variable, but not a whole block. */\ntype InterpolatedRef = AnyRef & { readonly [NODE]?: never }\n\ntype Interpolation = InterpolatedRef | EnvRef | VarRef | string | number | boolean\n\n/** Text with interpolated references: `` t`New ${cls.category} ticket` ``. */\nexport declare function t(strings: TemplateStringsArray, ...values: Interpolation[]): Template\n/**\n * JavaScript code (condition expressions, inline function code), kept exactly as written: like\n * `String.raw`, `` js`/\\s+/` `` is `/\\s+/`. Only `` \\` `` and `\\${` are escapes, for a backtick\n * and a literal `${`. So are `py`, `sh`, `json` and `md`; `t` text reads like a JS string.\n */\nexport declare const js: typeof t\n/** Python code, kept exactly as written (see {@link js}). */\nexport declare const py: typeof t\n/** Shell code, kept exactly as written (see {@link js}). */\nexport declare const sh: typeof t\n/**\n * JSON text kept verbatim, for bodies an object literal cannot reproduce byte for byte. In a JSON\n * field an object literal is the usual form: a bare reference keeps its value\u0027s type (`n: score.value`\n * is a number), and a template is text.\n */\nexport declare const json: typeof t\n/** Markdown text (note content). */\nexport declare const md: typeof t\n\n/** A reference with a non-canonical spelling, such as `ref(\u0027Classify.content\u0027)`. */\nexport declare function ref(path: string): Ref\n\n/** A stored value outside the generated type (a legacy option id, say), kept verbatim. */\nexport declare function raw(value: unknown): T & { readonly [RAW]: true }\n\n/** A required value that is still missing; compiles to absent, so canvas drafts type-check. */\nexport declare function todo(): never\n\n/**\n * Keeps the value the stored workflow holds for this param, without showing it: the printer writes\n * it for a secret pasted into a password field or a value that looks like a credential. Valid only\n * on a param of a block the stored workflow already has (same name and type) and holds a value\n * for, or as the `value` of a variable the stored workflow declares; anything else is\n * `E_STORED_VALUE_MISSING`.\n */\nexport declare function stored(): never\n\n/** Function code kept in a file next to the workflow (`.js`, `.py` or `.sh`), stored verbatim. */\nexport interface CodeFileRef {\n readonly [CODE_FILE]: string\n}\nexport declare function codeFile(path: `./${string}`): CodeFileRef\n\n/**\n * Environment variable names known to the workspace. `workspace.d.ts` adds one member per name;\n * until it exists `env` accepts any name.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceEnv {}\n\nexport declare const env: keyof WorkspaceEnv extends never\n ? { readonly [name: string]: EnvRef }\n : { readonly [K in keyof WorkspaceEnv]: EnvRef }\n\n/**\n * Workspace resources by stable key, filled in by the generated `workspace.d.ts`. Each map\u0027s\n * values describe the resource: a table\u0027s row type, a credential\u0027s provider, a workflow\u0027s inputs.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceTables {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceKnowledgeBases {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCredentials {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceWorkflows {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceSkills {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCustomTools {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceMcpServers {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceFiles {}\n\ntype KeyOf = keyof M extends never ? string : Extract\n\nexport type TableKey = KeyOf\nexport type KnowledgeBaseKey = KeyOf\nexport type CredentialKey = KeyOf\nexport type WorkflowKey = KeyOf\nexport type SkillKey = KeyOf\nexport type CustomToolKey = KeyOf\nexport type McpServerKey = KeyOf\n/** A workspace file\u0027s folder path and name (`docs/report.pdf`), as `files/` in a workspace directory holds it. */\nexport type FileKey = KeyOf\n/**\n * The tool names of MCP server `K`, as `workspace.d.ts` records them from the server\u0027s last\n * listing; any name for a server it could not list or does not know.\n */\nexport type McpToolName = K extends keyof WorkspaceMcpServers\n ? WorkspaceMcpServers[K] extends { tools: infer T extends string }\n ? T\n : string\n : string\n\n/** A workspace resource by stable key, compiled to the resource\u0027s internal id. */\nexport interface ResourceRef {\n readonly [RESOURCE]: Kind\n readonly key: Key\n}\n\n/** A saved credential: `credential(\u0027support-slack\u0027)`. */\nexport type CredentialRef = ResourceRef<\u0027credential\u0027, Key>\n\n/**\n * Keys of the saved credentials for one of `Providers`, as `workspace.d.ts` records each\n * credential\u0027s provider; any key until it exists.\n */\nexport type CredentialKeyFor = keyof WorkspaceCredentials extends never\n ? string\n : {\n [K in Extract]: WorkspaceCredentials[K] extends {\n provider: Providers\n }\n ? K\n : never\n }[Extract]\nexport declare function credential(key: K): CredentialRef\n\n/**\n * The other form a credential field takes beside `credential(\u0027key\u0027)`: a credential id produced at\n * run time by a reference, a template or an environment variable, stored in the field\u0027s advanced\n * twin (`manualCredential`). Literal text is not one, so a pasted token never type-checks; a\n * literal id the stored workflow already holds prints as `raw(\u0027…\u0027)`.\n */\nexport type CredentialIdValue = RefTo | Template | EnvRef\n\n/** The columns of a workspace table, or loose JSON when `workspace.d.ts` does not know it. */\nexport type TableColumns = K extends keyof WorkspaceTables\n ? WorkspaceTables[K]\n : { [column: string]: Json }\n/**\n * One row as the table blocks output it: the row id, and its cells keyed by column name under\n * `data` (`row.data.status`). Times are ISO strings.\n */\nexport interface TableRow {\n id: string\n data: TableColumns\n position: number\n createdAt: string\n updatedAt: string\n}\n/**\n * A value written to a field of type `T` (a table cell, a child workflow input): a JSON or JSON\n * array field takes JSON with references in it, and `null` leaves the field empty.\n */\ntype FieldValue = [Json] extends [T]\n ? JsonWithRefs\n : [Json[]] extends [T]\n ? JsonWithRefs\n : Value | null\n\n/** The columns of table `K` every row must hold: those whose cell type does not admit `null`. */\ntype RequiredColumns = {\n [C in keyof WorkspaceTables[K]]-?: null extends WorkspaceTables[K][C] ? never : C\n}[keyof WorkspaceTables[K]]\n\n/**\n * A whole row, as an insert, an upsert or a batch insert writes it, each value checked against\n * its column\u0027s type. A required column must be present and not `null`: the table refuses a row\n * without it (`Missing required field`), and an upsert checks the whole row before it looks for a\n * match.\n */\nexport type TableData = K extends keyof WorkspaceTables\n ? { [C in RequiredColumns]-?: Exclude, null> } & {\n [C in Exclude>]?: FieldValue<\n WorkspaceTables[K][C]\n >\n }\n : { [column: string]: JsonWithRefs }\n\n/**\n * The cells an update writes, each checked against its column\u0027s type. Every column is optional:\n * an update merges these cells over the stored row.\n */\nexport type TableDataPatch = K extends keyof WorkspaceTables\n ? { [C in keyof WorkspaceTables[K]]?: FieldValue }\n : { [column: string]: JsonWithRefs }\n\n/** A workspace table: `table(\u0027leads\u0027)`. Table block operations live on `table.*`. */\nexport type TableRef = ResourceRef<\u0027table\u0027, Key>\nexport declare function table(key: K): TableRef\n\n/** A knowledge base: `knowledgeBase(\u0027docs\u0027)`. */\nexport type KnowledgeBaseRef = ResourceRef<\u0027knowledge-base\u0027, Key>\nexport declare function knowledgeBase(key: K): KnowledgeBaseRef\n\n/** A workspace skill: `skill(\u0027triage\u0027)`. */\nexport type SkillRef = ResourceRef<\u0027skill\u0027, Key>\nexport declare function skill(key: K): SkillRef\n\n/** A workspace folder: `folder(\u0027reports\u0027)`. */\nexport type FolderRef = ResourceRef<\u0027file-folder\u0027>\nexport declare function folder(key: string): FolderRef\n\n/**\n * A workspace file by its folder path and name: `file(\u0027contracts/acme.pdf\u0027)`, written as a\n * file-upload field\u0027s value (or one item of a multi-file field\u0027s list); the same source names the\n * file at that path in whichever workspace it is applied to. File block operations live on\n * `file.*`.\n */\nexport type FileRef = ResourceRef<\u0027file\u0027, Key>\nexport declare function file(path: K): FileRef\n\n/**\n * A file a file-upload field holds, as the editor stores it, for a file that is not a workspace\n * file (one uploaded in place); a workspace file is written `file(\u0027/\u0027)`.\n */\nexport interface UploadedFile {\n name: string\n path: string\n size?: number\n type?: string\n key?: string\n id?: string\n folderPath?: string\n}\n\n/** A file produced at run time (`file` / `file[]` outputs). */\nexport interface SimFile {\n id: string\n name: string\n url: string\n size: number\n type: string\n key: string\n}\n\n// Agent tools\n\n/** One entry of an agent\u0027s `tools` list. */\nexport interface Tool {\n readonly [TOOL]: true\n}\n\n/** How the model may use a tool, and the stored tool fields a print carries. */\nexport interface ToolOpts {\n usageControl?: \u0027auto\u0027 | \u0027force\u0027 | \u0027none\u0027\n usageControlExpression?: string\n title?: string\n /** The stored operation, when the method does not pin it. */\n operation?: string\n toolId?: string\n /** Pair modes of the tool\u0027s params, which pick the member the agent reads. */\n modes?: Record\n customTool?: JsonWithRefs\n operationPolicy?: Json\n /** Unknown stored tool keys, kept verbatim. */\n extra?: Json\n}\n\n/**\n * A workspace custom tool by key, as an agent tool: `customTool(\u0027lookup-order\u0027)`. A stored tool\n * whose definition was copied into the workflow (and may have drifted from the workspace tool)\n * prints as `raw(tool)` instead.\n */\nexport declare function customTool(key: K, options?: ToolUsage): Tool\n\n/** How the model may use a tool the SDK writes by name (`customTool`, `mcp().tool`, `asTool`). */\nexport type ToolUsage = Pick\n\n/** An MCP tool\u0027s arguments and the editor\u0027s snapshot of its server. */\nexport interface McpToolOpts extends ToolUsage {\n /** Argument values the workflow fixes; the model fills in the rest. */\n args?: Record\n /**\n * What the editor saved about the server and the tool\u0027s input schema when the tool was picked.\n * Shown in the editor; never run.\n */\n snapshot?: { serverName?: string; serverUrl?: string; schema?: Json }\n}\n\n/** An MCP server by key: `mcp(\u0027linear\u0027)`. */\nexport interface McpServerRef extends ResourceRef<\u0027mcp-server\u0027, Key> {\n /** One of the server\u0027s tools, as an agent tool: `mcp(\u0027linear\u0027).tool(\u0027create_issue\u0027)`. */\n tool(name: McpToolName, options?: McpToolOpts): Tool\n}\nexport declare function mcp(key: K): McpServerRef\n\n// Graph\n\n/** Block-level fields (`BlockState`), written as the third builder argument. */\nexport interface BlockMeta {\n /**\n * A legacy key the display name cannot carry (a `name~n` collision key or a reserved name such\n * as `Loop`). Printed only for such a stored block; apply accepts it only for a key the stored\n * workflow already has, so it can never introduce one.\n */\n key?: string\n /** Stored as `enabled: false`. */\n disabled?: true\n /** Locked: apply refuses any change to this block. */\n locked?: true\n /** Exposes the error port without an `onError` edge. */\n errorPort?: boolean\n /** The block-level advanced toggle (`advancedMode`). */\n advancedMode?: boolean\n /**\n * Runs the block as its trigger (`triggerMode`). Trigger builders (`trigger.gmail.poller`) set\n * it themselves; write it on any other builder only for a block stored in trigger mode.\n */\n triggerMode?: boolean\n /** The stored retry policy, written whole. */\n retry?: BlockRetryConfig\n /**\n * Per branch key of a condition or router, the row\u0027s display `title` and any stored fields the\n * SDK has no syntax for (`extra`, plain JSON). `title: null` keeps a row stored with no title,\n * which the executor never takes for `else`.\n */\n branches?: Record }>\n /**\n * Stored params that run but have no SDK syntax: a schema-agnostic custom block\u0027s inputs, the\n * agent\u0027s legacy prompt fields, a container\u0027s stored params. Values the block keeps but never\n * runs are not written; apply keeps them from the stored workflow.\n */\n extra?: Record\n /**\n * A loop or parallel\u0027s `block.data` subflow keys the loader could not read as config, kept\n * verbatim (plain JSON).\n */\n subflowData?: Record\n}\n\n/** A block\u0027s retry policy, field for field the stored `BlockRetryConfig`. */\nexport interface BlockRetryConfig {\n /** Absent config and `false` mean the same thing: the block runs once. */\n enabled: boolean\n /** Total tries including the first. */\n maxTries: number\n /** Delay between tries. */\n waitBetweenTriesMs: number\n}\n\n/** Anything an edge can point at. */\nexport type Target = Node | Group\n\n/** A block or container in the graph. */\nexport interface Node {\n readonly [NODE]: true\n /** Wires this node\u0027s default port to each target. Returns the target, or a group of them. */\n to(...targets: T): T extends [infer One] ? One : Group\n /** Wires this node\u0027s error port to each target. */\n onError(...targets: Target[]): void\n}\n\n/** Several nodes; `.to()` wires every member (fan-in). */\nexport interface Group {\n to(...targets: Target[]): Group\n}\n\n/**\n * What a block outputs when it fails and an error edge leaves it (`x.onError(y)` runs `y` with\n * `x.error`): the failure message `error` on every block, plus the error outputs `E` its catalog\n * entry declares (a Function\u0027s `errorMessage`, the thrown message without its line and code). A\n * check refuses each on a block without an error edge, which fails the run instead. An output the\n * block declares under the same name keeps its declared type.\n */\ntype ErrorOutputs = {\n readonly [K in \u0027error\u0027 | E as [O] extends [Record] ? never : K]: Ref\n}\n\n/** A block: a node whose outputs can be referenced, and its error outputs after an `onError` edge. */\nexport type Block = Node & Ref & ErrorOutputs\n\n/** The named ports of a condition or router. */\nexport type Branches = { readonly [P in K]: Node }\n\n/** Trigger builders (`trigger.start`, `trigger.gmail.poller`, ...), generated from the catalog. */\nexport declare namespace trigger {}\n\n/** Builders for hidden legacy block versions (`legacy.slack.send`), generated from the catalog. */\nexport declare namespace legacy {}\n\n/** A raw edge from a handle the SDK has no name for (a legacy or unknown port). */\nexport declare function edge(from: Node, handle: string, to: Target): void\n\n/** Any stored block type without a builder (legacy, unknown or custom), with untyped outputs. */\nexport declare function block(\n type: string,\n name: string,\n params: Record,\n meta?: BlockMeta\n): Block\n\n// Workflow and variables\n\nexport type VariableType = \u0027string\u0027 | \u0027number\u0027 | \u0027boolean\u0027 | \u0027object\u0027 | \u0027array\u0027 | \u0027plain\u0027\n\n/** A workflow variable declared in `workflow(name, { variables })`: its type and initial value. */\nexport interface VariableDeclaration {\n /**\n * The display name, written only when it differs from the key. It must normalize to the key\n * (lowercased, spaces and dots removed), as `\u0027Total Count\u0027` does to `totalcount`.\n */\n name?: string\n type: VariableType\n value: Json\n}\n\n/** The variables a workflow declares, by name. */\nexport type VariableDeclarations = Record\n\ndeclare const VAR: unique symbol\n\n/** A workflow variable, compiled to ``. */\nexport interface VarRef {\n readonly [VAR]: string\n}\n\ntype VariableValue = T extends \u0027number\u0027\n ? number\n : T extends \u0027boolean\u0027\n ? boolean\n : T extends \u0027string\u0027 | \u0027plain\u0027\n ? string\n : Json\n\n/** `vars` in the workflow body: one typed reference per declared variable. */\nexport type VarRefs = {\n readonly [K in keyof V]: VarRef & Ref>\n}\n\n/**\n * Workflow variables by name, untyped. Prefer the `vars` the `workflow()` body receives, which is\n * typed from the declared variables.\n */\nexport declare const vars: { readonly [name: string]: VarRef & Ref }\n\ndeclare const WORKFLOW_DEF: unique symbol\n\n/** The default export of a workflow file. */\nexport interface WorkflowDef {\n readonly [WORKFLOW_DEF]: true\n}\n\n/** A child workflow by key, for `runWorkflow` or as an agent tool. */\nexport interface WorkflowRef extends ResourceRef<\u0027workflow\u0027, Key> {\n /**\n * The workflow as an agent tool, as the editor\u0027s tool picker adds it:\n * `childWorkflow(\u0027enrich-lead\u0027).asTool()`. A tool with fixed inputs is written `raw(tool)`.\n */\n asTool(options?: ToolUsage): Tool\n}\n\n/**\n * Declares a workflow. The body wires blocks; it never runs. With no description or variables the\n * options may be left out: `workflow(\u0027Name\u0027, () => { ... })`.\n */\nexport declare function workflow>(\n name: string,\n options: { description?: string; variables?: V },\n body: (scope: { vars: VarRefs }) => void\n): WorkflowDef\nexport declare function workflow(\n name: string,\n body: (scope: { vars: VarRefs> }) => void\n): WorkflowDef\n/** A child workflow by key: `childWorkflow(\u0027enrich-lead\u0027)`. */\nexport declare function childWorkflow(key: K): WorkflowRef\n\n// Containers\n\ntype ItemOf = C extends { readonly [REF]: readonly (infer E)[] }\n ? E\n : C extends readonly (infer E)[]\n ? E\n : Json\n\n/** Inside a loop or parallel body. As a node it is the container\u0027s start port: `p.to(first)`. */\nexport interface SubflowScope extends Node {\n readonly index: Ref\n readonly currentItem: Ref\n readonly items: Ref\n}\n\n/**\n * A container\u0027s outputs, plus its iteration fields by name (`outer.index`), which a block inside\n * the container reads (in a nested container too: an outer loop\u0027s index or item). Outside the\n * container only `results` resolves: check reports `W_REF_OUT_OF_SCOPE` on `outer.index` there.\n */\nexport interface SubflowOutput {\n results: Json[]\n index: number\n currentItem: Json\n items: Json[]\n}\n\n/** A loop or parallel container. Its `.to()` wires the port taken after it finishes. */\nexport type Container = Block\n\ntype Collection = AnyRef | Template | Json[] | string\n\n/**\n * A loop container: `forEach` over a list, `for` a count, `while` or `doWhile` a condition. The\n * body callback declares the blocks each iteration runs and wires the first from the scope\n * (`p.to(first)`), which reads the iteration as `p.currentItem` and `p.index` (a code file:\n * `$ref.loop.currentItem`). After it, `each.results` lists every iteration\u0027s output, and\n * `each.to(next)` wires what runs once all finish.\n * @example const each = loop.forEach(\u0027Each Order\u0027, { collection: orders.rows }, (p) => { const line = fn(\u0027Line\u0027, { code: js`return ${p.currentItem.data.id}` }); p.to(line) })\n */\nexport declare const loop: {\n for(\n name: string,\n params: { count?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n forEach(\n name: string,\n params: { collection: C },\n body: (scope: SubflowScope>) => void,\n meta?: BlockMeta\n ): Container\n while(\n name: string,\n params: { condition: Template | string },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n doWhile(\n name: string,\n params: { condition?: Template | string; count?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n}\n\nexport declare const parallel: {\n /** A parallel with no stored type, which the loader runs as `count`. */\n (\n name: string,\n params: { count?: number; collection?: Collection; batchSize?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n count(\n name: string,\n params: { count: number; batchSize?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n collection(\n name: string,\n params: { collection: C; batchSize?: number },\n body: (scope: SubflowScope>) => void,\n meta?: BlockMeta\n ): Container\n}\n\n// Blocks with a source form of their own\n\n/**\n * Params and outputs of the blocks below, generated from the catalog. Each entry is\n * `{ params; output }`, with `errorOutputs` when the block declares any; without generated types\n * the params are loose.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface SpecialBuilderTypes {}\n\ntype SpecialParams = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { params: infer P }\n ? P\n : never\n : Record\n\ntype SpecialOutput = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { output: infer O }\n ? O\n : never\n : Json\n\n/** The error outputs a special builder\u0027s block declares; a builder whose block has any passes them. */\ntype SpecialErrorOutputs = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { errorOutputs: infer E extends string }\n ? E\n : never\n : never\n\n/** A condition expression, or `true` for the `else` branch. */\nexport type BranchExpression = Template | string | true\n\ndeclare const ONLY_ELSE: unique symbol\n\n/** What a branch other than `else` written as `true` must be, which no value is: the error names it. */\ninterface OnlyElseMayBeTrue {\n readonly [ONLY_ELSE]: true\n}\n\n/**\n * A condition\u0027s branches: every key holds an expression, and only `else` may be `true`. Another\n * branch written as `true` is checked against {@link OnlyElseMayBeTrue}, so the error names that\n * branch alone.\n */\ntype ConditionBranches = {\n [K in keyof B]: K extends \u0027else\u0027\n ? BranchExpression\n : B[K] extends true\n ? OnlyElseMayBeTrue\n : Template | string\n}\n\n/**\n * Keys of a condition written with no rows (`condition(\u0027Name\u0027, {})`, the source form of rows\n * that were never persisted): the implicit `if` and `else` ports stay addressable.\n */\ntype ConditionKeys = keyof B extends never ? \u0027if\u0027 | \u0027else\u0027 : Extract\ntype RouterKeys = keyof R extends never ? \u0027route0\u0027 : Extract\n\n/**\n * A condition: named branches tested in order, top to bottom; the first whose expression holds\n * runs, and `else` (last, written `true`) runs when none does. Wire each as `x..to(block)`.\n * @example condition(\u0027Route\u0027, { big: js`${order.total} >= 500`, small: js`${order.total} < 50`, else: true })\n */\nexport declare function condition>(\n name: string,\n branches: B & ConditionBranches,\n meta?: BlockMeta\n): Block> & Branches>\n\n/** A router: named routes described for the model. */\nexport declare function router>(\n name: string,\n params: SpecialParams<\u0027router\u0027> & { routes: R },\n meta?: BlockMeta\n): Block> & Branches>\n\n/** A function block. `code` is inline (`` js`...` ``) or a code file (`codeFile(\u0027./functions/x.js\u0027)`). */\nexport declare function fn(\n name: string,\n params: SpecialParams<\u0027fn\u0027> & { code: Template | CodeFileRef | string },\n meta?: BlockMeta\n): Block, SpecialErrorOutputs<\u0027fn\u0027>>\n\n/**\n * The inputs of a child workflow by key, each checked against the input its start block\n * declares when `workspace.d.ts` knows the workflow; loose JSON otherwise.\n */\nexport type WorkflowInputMapping = K extends keyof WorkspaceWorkflows\n ? WorkspaceWorkflows[K] extends { inputs: infer I }\n ? { [N in keyof I]?: FieldValue }\n : InputMapping\n : InputMapping\n\n/**\n * Runs a child workflow. A `childWorkflow(\u0027key\u0027)` checks `inputMapping` against its inputs. Its\n * `result` is the child\u0027s output: its first response block\u0027s `{ data, status, headers }` (a body\n * field is `result.data.field`), else the output of the last block it ran.\n */\nexport declare function runWorkflow(\n name: string,\n params: Omit, \u0027workflowId\u0027 | \u0027inputMapping\u0027> & {\n workflowId: WorkflowRef | Exclude[\u0027workflowId\u0027], WorkflowRef>\n inputMapping?: WorkflowInputMapping\n },\n meta?: BlockMeta\n): Block>\n\n/**\n * Pauses for a person; the form in `inputFormat` types `submission`. A resumed block also holds\n * each form field at its top level (the runtime copies the submission up, over any output of the\n * same name), so `approval.approved` and `approval.submission.approved` both read it.\n */\nexport declare function human>(\n name: string,\n params: SpecialParams<\u0027human\u0027> & { inputFormat?: F },\n meta?: BlockMeta\n): Block<\n Omit, \u0027submission\u0027 | keyof F> & {\n submission: InputFieldsOutput\n } & InputFieldsOutput\n>\n\n/**\n * A response\u0027s body, status and headers: the editor\u0027s JSON mode, `body` standing for\n * `{ dataMode: \u0027json\u0027, data }`. An object or array `body` is JSON whose references keep their\n * types; a template or reference is the body text as written.\n */\nexport interface ResponseBody {\n body: JsonWithRefs\n /** HTTP status; 200 when omitted. A template or reference must produce a number. */\n status?: number | RefTo | Template | EnvRef\n /** Response headers by name. */\n headers?: Record>\n}\n\n/**\n * Ends the workflow with an API response: `response(\u0027Reply\u0027, { body: { ok: true }, status: 201 })`\n * (`body` is short for `dataMode: \u0027json\u0027` with `data`), or the block\u0027s own params (`dataMode`,\n * `builderData`, ...) when the body is built field by field.\n */\nexport declare function response(\n name: string,\n params: ResponseBody,\n meta?: BlockMeta\n): Block>\nexport declare function response(\n name: string,\n params: SpecialParams<\u0027response\u0027>,\n meta?: BlockMeta\n): Block>\n\n/** Assigns workflow variables. */\nexport declare function setVariables(\n name: string,\n params: SpecialParams<\u0027setVariables\u0027>,\n meta?: BlockMeta\n): Block>\n\ndeclare const ANNOTATION: unique symbol\n\n/** A canvas note: no edges, no outputs. */\nexport interface Annotation {\n readonly [ANNOTATION]: true\n}\nexport declare function note(\n name: string,\n params: SpecialParams<\u0027note\u0027>,\n meta?: BlockMeta\n): Annotation\n\n// Structured param shapes\n\n/** Type names an input-format field may declare. */\nexport type InputFieldType = \u0027string\u0027 | \u0027number\u0027 | \u0027boolean\u0027 | \u0027object\u0027 | \u0027array\u0027 | \u0027file[]\u0027\n\n/** A structured input field: its type plus a default value, description or required flag. */\nexport interface InputFieldSpec {\n type: InputFieldType\n value?: JsonWithRefs\n description?: string\n required?: boolean\n}\n\n/** `input-format` fields by name: `{ subject: \u0027string\u0027, amount: { type: \u0027number\u0027, value: 0 } }`. */\nexport type InputFields = Record\n\ntype InputFieldValue = T extends \u0027string\u0027\n ? string\n : T extends \u0027number\u0027\n ? number\n : T extends \u0027boolean\u0027\n ? boolean\n : T extends \u0027array\u0027\n ? Json[]\n : T extends \u0027file[]\u0027\n ? SimFile[]\n : Json\n\n/** The outputs an `input-format` declares. */\nexport type InputFieldsOutput = {\n [K in keyof F]: F[K] extends { type: infer T } ? InputFieldValue : InputFieldValue\n}\n\n/**\n * One `response-format` field as the editor\u0027s builder stores it. An `object` or `array` field\u0027s\n * `value` may hold nested fields. A response is usually written with `body` instead.\n */\nexport interface ResponseField {\n id?: string\n name: string\n type: string\n value?: JsonWithRefs\n collapsed?: boolean\n}\n\n/** `response-format` fields: `[{ name: \u0027ok\u0027, type: \u0027boolean\u0027, value: true }]`. */\nexport type ResponseFields = ResponseField[]\n\n/** An agent message. */\nexport interface Message {\n role: \u0027system\u0027 | \u0027user\u0027 | \u0027assistant\u0027\n content: Value\n}\n\n/** One `variables-input` assignment, with any other stored keys kept. */\nexport interface VariableAssignment {\n variableId: VarRef\n value?: JsonWithRefs\n [key: string]: JsonWithRefs | VarRef | undefined\n}\n\n/** Child workflow inputs by name (`input-mapping`, `workflow-input-mapper`). */\nexport type InputMapping = Record\n\n/** An operator a table filter condition or builder rule can use. */\nexport type FilterOperator = LiteralUnion<\n | \u0027eq\u0027\n | \u0027ne\u0027\n | \u0027gt\u0027\n | \u0027gte\u0027\n | \u0027lt\u0027\n | \u0027lte\u0027\n | \u0027in\u0027\n | \u0027nin\u0027\n | \u0027like\u0027\n | \u0027ilike\u0027\n | \u0027nlike\u0027\n | \u0027nilike\u0027\n | \u0027contains\u0027\n | \u0027ncontains\u0027\n | \u0027startsWith\u0027\n | \u0027endsWith\u0027\n | \u0027isNull\u0027\n | \u0027isNotNull\u0027\n | \u0027isEmpty\u0027\n | \u0027isNotEmpty\u0027\n>\n\n/** One row of the editor\u0027s filter builder, as it stores it. */\nexport interface FilterRule {\n id?: string\n /** How this row joins the rows before it; `and` when omitted. */\n logicalOperator?: \u0027and\u0027 | \u0027or\u0027\n column: string\n operator: FilterOperator\n value: Value\n collapsed?: boolean\n}\n\n/** A filter-builder value: the editor\u0027s rows, `[{ column: \u0027status\u0027, operator: \u0027eq\u0027, value: \u0027new\u0027 }]`. */\nexport type Filter = FilterRule[]\n\n/** One table filter condition: `{ field: \u0027status\u0027, op: \u0027eq\u0027, value: \u0027new\u0027 }`. */\nexport interface TableCondition {\n field: string\n op: FilterOperator\n value?: JsonWithRefs\n}\n\n/**\n * A table predicate: a condition, or an `all` (and) / `any` (or) group of predicates. The\n * `{ status: { $eq: \u0027new\u0027 } }` operator-object grammar is not one: the runtime refuses it.\n */\nexport type TablePredicate = TableCondition | { all: TablePredicate[] } | { any: TablePredicate[] }\n\n/** A table sort by column: `{ createdAt: \u0027desc\u0027 }`. */\nexport type Sort =\n | Record\n | Array<{ column: string; direction: \u0027asc\u0027 | \u0027desc\u0027 }>\n\n/** One knowledge tag filter. */\nexport interface TagFilter {\n tagName: string\n tagValue: Value\n [key: string]: JsonWithRefs\n}\n\n/** One document tag. */\nexport interface DocumentTag {\n tagName: string\n value: Value\n [key: string]: JsonWithRefs\n}\n\n/** One `eval-input` metric. */\nexport interface EvalMetric {\n name: string\n description?: string\n range?: { min: number; max: number }\n [key: string]: JsonWithRefs | undefined\n}\n\n/** One `model-fallback-list` entry. */\nexport interface ModelFallback {\n model: LiteralUnion\n [key: string]: JsonWithRefs\n}\n\n/**\n * Model ids, generated into `models.d.ts` (which adds one member per model). Kept apart from the\n * block files so a model-list change touches one file.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface ModelIds {}\nexport type Model = Extract\n\n/** A JSON Schema `responseFormat`, or `{ name, strict, schema }` around one. */\nexport type ResponseFormat = JsonWithRefs\n\ntype Depth = [never, 0, 1, 2, 3, 4]\n\ntype FromSchema = [D] extends [never]\n ? Json\n : S extends { enum: readonly (infer E)[] }\n ? E\n : S extends { type: \u0027object\u0027; properties: infer P }\n ? { [K in keyof P]: FromSchema }\n : S extends { type: \u0027array\u0027; items: infer I }\n ? FromSchema[]\n : S extends { type: \u0027string\u0027 }\n ? string\n : S extends { type: \u0027number\u0027 | \u0027integer\u0027 }\n ? number\n : S extends { type: \u0027boolean\u0027 }\n ? boolean\n : Json\n\n/**\n * The outputs a literal `responseFormat` adds, read from its JSON Schema with recursion capped at\n * depth 4. A template or reference adds untyped JSON.\n */\nexport type ResponseFormatOutput = [RF] extends [undefined]\n ? unknown\n : RF extends { schema: infer S }\n ? FromSchema\n : RF extends { type: \u0027object\u0027; properties: object }\n ? FromSchema\n : { [key: string]: Json }\n" +export const CORE_DTS = "/**\n * The authoring surface for Sim workflows written as TypeScript.\n *\n * Nothing declared here runs. `@sim/workflow-code` compiles a workflow file statically, and every\n * runtime export of this package throws `SimSdkNotExecutable`. These declarations exist so an\n * editor, `tsc` (the type-check command `sim` prints) or an agent can check a workflow file before\n * the compiler sees it.\n *\n * Block builders (`slack.sendMessage`, `agent`, `trigger.gmail.poller`, ...) are not declared here:\n * they are generated from the block catalog into `blocks/{type}.d.ts`, which augment this module.\n * The generic `block(type, name, params)` covers any stored type without a builder.\n *\n * Every workflow file starts with the SDK header line, before any import:\n *\n * ```ts\n * // @sim-sdk 1\n * import { agent, trigger, workflow } from \u0027@sim/workflow-sdk\u0027\n * ```\n *\n * The number is the SDK major version the file is written against. A file without the header is\n * refused with `E_SDK_HEADER`, and one written for a newer major than the server supports with\n * `E_SDK_MAJOR`.\n */\n\n/** Plain JSON. */\nexport type Json = null | boolean | number | string | Json[] | { [key: string]: Json }\n\ndeclare const REF: unique symbol\ndeclare const TEMPLATE: unique symbol\ndeclare const ENV: unique symbol\ndeclare const RESOURCE: unique symbol\ndeclare const TOOL: unique symbol\ndeclare const NODE: unique symbol\ndeclare const CODE_FILE: unique symbol\ndeclare const RAW: unique symbol\ndeclare const UNTYPED: unique symbol\n\n/** Any reference, whatever it points at. */\nexport interface AnyRef {\n readonly [REF]: unknown\n}\n\n/** Marks a reference into untyped JSON, which any param accepts: its value is known only at run time. */\ninterface Untyped {\n readonly [UNTYPED]: true\n}\n\n/**\n * A reference into untyped JSON, where any path is allowed at any depth. An interface rather than\n * `Ref`, which TypeScript stops resolving after one step (`a.b.c` failed at `c`).\n */\ninterface UntypedRef extends Untyped {\n readonly [REF]: Json\n readonly [key: string]: UntypedRef\n}\n\ntype RefPaths = [Json] extends [T]\n ? Untyped & { readonly [key: string]: UntypedRef }\n : T extends readonly (infer E)[]\n ? { readonly [index: number]: Ref; readonly length: Ref }\n : T extends object\n ? { readonly [K in keyof T]-?: Ref }\n : unknown\n\n/**\n * A typed reference to a block output, compiled to ``.\n * Paths map exactly: `.seg`, `[\u0027seg\u0027]` and `[n]`. Untyped JSON allows any path.\n */\nexport type Ref = { readonly [REF]: T } & RefPaths\n\n/** Text with references in it, written with one of the tags below. */\nexport type Template = string & { readonly [TEMPLATE]: true }\n\n/** A workspace environment variable, compiled to `{{NAME}}`. */\nexport interface EnvRef {\n readonly [ENV]: string\n}\n\n/**\n * What a reference must hold to fill a param of type `T`. A param taking some strings takes any\n * string (an option id computed at run time); `null` (an output a step left empty) fits anywhere.\n */\ntype RefValue = [Extract] extends [never] ? T | null : T | string | null\n\n/**\n * A reference that fits a param of type `T`: one whose value has that type, or one into untyped\n * JSON. A whole block is not a value: reference one of its outputs.\n */\nexport type RefTo = ({ readonly [REF]: RefValue } | (AnyRef & Untyped)) & {\n readonly [NODE]?: never\n}\n\n/** A param value: a literal, a reference of a fitting type, a template or an environment variable. */\nexport type Value = T | RefTo | Template | EnvRef\n\n/** JSON whose leaves may be references, templates or environment variables. */\nexport type JsonWithRefs =\n | null\n | boolean\n | number\n | string\n | AnyRef\n | Template\n | EnvRef\n | JsonWithRefs[]\n | { [key: string]: JsonWithRefs }\n\n/** A literal union that still accepts any other string (option ids read from values). */\nexport type LiteralUnion = T | (string & {})\n\n/** A `time-input` value, `HH:MM`. */\nexport type TimeString = `${number}:${number}`\n\n/** A reference written into text: any output or variable, but not a whole block. */\ntype InterpolatedRef = AnyRef & { readonly [NODE]?: never }\n\ntype Interpolation = InterpolatedRef | EnvRef | VarRef | string | number | boolean\n\n/** Text with interpolated references: `` t`New ${cls.category} ticket` ``. */\nexport declare function t(strings: TemplateStringsArray, ...values: Interpolation[]): Template\n/**\n * JavaScript code (condition expressions, inline function code), kept exactly as written: like\n * `String.raw`, `` js`/\\s+/` `` is `/\\s+/`. Only `` \\` `` and `\\${` are escapes, for a backtick\n * and a literal `${`. So are `py`, `sh`, `json` and `md`; `t` text reads like a JS string.\n */\nexport declare const js: typeof t\n/** Python code, kept exactly as written (see {@link js}). */\nexport declare const py: typeof t\n/** Shell code, kept exactly as written (see {@link js}). */\nexport declare const sh: typeof t\n/**\n * JSON text kept verbatim, for bodies an object literal cannot reproduce byte for byte. In a JSON\n * field an object literal is the usual form: a bare reference keeps its value\u0027s type (`n: score.value`\n * is a number), and a template is text.\n */\nexport declare const json: typeof t\n/** Markdown text (note content). */\nexport declare const md: typeof t\n\n/** A reference with a non-canonical spelling, such as `ref(\u0027Classify.content\u0027)`. */\nexport declare function ref(path: string): Ref\n\n/** A stored value outside the generated type (a legacy option id, say), kept verbatim. */\nexport declare function raw(value: unknown): T & { readonly [RAW]: true }\n\n/** A required value that is still missing; compiles to absent, so canvas drafts type-check. */\nexport declare function todo(): never\n\n/**\n * Keeps the value the stored workflow holds for this param, without showing it: the printer writes\n * it for a secret pasted into a password field or a value that looks like a credential. Valid only\n * on a param of a block the stored workflow already has (same name and type) and holds a value\n * for, or as the `value` of a variable the stored workflow declares; anything else is\n * `E_STORED_VALUE_MISSING`.\n */\nexport declare function stored(): never\n\n/** Function code kept in a file next to the workflow (`.js`, `.py` or `.sh`), stored verbatim. */\nexport interface CodeFileRef {\n readonly [CODE_FILE]: string\n}\nexport declare function codeFile(path: `./${string}`): CodeFileRef\n\n/**\n * Environment variable names known to the workspace. `workspace.d.ts` adds one member per name;\n * until it exists `env` accepts any name.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceEnv {}\n\nexport declare const env: keyof WorkspaceEnv extends never\n ? { readonly [name: string]: EnvRef }\n : { readonly [K in keyof WorkspaceEnv]: EnvRef }\n\n/**\n * Workspace resources by stable key, filled in by the generated `workspace.d.ts`. Each map\u0027s\n * values describe the resource: a table\u0027s row type, a credential\u0027s provider, a workflow\u0027s inputs.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceTables {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceKnowledgeBases {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCredentials {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceWorkflows {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceSkills {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCustomTools {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceMcpServers {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceFiles {}\n\ntype KeyOf = keyof M extends never ? string : Extract\n\nexport type TableKey = KeyOf\nexport type KnowledgeBaseKey = KeyOf\nexport type CredentialKey = KeyOf\nexport type WorkflowKey = KeyOf\nexport type SkillKey = KeyOf\nexport type CustomToolKey = KeyOf\nexport type McpServerKey = KeyOf\n/** A workspace file\u0027s folder path and name (`docs/report.pdf`), as `files/` in a workspace directory holds it. */\nexport type FileKey = KeyOf\n/**\n * The tool names of MCP server `K`, as `workspace.d.ts` records them from the server\u0027s last\n * listing; any name for a server it could not list or does not know.\n */\nexport type McpToolName = K extends keyof WorkspaceMcpServers\n ? WorkspaceMcpServers[K] extends { tools: infer T extends string }\n ? T\n : string\n : string\n\n/** A workspace resource by stable key, compiled to the resource\u0027s internal id. */\nexport interface ResourceRef {\n readonly [RESOURCE]: Kind\n readonly key: Key\n}\n\n/** A saved credential: `credential(\u0027support-slack\u0027)`. */\nexport type CredentialRef = ResourceRef<\u0027credential\u0027, Key>\n\n/**\n * Keys of the saved credentials for one of `Providers`, as `workspace.d.ts` records each\n * credential\u0027s provider; any key until it exists.\n */\nexport type CredentialKeyFor = keyof WorkspaceCredentials extends never\n ? string\n : {\n [K in Extract]: WorkspaceCredentials[K] extends {\n provider: Providers\n }\n ? K\n : never\n }[Extract]\nexport declare function credential(key: K): CredentialRef\n\n/**\n * The other form a credential field takes beside `credential(\u0027key\u0027)`: a credential id produced at\n * run time by a reference, a template or an environment variable, stored in the field\u0027s advanced\n * twin (`manualCredential`). Literal text is not one, so a pasted token never type-checks; a\n * literal id the stored workflow already holds prints as `raw(\u0027…\u0027)`.\n */\nexport type CredentialIdValue = RefTo | Template | EnvRef\n\n/** The columns of a workspace table, or loose JSON when `workspace.d.ts` does not know it. */\nexport type TableColumns = K extends keyof WorkspaceTables\n ? WorkspaceTables[K]\n : { [column: string]: Json }\n/**\n * One row as the table blocks output it: the row id, and its cells keyed by column name under\n * `data` (`row.data.status`). Times are ISO strings.\n */\nexport interface TableRow {\n id: string\n data: TableColumns\n position: number\n createdAt: string\n updatedAt: string\n}\n/**\n * A value written to a field of type `T` (a table cell, a child workflow input): a JSON or JSON\n * array field takes JSON with references in it, and `null` leaves the field empty.\n */\ntype FieldValue = [Json] extends [T]\n ? JsonWithRefs\n : [Json[]] extends [T]\n ? JsonWithRefs\n : Value | null\n\n/** The columns of table `K` every row must hold: those whose cell type does not admit `null`. */\ntype RequiredColumns = {\n [C in keyof WorkspaceTables[K]]-?: null extends WorkspaceTables[K][C] ? never : C\n}[keyof WorkspaceTables[K]]\n\n/**\n * A whole row, as an insert, an upsert or a batch insert writes it, each value checked against\n * its column\u0027s type. A required column must be present and not `null`: the table refuses a row\n * without it (`Missing required field`), and an upsert checks the whole row before it looks for a\n * match.\n */\nexport type TableData = K extends keyof WorkspaceTables\n ? { [C in RequiredColumns]-?: Exclude, null> } & {\n [C in Exclude>]?: FieldValue<\n WorkspaceTables[K][C]\n >\n }\n : { [column: string]: JsonWithRefs }\n\n/**\n * The cells an update writes, each checked against its column\u0027s type. Every column is optional:\n * an update merges these cells over the stored row.\n */\nexport type TableDataPatch = K extends keyof WorkspaceTables\n ? { [C in keyof WorkspaceTables[K]]?: FieldValue }\n : { [column: string]: JsonWithRefs }\n\n/** A workspace table: `table(\u0027leads\u0027)`. Table block operations live on `table.*`. */\nexport type TableRef = ResourceRef<\u0027table\u0027, Key>\nexport declare function table(key: K): TableRef\n\n/** A knowledge base: `knowledgeBase(\u0027docs\u0027)`. */\nexport type KnowledgeBaseRef = ResourceRef<\u0027knowledge-base\u0027, Key>\nexport declare function knowledgeBase(key: K): KnowledgeBaseRef\n\n/** A workspace skill: `skill(\u0027triage\u0027)`. */\nexport type SkillRef = ResourceRef<\u0027skill\u0027, Key>\nexport declare function skill(key: K): SkillRef\n\n/** A workspace folder: `folder(\u0027reports\u0027)`. */\nexport type FolderRef = ResourceRef<\u0027file-folder\u0027>\nexport declare function folder(key: string): FolderRef\n\n/**\n * A workspace file by its folder path and name: `file(\u0027contracts/acme.pdf\u0027)`, written as a\n * file-upload field\u0027s value (or one item of a multi-file field\u0027s list); the same source names the\n * file at that path in whichever workspace it is applied to. File block operations live on\n * `file.*`.\n */\nexport type FileRef = ResourceRef<\u0027file\u0027, Key>\nexport declare function file(path: K): FileRef\n\n/**\n * A file a file-upload field holds, as the editor stores it, for a file that is not a workspace\n * file (one uploaded in place); a workspace file is written `file(\u0027/\u0027)`.\n */\nexport interface UploadedFile {\n name: string\n path: string\n size?: number\n type?: string\n key?: string\n id?: string\n folderPath?: string\n}\n\n/** A file produced at run time (`file` / `file[]` outputs). */\nexport interface SimFile {\n id: string\n name: string\n url: string\n size: number\n type: string\n key: string\n}\n\n// Agent tools\n\n/** One entry of an agent\u0027s `tools` list. */\nexport interface Tool {\n readonly [TOOL]: true\n}\n\n/** How the model may use a tool, and the stored tool fields a print carries. */\nexport interface ToolOpts {\n usageControl?: \u0027auto\u0027 | \u0027force\u0027 | \u0027none\u0027\n usageControlExpression?: string\n title?: string\n /** The stored operation, when the method does not pin it. */\n operation?: string\n toolId?: string\n /** Pair modes of the tool\u0027s params, which pick the member the agent reads. */\n modes?: Record\n customTool?: JsonWithRefs\n operationPolicy?: Json\n /** Unknown stored tool keys, kept verbatim. */\n extra?: Json\n}\n\n/**\n * A workspace custom tool by key, as an agent tool: `customTool(\u0027lookup-order\u0027)`. A stored tool\n * whose definition was copied into the workflow (and may have drifted from the workspace tool)\n * prints as `raw(tool)` instead.\n */\nexport declare function customTool(key: K, options?: ToolUsage): Tool\n\n/** How the model may use a tool the SDK writes by name (`customTool`, `mcp().tool`, `asTool`). */\nexport type ToolUsage = Pick\n\n/** An MCP tool\u0027s arguments and the editor\u0027s snapshot of its server. */\nexport interface McpToolOpts extends ToolUsage {\n /** Argument values the workflow fixes; the model fills in the rest. */\n args?: Record\n /**\n * What the editor saved about the server and the tool\u0027s input schema when the tool was picked.\n * Shown in the editor; never run.\n */\n snapshot?: { serverName?: string; serverUrl?: string; schema?: Json }\n}\n\n/** An MCP server by key: `mcp(\u0027linear\u0027)`. */\nexport interface McpServerRef extends ResourceRef<\u0027mcp-server\u0027, Key> {\n /** One of the server\u0027s tools, as an agent tool: `mcp(\u0027linear\u0027).tool(\u0027create_issue\u0027)`. */\n tool(name: McpToolName, options?: McpToolOpts): Tool\n}\nexport declare function mcp(key: K): McpServerRef\n\n// Graph\n\n/** Block-level fields (`BlockState`), written as the third builder argument. */\nexport interface BlockMeta {\n /**\n * A legacy key the display name cannot carry (a `name~n` collision key or a reserved name such\n * as `Loop`). Printed only for such a stored block; apply accepts it only for a key the stored\n * workflow already has, so it can never introduce one.\n */\n key?: string\n /** Stored as `enabled: false`. */\n disabled?: true\n /** Locked: apply refuses any change to this block. */\n locked?: true\n /** Exposes the error port without an `onError` edge. */\n errorPort?: boolean\n /** The block-level advanced toggle (`advancedMode`). */\n advancedMode?: boolean\n /**\n * Runs the block as its trigger (`triggerMode`). Trigger builders (`trigger.gmail.poller`) set\n * it themselves; write it on any other builder only for a block stored in trigger mode.\n */\n triggerMode?: boolean\n /** The stored retry policy, written whole. */\n retry?: BlockRetryConfig\n /**\n * Per branch key of a condition or router, the row\u0027s display `title` and any stored fields the\n * SDK has no syntax for (`extra`, plain JSON). `title: null` keeps a row stored with no title,\n * which the executor never takes for `else`.\n */\n branches?: Record }>\n /**\n * Stored params that run but have no SDK syntax: a schema-agnostic custom block\u0027s inputs, the\n * agent\u0027s legacy prompt fields, a container\u0027s stored params. Values the block keeps but never\n * runs are not written; apply keeps them from the stored workflow.\n */\n extra?: Record\n /**\n * A loop or parallel\u0027s `block.data` subflow keys the loader could not read as config, kept\n * verbatim (plain JSON).\n */\n subflowData?: Record\n}\n\n/** A block\u0027s retry policy, field for field the stored `BlockRetryConfig`. */\nexport interface BlockRetryConfig {\n /** Absent config and `false` mean the same thing: the block runs once. */\n enabled: boolean\n /** Total tries including the first. */\n maxTries: number\n /** Delay between tries. */\n waitBetweenTriesMs: number\n}\n\n/** Anything an edge can point at. */\nexport type Target = Node | Group\n\n/** A block or container in the graph. */\nexport interface Node {\n readonly [NODE]: true\n /** Wires this node\u0027s default port to each target. Returns the target, or a group of them. */\n to(...targets: T): T extends [infer One] ? One : Group\n /** Wires this node\u0027s error port to each target. */\n onError(...targets: Target[]): void\n}\n\n/** Several nodes; `.to()` wires every member (fan-in). */\nexport interface Group {\n to(...targets: Target[]): Group\n}\n\n/**\n * What a block outputs when it fails and an error edge leaves it (`x.onError(y)` runs `y` with\n * `x.error`): the failure message `error` on every block, plus the error outputs `E` its catalog\n * entry declares (a Function\u0027s `errorMessage`, the thrown message without its line and code). A\n * check refuses each on a block without an error edge, which fails the run instead. An output the\n * block declares under the same name keeps its declared type.\n */\ntype ErrorOutputs = {\n readonly [K in \u0027error\u0027 | E as [O] extends [Record] ? never : K]: Ref\n}\n\n/** A block: a node whose outputs can be referenced, and its error outputs after an `onError` edge. */\nexport type Block = Node & Ref & ErrorOutputs\n\n/** The named ports of a condition or router. */\nexport type Branches = { readonly [P in K]: Node }\n\n/** Trigger builders (`trigger.start`, `trigger.gmail.poller`, ...), generated from the catalog. */\nexport declare namespace trigger {}\n\n/** Builders for hidden legacy block versions (`legacy.slack.send`), generated from the catalog. */\nexport declare namespace legacy {}\n\n/** A raw edge from a handle the SDK has no name for (a legacy or unknown port). */\nexport declare function edge(from: Node, handle: string, to: Target): void\n\n/** Any stored block type without a builder (legacy, unknown or custom), with untyped outputs. */\nexport declare function block(\n type: string,\n name: string,\n params: Record,\n meta?: BlockMeta\n): Block\n\n// Workflow and variables\n\nexport type VariableType = \u0027string\u0027 | \u0027number\u0027 | \u0027boolean\u0027 | \u0027object\u0027 | \u0027array\u0027 | \u0027plain\u0027\n\n/** A workflow variable declared in `workflow(name, { variables })`: its type and initial value. */\nexport interface VariableDeclaration {\n /**\n * The display name, written only when it differs from the key. It must normalize to the key\n * (lowercased, spaces and dots removed), as `\u0027Total Count\u0027` does to `totalcount`.\n */\n name?: string\n type: VariableType\n value: Json\n}\n\n/** The variables a workflow declares, by name. */\nexport type VariableDeclarations = Record\n\ndeclare const VAR: unique symbol\n\n/** A workflow variable, compiled to ``. */\nexport interface VarRef {\n readonly [VAR]: string\n}\n\ntype VariableValue = T extends \u0027number\u0027\n ? number\n : T extends \u0027boolean\u0027\n ? boolean\n : T extends \u0027string\u0027 | \u0027plain\u0027\n ? string\n : Json\n\n/** `vars` in the workflow body: one typed reference per declared variable. */\nexport type VarRefs = {\n readonly [K in keyof V]: VarRef & Ref>\n}\n\n/**\n * Workflow variables by name, untyped. Prefer the `vars` the `workflow()` body receives, which is\n * typed from the declared variables.\n */\nexport declare const vars: { readonly [name: string]: VarRef & Ref }\n\ndeclare const WORKFLOW_DEF: unique symbol\n\n/** The default export of a workflow file. */\nexport interface WorkflowDef {\n readonly [WORKFLOW_DEF]: true\n}\n\n/** A child workflow by key, for `runWorkflow` or as an agent tool. */\nexport interface WorkflowRef extends ResourceRef<\u0027workflow\u0027, Key> {\n /**\n * The workflow as an agent tool, as the editor\u0027s tool picker adds it:\n * `childWorkflow(\u0027enrich-lead\u0027).asTool()`. A tool with fixed inputs is written `raw(tool)`.\n */\n asTool(options?: ToolUsage): Tool\n}\n\n/**\n * Declares a workflow. The body wires blocks; it never runs. With no description or variables the\n * options may be left out: `workflow(\u0027Name\u0027, () => { ... })`.\n */\nexport declare function workflow>(\n name: string,\n options: { description?: string; variables?: V },\n body: (scope: { vars: VarRefs }) => void\n): WorkflowDef\nexport declare function workflow(\n name: string,\n body: (scope: { vars: VarRefs> }) => void\n): WorkflowDef\n/** A child workflow by key: `childWorkflow(\u0027enrich-lead\u0027)`. */\nexport declare function childWorkflow(key: K): WorkflowRef\n\n// Containers\n\ntype ItemOf = C extends { readonly [REF]: readonly (infer E)[] }\n ? E\n : C extends readonly (infer E)[]\n ? E\n : Json\n\n/** Inside a loop or parallel body. As a node it is the container\u0027s start port: `p.to(first)`. */\nexport interface SubflowScope extends Node {\n readonly index: Ref\n readonly currentItem: Ref\n readonly items: Ref\n}\n\n/**\n * A container\u0027s outputs, plus its iteration fields by name (`outer.index`), which a block inside\n * the container reads (in a nested container too: an outer loop\u0027s index or item). Outside the\n * container only `results` resolves: check reports `W_REF_OUT_OF_SCOPE` on `outer.index` there.\n */\nexport interface SubflowOutput {\n /**\n * One entry per iteration (a parallel: per branch), each the list of outputs of the body blocks\n * that ran in it, in the order they finished. With one block in the body its output is\n * `results[i][0]`; in code, `results.flat()` lists every output.\n */\n results: Json[][]\n index: number\n currentItem: Json\n items: Json[]\n}\n\n/** A loop or parallel container. Its `.to()` wires the port taken after it finishes. */\nexport type Container = Block\n\ntype Collection = AnyRef | Template | Json[] | string\n\n/**\n * A loop container: `forEach` over a list, `for` a count, `while` or `doWhile` a condition. The\n * body callback declares the blocks each iteration runs and wires the first from the scope\n * (`p.to(first)`), which reads the iteration as `p.currentItem` and `p.index` (a code file:\n * `$ref.loop.currentItem`). After it, `each.results[i]` lists iteration `i`\u0027s body-block outputs\n * (one block: `each.results[i][0]`), and `each.to(next)` wires what runs once all finish.\n * @example const each = loop.forEach(\u0027Each Order\u0027, { collection: orders.rows }, (p) => { const line = fn(\u0027Line\u0027, { code: js`return ${p.currentItem.data.id}` }); p.to(line) })\n */\nexport declare const loop: {\n for(\n name: string,\n params: { count?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n forEach(\n name: string,\n params: { collection: C },\n body: (scope: SubflowScope>) => void,\n meta?: BlockMeta\n ): Container\n while(\n name: string,\n params: { condition: Template | string },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n doWhile(\n name: string,\n params: { condition?: Template | string; count?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n}\n\nexport declare const parallel: {\n /** A parallel with no stored type, which the loader runs as `count`. */\n (\n name: string,\n params: { count?: number; collection?: Collection; batchSize?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n count(\n name: string,\n params: { count: number; batchSize?: number },\n body: (scope: SubflowScope) => void,\n meta?: BlockMeta\n ): Container\n collection(\n name: string,\n params: { collection: C; batchSize?: number },\n body: (scope: SubflowScope>) => void,\n meta?: BlockMeta\n ): Container\n}\n\n// Blocks with a source form of their own\n\n/**\n * Params and outputs of the blocks below, generated from the catalog. Each entry is\n * `{ params; output }`, with `errorOutputs` when the block declares any; without generated types\n * the params are loose.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface SpecialBuilderTypes {}\n\ntype SpecialParams = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { params: infer P }\n ? P\n : never\n : Record\n\ntype SpecialOutput = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { output: infer O }\n ? O\n : never\n : Json\n\n/** The error outputs a special builder\u0027s block declares; a builder whose block has any passes them. */\ntype SpecialErrorOutputs = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { errorOutputs: infer E extends string }\n ? E\n : never\n : never\n\n/** A condition expression, or `true` for the `else` branch. */\nexport type BranchExpression = Template | string | true\n\ndeclare const ONLY_ELSE: unique symbol\n\n/** What a branch other than `else` written as `true` must be, which no value is: the error names it. */\ninterface OnlyElseMayBeTrue {\n readonly [ONLY_ELSE]: true\n}\n\n/**\n * A condition\u0027s branches: every key holds an expression, and only `else` may be `true`. Another\n * branch written as `true` is checked against {@link OnlyElseMayBeTrue}, so the error names that\n * branch alone.\n */\ntype ConditionBranches = {\n [K in keyof B]: K extends \u0027else\u0027\n ? BranchExpression\n : B[K] extends true\n ? OnlyElseMayBeTrue\n : Template | string\n}\n\n/**\n * Keys of a condition written with no rows (`condition(\u0027Name\u0027, {})`, the source form of rows\n * that were never persisted): the implicit `if` and `else` ports stay addressable.\n */\ntype ConditionKeys = keyof B extends never ? \u0027if\u0027 | \u0027else\u0027 : Extract\ntype RouterKeys = keyof R extends never ? \u0027route0\u0027 : Extract\n\n/**\n * A condition: named branches tested in order, top to bottom; the first whose expression holds\n * runs, and `else` (last, written `true`) runs when none does. Wire each as `x..to(block)`.\n * @example condition(\u0027Route\u0027, { big: js`${order.total} >= 500`, small: js`${order.total} < 50`, else: true })\n */\nexport declare function condition>(\n name: string,\n branches: B & ConditionBranches,\n meta?: BlockMeta\n): Block> & Branches>\n\n/** A router: named routes described for the model. */\nexport declare function router>(\n name: string,\n params: SpecialParams<\u0027router\u0027> & { routes: R },\n meta?: BlockMeta\n): Block> & Branches>\n\n/** A function block. `code` is inline (`` js`...` ``) or a code file (`codeFile(\u0027./functions/x.js\u0027)`). */\nexport declare function fn(\n name: string,\n params: SpecialParams<\u0027fn\u0027> & { code: Template | CodeFileRef | string },\n meta?: BlockMeta\n): Block, SpecialErrorOutputs<\u0027fn\u0027>>\n\n/**\n * The inputs of a child workflow by key, each checked against the input its start block\n * declares when `workspace.d.ts` knows the workflow; loose JSON otherwise.\n */\nexport type WorkflowInputMapping = K extends keyof WorkspaceWorkflows\n ? WorkspaceWorkflows[K] extends { inputs: infer I }\n ? { [N in keyof I]?: FieldValue }\n : InputMapping\n : InputMapping\n\n/**\n * Runs a child workflow. A `childWorkflow(\u0027key\u0027)` checks `inputMapping` against its inputs. Its\n * `result` is the child\u0027s output: its first response block\u0027s `{ data, status, headers }` (a body\n * field is `result.data.field`), else the output of the last block it ran.\n */\nexport declare function runWorkflow(\n name: string,\n params: Omit, \u0027workflowId\u0027 | \u0027inputMapping\u0027> & {\n workflowId: WorkflowRef | Exclude[\u0027workflowId\u0027], WorkflowRef>\n inputMapping?: WorkflowInputMapping\n },\n meta?: BlockMeta\n): Block>\n\n/**\n * Pauses for a person; the form in `inputFormat` types `submission`. A resumed block also holds\n * each form field at its top level (the runtime copies the submission up, over any output of the\n * same name), so `approval.approved` and `approval.submission.approved` both read it.\n */\nexport declare function human>(\n name: string,\n params: SpecialParams<\u0027human\u0027> & { inputFormat?: F },\n meta?: BlockMeta\n): Block<\n Omit, \u0027submission\u0027 | keyof F> & {\n submission: InputFieldsOutput\n } & InputFieldsOutput\n>\n\n/**\n * A response\u0027s body, status and headers: the editor\u0027s JSON mode, `body` standing for\n * `{ dataMode: \u0027json\u0027, data }`. An object or array `body` is JSON whose references keep their\n * types; a template or reference is the body text as written.\n */\nexport interface ResponseBody {\n body: JsonWithRefs\n /** HTTP status; 200 when omitted. A template or reference must produce a number. */\n status?: number | RefTo | Template | EnvRef\n /** Response headers by name. */\n headers?: Record>\n}\n\n/**\n * Ends the workflow with an API response: `response(\u0027Reply\u0027, { body: { ok: true }, status: 201 })`\n * (`body` is short for `dataMode: \u0027json\u0027` with `data`), or the block\u0027s own params (`dataMode`,\n * `builderData`, ...) when the body is built field by field.\n */\nexport declare function response(\n name: string,\n params: ResponseBody,\n meta?: BlockMeta\n): Block>\nexport declare function response(\n name: string,\n params: SpecialParams<\u0027response\u0027>,\n meta?: BlockMeta\n): Block>\n\n/** Assigns workflow variables. */\nexport declare function setVariables(\n name: string,\n params: SpecialParams<\u0027setVariables\u0027>,\n meta?: BlockMeta\n): Block>\n\ndeclare const ANNOTATION: unique symbol\n\n/** A canvas note: no edges, no outputs. */\nexport interface Annotation {\n readonly [ANNOTATION]: true\n}\nexport declare function note(\n name: string,\n params: SpecialParams<\u0027note\u0027>,\n meta?: BlockMeta\n): Annotation\n\n// Structured param shapes\n\n/** Type names an input-format field may declare. */\nexport type InputFieldType = \u0027string\u0027 | \u0027number\u0027 | \u0027boolean\u0027 | \u0027object\u0027 | \u0027array\u0027 | \u0027file[]\u0027\n\n/** A structured input field: its type plus a default value, description or required flag. */\nexport interface InputFieldSpec {\n type: InputFieldType\n value?: JsonWithRefs\n description?: string\n required?: boolean\n}\n\n/** `input-format` fields by name: `{ subject: \u0027string\u0027, amount: { type: \u0027number\u0027, value: 0 } }`. */\nexport type InputFields = Record\n\ntype InputFieldValue = T extends \u0027string\u0027\n ? string\n : T extends \u0027number\u0027\n ? number\n : T extends \u0027boolean\u0027\n ? boolean\n : T extends \u0027array\u0027\n ? Json[]\n : T extends \u0027file[]\u0027\n ? SimFile[]\n : Json\n\n/** The outputs an `input-format` declares. */\nexport type InputFieldsOutput = {\n [K in keyof F]: F[K] extends { type: infer T } ? InputFieldValue : InputFieldValue\n}\n\n/**\n * One `response-format` field as the editor\u0027s builder stores it. An `object` or `array` field\u0027s\n * `value` may hold nested fields. A response is usually written with `body` instead.\n */\nexport interface ResponseField {\n id?: string\n name: string\n type: string\n value?: JsonWithRefs\n collapsed?: boolean\n}\n\n/** `response-format` fields: `[{ name: \u0027ok\u0027, type: \u0027boolean\u0027, value: true }]`. */\nexport type ResponseFields = ResponseField[]\n\n/** An agent message. */\nexport interface Message {\n role: \u0027system\u0027 | \u0027user\u0027 | \u0027assistant\u0027\n content: Value\n}\n\n/** One `variables-input` assignment, with any other stored keys kept. */\nexport interface VariableAssignment {\n variableId: VarRef\n value?: JsonWithRefs\n [key: string]: JsonWithRefs | VarRef | undefined\n}\n\n/** Child workflow inputs by name (`input-mapping`, `workflow-input-mapper`). */\nexport type InputMapping = Record\n\n/** An operator a table filter condition or builder rule can use. */\nexport type FilterOperator = LiteralUnion<\n | \u0027eq\u0027\n | \u0027ne\u0027\n | \u0027gt\u0027\n | \u0027gte\u0027\n | \u0027lt\u0027\n | \u0027lte\u0027\n | \u0027in\u0027\n | \u0027nin\u0027\n | \u0027like\u0027\n | \u0027ilike\u0027\n | \u0027nlike\u0027\n | \u0027nilike\u0027\n | \u0027contains\u0027\n | \u0027ncontains\u0027\n | \u0027startsWith\u0027\n | \u0027endsWith\u0027\n | \u0027isNull\u0027\n | \u0027isNotNull\u0027\n | \u0027isEmpty\u0027\n | \u0027isNotEmpty\u0027\n>\n\n/** One row of the editor\u0027s filter builder, as it stores it. */\nexport interface FilterRule {\n id?: string\n /** How this row joins the rows before it; `and` when omitted. */\n logicalOperator?: \u0027and\u0027 | \u0027or\u0027\n column: string\n operator: FilterOperator\n value: Value\n collapsed?: boolean\n}\n\n/** A filter-builder value: the editor\u0027s rows, `[{ column: \u0027status\u0027, operator: \u0027eq\u0027, value: \u0027new\u0027 }]`. */\nexport type Filter = FilterRule[]\n\n/** One table filter condition: `{ field: \u0027status\u0027, op: \u0027eq\u0027, value: \u0027new\u0027 }`. */\nexport interface TableCondition {\n field: string\n op: FilterOperator\n value?: JsonWithRefs\n}\n\n/**\n * A table predicate: a condition, or an `all` (and) / `any` (or) group of predicates. The\n * `{ status: { $eq: \u0027new\u0027 } }` operator-object grammar is not one: the runtime refuses it.\n */\nexport type TablePredicate = TableCondition | { all: TablePredicate[] } | { any: TablePredicate[] }\n\n/** A table sort by column: `{ createdAt: \u0027desc\u0027 }`. */\nexport type Sort =\n | Record\n | Array<{ column: string; direction: \u0027asc\u0027 | \u0027desc\u0027 }>\n\n/** One knowledge tag filter. */\nexport interface TagFilter {\n tagName: string\n tagValue: Value\n [key: string]: JsonWithRefs\n}\n\n/** One document tag. */\nexport interface DocumentTag {\n tagName: string\n value: Value\n [key: string]: JsonWithRefs\n}\n\n/** One `eval-input` metric. */\nexport interface EvalMetric {\n name: string\n description?: string\n range?: { min: number; max: number }\n [key: string]: JsonWithRefs | undefined\n}\n\n/** One `model-fallback-list` entry. */\nexport interface ModelFallback {\n model: LiteralUnion\n [key: string]: JsonWithRefs\n}\n\n/**\n * Model ids, generated into `models.d.ts` (which adds one member per model). Kept apart from the\n * block files so a model-list change touches one file.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface ModelIds {}\nexport type Model = Extract\n\n/** A JSON Schema `responseFormat`, or `{ name, strict, schema }` around one. */\nexport type ResponseFormat = JsonWithRefs\n\ntype Depth = [never, 0, 1, 2, 3, 4]\n\ntype FromSchema = [D] extends [never]\n ? Json\n : S extends { enum: readonly (infer E)[] }\n ? E\n : S extends { type: \u0027object\u0027; properties: infer P }\n ? { [K in keyof P]: FromSchema }\n : S extends { type: \u0027array\u0027; items: infer I }\n ? FromSchema[]\n : S extends { type: \u0027string\u0027 }\n ? string\n : S extends { type: \u0027number\u0027 | \u0027integer\u0027 }\n ? number\n : S extends { type: \u0027boolean\u0027 }\n ? boolean\n : Json\n\n/**\n * The outputs a literal `responseFormat` adds, read from its JSON Schema with recursion capped at\n * depth 4. A template or reference adds untyped JSON.\n */\nexport type ResponseFormatOutput = [RF] extends [undefined]\n ? unknown\n : RF extends { schema: infer S }\n ? FromSchema\n : RF extends { type: \u0027object\u0027; properties: object }\n ? FromSchema\n : { [key: string]: Json }\n"