diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 273001782dc..acee6ef0e6c 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8698,7 +8698,7 @@ sim workflows source create [options] -Exit codes: 0 created (or a clean dry run, or a starter written); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflow name is taken (SOURCE_NAME_TAKEN: pass --name), or the command failed (a starter is created in the workspace its types were written for unless --workspace names another); 6 the folder is locked; 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was created: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was created (run the same command with --yes); 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 created (or a clean dry run, or a starter written); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflow name is taken (SOURCE_NAME_TAKEN: pass --name), or the command failed (a starter is created in the workspace its types were written for unless --workspace or SIM_WORKSPACE names another); 6 the folder is locked; 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was created: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was created (run the same command with --yes); 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. API request and response schemas: [createWorkflowFromSource](/api-reference/workflows/createWorkflowFromSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getSourceResources](/api-reference/workflows/getSourceResources), [deployWorkflow](/api-reference/workflows/deployWorkflow), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment). @@ -10053,7 +10053,7 @@ sim workspaces source get [options] A directory that already holds a .sim/base.json is refreshed from the workspace it was read from, whatever the profile's default workspace. -Exit codes: 0 written; 1 the command failed, the directory holds edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force), --workspace names another workspace than the one the directory was read from (SOURCE_OTHER_WORKSPACE), the directory is a workflow source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or a downloaded binary file does not match its listing (SOURCE_BLOB_MISMATCH: nothing was written); 9 rate limited (HTTP 429) after the CLI's retries: nothing was written, the binary files already downloaded are kept in .sim/downloads, and running the get again downloads only the rest; 10 (busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was read or written, run `sim login` and the get again. +Exit codes: 0 written; 1 the command failed, the directory holds edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force), --workspace or SIM_WORKSPACE names another workspace than the one the directory was read from (SOURCE_OTHER_WORKSPACE), the directory is a workflow source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or a downloaded binary file does not match its listing (SOURCE_BLOB_MISMATCH: nothing was written); 9 rate limited (HTTP 429) after the CLI's retries: nothing was written, the binary files already downloaded are kept in .sim/downloads, and running the get again downloads only the rest; 10 (busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was read or written, run `sim login` and the get again. API request and response schemas: [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getSourceResources](/api-reference/workflows/getSourceResources), [downloadFile](/api-reference/files/downloadFile), [downloadKnowledgeDocument](/api-reference/knowledge-bases/downloadKnowledgeDocument). @@ -10083,7 +10083,7 @@ sim workspaces source apply [options] -Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing; 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace or SIM_WORKSPACE names (SOURCE_OTHER_WORKSPACE: drop it, or promote it with --to; without either an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing; 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. API request and response schemas: [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource), [findMissingWorkspaceSourceBlobs](/api-reference/workflows/findMissingWorkspaceSourceBlobs), [stageWorkspaceSourceBlobs](/api-reference/workflows/stageWorkspaceSourceBlobs), [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment). diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 406609a9d65..b21e98f0ed3 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1440,7 +1440,7 @@ sim workflows source create [options] -Exit codes: 0 created (or a clean dry run, or a starter written); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflow name is taken (SOURCE_NAME_TAKEN: pass --name), or the command failed (a starter is created in the workspace its types were written for unless --workspace names another); 6 the folder is locked; 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was created: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was created (run the same command with --yes); 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 created (or a clean dry run, or a starter written); 1 the source has errors (each printed as file:line:column with its frame and hint), the workflow name is taken (SOURCE_NAME_TAKEN: pass --name), or the command failed (a starter is created in the workspace its types were written for unless --workspace or SIM_WORKSPACE names another); 6 the folder is locked; 7 the source is too large; 9 rate limited (HTTP 429) after the CLI's retries, so nothing was created: wait a minute and run it again; 10 (busy, retry) another sim command is using --dir, or the workspace directory it is a workflow folder of (SOURCE_DIR_BUSY): nothing was read or written, run it again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was created (run the same command with --yes); 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. API request and response schemas: [createWorkflowFromSource](/api-reference/workflows/createWorkflowFromSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getSourceResources](/api-reference/workflows/getSourceResources), [deployWorkflow](/api-reference/workflows/deployWorkflow), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment). diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index 4ee1e4b049a..897cc24d62c 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -708,7 +708,7 @@ sim workspaces source get [options] A directory that already holds a .sim/base.json is refreshed from the workspace it was read from, whatever the profile's default workspace. -Exit codes: 0 written; 1 the command failed, the directory holds edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force), --workspace names another workspace than the one the directory was read from (SOURCE_OTHER_WORKSPACE), the directory is a workflow source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or a downloaded binary file does not match its listing (SOURCE_BLOB_MISMATCH: nothing was written); 9 rate limited (HTTP 429) after the CLI's retries: nothing was written, the binary files already downloaded are kept in .sim/downloads, and running the get again downloads only the rest; 10 (busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was read or written, run `sim login` and the get again. +Exit codes: 0 written; 1 the command failed, the directory holds edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force), --workspace or SIM_WORKSPACE names another workspace than the one the directory was read from (SOURCE_OTHER_WORKSPACE), the directory is a workflow source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or a downloaded binary file does not match its listing (SOURCE_BLOB_MISMATCH: nothing was written); 9 rate limited (HTTP 429) after the CLI's retries: nothing was written, the binary files already downloaded are kept in .sim/downloads, and running the get again downloads only the rest; 10 (busy, retry) another sim workspaces source or workflows source command is using this directory or a workflow folder in it (SOURCE_DIR_BUSY): nothing was read or written, run it again once it finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was read or written, run `sim login` and the get again. API request and response schemas: [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getSourceResources](/api-reference/workflows/getSourceResources), [downloadFile](/api-reference/files/downloadFile), [downloadKnowledgeDocument](/api-reference/knowledge-bases/downloadKnowledgeDocument). @@ -762,7 +762,7 @@ sim workspaces source apply [options] -Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing; 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. +Exit codes: 0 applied (or a clean dry run); 1 the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace or SIM_WORKSPACE names (SOURCE_OTHER_WORKSPACE: drop it, or promote it with --to; without either an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed; 5 a resource changed or was deleted on the server since the directory was read (SOURCE_STALE: get it again into a fresh directory, reapply the edit, retry); 6 a resource (a workflow or its folder, a table) is locked (a locked block exits 1, E_APPLY_LOCKED_BLOCK); 7 the directory is too large; 8 the apply stopped part-way on a server failure: what was written is saved into the directory, and applying again continues. An apply a resource refused part-way (stale, locked, forbidden) saves what was written too, and exits as that refusal: 5, 6 or 1; 9 rate limited (HTTP 429) after the CLI's retries, before anything was written: wait a minute and apply again (binary files already uploaded are not sent again); 10 another apply is writing the workspace (SOURCE_BUSY), or another command is using the directory (SOURCE_DIR_BUSY): nothing was written, run the command again once the other finished; 13 not logged in, the login expired, or the server refused the credential (AUTH_REQUIRED): nothing was sent, run `sim login` (or fix or unset SIM_API_KEY when the key comes from it) and the command again; 14 without --yes and with no terminal to ask: the plan was printed with no errors and nothing was written (run the same command with --yes to apply it); 15 written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing; 130 interrupted (Ctrl-C): a write already sent is finished and saved into the directory first, waiting up to 60s for its answer, and a second Ctrl-C, or no answer by then, stops at once and prints that it may have been written and how to check. API request and response schemas: [applyWorkspaceSource](/api-reference/workflows/applyWorkspaceSource), [findMissingWorkspaceSourceBlobs](/api-reference/workflows/findMissingWorkspaceSourceBlobs), [stageWorkspaceSourceBlobs](/api-reference/workflows/stageWorkspaceSourceBlobs), [getWorkspaceSource](/api-reference/workflows/getWorkspaceSource), [getSourceCatalog](/api-reference/catalog/getSourceCatalog), [getWorkflowDeployment](/api-reference/workflows/getWorkflowDeployment). diff --git a/apps/docs/content/docs/workflows/code/how-it-works.mdx b/apps/docs/content/docs/workflows/code/how-it-works.mdx index da27f0d19f0..8241a7bd726 100644 --- a/apps/docs/content/docs/workflows/code/how-it-works.mdx +++ b/apps/docs/content/docs/workflows/code/how-it-works.mdx @@ -31,7 +31,7 @@ The stored workflow and the file are two views of one canonical form, so a round Some state has no syntax in the file. Sim keeps it from the stored workflow on every apply: -- **Layout.** Block positions stay in Sim. A new block is placed automatically. Moving blocks never makes a directory stale. +- **Layout.** Block positions stay in Sim. `.sim/lock.json` keeps a copy, used only to place a block the target does not hold yet (a promotion or a fresh create); a new block is placed automatically. Moving blocks never makes a directory stale. - **Settings that do not run.** A value in a field that the block's current choices hide stays stored, so switching back in the workflow builder brings it back. - **Comments.** Comments in `workflow.ts` are stored with the workflow, by block, so a builder edit or a rename keeps them. diff --git a/apps/sim/lib/workflows/application/read-workflow-source.ts b/apps/sim/lib/workflows/application/read-workflow-source.ts index ee66f0cd412..56fa44f90c6 100644 --- a/apps/sim/lib/workflows/application/read-workflow-source.ts +++ b/apps/sim/lib/workflows/application/read-workflow-source.ts @@ -4,6 +4,7 @@ import { mapWithConcurrency } from '@sim/utils/concurrency' import { compareStrings } from '@sim/utils/string' import { type CanonicalWorkflow, + calledWorkflowKeys, type Diagnostic, type SourceBase, type SourceFingerprint, @@ -36,6 +37,13 @@ import { loadWorkflowGraphs, } from '@/lib/workflows/application/read-workflow-graph' import { recordSourceRead } from '@/lib/workflows/application/source-analytics' +import { + type ChildResultsMemo, + loadChildGraphs, + loadChildResultsFrom, + type StoredGraphs, + storedChildWorkflowIds, +} from '@/lib/workflows/application/source-child-results' import type { WorkflowSourceDiagnostic } from '@/lib/workflows/application/source-error' import { buildSourceCatalog, storedCatalogTypes } from '@/lib/workflows/code/catalog/workspace' import { @@ -230,11 +238,16 @@ interface LoadedSource { gate: CatalogGate sourceMeta: WorkflowSourceMetaV1 | null prefetched: PrefetchedStoredResources + /** The child workflows read for this read, shared by the workflows a batched read prints. */ + childMemo: ChildResultsMemo + /** The graphs of the workflows this one may call ({@link storedChildWorkflowIds}), by id. */ + childGraphs: StoredGraphs } /** * Prints a loaded workflow as source: builds its catalog, canonicalizes the stored graph with its - * resource keys and prints it with its source meta, refusing one over `SOURCE_LIMITS`. + * resource keys and prints it with its source meta and the result fields of the children it calls + * (as an apply of the printed source types them), refusing one over `SOURCE_LIMITS`. */ async function printLoadedSource( loaded: LoadedSource, @@ -252,6 +265,17 @@ async function printLoadedSource( { organizationId: scope.workspaceOrganizationId, gate, prefetched, stored: loaded.stored }, async ({ canonical, resources }, catalog) => { const canonicalHash = storedCanonicalHash(canonical, resources) + const childResults = await loadChildResultsFrom( + { + workspaceId: scope.workspaceId, + workspaceOrganizationId: scope.workspaceOrganizationId, + gate, + memo: loaded.childMemo, + }, + calledWorkflowKeys(canonical.workflow), + loaded.childGraphs, + (key) => resources.toId('workflow', key) + ) const printed = printStoredSource({ state, meta, @@ -260,6 +284,7 @@ async function printLoadedSource( sourceMeta, functionCode, lockless: canonical, + childResults, }) assertFitsSourceLimits(printed, counts) return { @@ -297,8 +322,14 @@ export const readWorkflowSource = defineAuthorizedWorkflowUseCase({ operation: workflowOperations.readSource, resolveContext: resolvePrincipalWorkflowContext, async execute({ principal, input, context }): Promise { - const [stored, gate, sourceMeta, prefetched] = await Promise.all([ - loadStoredSource(context), + const [{ stored, childGraphs }, gate, sourceMeta, prefetched] = await Promise.all([ + loadStoredSource(context).then(async (stored) => ({ + stored, + childGraphs: await loadChildGraphs( + context.workspaceId, + storedChildWorkflowIds(Object.values(stored.state.blocks)) + ), + })), resolveCatalogGate(principal, context, { customBlockInputs: true }), readWorkflowSourceMeta(db, context.workflowId), prefetchStoredResources({ @@ -309,7 +340,7 @@ export const readWorkflowSource = defineAuthorizedWorkflowUseCase({ }), ]) const read = await printLoadedSource( - { scope: context, stored, gate, sourceMeta, prefetched }, + { scope: context, stored, gate, sourceMeta, prefetched, childMemo: new Map(), childGraphs }, input.functionCode ?? 'files' ) if (!input.plan) recordSourceRead(principal, context) @@ -370,6 +401,14 @@ export const readWorkflowSources = defineAuthorizedWorkflowUseCase({ input.workflowIds ), ]) + const childGraphs = await loadChildGraphs( + workspaceId, + [...graphs.values()].flatMap((loaded) => + storedChildWorkflowIds(Object.values(loaded.graph.blocks)) + ), + graphs + ) + const childMemo: ChildResultsMemo = new Map() const printed = await mapWithConcurrency( input.workflowIds, PRINT_CONCURRENCY, @@ -392,6 +431,8 @@ export const readWorkflowSources = defineAuthorizedWorkflowUseCase({ gate, sourceMeta: sourceMetas.get(workflowId) ?? null, prefetched: { ...prefetched, workflowId }, + childMemo, + childGraphs, }, 'files' ) diff --git a/apps/sim/lib/workflows/application/source-child-results.ts b/apps/sim/lib/workflows/application/source-child-results.ts new file mode 100644 index 00000000000..82ecdfe7cc1 --- /dev/null +++ b/apps/sim/lib/workflows/application/source-child-results.ts @@ -0,0 +1,284 @@ +/** + * How the server types a child workflow call's `>` in a JSON field: by + * the fields the child's Response data holds (`childResultFields`), read from the child's draft + * as stored, or as the workspace source apply that holds the call submits it, each typed in turn + * by the workflows it calls (`resolveChildResults`). Every source compile and print of a workflow + * goes through the same reading, so a get prints a reference in the form the next apply stores + * again, and a workspace directory's check (which reads the children from the directory the same + * way) agrees with both. + */ +import { + type ChildResultFields, + type ChildResultNode, + canonicalize, + canonicalResultNode, + compiledResultNode, + folderCompileInput, + parseWorkflowLock, + type ResourceKeyResolver, + resolveChildResults, +} from '@sim/workflow-code' +import { SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits' +import type { BlockState } from '@sim/workflow-types/workflow' +import { type CatalogGate, withCatalogBlockScope } from '@/lib/catalog/application/context' +import { loadWorkflowGraphs } from '@/lib/workflows/application/read-workflow-graph' +import { buildSourceCatalog, storedCatalogTypes } from '@/lib/workflows/code/catalog/workspace' +import { resolveIds, resolveKeys } from '@/lib/workspaces/resource-keys' + +/** A child's typed result fields, or `null` when it can end without responding or is unreadable. */ +type ChildFields = ChildResultFields | null + +/** + * One request's readings of child workflows by key, each read at most once: a workspace apply + * shares one across every workflow it evaluates. + */ +export type ChildResultsMemo = Map> + +/** A workflow folder as a workspace source apply submits it: its files and `.sim/lock.json`. */ +interface ChildSource { + files: Readonly> + lock: unknown +} + +/** + * The workflow folders a workspace source apply writes with files, by key: a workflow calling + * one is typed by the child's Response data as the folder holds it, as the directory's check + * types it, not as stored. + */ +export type ChildSources = ReadonlyMap + +export interface ChildResultsScope { + workspaceId: string + workspaceOrganizationId: string | null + /** The caller's catalog gate, which the children are compiled or canonicalized under. */ + gate: CatalogGate + memo: ChildResultsMemo + /** The folders the enclosing workspace source apply writes: such a child is read as submitted. */ + submitted?: ChildSources +} + +/** Stored workflow graphs by id, as `loadWorkflowGraphs` reads them. */ +export type StoredGraphs = Awaited> + +/** One stored workflow graph, as `loadWorkflowGraphs` reads it. */ +type StoredGraph = NonNullable> + +/** Graphs a read already loaded, and the workflow each child key resolves to for it. */ +interface LoadedChildren { + graphs: StoredGraphs + toId: (key: string) => string | null +} + +/** + * A submitted folder compiled as the directory's check compiles it ({@link folderCompileInput}): + * continuing the stored workflow its lock binds, so a `stored()` param compiles unread, against + * the catalog the child's own apply compiles it with: the workspace catalog plus the types its + * stored draft holds (`stored`, absent for a workflow the apply creates). + */ +function submittedNode( + source: ChildSource, + stored: StoredGraph | undefined, + scope: ChildResultsScope +): ChildResultNode | null { + const entry = source.files[SOURCE_ENTRY_FILE] + if (entry === undefined) return null + const catalog = buildSourceCatalog({ + gate: scope.gate, + organizationId: scope.workspaceOrganizationId, + storedTypes: storedCatalogTypes(Object.values(stored?.graph.blocks ?? {})), + }) + const lock = source.lock === undefined ? undefined : parseWorkflowLock(source.lock).lock + return compiledResultNode(folderCompileInput(entry, source.files, lock, catalog)) +} + +/** + * A stored workflow canonicalized under its own source catalog, with only the workflows it calls + * lifted to their keys: no Response field's type depends on any other resource's key. + */ +function storedNode( + loaded: StoredGraph, + workflowKeys: ReadonlyMap, + scope: ChildResultsScope +): ChildResultNode { + const { blocks, edges, loops, parallels, variables } = loaded.graph + const catalog = buildSourceCatalog({ + gate: scope.gate, + organizationId: scope.workspaceOrganizationId, + storedTypes: storedCatalogTypes(Object.values(blocks)), + }) + const resources: ResourceKeyResolver = { + toKey: (kind, id) => (kind === 'workflow' ? (workflowKeys.get(id) ?? null) : null), + toId: () => null, + } + const { workflow } = canonicalize( + { blocks, edges, loops, parallels, variables }, + { catalog, meta: { name: loaded.name, description: loaded.description ?? null }, resources } + ) + return canonicalResultNode(workflow, catalog) +} + +/** + * The stored graph of each workflow `keys` name in the workspace, by key (one the workspace does + * not hold, or holds archived, is left out): from `loaded` when it holds the graph a key resolves + * to, else read in one query. + */ +async function keyedGraphs( + keys: readonly string[], + scope: ChildResultsScope, + loaded: LoadedChildren | undefined +): Promise> { + const ids = new Map() + for (const key of keys) { + const id = loaded ? loaded.toId(key) : null + if (id !== null && loaded?.graphs.has(id)) ids.set(key, id) + } + const unloaded = keys.filter((key) => !ids.has(key)) + if (unloaded.length > 0) { + const resolved = + ( + await resolveIds( + scope.workspaceId, + unloaded.map((key) => ({ kind: 'workflow' as const, key })) + ) + ).get('workflow') ?? new Map() + for (const [key, id] of resolved) ids.set(key, id) + } + const graphs = await loadChildGraphs(scope.workspaceId, [...ids.values()], loaded?.graphs) + const byKey = new Map() + for (const [key, id] of ids) { + const graph = graphs.get(id) + if (graph) byKey.set(key, graph) + } + return byKey +} + +/** The node of each stored workflow `graphs` holds, by key ({@link storedNode}). */ +async function storedNodes( + graphs: ReadonlyMap, + scope: ChildResultsScope +): Promise> { + const calledIds = [...graphs.values()].flatMap((graph) => + storedChildWorkflowIds(Object.values(graph.graph.blocks)) + ) + const workflowKeys = + calledIds.length === 0 + ? new Map() + : (( + await resolveKeys( + scope.workspaceId, + calledIds.map((id) => ({ kind: 'workflow' as const, id })), + { allocate: false } + ) + ).get('workflow') ?? new Map()) + const nodes = new Map() + for (const [key, graph] of graphs) nodes.set(key, storedNode(graph, workflowKeys, scope)) + return nodes +} + +/** + * The fields of each workflow `keys` name and every workflow they reach by calls, by key: read + * level by level (a submitted folder as submitted, any other as stored), then resolved callees + * first ({@link resolveChildResults}). + */ +async function readChildResults( + scope: ChildResultsScope, + keys: readonly string[], + loaded: LoadedChildren | undefined +): Promise> { + const nodes = new Map() + let frontier = [...new Set(keys)] + while (frontier.length > 0) { + const graphs = await keyedGraphs(frontier, scope, loaded) + const stored = new Map([...graphs].filter(([key]) => !scope.submitted?.has(key))) + const read = stored.size > 0 ? await storedNodes(stored, scope) : new Map() + for (const key of frontier) { + const source = scope.submitted?.get(key) + nodes.set( + key, + source ? submittedNode(source, graphs.get(key), scope) : (read.get(key) ?? null) + ) + } + const next = new Set(frontier.flatMap((key) => nodes.get(key)?.calls ?? [])) + frontier = [...next].filter((key) => !nodes.has(key)) + } + const present = new Map() + for (const [key, node] of nodes) if (node) present.set(key, node) + const resolved = resolveChildResults(present) + return new Map([...nodes.keys()].map((key) => [key, resolved.get(key) ?? null])) +} + +/** + * The ids of the workflows stored `blocks` may run as children (each `workflowId` value), for a + * read to load their graphs with its own: a superset of the calls its canonical model names. + */ +export function storedChildWorkflowIds(blocks: Iterable): string[] { + const ids = new Set() + for (const block of blocks) { + const value = block.subBlocks?.workflowId?.value + if (typeof value === 'string' && value !== '') ids.add(value) + } + return [...ids] +} + +/** + * Loads the graphs of the workflows `ids` name that `loaded` lacks, in one read, and returns them + * with `loaded`'s ({@link storedChildWorkflowIds}). + */ +export async function loadChildGraphs( + workspaceId: string, + ids: readonly string[], + loaded: StoredGraphs = new Map() +): Promise { + const missing = [...new Set(ids)].filter((id) => !loaded.has(id)) + if (missing.length === 0) return loaded + return new Map([...loaded, ...(await loadWorkflowGraphs(workspaceId, missing))]) +} + +/** + * The typed result fields of each child workflow `keys` name that always responds, by key: a + * child the enclosing apply submits as submitted, any other as its stored draft in the workspace + * (one the workspace does not hold, or holds archived, is left out), each typed by the workflows + * it calls in turn. Each key is read once per `scope.memo`; the workflows a reading reaches + * through calls are kept there too. + */ +export async function loadChildResults( + scope: ChildResultsScope, + keys: readonly string[], + loaded?: LoadedChildren +): Promise> { + const unread = keys.filter((key) => !scope.memo.has(key)) + if (unread.length > 0) { + const reading = withCatalogBlockScope(scope.gate, async () => { + const fields = await readChildResults(scope, unread, loaded) + for (const [key, value] of fields) { + if (!scope.memo.has(key)) scope.memo.set(key, Promise.resolve(value)) + } + return fields + }) + for (const key of unread) { + scope.memo.set( + key, + reading.then((fields) => fields.get(key) ?? null) + ) + } + } + const read = await Promise.all(keys.map(async (key) => [key, await scope.memo.get(key)] as const)) + const results = new Map() + for (const [key, fields] of read) if (fields) results.set(key, fields) + return results +} + +/** + * {@link loadChildResults} for a read of stored workflows that loaded their children's graphs with + * {@link loadChildGraphs} (`toId` names the workflow a key resolves to): a child whose graph is + * there is read from there, any other (a workflow those children call, or a key `toId` does not + * resolve) as {@link loadChildResults} reads it. + */ +export function loadChildResultsFrom( + scope: ChildResultsScope, + keys: readonly string[], + graphs: StoredGraphs, + toId: (key: string) => string | null +): Promise> { + return loadChildResults(scope, keys, { graphs, toId }) +} diff --git a/apps/sim/lib/workflows/application/source-pipeline/evaluate/compile.ts b/apps/sim/lib/workflows/application/source-pipeline/evaluate/compile.ts index 9095c160720..94c1d8a4c44 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/evaluate/compile.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/evaluate/compile.ts @@ -1,6 +1,7 @@ import { type CanonicalizeResult, type CanonicalWorkflowMeta, + calledWorkflowKeys, canonicalizeUnderLock, type Diagnostic, parseWorkflowLock, @@ -33,12 +34,15 @@ export interface CompiledSubmission { /** * Parses the submitted lock and compiles the files against the live catalog and the stored graph - * read under that lock. Refuses a lock that does not parse, or a source that does not compile - * (noting a catalog that moved since the read, which can explain the errors). + * read under that lock, typing child calls' results by the fields of the children the compiled + * source calls (`input.loadChildResults`): a compile names its calls only once it has run, so a + * source calling a child that responds is compiled again with those fields (the lock and the + * stored graph are read once). Refuses a lock that does not parse, or a source that does not + * compile (noting a catalog that moved since the read, which can explain the errors). */ -export function compileSubmission( +export async function compileSubmission( input: SourceEvaluationInput -): { refused: WorkflowSourceDiagnostic[] } | CompiledSubmission { +): Promise<{ refused: WorkflowSourceDiagnostic[] } | CompiledSubmission> { const { catalog, files } = input const parsedLock = parseWorkflowLock(input.lock) @@ -47,9 +51,8 @@ export function compileSubmission( } const lock = parsedLock.lock - const { state } = input.stored const storedCanonical = canonicalizeUnderLock( - state, + input.stored.state, { catalog, meta: input.stored.meta, resources: input.storedCanonical.resources }, input.storedCanonical.canonical, lock @@ -65,6 +68,24 @@ export function compileSubmission( ]), envNames: input.envNames, } + const read = { lock, storedCanonical, compileInput } + + const untyped = compileUnder(input, read) + if ('refused' in untyped || !input.loadChildResults) return untyped + const called = calledWorkflowKeys(untyped.compiledWorkflow) + if (called.length === 0) return untyped + const childResults = await input.loadChildResults(called) + if (childResults.size === 0) return untyped + return compileUnder(input, { ...read, compileInput: { ...compileInput, childResults } }) +} + +/** Compiles the files under the lock and stored graph {@link compileSubmission} read. */ +function compileUnder( + input: SourceEvaluationInput, + read: Pick +): { refused: WorkflowSourceDiagnostic[] } | CompiledSubmission { + const { catalog, files } = input + const { lock, storedCanonical, compileInput } = read const compiled = compileSource({ ...compileInput, stored: storedCanonical.workflow, lock }) const compiledWorkflow = compiled.workflow if (!compiledWorkflow || hasErrors(compiled.diagnostics)) { diff --git a/apps/sim/lib/workflows/application/source-pipeline/evaluate/finalize.ts b/apps/sim/lib/workflows/application/source-pipeline/evaluate/finalize.ts index 179f91d8d64..445414c8dde 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/evaluate/finalize.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/evaluate/finalize.ts @@ -329,6 +329,9 @@ export async function finalizePlan( resources: resolved.resources, references: compiledKeys, envReferences: compiled.envReferences, + ...(submission.compileInput.childResults + ? { childResults: submission.compileInput.childResults } + : {}), }, } } diff --git a/apps/sim/lib/workflows/application/source-pipeline/evaluate/run.ts b/apps/sim/lib/workflows/application/source-pipeline/evaluate/run.ts index a00f70f55cc..25af66bde55 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/evaluate/run.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/evaluate/run.ts @@ -16,7 +16,7 @@ import type { * in the submitted text, or the plan the write stores. */ export async function evaluateSource(input: SourceEvaluationInput): Promise { - const submission = compileSubmission(input) + const submission = await compileSubmission(input) if ('refused' in submission) return { refused: submission.refused } const resolved = await resolveSubmission(input, submission) if ('refused' in resolved) return resolved diff --git a/apps/sim/lib/workflows/application/source-pipeline/evaluate/types.ts b/apps/sim/lib/workflows/application/source-pipeline/evaluate/types.ts index aa332764e90..025ef5ccef6 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/evaluate/types.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/evaluate/types.ts @@ -3,6 +3,7 @@ import type { BlockCatalog, CanonicalWorkflow, CanonicalWorkflowMeta, + ChildResultFields, LockIdentity, ResourceKeyResolver, ResourceKind, @@ -62,6 +63,12 @@ export interface SourceEvaluationInput { * created in the same apply resolves instead of failing `E_MAT_UNKNOWN_RESOURCE`. */ pendingResources?: readonly PendingResource[] + /** + * Reads the typed result fields of the child workflows the source calls, by key + * (`loadChildResults`), which type a call's `>`. Absent, those + * references are untyped. + */ + loadChildResults?: (keys: readonly string[]) => Promise> } /** @@ -128,6 +135,8 @@ export interface SourcePlan { references: SourceReference[] /** Every env name the submitted source reads, as the compiler read it. */ envReferences: string[] + /** The child result fields the compile typed with, which every print of the plan types with. */ + childResults?: ReadonlyMap } /** What the submitted source references, as the compiler read it. */ diff --git a/apps/sim/lib/workflows/application/source-pipeline/load.ts b/apps/sim/lib/workflows/application/source-pipeline/load.ts index 33f29a2a8e8..a371d092c5d 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/load.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/load.ts @@ -15,6 +15,10 @@ import { } from '@/lib/catalog/application/context' import type { ActiveWorkflowApplicationContext } from '@/lib/workflows/application/context' import { loadStoredSource } from '@/lib/workflows/application/read-workflow-source' +import type { + ChildResultsMemo, + ChildSources, +} from '@/lib/workflows/application/source-child-results' import type { SourceScope } from '@/lib/workflows/application/source-pipeline/evaluate' import { buildSourceCatalog, storedCatalogTypes } from '@/lib/workflows/code/catalog/workspace' import { type StoredSource, storedSourceFingerprint } from '@/lib/workflows/code/print-stored' @@ -73,6 +77,10 @@ export type SourceTarget = export interface SourceLoads { catalogGate?: Promise envNames?: Promise + /** The child workflows read to type their callers' results (`loadChildResults`). */ + childResults?: ChildResultsMemo + /** The workflow folders the workspace source apply writes, which its callers are typed by. */ + childSources?: ChildSources } /** Everything a plan reads before it evaluates: the stored draft, its catalog and fingerprint. */ diff --git a/apps/sim/lib/workflows/application/source-pipeline/outcome.ts b/apps/sim/lib/workflows/application/source-pipeline/outcome.ts index 17396801def..cef70da652a 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/outcome.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/outcome.ts @@ -114,6 +114,7 @@ export function printPlanned( identity: plan.identity, codeFiles, ...(lockless ? { lockless } : {}), + ...(plan.childResults ? { childResults: plan.childResults } : {}), }) } diff --git a/apps/sim/lib/workflows/application/source-pipeline/plan.ts b/apps/sim/lib/workflows/application/source-pipeline/plan.ts index a2c5e027911..adf25a781f3 100644 --- a/apps/sim/lib/workflows/application/source-pipeline/plan.ts +++ b/apps/sim/lib/workflows/application/source-pipeline/plan.ts @@ -9,6 +9,7 @@ import type { import { diagnostic } from '@sim/workflow-code/diagnostics' import { isEqual } from 'es-toolkit' import { withCatalogBlockScope } from '@/lib/catalog/application/context' +import { loadChildResults } from '@/lib/workflows/application/source-child-results' import { assertCreateNameFree } from '@/lib/workflows/application/source-commit' import { emptyDiffSummary, type SourceDiffSummary } from '@/lib/workflows/application/source-diff' import { @@ -264,6 +265,13 @@ export async function planSource( }) } + const childScope = { + workspaceId: scope.workspaceId, + workspaceOrganizationId: scope.workspaceOrganizationId, + gate: loaded.gate, + memo: options.loads ? (options.loads.childResults ??= new Map()) : new Map(), + ...(options.loads?.childSources ? { submitted: options.loads.childSources } : {}), + } const evaluation = await evaluateSource({ principal, scope, @@ -276,6 +284,7 @@ export async function planSource( files: submission.files, lock: submission.lock, ...(submission.pendingResources ? { pendingResources: submission.pendingResources } : {}), + loadChildResults: (keys) => loadChildResults(childScope, keys), ...(target.kind === 'existing' ? { base: target.base, allowDelete: target.allowDelete } : { create: target.create }), diff --git a/apps/sim/lib/workflows/code/print-stored.ts b/apps/sim/lib/workflows/code/print-stored.ts index 4aea2e05319..69bd73dc263 100644 --- a/apps/sim/lib/workflows/code/print-stored.ts +++ b/apps/sim/lib/workflows/code/print-stored.ts @@ -2,6 +2,7 @@ import { type BlockCatalog, type CanonicalizeResult, type CanonicalWorkflowMeta, + type ChildResultFields, canonicalDigests, canonicalHash, canonicalize, @@ -44,6 +45,11 @@ interface PrintStoredSourceInput extends StoredSource { * with the author's file names instead of deriving new ones from the idents. */ codeFiles?: Record + /** + * The typed result fields of the child workflows the state calls, by key: what the apply of the + * printed source types a call's `>` by (`loadChildResults`). + */ + childResults?: ReadonlyMap } /** A stored workflow printed as source, with the lock and freshness token that go with it. */ @@ -142,6 +148,7 @@ export function printStoredSource(input: PrintStoredSourceInput): PrintedSource catalog, hints: metaInputs.hints, options: { functionCode: input.functionCode }, + ...(input.childResults ? { childResults: input.childResults } : {}), }) return { files: Object.fromEntries(printed.files.map((file) => [file.path, file.text])), diff --git a/apps/sim/lib/workspace-source/application/cross-kind.integration.ts b/apps/sim/lib/workspace-source/application/cross-kind.integration.ts index af5c89493ab..4dce2ebfa37 100644 --- a/apps/sim/lib/workspace-source/application/cross-kind.integration.ts +++ b/apps/sim/lib/workspace-source/application/cross-kind.integration.ts @@ -33,6 +33,7 @@ import { } from '@sim/testing/mocks/uploads-setup.mock' import { generateId } from '@sim/utils/id' import { compareStrings } from '@sim/utils/string' +import { saveWorkflowToNormalizedTables } from '@sim/workflow-persistence/save' import { WORKSPACE_COOKBOOK } from '@sim/workflow-sdk/codegen' import type { WorkspaceBaseV1, WorkspaceKind } from '@sim/workspace-code' import { WORKSPACE_SOURCE_LIMITS } from '@sim/workspace-code/limits' @@ -74,8 +75,10 @@ import { setSecretUseCase } from '@/lib/secrets/application/use-cases' import { createSkillUseCase } from '@/lib/skills/application/use-cases' import { createTableUseCase, deleteTableUseCase } from '@/lib/table/application/tables' import { uploadWorkspaceFile } from '@/lib/uploads/contexts/workspace/file-manager' +import { applyWorkflowSource } from '@/lib/workflows/application/apply-workflow-source' import { deleteWorkflow } from '@/lib/workflows/application/delete-workflow' import { duplicateWorkflow } from '@/lib/workflows/application/duplicate-workflow' +import { readWorkflowSource } from '@/lib/workflows/application/read-workflow-source' import { loadWorkflowFromNormalizedTables } from '@/lib/workflows/persistence/utils' import { deleteWorkspaceFileOperation } from '@/lib/workspace-files/application/delete-workspace-file' import { withBoundWorkspaceFindings } from '@/lib/workspace-source/api/route-policies' @@ -1428,6 +1431,205 @@ export default workflow('Secret', {}, () => { expect(read.files['workflows/ping/workflow.ts']).toContain("childWorkflow('pong')") }) + check( + "types a call's result.data fields by the child's Response data, as submitted or as stored", + async () => { + const workspaceId = await newWorkspace() + const files = { + 'workflows/parent/workflow.ts': PHONE_PARENT, + 'workflows/normalize/workflow.ts': PHONE_CHILD, + } + + const dryRun = await apply(workspaceId, { files, blobs: {} }, { dryRun: true }) + expect(codes(dryRun.diagnostics, 'warning')).not.toContain('W_JSON_REF_UNTYPED') + const created = await apply(workspaceId, { files, blobs: {} }) + expect(created.failed).toBeUndefined() + const parentId = created.base.resources['workflow:parent']?.id + if (!parentId) throw new Error('The parent was not created') + expect(await responseData(parentId)).toEqual({ + mobile: '""', + digits: '', + }) + + const read = await get(workspaceId) + const printed = read.files['workflows/parent/workflow.ts'] + expect(printed).toContain( + 'body: { mobile: run.result.data.mobile, digits: run.result.data.digits }' + ) + const single = await withPermissionGroupScope(() => + readWorkflowSource.execute({ principal: owner, input: { workflowId: parentId } }) + ) + expect(single.files['workflow.ts']).toBe(printed) + + // A single-workflow apply types the call by the child as stored. + const edited = await withPermissionGroupScope(() => + applyWorkflowSource.execute({ + principal: owner, + input: { + workflowId: parentId, + files: { + ...single.files, + 'workflow.ts': printed.replace( + 'digits: run.result.data.digits', + 'digits: run.result.data.digits, again: run.result.data.mobile' + ), + }, + lock: single.lock, + base: single.base, + }, + }) + ) + expect(codes(edited.diagnostics, 'warning')).not.toContain('W_JSON_REF_UNTYPED') + expect(await responseData(parentId)).toEqual({ + mobile: '""', + digits: '', + again: '""', + }) + expect(edited.files['workflow.ts']).toContain('again: run.result.data.mobile,') + } + ) + + check( + 'types a call by a field its child forwards from a grandchild, on apply, get and reapply alike', + async () => { + const workspaceId = await newWorkspace() + const files = { + 'workflows/a/workflow.ts': forwarder('A', 'b'), + 'workflows/b/workflow.ts': forwarder('B', 'c'), + 'workflows/c/workflow.ts': TEXT_CHILD, + } + const typed = { text: '""', n: '' } + + const dryRun = await apply(workspaceId, { files, blobs: {} }, { dryRun: true }) + expect(codes(dryRun.diagnostics, 'warning')).not.toContain('W_JSON_REF_UNTYPED') + const created = await apply(workspaceId, { files, blobs: {} }) + expect(created.failed).toBeUndefined() + const id = (key: string) => { + const entry = created.base.resources[`workflow:${key}`] + if (!entry) throw new Error(`${key} was not created`) + return entry.id + } + expect(await responseData(id('a'))).toEqual(typed) + expect(await responseData(id('b'))).toEqual(typed) + + const read = await get(workspaceId) + const printed = read.files['workflows/a/workflow.ts'] + expect(printed).toContain('body: { text: call.result.data.text, n: call.result.data.n }') + const single = await withPermissionGroupScope(() => + readWorkflowSource.execute({ principal: owner, input: { workflowId: id('a') } }) + ) + expect(single.files['workflow.ts']).toBe(printed) + + // Every folder sent with its files, so each child is typed as submitted, through the chain. + const reapplied = await apply( + workspaceId, + { files: read.files, blobs: {} }, + { base: read.base } + ) + expect(reapplied.failed).toBeUndefined() + expect(codes(reapplied.diagnostics, 'warning')).not.toContain('W_JSON_REF_UNTYPED') + expect(await responseData(id('a'))).toEqual(typed) + } + ) + + check( + 'types a call by a child sent with a stored() secret, as the directory check types it', + async () => { + const workspaceId = await newWorkspace() + const files = { + 'workflows/parent/workflow.ts': PHONE_PARENT, + 'workflows/normalize/workflow.ts': SECRET_PHONE_CHILD, + } + const created = await apply(workspaceId, { files, blobs: {} }) + expect(created.failed).toBeUndefined() + const parentId = created.base.resources['workflow:parent']?.id + if (!parentId) throw new Error('The parent was not created') + const typed = { mobile: '""', digits: '' } + expect(await responseData(parentId)).toEqual(typed) + + const read = await get(workspaceId) + expect(read.files['workflows/normalize/workflow.ts']).toContain('apiKey: stored()') + const reapplied = await apply( + workspaceId, + { files: read.files, blobs: {} }, + { base: read.base } + ) + expect(reapplied.failed).toBeUndefined() + expect(codes(reapplied.diagnostics, 'warning')).not.toContain('W_JSON_REF_UNTYPED') + expect(await responseData(parentId)).toEqual(typed) + } + ) + + check( + 'types a call by a child sent holding a block type the workspace catalog no longer offers', + async () => { + const workspaceId = await newWorkspace() + const files = { + 'workflows/a/workflow.ts': forwarder('A', 'c'), + 'workflows/c/workflow.ts': TEXT_CHILD, + } + const created = await apply(workspaceId, { files, blobs: {} }) + expect(created.failed).toBeUndefined() + const parentId = created.base.resources['workflow:a']?.id + const childId = created.base.resources['workflow:c']?.id + if (!parentId || !childId) throw new Error('The workflows were not created') + + // `thinking` is hidden from the toolbar, so only the child's own catalog declares it. + const child = await loadWorkflowFromNormalizedTables(childId) + const blockOf = (type: string) => + Object.values(child?.blocks ?? {}).find((block) => block.type === type)?.id + const startId = blockOf('start_trigger') + const replyId = blockOf('response') + if (!child || !startId || !replyId) throw new Error('The child was not stored') + const thinkingId = generateId() + const saved = await saveWorkflowToNormalizedTables(childId, { + ...child, + edges: [ + ...child.edges, + { id: generateId(), source: startId, target: thinkingId }, + { id: generateId(), source: thinkingId, target: replyId }, + ], + blocks: { + ...child.blocks, + [thinkingId]: { + id: thinkingId, + type: 'thinking', + name: 'Ponder', + position: { x: 0, y: 200 }, + subBlocks: { thought: { id: 'thought', type: 'long-input', value: 'Think first' } }, + outputs: {}, + enabled: true, + }, + }, + }) + if (!saved.success) throw new Error(`Seeding the child failed: ${saved.error}`) + + const read = await get(workspaceId) + expect(read.files['workflows/c/workflow.ts']).toContain('Ponder') + const reapplied = await apply( + workspaceId, + { + files: { + ...read.files, + 'workflows/a/workflow.ts': read.files['workflows/a/workflow.ts'].replace( + 'n: call.result.data.n', + 'n: call.result.data.n, again: call.result.data.text' + ), + }, + blobs: {}, + }, + { base: read.base } + ) + expect(reapplied.failed).toBeUndefined() + expect(codes(reapplied.diagnostics, 'warning')).not.toContain('W_JSON_REF_UNTYPED') + expect(await responseData(parentId)).toEqual({ + text: '""', + n: '', + again: '""', + }) + } + ) + check( 'renaming the key of a table or a tool is reported as a key rename, not a taken name', async () => { @@ -1485,6 +1687,93 @@ export default workflow('Child', {}, () => { 'workflows/keep/workflow.ts': TEXT['workflows/keep/workflow.ts'], } +/** A child that always responds with a text `mobile` and a number `digits`. */ +const PHONE_CHILD = `// @sim-sdk 1 +import { response, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('Normalize', {}, () => { + const start = trigger.start('Start', { inputFormat: { phone: 'string', n: 'number' } }) + const reply = response('Reply', { body: { mobile: start.phone, digits: start.n } }) + start.to(reply) +}) +` + +/** A parent that responds with the fields of what `normalize` responds with. */ +const PHONE_PARENT = `// @sim-sdk 1 +import { childWorkflow, response, runWorkflow, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('Parent', {}, () => { + const start = trigger.start('Start', { inputFormat: { phone: 'string' } }) + const run = runWorkflow('Run', { + workflowId: childWorkflow('normalize'), + inputMapping: { phone: start.phone }, + }) + const reply = response('Reply', { + body: { mobile: run.result.data.mobile, digits: run.result.data.digits }, + }) + start.to(run) + run.to(reply) +}) +` + +/** A child that always responds with a text `text` and a number `n`. */ +const TEXT_CHILD = `// @sim-sdk 1 +import { response, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('C', {}, () => { + const start = trigger.start('Start', { inputFormat: { phone: 'string', n: 'number' } }) + const reply = response('Reply', { body: { text: start.phone, n: start.n } }) + start.to(reply) +}) +` + +/** A workflow that responds with the `text` and `n` the workflow under `child` responds with. */ +function forwarder(name: string, child: string): string { + return `// @sim-sdk 1 +import { childWorkflow, response, runWorkflow, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('${name}', {}, () => { + const start = trigger.start('Start', { inputFormat: { phone: 'string' } }) + const call = runWorkflow('Call', { + workflowId: childWorkflow('${child}'), + inputMapping: { phone: start.phone }, + }) + const reply = response('Reply', { + body: { text: call.result.data.text, n: call.result.data.n }, + }) + start.to(call) + call.to(reply) +}) +` +} + +/** {@link PHONE_CHILD} with an Agent on the way to its Response, holding a literal secret. */ +const SECRET_PHONE_CHILD = `// @sim-sdk 1 +import { agent, response, trigger, workflow } from '@sim/workflow-sdk' + +export default workflow('Normalize', {}, () => { + const start = trigger.start('Start', { inputFormat: { phone: 'string', n: 'number' } }) + const answer = agent('Answer', { model: 'gpt-4o', messages: [], apiKey: 'placeholder-not-a-real-key' }) + const reply = response('Reply', { body: { mobile: start.phone, digits: start.n } }) + start.to(answer) + answer.to(reply) +}) +` + +/** + * The Response data workflow `workflowId` stores, each field's raw JSON text by key: a quoted + * reference keeps its quotes, a bare one is the reference alone. + */ +async function responseData(workflowId: string): Promise> { + const loaded = await loadWorkflowFromNormalizedTables(workflowId) + const reply = Object.values(loaded?.blocks ?? {}).find((block) => block.type === 'response') + const data = reply?.subBlocks.data?.value + if (typeof data !== 'string') throw new Error('The Response block stores no data') + return Object.fromEntries( + [...data.matchAll(/"(\w+)": ("?<[^>]+>"?)/g)].map(([, key, value]) => [key, value]) + ) +} + /** The workflow ids the Run Workflow blocks of workflow `workflowId` store. */ async function runsWorkflow(workflowId: string): Promise { const loaded = await loadWorkflowFromNormalizedTables(workflowId) diff --git a/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts b/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts index cdb4422df52..d4511b3e614 100644 --- a/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts +++ b/apps/sim/lib/workspace-source/application/kinds/workflow/adapter.ts @@ -726,6 +726,13 @@ export const workflowAdapter: KindAdapter<'workflow', StoredWorkflowState> = { : [] ) const pending = [...ctx.pending, ...creates.map(({ created }) => created)] + ctx.loads.childSources = new Map( + [...desired].flatMap(([key, decl]) => + Object.keys(decl.files).length > 0 + ? [[key, { files: decl.files, lock: decl.lock }] as const] + : [] + ) + ) const names = new Map() const evaluatedCreates = new Map() await mapWithConcurrency(creates, PLAN_CONCURRENCY, async ({ step, created }) => { diff --git a/packages/sim-cli/scripts/print-source-primers.ts b/packages/sim-cli/scripts/print-source-primers.ts new file mode 100644 index 00000000000..911bd54f640 --- /dev/null +++ b/packages/sim-cli/scripts/print-source-primers.ts @@ -0,0 +1,15 @@ +/** + * Prints the workflow and workspace source primers as JSON, for the mothership worker's + * `workflow-source` skill. The text is the one `sim workflows source get` and `sim workspaces + * source get` write atop `.sim/AGENTS.md`, so the agent's preloaded guide never differs from the + * one the CLI gives a coding agent. + * + * bun run packages/sim-cli/scripts/print-source-primers.ts > primers.json + */ +import { type PrimerKind, sourcePrimer } from '#sim-cli/commands/protocol/source-primer' + +const KINDS: readonly PrimerKind[] = ['workflow', 'workspace'] + +const primers = Object.fromEntries(KINDS.map((kind) => [kind, sourcePrimer(kind)])) + +process.stdout.write(`${JSON.stringify(primers, null, 2)}\n`) diff --git a/packages/sim-cli/src/commands/auth.ts b/packages/sim-cli/src/commands/auth.ts index ce945ee507f..2734ebfd383 100644 --- a/packages/sim-cli/src/commands/auth.ts +++ b/packages/sim-cli/src/commands/auth.ts @@ -1119,7 +1119,15 @@ export function whoamiCommand(): Command { ...(verification.boundWorkspaceId ? [['Key bound to', safeOneLine(verification.boundWorkspaceId)] as [string, string]] : []), - ['Workspace', annotate(profile.workspaceId ?? '', sources.workspaceId)], + [ + 'Workspace', + annotate( + profile.workspaceId ?? '', + profile.workspaceDirectory + ? `source directory ${safeOneLine(profile.workspaceDirectory)}` + : sources.workspaceId + ), + ], ['Output', annotate(profile.output, sources.output)], ['Verified', presentVerification(verification)], ], @@ -1132,7 +1140,7 @@ export function whoamiCommand(): Command { sources: { endpoint: sources.endpoint, authentication: authentication.source, - workspaceId: sources.workspaceId, + workspaceId: profile.workspaceDirectory ? 'directory' : sources.workspaceId, output: sources.output, }, verification: { diff --git a/packages/sim-cli/src/commands/protocol/source-check.ts b/packages/sim-cli/src/commands/protocol/source-check.ts index b23b612214f..86bd4a41fd0 100644 --- a/packages/sim-cli/src/commands/protocol/source-check.ts +++ b/packages/sim-cli/src/commands/protocol/source-check.ts @@ -10,13 +10,19 @@ import { collectStringLeaves, findWorkflowReferenceTokens } from '@sim/utils/wor import { type BlockCatalog, type CanonicalWorkflow, + type ChildResultNode, + type ChildResults, + type CompileInput, + calledWorkflowKey, catalogBlock, codeFrame, codePointLabel, + compiledResultNode, compileWorkflow, didYouMean, EDIT_REFUSALS, encodeAnchor, + folderCompileInput, formatStoredPath, getOwn, parseJsonField, @@ -26,6 +32,7 @@ import { raisedMessage, refuseEditedFindings, refusesEdited, + resolveChildResults, respondsOnEveryRun, scriptName, startInputs, @@ -46,9 +53,11 @@ import { readSourceText, unchangedTexts, type Written, + workspaceFolderOf, } from './source-dir' import { STRICT_FINDINGS } from './source-strict' import { + cachedCatalog, cachedSourceCatalog, type LocalDeclarations, refreshTsconfigs, @@ -57,7 +66,12 @@ import { } from './source-tree' import { type TypeCheck, typeCheck } from './source-types' import { type Diagnostic, findingsOutput } from './source-ui' -import { blockDigest, readStoredBlockDigests, readStoredEdges } from './stored-edges' +import { + blockDigest, + compiledWithChildResults, + readStoredBlockDigests, + readStoredEdges, +} from './stored-edges' import { lockRecoveryHint, readSourceFiles } from './workflow-dir' import { type DeclaredColumn, @@ -255,13 +269,6 @@ function inputMappingOf(canonical: CanonicalWorkflow['blocks'][string]): Record< return toRecord(value) } -/** The workflow a child workflow call names by key, or `null` for an id, a reference or none. */ -function calledWorkflowKey(canonical: CanonicalWorkflow['blocks'][string]): string | null { - const ref = canonical.params.workflowId - const child = ref?.kind === 'value' ? resourceNode(ref.value) : null - return child?.kind === 'workflow' ? child.key : null -} - /** * A child workflow call checked against the child's own `workflow.ts` in this directory: a child * without a Start trigger (`W_CHILD_NO_START`), and an `inputMapping` key its Start trigger does @@ -462,13 +469,13 @@ function declarationFindings( /** * Compiles the workflow source directory `dir` against the catalog its base names when that one is * cached (a workflow holding a type the workspace catalog lacks was printed with its own), else - * `catalog`, checking env names against the names `secrets.ts` declares when `declarations` hold - * them. + * `catalog`, checking env names against `envNames` (what `secrets.ts` declares) when given. Its + * calls are untyped: {@link compiledWithChildResults} types them. */ async function compileWorkflowDir( dir: string, workspaceCatalog: BlockCatalog, - declarations?: WorkspaceDeclarations + envNames?: ReadonlySet ) { const lockText = await readSourceText(dir, SOURCE_LOCK_FILE) const parsedLock = lockText === null ? null : parseWorkflowLock(lockText) @@ -480,28 +487,25 @@ async function compileWorkflowDir( cachedSourceCatalog(dir), ]) const catalog = printedWith ?? workspaceCatalog - const envNames = declarations?.envNames - const compiled = compileWorkflow({ - entry: { path: SOURCE_ENTRY_FILE, text: files[SOURCE_ENTRY_FILE] }, - files: new Map(Object.entries(files).filter(([path]) => path !== SOURCE_ENTRY_FILE)), - catalog, - sdkMajor: catalog.sdkMajor, - knownKeys: new Set(Object.keys(lock?.blocks ?? {})), - storedUnread: lock ?? undefined, + const input: CompileInput = { + ...folderCompileInput(files[SOURCE_ENTRY_FILE], files, lock, catalog), ...(storedEdges ? { storedUnreadEdges: storedEdges } : {}), ...(envNames ? { envNames, envDeclaredIn: KIND_DIRS.secret } : {}), - }) + } return { lock, lockProblems: parsedLock?.diagnostics ?? [], files, - compiled, + input, + compiled: compileWorkflow(input), storedBlocks, printedWith, catalog, } } +type CompiledWorkflowDir = Awaited> + /** What {@link readCheckDeclarations} reads: the declarations and the compiled workflows' facts. */ type CheckDeclarations = WorkspaceDeclarations & Awaited> @@ -510,30 +514,59 @@ type CheckDeclarations = WorkspaceDeclarations & * The workspace directory `root`'s declarations, with what a child workflow call is checked * against from compiling each of its workflows: the inputs of each workflow that compiles * (`startInputs`, `null` without a Start trigger), which `workspace.d.ts` also types - * `inputMapping` with, and the keys of those that end at a Response block on every run, whose - * `result` is that block's output. + * `inputMapping` with, the keys of those that end at a Response block on every run, whose + * `result` is that block's output, and the typed fields of the data each of those responds with, + * which type a call's `>`. Each compile is kept (`compiledWorkflows`, by + * key) for {@link checkWorkflowDir}: env names change only its findings, never its blocks. */ export async function readCheckDeclarations( root: string, catalog: BlockCatalog ): Promise { - const [declared, workflows] = await Promise.all([ - readWorkspaceDeclarations(root), - compileWorkspaceWorkflows(root, catalog), - ]) - return { ...declared, ...workflows } + const declared = await readWorkspaceDeclarations(root) + return { ...declared, ...(await compileWorkspaceWorkflows(root, catalog, declared.envNames)) } } -async function compileWorkspaceWorkflows(root: string, catalog: BlockCatalog) { +async function compileWorkspaceWorkflows( + root: string, + catalog: BlockCatalog, + envNames?: ReadonlySet +) { const workflowInputs = new Map() const respondingWorkflows = new Set() + const nodes = new Map() + const compiledWorkflows = new Map() for (const key of await workspaceWorkflowKeys(root)) { - const { compiled } = await compileWorkflowDir(join(root, KIND_DIRS.workflow, key), catalog) - if (!compiled.workflow) continue - workflowInputs.set(key, startInputs(compiled.workflow)) - if (respondsOnEveryRun(compiled.workflow)) respondingWorkflows.add(key) + const dir = await compileWorkflowDir(join(root, KIND_DIRS.workflow, key), catalog, envNames) + compiledWorkflows.set(key, dir) + const { workflow } = dir.compiled + if (!workflow) continue + workflowInputs.set(key, startInputs(workflow)) + if (respondsOnEveryRun(workflow)) respondingWorkflows.add(key) + const node = compiledResultNode(dir.input, dir.compiled) + if (node) nodes.set(key, node) + } + const childResults = resolveChildResults(nodes) + return { workflowInputs, respondingWorkflows, childResults, compiledWorkflows } +} + +/** + * The child results that type the calls of a workflow written into `dir`, as a check of it types + * them: those of the workspace directory it is a workflow folder of, compiled from disk against + * the workspace's cached catalog; `undefined` for a workflow directory of its own, which has none. + * `null` when that directory cannot be read (a symbolic link in any of its workflow folders, say): + * they only type the folder's stored-edges record, a cache fill, so that record is skipped + * ({@link storedEdgesWrite}) and nothing else. + */ +export async function folderChildResults(dir: string): Promise { + try { + const folder = await workspaceFolderOf(dir) + const catalog = folder && cachedCatalog(folder.workspaceId) + if (!folder || !catalog) return undefined + return (await compileWorkspaceWorkflows(folder.root, catalog)).childResults + } catch { + return null } - return { workflowInputs, respondingWorkflows } } /** @@ -607,9 +640,22 @@ async function writtenWorkspaceTypes( export async function checkWorkflowDir( dir: string, catalog: BlockCatalog, - options: { declarations?: WorkspaceDeclarations; strict: StrictMode; prefix?: string } + options: { + declarations?: CheckDeclarations + strict: StrictMode + /** The key of the workflow folder `dir` is, whose compile `declarations` hold. */ + key?: string + prefix?: string + } ): Promise<{ findings: CheckFinding[]; entry: string; unlisted: UnlistedCounts }> { - const compiledDir = await compileWorkflowDir(dir, catalog, options.declarations) + const { declarations } = options + const untyped = + (options.key === undefined ? undefined : declarations?.compiledWorkflows.get(options.key)) ?? + (await compileWorkflowDir(dir, catalog, declarations?.envNames)) + const compiledDir = { + ...untyped, + compiled: compiledWithChildResults(untyped.input, untyped.compiled, declarations?.childResults), + } const { lock, lockProblems, files, compiled, storedBlocks, printedWith } = compiledDir const entryText = files[SOURCE_ENTRY_FILE] const locate = (block: string, param: string, names: string | undefined) => { diff --git a/packages/sim-cli/src/commands/protocol/source-dir/dir-kind.ts b/packages/sim-cli/src/commands/protocol/source-dir/dir-kind.ts index 5bfbcbed08d..83ae693c68a 100644 --- a/packages/sim-cli/src/commands/protocol/source-dir/dir-kind.ts +++ b/packages/sim-cli/src/commands/protocol/source-dir/dir-kind.ts @@ -8,7 +8,7 @@ import { toRecord } from '@sim/utils/object' import { SOURCE_BASE_FILE, SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits' import { KIND_DIRS } from '@sim/workspace-code' import type { Command } from 'commander' -import type { ResolvedProfile } from '../../../config/index' +import { explicitWorkspaceSetting, type ResolvedProfile } from '../../../config/index' import { embedStore } from '../../../embed-context' import { SourceDirError } from '../local-errors' import { readSourceJson, readSourceText } from './files' @@ -30,24 +30,24 @@ export function absoluteDirOption(command: Command): Command { /** * The workspace a source command acts on for a directory read from `readFrom`: that workspace, - * whatever the profile's default, so a directory stays bound to where it came from. Only a - * `--workspace` naming another one is refused, with `next` saying what to run instead (given the - * workspace the directory was read from and the one named). A directory that records no workspace - * takes the profile's (`null` when none is selected). + * whatever the profile's default, so a directory stays bound to where it came from. A + * `--workspace` or `SIM_WORKSPACE` naming another one is refused rather than ignored, with `next` + * saying what to run instead (given the workspace the directory was read from, the one named, and + * the setting that named it). A directory that records no workspace takes the resolved one (`null` + * when none is selected). */ export function directoryWorkspace( dir: string, readFrom: string | null, profile: Pick, - next: (readFrom: string, named: string) => string + next: (readFrom: string, named: string, setting: string) => string ): string | null { const named = profile.workspaceId if (readFrom === null) return named - if (profile.sources.workspaceId !== 'flag' || named === null || named === readFrom) { - return readFrom - } + const setting = explicitWorkspaceSetting(profile) + if (setting === null || named === null || named === readFrom) return readFrom throw new SourceDirError( - `${dir} was read from workspace ${readFrom}, but --workspace names ${named}. ${next(readFrom, named)}`, + `${dir} was read from workspace ${readFrom}, but ${setting} names ${named}. ${next(readFrom, named, setting)}`, { code: 'SOURCE_OTHER_WORKSPACE' } ) } @@ -98,21 +98,60 @@ export async function readStarterWorkspace(dir: string): Promise return typeof workspaceId === 'string' ? workspaceId : null } +/** The workspace a source directory names, and the directory whose record names it. */ +export interface NamedWorkspace { + workspaceId: string + /** `dir` itself, or the workspace directory it is a workflow folder of. */ + dir: string + /** Whether a starter's record names it, which an explicit workspace overrides. */ + starter: boolean +} + /** - * The workspace `dir` records it belongs to: the one its `.sim/base.json` was read from, else the + * The workspace `dir` names: the one its `.sim/base.json` was read from, else that of the * workspace directory it is a workflow folder of, else the one its starter's types were written - * for (`null` when none). A starter yields to a `--workspace` flag, which chooses another; a base - * or workspace folder does not ({@link directoryWorkspace} refuses that flag). + * for (`null` when none). The one definition of the workspace a directory names, for a source + * command's `--dir` ({@link recordedWorkspace}) and the directory any command runs in + * ({@link enclosingWorkspace}). + */ +async function namedWorkspace(dir: string): Promise { + const base = toRecord(await readSourceJson(dir, SOURCE_BASE_FILE)) + if (typeof base.workspaceId === 'string') { + return { workspaceId: base.workspaceId, dir, starter: false } + } + const folder = await workspaceFolderOf(dir) + if (folder) return { workspaceId: folder.workspaceId, dir: folder.root, starter: false } + const starter = await readStarterWorkspace(dir) + return starter === null ? null : { workspaceId: starter, dir, starter: true } +} + +/** + * The workspace `dir` records it belongs to ({@link namedWorkspace}). A starter yields to a + * `--workspace` or `SIM_WORKSPACE`, which chooses another; a base or workspace folder does not + * ({@link directoryWorkspace} refuses either). */ export async function recordedWorkspace( dir: string, profile: Pick ): Promise { - const base = toRecord(await readSourceJson(dir, SOURCE_BASE_FILE)) - if (typeof base.workspaceId === 'string') return base.workspaceId - const folder = await workspaceFolderOf(dir) - if (folder) return folder.workspaceId - return profile.sources.workspaceId === 'flag' ? null : readStarterWorkspace(dir) + const named = await namedWorkspace(dir) + if (!named || (named.starter && explicitWorkspaceSetting(profile) !== null)) return null + return named.workspaceId +} + +/** + * The workspace the nearest directory at or above `cwd` names ({@link namedWorkspace}), which a + * command run in `cwd` acts on unless `--workspace` or `SIM_WORKSPACE` names one; `null` when none + * up to the root names one. + */ +export async function enclosingWorkspace(cwd: string): Promise { + for (let dir = resolve(cwd); ; dir = dirname(dir)) { + // One whose records cannot be read (a symbolic link, no permission) names none: a directory + // above the one a command runs in, such as a linked `~/.sim`, must not stop the command. + const named = await namedWorkspace(dir).catch(() => null) + if (named) return named + if (dirname(dir) === dir) return null + } } /** diff --git a/packages/sim-cli/src/commands/protocol/source-dir/index.ts b/packages/sim-cli/src/commands/protocol/source-dir/index.ts index 8a3926f0902..0667c6cb9d2 100644 --- a/packages/sim-cli/src/commands/protocol/source-dir/index.ts +++ b/packages/sim-cli/src/commands/protocol/source-dir/index.ts @@ -16,6 +16,8 @@ export { absoluteDirOption, assertSourceDirKind, directoryWorkspace, + enclosingWorkspace, + type NamedWorkspace, readStarterWorkspace, recordedWorkspace, workspaceFolderOf, diff --git a/packages/sim-cli/src/commands/protocol/source-exit-codes.ts b/packages/sim-cli/src/commands/protocol/source-exit-codes.ts index 4040a106e12..c3f02b5ed65 100644 --- a/packages/sim-cli/src/commands/protocol/source-exit-codes.ts +++ b/packages/sim-cli/src/commands/protocol/source-exit-codes.ts @@ -106,14 +106,14 @@ export function sourceExitCodeRows(prefix: SourceCommandGroup): SourceExitCodeRo 'workflows source apply': "the source has errors (each printed as file:line:column with its frame and hint), the workflowId given is not the one .sim/base.json names (SOURCE_WORKFLOW_MISMATCH: the directory holds another workflow's source), or the command failed", 'workflows source create': - 'the source has errors (each printed as file:line:column with its frame and hint), the workflow name is taken (SOURCE_NAME_TAKEN: pass --name), or the command failed (a starter is created in the workspace its types were written for unless --workspace names another)', + 'the source has errors (each printed as file:line:column with its frame and hint), the workflow name is taken (SOURCE_NAME_TAKEN: pass --name), or the command failed (a starter is created in the workspace its types were written for unless --workspace or SIM_WORKSPACE names another)', 'workflows source get': "the command failed, the directory is a workspace source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or it holds another workflow's source (SOURCE_WORKFLOW_MISMATCH) or edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force)", 'workflows source status': 'the command failed', 'workspaces source apply': - 'the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed', + 'the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace or SIM_WORKSPACE names (SOURCE_OTHER_WORKSPACE: drop it, or promote it with --to; without either an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed', 'workspaces source get': - 'the command failed, the directory holds edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force), --workspace names another workspace than the one the directory was read from (SOURCE_OTHER_WORKSPACE), the directory is a workflow source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or a downloaded binary file does not match its listing (SOURCE_BLOB_MISMATCH: nothing was written)', + 'the command failed, the directory holds edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force), --workspace or SIM_WORKSPACE names another workspace than the one the directory was read from (SOURCE_OTHER_WORKSPACE), the directory is a workflow source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or a downloaded binary file does not match its listing (SOURCE_BLOB_MISMATCH: nothing was written)', 'workspaces source status': 'the command failed', }, }, diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index abfa3743da4..d342918e843 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -20,7 +20,7 @@ import { SOURCE_LOCAL_CHANGES_EXIT_CODE, SOURCE_STALE_EXIT_CODE, } from '../../exit-codes' -import { SOURCE_AGENTS_FILE } from './source-dir' +import { SOURCE_AGENTS_FILE, SOURCE_STARTER_FILE } from './source-dir' /** Which directory a primer is for. */ export type PrimerKind = 'workflow' | 'workspace' @@ -40,21 +40,21 @@ const PARAMS_COMMAND = 'sim workflows source params' /** The rules every source directory shares, after the kind's own edit loop. */ function sharedRules(group: string, extraRenames = ''): string { - return `- **Identity**: a block is its entry in \`${SOURCE_LOCK_FILE}\`, which binds it by its const name or its display name. Change the display name (first argument) freely: the apply rewrites every reference to it. Renaming the const too keeps it when settings, neighbours or references still tie it to the old block; otherwise the apply refuses a delete (\`E_APPLY_BLOCK_DELETE\`). -- **References**: in \`${SOURCE_ENTRY_FILE}\` read an output as \`x.content\`, a loop or parallel item as \`p.currentItem\` (\`p.index\`), a child workflow's response field as \`c.result.data.\`, text as \`\` t\`…\` \`\`, env as \`env.NAME\`. In a function file (\`codeFile('./functions/x.js')\`) read an output as \`$ref..\`, the key: the display name lowercased, whitespace and dots removed ("Triage Agent" → \`$ref.triageagent.content\`); in a loop body \`$ref.loop.currentItem\` / \`$ref.loop.index\` (a parallel: \`$ref.parallel.…\`); env as \`$env.NAME\`. In \`.py\`/\`.sh\` files write \`\` and \`{{NAME}}\`, not \`$ref\`/\`$env\`. Read an index or item only inside its container (\`E_APPLY_REF_OUT_OF_SCOPE\`), after it its \`.results\`. A \`$ref\` naming no block is an error in a function file you edited (\`E_APPLY_UNRESOLVED_REF\`). -- **Renames**: one variable per apply (two at once read as a delete and an add).${extraRenames} -- **Look up a builder**: \`${PARAMS_COMMAND} \` (a namespace like \`gmail\` lists them). + return `- **Identity**: a block is its entry in \`${SOURCE_LOCK_FILE}\`, bound by its const or its display name. Rename display names (first argument) or consts, any number per apply: apply rewrites each reference, \`$ref.\` in function files too. Renaming both (one block per apply) keeps it only if settings, neighbours or references still tie it to the old block, else it is a delete (\`E_APPLY_BLOCK_DELETE\`). +- **References**: in \`${SOURCE_ENTRY_FILE}\` read an output as \`x.content\`, a loop or parallel item as \`p.currentItem\` (\`p.index\`), a child's response field as \`c.result.data.\` (typed by its \`response\`), text as \`\` t\`…\` \`\`, env as \`env.NAME\`. In a function file (\`codeFile('./functions/x.js')\`) read an output as \`$ref..\`, the key: the display name lowercased, no whitespace or dots ("Triage Agent" → \`$ref.triageagent.content\`); in a loop body \`$ref.loop.currentItem\` / \`$ref.loop.index\` (a parallel: \`$ref.parallel.…\`); env as \`$env.NAME\`. In \`.py\`/\`.sh\` files write \`\` and \`{{NAME}}\`, not \`$ref\`/\`$env\`. Read an index or item only inside its container (\`E_APPLY_REF_OUT_OF_SCOPE\`), after it its \`.results\`. A \`$ref\` naming no block errors in a function file you edited (\`E_APPLY_UNRESOLVED_REF\`). +- **Renames**: one workflow variable per apply (two at once: delete + add).${extraRenames} +- **Builders**: \`${PARAMS_COMMAND} \` (a namespace lists its builders). - **Credentials**: \`sim credentials connect --name ""\`, give the owner its link, then \`credential('')\` (\`sim workflows source resources\`). -- **Failures**: \`x.onError(y)\` runs \`y\` when \`x\` fails, reading the message as \`x.error\` (a Function's \`x.errorMessage\` drops the line and code: reply with it). Retry is block meta (third argument): \`agent('Name', {…}, { retry: { enabled: true, maxTries: 3, waitBetweenTriesMs: 2000 } })\` reruns the whole block after a failure; an \`api\` block's \`retries\` repeat only the request (timeout, reset, 429, 5xx) inside each try. A reference to a block that did not run is \`null\` (a whole value, function code, a condition) or \`''\` in text. Branches may rejoin; only branches that end separately each need a \`response\`. -- **Run and debug**: \`--manual\` runs the saved draft, without it the deployed version. Runs write real data (rows, emails): use test resources. With \`--dir \`, a failed run names the failing file and line; then \`sim logs get --trace --no-include-workflow-state\`; rows: \`sim tables rows list \`. +- **Failures**: \`x.onError(y)\` runs \`y\` when \`x\` fails, reading the message as \`x.error\` (a Function's \`x.errorMessage\` drops the line and code: reply with it). Retry is block meta (third argument): \`agent('Name', {…}, { retry: { enabled: true, maxTries: 3, waitBetweenTriesMs: 2000 } })\` reruns the block after a failure; an \`api\` block's \`retries\` repeat only the request (timeout, reset, 429, 5xx) inside each try. A reference to a block that did not run is \`null\` (a whole value, function code, a condition) or \`''\` in text. Branches may rejoin before one \`response\` (a function picks the value with \`??\`: \`.sim/examples/cookbook.ts\`); branches that end apart each need one. +- **Run and debug**: \`--manual\` runs the saved draft, without it the deployed version. Runs write real data (rows, emails): use test resources. With \`--dir \`, a failed run names the file and line; then \`sim logs get --trace --no-include-workflow-state\`; rows: \`sim tables rows list
\`. - **Exit codes**: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (\`${group} get --dir \`, redo the edit there), ${RATE_LIMITED_EXIT_CODE} rate limited, ${SOURCE_BUSY_EXIT_CODE} busy, ${SOURCE_LOCAL_CHANGES_EXIT_CODE}/${SOURCE_DRIFT_EXIT_CODE} \`status\`: your edits / the server changed.` } const WORKFLOW_PRIMER = `# Sim workflow source: primer -\`${SOURCE_ENTRY_FILE}\` is a Sim workflow as TypeScript; the server compiles it statically and nothing in it runs. Commands read the workflow id from \`${SOURCE_BASE_FILE}\`; run them from this directory. +\`${SOURCE_ENTRY_FILE}\` is a Sim workflow as TypeScript; the server compiles it statically and nothing in it runs. Run commands here: they read the workflow id from \`${SOURCE_BASE_FILE}\` (a starter has none: \`${SOURCE_STARTER_FILE}\` names its workspace, and its loop ends in \`sim workflows source create --dir . --yes\`, not \`apply\`, which makes the workflow), and each (table commands too) acts on its workspace; source commands refuse a \`-w\` naming another, the rest follow it. -**Edit loop**: write every file, then run one chained command and fix what it reports next: \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run --manual --input '{…}'\`. A non-zero exit stops the chain. \`check\` compiles and type-checks (no separate \`tsc\`). Apply re-checks, so \`apply --dry-run\` is only for review. Apply saves the draft in canonical form: read \`${SOURCE_ENTRY_FILE}\` again before the next edit. +**Edit loop**: write every file, then run one chained command; fix what it reports next: \`sim workflows source check --dir . && sim workflows source apply --dir . --yes && sim workflows run --manual --input '{…}'\`. A non-zero exit stops the chain. \`check\` compiles and type-checks (no separate \`tsc\`). Apply re-checks, so \`apply --dry-run\` is only for review. Apply saves the draft in canonical form: read \`${SOURCE_ENTRY_FILE}\` again before the next edit. - **Deletes**: removing a block or a variable needs \`apply --allow-delete\` (\`E_APPLY_BLOCK_DELETE\` / \`E_APPLY_VARIABLE_DELETE\`). - **Deploy**: apply saves a draft; \`apply --deploy\` also deploys it, or \`sim workflows deploy \` publishes the saved draft later. @@ -63,17 +63,17 @@ ${sharedRules('sim workflows source')} /** What a rename in a workspace directory rewrites beyond a workflow's own blocks. */ const WORKSPACE_RENAMES = - " A column: change its \`name\`, keep its key (cells stay). Table blocks (\`data\`, \`conflictColumn\`, filters) use the name, not the key, and keep old names (\`W_TABLE_COLUMN_RENAMED_IN_USE\`). A file's key never changes (\`E_KEY_RENAMED\`): rename by \`name\`." + " A column or file: change its \`name\`, keep its key (cells stay; a file's never changes: \`E_KEY_RENAMED\`). Table blocks (\`data\`, \`conflictColumn\`, filters) use the column name, not the key, and keep old names (\`W_TABLE_COLUMN_RENAMED_IN_USE\`)." const WORKSPACE_PRIMER = `# Sim workspace source: primer -This directory is a Sim workspace as files (\`tables/\`, \`workflows//workflow.ts\`, …); nothing in it runs. Commands read the workspace id from \`${SOURCE_BASE_FILE}\`; run them from this directory. Every \`.ts\` file, \`deployments/\` too, starts with \`// @sim-sdk ${SDK_MAJOR}\`. +This directory is a Sim workspace as files (\`tables/\`, \`workflows//\`); nothing here runs. Run commands here: each (table commands too) acts on the workspace \`${SOURCE_BASE_FILE}\` names; source commands refuse a \`-w\` naming another, the rest follow it. Every \`.ts\` file starts with \`// @sim-sdk ${SDK_MAJOR}\`. -**Edit loop**: write every file, then run one chained command and fix what it reports next: \`sim workspaces source check --dir . && sim workspaces source apply --dir . --yes\`; test with \`sim workflows run --manual --input '{…}'\`. A non-zero exit stops the chain. \`check\` compiles and type-checks (no separate \`tsc\`). Apply re-checks, so \`apply --dry-run\` is only for review. Apply rewrites files: read one again before editing it. +**Edit loop**: write every file, then run one chained command; fix what it reports next: \`sim workspaces source check --dir . && sim workspaces source apply --dir . --yes\`; test with \`sim workflows run --manual --input '{…}'\`. \`check\` compiles and type-checks (no separate \`tsc\`). Apply re-checks, so \`apply --dry-run\` is only for review. Apply rewrites files: reread one before editing it. -- **Deletes**: removing a file, folder, table column, workflow block or variable is a delete: refused without \`apply --allow-delete\`, and it cannot be undone. -- **Deploy**: \`deployments/.ts\` (\`defineDeployment({ live: 'draft' })\`) deploys that workflow on apply; without one, apply never deploys. -- **Exit ${SOURCE_HELD_EXIT_CODE}**: written in part; changes using an unset secret or unbound credential were held back: set it, apply again. +- **Deletes**: removing a file, folder, column, block or variable needs \`apply --allow-delete\` and is permanent. +- **Deploy**: \`deployments/.ts\` (\`defineDeployment({ live: 'draft' })\`) deploys it on apply; without one, apply never deploys. +- **Exit ${SOURCE_HELD_EXIT_CODE}**: partly written; changes needing an unset secret or unbound credential were held: set it, apply again. ${sharedRules('sim workspaces source', WORKSPACE_RENAMES)} ` @@ -100,7 +100,11 @@ Exit codes: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (get a fresh copy an ` } -/** The primer for a `kind` directory, without builder snippets. */ +/** + * The primer for a `kind` directory, without builder snippets. The mothership worker preloads the + * same text as its `workflow-source` skill (`scripts/print-source-primers.ts`), so an edit here + * shows up as worker drift until the next grammar sync. + */ export function sourcePrimer(kind: PrimerKind): string { return kind === 'workflow' ? WORKFLOW_PRIMER : WORKSPACE_PRIMER } diff --git a/packages/sim-cli/src/commands/protocol/stored-edges.ts b/packages/sim-cli/src/commands/protocol/stored-edges.ts index 5df1625a9f7..b1f04aac306 100644 --- a/packages/sim-cli/src/commands/protocol/stored-edges.ts +++ b/packages/sim-cli/src/commands/protocol/stored-edges.ts @@ -2,8 +2,15 @@ import { isRecordLike, toRecord } from '@sim/utils/object' import { type BlockCatalog, type CanonicalBlock, + type ChildResultNode, + type ChildResults, + type CompileResult, + calledWorkflowKeys, + compiledResultNode, compileWorkflow, + folderCompileInput, parseWorkflowLock, + resolveChildResults, type StoredEdgeRef, setOwn, stableStringify, @@ -26,29 +33,45 @@ export function blockDigest(block: CanonicalBlock): string { return digest(stableStringify(block)) } +type CompileInput = Parameters[0] + /** - * The `.sim/stored-edges.json` write for a printed source: its edges and a digest of each block - * ({@link blockDigest}, by key), compiled against `catalog` (the one it was printed with), tagged - * with its base fingerprint. `null` when the answer has no fingerprint or entry, or nothing to - * compile it with; the record left on disk then names an older fingerprint, which a check ignores. + * `compiled`, the compile of `input`, as `childResults` type it: the same compile when none types + * a call it makes, else `input` compiled again with them. */ -export function storedEdgesWrite( +export function compiledWithChildResults( + input: CompileInput, + compiled: CompileResult, + childResults: ChildResults | undefined +): CompileResult { + if (!childResults || childResults.size === 0) return compiled + const { workflow } = compiled + if (workflow && !calledWorkflowKeys(workflow).some((key) => childResults.has(key))) { + return compiled + } + return compileWorkflow({ ...input, childResults }) +} + +/** What a printed source compiles from against `catalog`, or `null` without an entry or lock. */ +function printedInput(answer: PrintedAnswer, catalog: BlockCatalog): CompileInput | null { + const entry = answer.files[SOURCE_ENTRY_FILE] + const { lock } = parseWorkflowLock(answer.lock) + return entry !== undefined && lock ? folderCompileInput(entry, answer.files, lock, catalog) : null +} + +/** + * The `.sim/stored-edges.json` write (at `folder`) of a printed source compiled as `compiled`: its + * edges and a digest of each block ({@link blockDigest}, by key), tagged with its base fingerprint. + * `null` when the answer has no fingerprint; the record left on disk then names an older + * fingerprint, which a check ignores. + */ +function storedEdgesRecord( answer: PrintedAnswer, - catalog: BlockCatalog | null, - folder = '' + { edges, workflow }: CompileResult, + folder: string ): readonly [string, string] | null { const { fingerprint } = toRecord(answer.base) - const entry = answer.files[SOURCE_ENTRY_FILE] - const { lock } = parseWorkflowLock(answer.lock) - if (!catalog || typeof fingerprint !== 'string' || entry === undefined || !lock) return null - const { edges, workflow } = compileWorkflow({ - entry: { path: SOURCE_ENTRY_FILE, text: entry }, - files: new Map(Object.entries(answer.files).filter(([path]) => path !== SOURCE_ENTRY_FILE)), - catalog, - sdkMajor: catalog.sdkMajor, - knownKeys: new Set(Object.keys(lock.blocks)), - storedUnread: lock, - }) + if (typeof fingerprint !== 'string') return null return [ `${folder}${SOURCE_STORED_EDGES_FILE}`, `${JSON.stringify( @@ -70,6 +93,27 @@ export function storedEdgesWrite( ] } +/** + * The `.sim/stored-edges.json` write for a printed source of one workflow, compiled against + * `catalog` (the one it was printed with) and typed as it was printed: each child call by + * `childResults`, which a workflow folder of a workspace directory takes from its workspace + * directory and a workflow directory of its own has none of. A check compiles it the same way, + * so a block it reports changed is one an edit changed. `null` when the answer has no fingerprint + * or entry, or nothing to compile or type it with (`childResults` `null`: the workspace directory + * could not be read); the record left on disk then names an older fingerprint, which a check + * ignores. + */ +export function storedEdgesWrite( + answer: PrintedAnswer, + catalog: BlockCatalog | null, + childResults?: ChildResults | null +): readonly [string, string] | null { + if (childResults === null) return null + const input = catalog && printedInput(answer, catalog) + if (!input) return null + return storedEdgesRecord(answer, compileWorkflow({ ...input, childResults }), '') +} + /** The workflow folders a workspace answer's files hold, by key, each as a printed source. */ function printedWorkflowFolders(files: Record): Map { const folders = new Map() @@ -106,11 +150,13 @@ export interface WorkflowFolderRecords { /** * The `.sim/stored-edges.json` write of each workflow folder a workspace get or apply answered - * with, each compiled against the catalog its base names. A workflow holding a type the workspace - * catalog lacks was printed with its own catalog: one not cached yet is fetched, once per distinct - * hash, and cached, so an offline check compiles that folder against it too. The records are a - * cache fill, never part of the write: a catalog fetch that fails skips the folders printed with - * that catalog (named in `unrecorded`) rather than failing a write the server already committed. + * with, each compiled against the catalog its base names and typed as the server printed it: a + * call by the result fields of the folder it calls, resolved through chains + * ({@link resolveChildResults}), as a check types it. A workflow holding a type the workspace + * catalog lacks was printed with its own catalog: one not cached yet is fetched, once per + * distinct hash, and cached, so an offline check compiles that folder against it too. The records are a cache fill, never part of the write: a + * catalog fetch that fails skips the folders printed with that catalog (named in `unrecorded`) + * rather than failing a write the server already committed. */ export async function workflowFolderRecords( client: OperationClient<'getSourceCatalog'>, @@ -131,7 +177,13 @@ export async function workflowFolderRecords( const catalog = await loadWorkflowCatalog(client, workspaceId, workflowId).catch(() => null) if (catalog) fetched.set(catalogHash, catalog) } - const records: Array = [] + const compiledFolders: Array<{ + key: string + folder: PrintedAnswer + input: CompileInput + compiled: CompileResult + }> = [] + const nodes = new Map() const unrecorded: string[] = [] for (const [key, folder] of folders) { const { catalogHash } = toRecord(folder.base) @@ -145,9 +197,19 @@ export async function workflowFolderRecords( unrecorded.push(key) continue } - const write = storedEdgesWrite(folder, catalog, `${KIND_DIRS.workflow}/${key}/`) - if (write) records.push(write) + const input = catalog && printedInput(folder, catalog) + if (!input) continue + const compiled = compileWorkflow(input) + compiledFolders.push({ key, folder, input, compiled }) + const node = compiledResultNode(input, compiled) + if (node) nodes.set(key, node) } + const childResults = resolveChildResults(nodes) + const records = compiledFolders.flatMap(({ key, folder, input, compiled }) => { + const typed = compiledWithChildResults(input, compiled, childResults) + const record = storedEdgesRecord(folder, typed, `${KIND_DIRS.workflow}/${key}/`) + return record ? [record] : [] + }) return { records, unrecorded } } diff --git a/packages/sim-cli/src/commands/protocol/workflow-dir.ts b/packages/sim-cli/src/commands/protocol/workflow-dir.ts index 3168211b708..2f5ac88a3dd 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-dir.ts @@ -5,7 +5,7 @@ */ import { mapWithConcurrency } from '@sim/utils/concurrency' -import type { BlockCatalog } from '@sim/workflow-code' +import type { BlockCatalog, ChildResults } from '@sim/workflow-code' import { parseSourceBase, parseWorkflowLock, type WorkflowLockV1 } from '@sim/workflow-code' import { codeFileReferences } from '@sim/workflow-code/code-files/references' import { @@ -228,7 +228,7 @@ Editing the \`workflow('…')\` name or description renames or redescribes the w ## A new workflow, or a fork -\`sim workflows source create --dir --workspace \` (without \`--dry-run\` or \`--yes\`) on a directory without \`${SOURCE_ENTRY_FILE}\` writes a starter \`${SOURCE_ENTRY_FILE}\`, the types of that workspace, \`tsconfig.json\` and this guide, records the workspace in \`${SOURCE_STARTER_FILE}\`, and creates nothing. Until the workflow exists there is no \`${SOURCE_BASE_FILE}\`, so \`status\`, \`diff\` and \`apply\` refuse the directory: edit the starter, check it, then \`sim workflows source create --dir --workspace --dry-run\` and the same with \`--yes\` (the starter prints both with its workspace filled in): it prints the new workflow id and writes the lock files. A create goes to the starter's workspace whatever the profile's default, unless \`--workspace\` names another. Exit 1 with \`SOURCE_NAME_TAKEN\` means another workflow has that name: pass \`--name\`. To fork a workflow, copy its directory, delete the copy's \`.sim/\` and run \`sim workflows source create --dir --workspace --name --yes\`. +\`sim workflows source create --dir --workspace \` (without \`--dry-run\` or \`--yes\`) on a directory without \`${SOURCE_ENTRY_FILE}\` writes a starter \`${SOURCE_ENTRY_FILE}\`, the types of that workspace, \`tsconfig.json\` and this guide, records the workspace in \`${SOURCE_STARTER_FILE}\`, and creates nothing. Until the workflow exists there is no \`${SOURCE_BASE_FILE}\`, so \`status\`, \`diff\` and \`apply\` refuse the directory: edit the starter, check it, then \`sim workflows source create --dir --workspace --dry-run\` and the same with \`--yes\` (the starter prints both with its workspace filled in): it prints the new workflow id and writes the lock files. A create goes to the starter's workspace whatever the profile's default, unless \`--workspace\` or \`SIM_WORKSPACE\` names another. Exit 1 with \`SOURCE_NAME_TAKEN\` means another workflow has that name: pass \`--name\`. To fork a workflow, copy its directory, delete the copy's \`.sim/\` and run \`sim workflows source create --dir --workspace --name --yes\`. ## File shape @@ -289,7 +289,8 @@ async function writeSourceTree( source: PrintedSource, catalog: BlockCatalog, workspaceTypes: WorkspaceTypes | null, - blockTypes: readonly string[] + blockTypes: readonly string[], + childResults: ChildResults | null | undefined ): Promise { const [previousLock, tree] = await Promise.all([ readPreviousLock(dir), @@ -298,7 +299,7 @@ async function writeSourceTree( blockTypes, }), ]) - const edges = storedEdgesWrite(source, catalog) + const edges = storedEdgesWrite(source, catalog, childResults) const written = await writeBack( dir, source, @@ -359,13 +360,15 @@ export async function writeSourceScaffold( * Writes a printed source with everything that makes the directory editable: the declarations * for the workspace catalog and its resources, `tsconfig.json`, the agent guide and the LF lines. * Shared by `get --dir` and `create --dir`, so a created workflow's directory is the one a get - * would have written. + * would have written. `childResults` type its calls as the server printed them + * (`folderChildResults` of `dir`). */ export async function writeSourceDirectory( client: OperationClient<'getSourceCatalog' | 'getSourceResources'>, dir: string, source: PrintedSource, - blockTypes: readonly string[] + blockTypes: readonly string[], + childResults: ChildResults | null | undefined ): Promise { const [catalog, workspaceTypes] = await Promise.all([ loadCatalog(client, { @@ -377,7 +380,7 @@ export async function writeSourceDirectory( loadWorkspaceTypes(client, source.workspaceId), ]) assertSdkMajor(catalog) - return writeSourceTree(dir, source, catalog, workspaceTypes, blockTypes) + return writeSourceTree(dir, source, catalog, workspaceTypes, blockTypes, childResults) } /** diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts index 1d6ada083f9..18fa6df5fe4 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.test.ts @@ -5,6 +5,7 @@ import { mkdtempSync, readFileSync, rmSync, + symlinkSync, writeFileSync, } from 'node:fs' import { hostname, tmpdir } from 'node:os' @@ -1303,6 +1304,33 @@ describe('sim workflows source apply in a workflow folder of a workspace directo expect(lockedDuringWrite).toBe(true) expect(existsSync(join(dir, '.sim/command.lock'))).toBe(false) }) + + it('writes the stored source back when another folder cannot be read to type its calls', async () => { + setTerminal(false) + const config = mkdtempSync(join(tmpdir(), 'sim-source-apply-config-')) + vi.stubEnv('SIM_CONFIG_DIR', config) + const catalogText = readFileSync(FIXTURE_CATALOG, 'utf8') + cacheCatalogText(config, WORKSPACE_ID, catalogText) + mkdirSync(join(dir, 'workflows/other')) + writeFileSync(join(config, 'elsewhere.ts'), ENTRY) + symlinkSync(join(config, 'elsewhere.ts'), join(dir, 'workflows/other/workflow.ts')) + const stored = outcome() + stored.data.base.catalogHash = JSON.parse(catalogText).hash + request.mockResolvedValue(stored) + + try { + await apply('--dir', folder(), '--yes') + } finally { + rmSync(config, { recursive: true, force: true }) + } + + expect(process.exitCode).toBeUndefined() + expect(readFileSync(join(folder(), 'workflow.ts'), 'utf8')).toBe(`${ENTRY}// stored\n`) + expect(JSON.parse(readFileSync(join(folder(), '.sim/base.json'), 'utf8')).fingerprint).toBe( + 'sf1:b' + ) + expect(existsSync(join(folder(), '.sim/stored-edges.json'))).toBe(false) + }) }) describe('a standalone workflow directory', () => { diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts index fa37c9e7176..1f4e3320582 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-apply.ts @@ -24,6 +24,7 @@ import { import { gitProvenance } from './git-provenance' import { CliUsageError, SourceDirError } from './local-errors' import { printProtocolResult } from './result' +import { folderChildResults } from './source-check' import { absoluteDirOption, assertSendableCodeFiles, @@ -475,6 +476,7 @@ export function attachWorkflowSourceApply(source: Command): void { if (!isReadOnly(mode)) { await refreshWorkflowWorkspaceTypes(client, options.dir, base.workspaceId) } + const childResults = isReadOnly(mode) ? undefined : await folderChildResults(options.dir) await writeWorkflowSource<'applyWorkflowSource'>({ options, mode, @@ -494,7 +496,8 @@ export function attachWorkflowSourceApply(source: Command): void { save: async (data) => { const edges = storedEdgesWrite( data, - cachedCatalogByHash(toRecord(data.base).catalogHash) + cachedCatalogByHash(toRecord(data.base).catalogHash), + childResults ) await writeBack(options.dir, data, lock, { write: edges ? [edges] : [] }) await refreshWorkflowTsconfigs(options.dir, data) @@ -583,13 +586,14 @@ export function attachWorkflowSourceCreate(source: Command): void { options.dir, await recordedWorkspace(options.dir, profile), profile, - (from) => `Run it without --workspace to create it in ${from}.` + (from, _named, setting) => `Run it without ${setting} to create it in ${from}.` ) const workspaceId = client.requireWorkspace(recorded ?? undefined) const files = await readSourceFiles(options.dir, null) if (!isReadOnly(mode)) { await refreshWorkflowWorkspaceTypes(client, options.dir, workspaceId) } + const childResults = isReadOnly(mode) ? undefined : await folderChildResults(options.dir) await writeWorkflowSource<'createWorkflowFromSource'>({ options, mode, @@ -602,7 +606,7 @@ export function attachWorkflowSourceCreate(source: Command): void { params: { workspaceId }, ifAnswerLost: `It may have been created. Run this command again: a SOURCE_NAME_TAKEN refusal means it was, so find its id with \`sim workflows list\` and run \`sim workflows source get --dir ${options.dir} --force\`.`, save: async (data) => { - await writeSourceDirectory(client, options.dir, data, []) + await writeSourceDirectory(client, options.dir, data, [], childResults) await updateSourceDir(options.dir, { write: [], remove: [SOURCE_STARTER_FILE] }) }, body: { diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts index 6978f473f83..170eeff6ab2 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.ts @@ -1,7 +1,7 @@ import { SOURCE_BASE_FILE } from '@sim/workflow-code/limits' import { KIND_DIRS } from '@sim/workspace-code' import type { Command } from 'commander' -import { profileFrom } from '../../context' +import { actingProfileFrom } from '../../context' import { CliUsageError } from './local-errors' import { cachedOrRefuse, @@ -67,7 +67,7 @@ export function attachWorkflowSourceCheck(source: Command): void { options: { dir: string; verbose?: boolean } & StrictOptions & TypesOptions, command: Command ) => { - const profile = profileFrom(command) + const profile = actingProfileFrom(command) await assertSourceDirKind(options.dir, 'workflow') await requireEntry(options.dir) const workspace = await workspaceFolderOf(options.dir) @@ -75,7 +75,8 @@ export function attachWorkflowSourceCheck(source: Command): void { options.dir, await recordedWorkspace(options.dir, profile), profile, - (from) => `Run it without --workspace to check it against the catalog of ${from}.` + (from, _named, setting) => + `Run it without ${setting} to check it against the catalog of ${from}.` ) if (!workspaceId) { throw new CliUsageError( @@ -99,7 +100,7 @@ export function attachWorkflowSourceCheck(source: Command): void { : undefined const { findings, entry, unlisted } = await checkWorkflowDir(options.dir, catalog, { strict: strictMode(options), - ...(declarations ? { declarations } : {}), + ...(workspace && declarations ? { declarations, key: workspace.key } : {}), }) const enabled = options.types !== false let types: TypeCheck diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-get.ts b/packages/sim-cli/src/commands/protocol/workflow-source-get.ts index 10a5bcd783e..76e4a420b07 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.ts @@ -5,6 +5,7 @@ import type { GetWorkflowSourceResponse } from '../../generated/v2-api' import { callsOperations } from '../../runtime/called-operations' import { buildRequest } from '../../runtime/request' import { SourceDirError } from './local-errors' +import { folderChildResults } from './source-check' import { absoluteDirOption, assertPrintedSourcePaths, @@ -127,7 +128,8 @@ export function attachWorkflowSourceGet(source: Command): void { client, dir, workflowSource, - workflowSource.blockTypes + workflowSource.blockTypes, + await folderChildResults(dir) ) const findings = findingsOutput(profile.output, false, dir) findings.print(workflowSource.diagnostics) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-params.ts b/packages/sim-cli/src/commands/protocol/workflow-source-params.ts index d3c4f2d76ce..9847a95445f 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-params.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-params.ts @@ -8,7 +8,7 @@ import { import type { Command } from 'commander' import { printLine } from '#sim-cli/output/io' import type { ResolvedProfile } from '../../config/index' -import { profileFrom } from '../../context' +import { actingProfileFrom } from '../../context' import { CliUsageError, SourceDirError } from './local-errors' import { printProtocolResult } from './result' import { recordedWorkspace } from './source-dir' @@ -66,7 +66,7 @@ export function attachWorkflowSourceParams(source: Command): void { .description("Print a builder's params and outputs from the cached block catalog (offline)") .addHelpText('after', PARAMS_HELP) .action(async (query: string, options: { dir: string; full?: boolean }, command: Command) => { - const profile = profileFrom(command) + const profile = actingProfileFrom(command) const catalog = await lookupCatalog(options.dir, profile) const found = lookupBuilder(catalog, query) const machine = isMachine(profile.output) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts index 66a75d3d802..55a870ea906 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-roundtrip.test.ts @@ -39,6 +39,7 @@ vi.mock('../../context', async () => { return { globalsOf: () => ({}), profileFrom: () => profile, + actingProfileFrom: () => profile, clientFrom: () => ({ client: new SimClient(profile), profile }), } }) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts index a678826462e..2ca12ac0e12 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.test.ts @@ -1300,7 +1300,7 @@ describe('workspaces source apply', () => { await expect(apply('--yes')).rejects.toThrow(/unsafe file path/) }) - it('applies to the workspace the directory was read from, refusing only a --workspace naming another', async () => { + it('applies to the workspace the directory was read from, refusing a --workspace or SIM_WORKSPACE naming another', async () => { write('.sim/base.json', JSON.stringify({ ...BASE, workspaceId: 'ws_other' })) request.mockResolvedValue(answer()) @@ -1316,6 +1316,14 @@ describe('workspaces source apply', () => { message: expect.stringContaining('--to ws_local'), }) expect(request).toHaveBeenCalledTimes(1) + + write('.sim/base.json', JSON.stringify({ ...BASE, workspaceId: 'ws_other' })) + contextMockState.workspaceSource = 'env' + await expect(apply('--yes')).rejects.toMatchObject({ + code: 'SOURCE_OTHER_WORKSPACE', + message: expect.stringContaining('but SIM_WORKSPACE names ws_local'), + }) + expect(request).toHaveBeenCalledTimes(1) }) it('names the directory by its absolute path when --dir is relative', async () => { diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts index 072ee9abac7..2c1916214ef 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-apply.ts @@ -735,8 +735,8 @@ export function attachWorkspaceSourceApply(source: Command): void { options.dir, readFrom, profile, - (from, named) => - `Run it without --workspace to apply it to ${from}, or promote it with --to ${named}: its resources bind by key to that workspace's own, and the directory stays bound to ${from}.` + (from, named, setting) => + `Run it without ${setting} to apply it to ${from}, or promote it with --to ${named}: its resources bind by key to that workspace's own, and the directory stays bound to ${from}.` ) ?? undefined ) const provenance = await gitProvenance(options.dir) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts index cf98b190708..e016df3ea58 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-check.test.ts @@ -7,6 +7,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { SimApiError } from '../../http/client' import { cacheCatalogText } from '../../test/catalog-cache' import { contextMockFns, mockedProfile } from '../../test/context-mock' +import { folderChildResults } from './source-check' +import { storedEdgesWrite, workflowFolderRecords } from './stored-edges' import { attachWorkspaceSourceCheck } from './workspace-source-check' vi.mock('../../context', async () => (await import('../../test/context-mock')).contextMock) @@ -381,7 +383,7 @@ describe('sim workspaces source check', () => { function workflowFile(...lines: string[]): string { return [ '// @sim-sdk 1', - "import { agent, childWorkflow, condition, env, fn, js, response, runWorkflow, skill, t, trigger, workflow } from '@sim/workflow-sdk'", + "import { agent, api, childWorkflow, condition, env, fn, js, loop, response, runWorkflow, skill, stored, t, trigger, workflow } from '@sim/workflow-sdk'", "export default workflow('W', {}, () => {", ...lines.map((line) => ` ${line}`), '})', @@ -572,6 +574,206 @@ describe('sim workspaces source check', () => { ]) }) + it("types a child call's result.data. by the child's Response body, so it needs no t`${…}`", async () => { + writeFile( + 'workflows/normalize-phone/workflow.ts', + workflowFile( + "const start = trigger.start('Start', { inputFormat: { phone: 'string', n: 'number' } })", + "const reply = response('Reply', { body: { mobile: start.phone, digits: start.n } })", + 'start.to(reply)' + ) + ) + writeFile( + 'workflows/parent/workflow.ts', + workflowFile( + "const start = trigger.start('Start', { inputFormat: { phone: 'string' } })", + "const call = runWorkflow('Call', { workflowId: childWorkflow('normalize-phone'), inputMapping: { phone: start.phone } })", + "const reply = response('Reply', { body: { mobile: call.result.data.mobile, digits: call.result.data.digits, other: call.result.data.missing } })", + 'start.to(call)', + 'call.to(reply)' + ) + ) + + await check() + + const untyped = (stdoutJson().diagnostics as Array>).filter( + (finding) => finding.code === 'W_JSON_REF_UNTYPED' + ) + expect(untyped).toEqual([ + expect.objectContaining({ + file: 'workflows/parent/workflow.ts', + message: expect.stringContaining(''), + }), + ]) + }) + + it("types a call by a field its child forwards from a grandchild's Response, through the chain", async () => { + writeFile( + 'workflows/c/workflow.ts', + workflowFile( + "const start = trigger.start('Start', { inputFormat: { phone: 'string', n: 'number' } })", + "const reply = response('Reply', { body: { text: start.phone, n: start.n } })", + 'start.to(reply)' + ) + ) + writeFile( + 'workflows/b/workflow.ts', + workflowFile( + "const start = trigger.start('Start', { inputFormat: { phone: 'string' } })", + "const callC = runWorkflow('Call C', { workflowId: childWorkflow('c'), inputMapping: { phone: start.phone } })", + "const reply = response('Reply', { body: { text: callC.result.data.text, n: callC.result.data.n } })", + 'start.to(callC)', + 'callC.to(reply)' + ) + ) + writeFile( + 'workflows/a/workflow.ts', + workflowFile( + "const start = trigger.start('Start', { inputFormat: { phone: 'string' } })", + "const callB = runWorkflow('Call B', { workflowId: childWorkflow('b'), inputMapping: { phone: start.phone } })", + "const reply = response('Reply', { body: { text: callB.result.data.text, n: callB.result.data.n } })", + 'start.to(callB)', + 'callB.to(reply)' + ) + ) + + await check() + + const untyped = (stdoutJson().diagnostics as Array>).filter( + (finding) => finding.code === 'W_JSON_REF_UNTYPED' + ) + expect(untyped).toEqual([]) + }) + + it('types a call by a child whose blocks keep stored() values, compiled under its lock', async () => { + writeFile( + 'workflows/normalize-phone/workflow.ts', + workflowFile( + "const start = trigger.start('Start', { inputFormat: { phone: 'string' } })", + "const lookup = api('Lookup', { url: 'https://example.com', proxyUrl: stored() })", + "const reply = response('Reply', { body: { mobile: start.phone } })", + 'start.to(lookup)', + 'lookup.to(reply)' + ) + ) + writeFile( + 'workflows/normalize-phone/.sim/lock.json', + JSON.stringify({ + version: 1, + blocks: Object.fromEntries( + ['start', 'lookup', 'reply'].map((key, order) => [ + key, + { id: `id-${key}`, parent: null, ident: key, order }, + ]) + ), + variables: {}, + }) + ) + writeFile( + 'workflows/parent/workflow.ts', + workflowFile( + "const start = trigger.start('Start', { inputFormat: { phone: 'string' } })", + "const call = runWorkflow('Call', { workflowId: childWorkflow('normalize-phone'), inputMapping: { phone: start.phone } })", + "const reply = response('Reply', { body: { mobile: call.result.data.mobile } })", + 'start.to(call)', + 'call.to(reply)' + ) + ) + + await check() + + const codes = (stdoutJson().diagnostics as Array>).map( + (finding) => finding.code + ) + expect(codes).not.toContain('W_JSON_REF_UNTYPED') + expect(codes).not.toContain('E_STORED_VALUE_MISSING') + }) + + it.each(['a workspace get', 'a workflow get into its folder'])( + "counts a block the get printed as unchanged while a child's Response data types its call, after %s", + async (get) => { + const child = workflowFile( + "const start = trigger.start('Start', { inputFormat: { phone: 'string' } })", + "const reply = response('Reply', { body: { mobile: start.phone } })", + 'start.to(reply)' + ) + const printed = workflowFile( + "const start = trigger.start('Start', { inputFormat: { phone: 'string' } })", + "const each = loop.for('Each', { count: 2 }, (p) => {", + " const inner = fn('Inner', { code: 'return 1' })", + ' p.to(inner)', + '})', + "const call = runWorkflow('Call', { workflowId: childWorkflow('normalize-phone'), inputMapping: { phone: start.phone } })", + "const reply = response('Reply', { body: { mobile: call.result.data.mobile, at: '' } })", + 'start.to(each)', + 'each.to(call)', + 'call.to(reply)' + ) + const lockOf = (keys: string[]) => ({ + version: 1, + blocks: Object.fromEntries( + keys.map((key, order) => [ + key, + { id: `id-${key}`, parent: key === 'inner' ? 'each' : null, ident: key, order }, + ]) + ), + variables: {}, + }) + const baseOf = (workflowId: string) => ({ + version: 1, + workflowId, + workspaceId: WORKSPACE_ID, + fingerprint: 'sf1:a', + catalogHash: 'fixture', + }) + const folders = { + 'normalize-phone': { + text: child, + lock: lockOf(['start', 'reply']), + base: baseOf('wf-child'), + }, + parent: { + text: printed, + lock: lockOf(['start', 'each', 'inner', 'call', 'reply']), + base: baseOf('wf-parent'), + }, + } + const files: Record = {} + for (const [key, folder] of Object.entries(folders)) { + files[`workflows/${key}/workflow.ts`] = folder.text + files[`workflows/${key}/.sim/lock.json`] = JSON.stringify(folder.lock) + files[`workflows/${key}/.sim/base.json`] = JSON.stringify(folder.base) + } + for (const [path, text] of Object.entries(files)) writeFile(path, text) + const catalog = JSON.parse(readFileSync(FIXTURE_CATALOG, 'utf8')) + if (get === 'a workspace get') { + const { records } = await workflowFolderRecords( + contextMockFns.mockClientFrom().client as never, + WORKSPACE_ID, + catalog, + files + ) + for (const [path, text] of records) writeFile(path, text) + } else { + const folder = join(dir, 'workflows', 'parent') + const record = storedEdgesWrite( + { files: { 'workflow.ts': printed }, ...folders.parent }, + catalog, + await folderChildResults(folder) + ) + if (!record) throw new Error('no stored-edges record') + writeFile(`workflows/parent/${record[0]}`, record[1]) + } + + await check() + + const findings = stdoutJson().diagnostics as Array> + expect(findings.filter((finding) => String(finding.code).includes('OUT_OF_SCOPE'))).toEqual([ + expect.objectContaining({ code: 'W_REF_OUT_OF_SCOPE', severity: 'warning' }), + ]) + } + ) + it("checks the cookbook example's table writes clean against the cookbook workspace's tables", async () => { for (const [path, text] of Object.entries(WORKSPACE_COOKBOOK)) writeFile(path, text) writeFile('workflows/cookbook/workflow.ts', COOKBOOK_EXAMPLES['cookbook.ts']) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-check.ts b/packages/sim-cli/src/commands/protocol/workspace-source-check.ts index 59c04333373..160b05aa373 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-check.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-check.ts @@ -3,7 +3,7 @@ import { toRecord } from '@sim/utils/object' import { KIND_DIRS, WORKSPACE_ANSWER_BOUND } from '@sim/workspace-code' import { WORKSPACE_BASE_FILE } from '@sim/workspace-code/layout' import type { Command } from 'commander' -import { profileFrom } from '../../context' +import { actingProfileFrom } from '../../context' import { AUTH_REQUIRED_EXIT_CODE } from '../../exit-codes' import { apiCommand, type Connection } from '../../runtime/called-operations' import { CliUsageError, SourceDirError } from './local-errors' @@ -110,14 +110,15 @@ export function attachWorkspaceSourceCheck(source: Command): void { options: { dir: string; verbose?: boolean } & StrictOptions & TypesOptions, command: Command ) => { - const profile = profileFrom(command) + const profile = actingProfileFrom(command) const base = toRecord(await readSourceJson(options.dir, WORKSPACE_BASE_FILE)) await assertWorkspaceDir(options.dir) const workspaceId = directoryWorkspace( options.dir, typeof base.workspaceId === 'string' ? base.workspaceId : null, profile, - (from) => `Run it without --workspace to check it against the catalog of ${from}.` + (from, _named, setting) => + `Run it without ${setting} to check it against the catalog of ${from}.` ) if (!workspaceId) { throw new CliUsageError( @@ -138,6 +139,7 @@ export function attachWorkspaceSourceCheck(source: Command): void { { declarations, strict: strictMode(options), + key, prefix: `${KIND_DIRS.workflow}/${key}/`, } ) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts index 94339d5287a..13b0660f22f 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-dir.ts @@ -7,7 +7,7 @@ import { realpath, stat } from 'node:fs/promises' import { mapWithConcurrency } from '@sim/utils/concurrency' import { compareStrings } from '@sim/utils/string' -import type { WorkflowInput } from '@sim/workflow-code' +import type { ChildResultFields, WorkflowInput } from '@sim/workflow-code' import { SOURCE_CODE_DIR, SOURCE_ENTRY_FILE, SOURCE_LOCK_FILE } from '@sim/workflow-code/limits' import { SDK_MAJOR, @@ -191,12 +191,12 @@ const ADVANCED_GUIDE = `# Sim workspace source: advanced - Commit the whole directory, \`.sim/\` included: \`${WORKSPACE_BASE_FILE}\`, each workflow's \`.sim/\` and \`.sim/written.json\` are what a later apply compares with, from any clone. \`.sim/cache/\` holds this machine's file stats and ignores itself. The generated \`.gitignore\` leaves out only what a command keeps while it runs (\`.sim/downloads/\`, \`.sim/command.lock/\`, \`.sim-staging-*\`) and \`${TSCONFIG_FULL_FILE}\`, which names the CLI's cache on this machine (\`check\` writes it again), and \`.gitattributes\` keeps workspace files and documents byte for byte. - A fresh clone runs \`check\` (it downloads the block catalog once when none is cached), \`apply --dry-run\` and \`apply --yes\` with only the committed files. A workspace API key may apply tables, rows, knowledge bases, files, custom tools, MCP servers and credential bindings; workflows, skills, secrets and deployments need a member's personal API key (deployments an admin's). - Plan on every pull request (\`apply --dry-run\`), apply on merge, and commit the files the apply rewrote. Two branches that each applied: merge them, then run the dry run. No changes means the merged files match the workspace. Exit ${SOURCE_STALE_EXIT_CODE} means a resource changed since the base this branch holds: \`sim workspaces source get --dir \`, carry the edit over, and apply from there. -- \`sim workspaces source get --dir .\` refreshes the workspace \`${WORKSPACE_BASE_FILE}\` names, whatever the profile's default; a \`--workspace\` naming another is refused. +- \`sim workspaces source get --dir .\` refreshes the workspace \`${WORKSPACE_BASE_FILE}\` names, whatever the profile's default; a \`--workspace\` or \`SIM_WORKSPACE\` naming another is refused. - One command at a time per directory: a second \`get\`, \`apply\` or \`check\` on the same directory exits ${SOURCE_BUSY_EXIT_CODE} while the first runs. ## Promote to another workspace -\`sim workspaces source apply --dir . --to --dry-run\`, then \`--yes\`: applies this directory to another workspace (dev to prod). Each resource binds by key to the target's own: one the target holds under the same key is updated in place (a workflow keeps its id and block ids, so its webhook URLs), a key it lacks is created (or adopts a resource of the same name). Each promote records what it left in the target in \`.sim/targets/.json\` (commit it), and the next promote compares with that: a resource changed in the target since is kept when this directory left it alone, and refused as stale (exit ${SOURCE_STALE_EXIT_CODE}) when this directory changed it too. A resource with no record (the first promote, or one created in the target since) is updated to match this directory; delete the record to take the target as it stands again. Secrets and credentials bind by name and key to the target's own; no value is copied. The target's resources this directory never declared (and no promote left there) are kept with a warning, even with \`--allow-delete\`; deleting them too takes \`--delete-target-only\` beside \`--allow-delete\`. A resource this directory deleted since the last promote is deleted in the target only with \`--allow-delete\`. Before the first promote, set the target's secrets (\`sim secrets set NAME --scope workspace -w \`) and connect its credentials, or the workflows using them are held back. This directory stays bound to the workspace it was read from. Without \`--to\`, \`check\`, \`status\`, \`diff\` and \`apply\` act on the workspace this directory was read from, whatever the profile's default; a \`--workspace\` naming another is refused (\`SOURCE_OTHER_WORKSPACE\`). +\`sim workspaces source apply --dir . --to --dry-run\`, then \`--yes\`: applies this directory to another workspace (dev to prod). Each resource binds by key to the target's own: one the target holds under the same key is updated in place (a workflow keeps its id and block ids, so its webhook URLs), a key it lacks is created (or adopts a resource of the same name). Each promote records what it left in the target in \`.sim/targets/.json\` (commit it), and the next promote compares with that: a resource changed in the target since is kept when this directory left it alone, and refused as stale (exit ${SOURCE_STALE_EXIT_CODE}) when this directory changed it too. A resource with no record (the first promote, or one created in the target since) is updated to match this directory, so deleting the record makes the next promote overwrite every change made in the target since (no stale refusal). Secrets and credentials bind by name and key to the target's own; no value is copied. The target's resources this directory never declared (and no promote left there) are kept with a warning, even with \`--allow-delete\`; deleting them too takes \`--delete-target-only\` beside \`--allow-delete\`. A resource this directory deleted since the last promote is deleted in the target only with \`--allow-delete\`. Before the first promote, set the target's secrets (\`sim secrets set NAME --scope workspace -w \`) and connect its credentials, or the workflows using them are held back. This directory stays bound to the workspace it was read from. Without \`--to\`, \`check\`, \`status\`, \`diff\` and \`apply\` act on the workspace this directory was read from, whatever the profile's default; a \`--workspace\` or \`SIM_WORKSPACE\` naming another is refused (\`SOURCE_OTHER_WORKSPACE\`). Any other command run in this directory or a folder of it (\`sim tables …\`, \`sim files …\`) acts on that workspace too, unless \`--workspace\` or \`SIM_WORKSPACE\` names another. ` /** The workspace directory's tree beside the printed source. */ @@ -355,6 +355,11 @@ export interface WorkspaceDeclarations { * `result` is that block's output; set by a check, which compiles them. */ respondingWorkflows?: ReadonlySet + /** + * By key, the typed top-level fields of the data each of those workflows responds with + * (`childResultFields`), which type a call's `>`; set by a check. + */ + childResults?: ReadonlyMap } /** diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-get.ts b/packages/sim-cli/src/commands/protocol/workspace-source-get.ts index ba5996b29a3..802f81189e4 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-get.ts @@ -359,8 +359,8 @@ export function attachWorkspaceSourceGet(source: Command): void { options.dir, typeof recorded === 'string' ? recorded : null, profile, - (readFrom, named) => - `Get ${named} into another directory, or run the get without --workspace to refresh ${readFrom}; to apply this directory to ${named}, use \`sim workspaces source apply --to ${named}\`.` + (readFrom, named, setting) => + `Get ${named} into another directory, or run the get without ${setting} to refresh ${readFrom}; to apply this directory to ${named}, use \`sim workspaces source apply --to ${named}\`.` ) ?? undefined ) const { data } = await client diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-status.ts b/packages/sim-cli/src/commands/protocol/workspace-source-status.ts index 065f6a325fc..c2c43b5b2fe 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-status.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-status.ts @@ -157,7 +157,7 @@ function localPaths(local: LocalWorkspace): string[] { /** * The workspace a status or diff asks about: the one the directory was read from (a `--workspace` - * naming another is refused), else the profile's. + * or `SIM_WORKSPACE` naming another is refused), else the resolved one. */ function targetWorkspace( connection: Connection<'planWorkspaceSource' | 'getWorkspaceSource'>, @@ -170,8 +170,8 @@ function targetWorkspace( dir, readFrom, profile, - (from, named) => - `Run it without --workspace to compare with ${from}, or get ${named} into another directory.` + (from, named, setting) => + `Run it without ${setting} to compare with ${from}, or get ${named} into another directory.` ) ?? undefined ) } diff --git a/packages/sim-cli/src/commands/search.test.ts b/packages/sim-cli/src/commands/search.test.ts index f48f106c94d..e86dc2c2b0c 100644 --- a/packages/sim-cli/src/commands/search.test.ts +++ b/packages/sim-cli/src/commands/search.test.ts @@ -141,6 +141,6 @@ describe('the agent discovery note', () => { const person = helpOf(['--help'], {}) expect(person).toContain('\nExamples:\n') expect(agent).not.toContain('\nExamples:\n') - expect(agent).toContain('A command targets the profile') + expect(agent).toContain("A command's workspace is, first to last") }) }) diff --git a/packages/sim-cli/src/config/index.ts b/packages/sim-cli/src/config/index.ts index f2fd85174d2..e1227fd7471 100644 --- a/packages/sim-cli/src/config/index.ts +++ b/packages/sim-cli/src/config/index.ts @@ -4,6 +4,7 @@ export { DEFAULT_OUTPUT_FORMAT, DEFAULT_PROFILE, deleteProfile, + explicitWorkspaceSetting, FORBIDDEN_IN_VALUE, listAuthenticationDependents, listProfiles, diff --git a/packages/sim-cli/src/config/profile.ts b/packages/sim-cli/src/config/profile.ts index 135372e851e..066e8e2b0a6 100644 --- a/packages/sim-cli/src/config/profile.ts +++ b/packages/sim-cli/src/config/profile.ts @@ -158,6 +158,12 @@ export interface ResolvedProfile { apiKey: string | null oauth: StoredOAuthCredential | null workspaceId: string | null + /** + * The source directory the command runs in whose workspace {@link workspaceId} is, when that + * directory chose it rather than {@link sources} (set where a command's requests take their + * workspace, never by {@link resolveProfile}). + */ + workspaceDirectory?: string output: OutputFormat /** * Replaces global `fetch` for every request. Only an embedding server sets it, to @@ -668,6 +674,16 @@ export function normalizeWorkspaceId(workspaceId: string, source: string): strin return trimmed } +/** + * The setting that named a profile's workspace explicitly, `--workspace` or `SIM_WORKSPACE`, or + * `null` when it came from the profile or nowhere: only these outrank the source directory a + * command runs in or acts on. + */ +export function explicitWorkspaceSetting(profile: Pick): string | null { + const source = profile.sources.workspaceId + return source === 'flag' ? '--workspace' : source === 'env' ? 'SIM_WORKSPACE' : null +} + /** * Resolves one setting through the precedence chain, reporting where it landed. * Order is flags → environment → files → built-in default, the same order every diff --git a/packages/sim-cli/src/context.ts b/packages/sim-cli/src/context.ts index d40e1095f24..098d1939179 100644 --- a/packages/sim-cli/src/context.ts +++ b/packages/sim-cli/src/context.ts @@ -1,6 +1,9 @@ import type { Command } from 'commander' import { refreshStoredOAuth } from './auth/refresh' +import type { NamedWorkspace } from './commands/protocol/source-dir' import { + explicitWorkspaceSetting, + normalizeWorkspaceId, type OutputFormat, type ProfileOverrides, type ResolvedProfile, @@ -36,8 +39,41 @@ export function profileFrom(command: Command, extra: ProfileOverrides = {}): Res }) } +/** The workspace the source directory the terminal runs in names, by the program running there. */ +const workingDirectoryWorkspaces = new WeakMap() + +/** + * Records the workspace the source directory `program` runs in names, which the terminal reads + * before each action: {@link actingProfileFrom} then gives it to every command `program` runs. + */ +export function setWorkingDirectoryWorkspace(program: Command, named: NamedWorkspace): void { + workingDirectoryWorkspaces.set(program, named) +} + +function rootOf(command: Command): Command { + let root = command + while (root.parent) root = root.parent + return root +} + +/** + * The profile a command acts with: {@link profileFrom}, whose workspace the source directory the + * terminal runs in chooses when neither `--workspace` nor `SIM_WORKSPACE` names one, so a command + * run there acts on that directory's workspace before the profile's. + */ +export function actingProfileFrom(command: Command): ResolvedProfile { + const profile = profileFrom(command) + const named = workingDirectoryWorkspaces.get(rootOf(command)) + if (!named || explicitWorkspaceSetting(profile) !== null) return profile + return { + ...profile, + workspaceId: normalizeWorkspaceId(named.workspaceId, `the source directory ${named.dir}`), + workspaceDirectory: named.dir, + } +} + /** The raw client behind a command. Only `connect` calls it: commands reach the API declared. */ export function clientFrom(command: Command): { client: SimClient; profile: ResolvedProfile } { - const profile = profileFrom(command) + const profile = actingProfileFrom(command) return { client: new SimClient(profile, { refreshOAuth: refreshStoredOAuth }), profile } } diff --git a/packages/sim-cli/src/program.ts b/packages/sim-cli/src/program.ts index c50c32992e0..fd11b923ea9 100644 --- a/packages/sim-cli/src/program.ts +++ b/packages/sim-cli/src/program.ts @@ -27,12 +27,17 @@ Profiles work like the AWS CLI: settings live in ~/.sim/config, keys in ~/.sim/credentials (0600), or under SIM_CONFIG_DIR when it is set. Select one with -P, --profile, or SIM_PROFILE. -A command targets the profile's workspace unless -w (--workspace ) or -SIM_WORKSPACE names another. A source directory records its own: a workflow -directory acts on the workflow its .sim/base.json names, a workspace directory -on the workspace its base names (refusing a -w naming another), and a starter -on the one .sim/starter.json names unless -w names another. In a script, export -SIM_WORKSPACE= once, or keep only the ID in a variable and write -w "$WS". +A command's workspace is, first to last: -w (--workspace ), then +SIM_WORKSPACE, then the source directory it runs in (the nearest directory at +or above the working directory whose .sim/base.json or .sim/starter.json names +one, a workflow folder counting as its workspace directory), then the +profile's. A source command acts on the directory +its --dir names: a workflow directory on the workflow its .sim/base.json names, +a workspace directory on the workspace its base names, refusing a -w or +SIM_WORKSPACE naming another (SOURCE_OTHER_WORKSPACE), and a starter on the one +.sim/starter.json names unless -w or SIM_WORKSPACE names another. In a script, +export SIM_WORKSPACE= once, or keep only the ID in a variable and write +-w "$WS". A variable holding "--workspace " is one argument: alone it is an unknown option, and after -w all of it is taken as the ID. diff --git a/packages/sim-cli/src/runtime/execute.ts b/packages/sim-cli/src/runtime/execute.ts index 70f367c71ad..1d4a44be5da 100644 --- a/packages/sim-cli/src/runtime/execute.ts +++ b/packages/sim-cli/src/runtime/execute.ts @@ -413,13 +413,15 @@ function foldOtherSpellings( /** * A 404 from a request scoped to the resolved workspace, stating which workspace was searched and * where that came from: a table or file that lives in another workspace answers only "not found", - * and a workspace taken from the profile or `SIM_WORKSPACE` is not on the command line to check. + * and a workspace taken from the profile, `SIM_WORKSPACE` or the source directory the command runs + * in is not on the command line to check. */ function withSearchedWorkspace(error: unknown, profile: ResolvedProfile): unknown { if (!(error instanceof SimApiError) || error.status !== 404 || !profile.workspaceId) return error const source = profile.sources.workspaceId - const from = - source === 'env' + const from = profile.workspaceDirectory + ? `, the workspace of the source directory ${safeOneLine(profile.workspaceDirectory)}; pass -w or set SIM_WORKSPACE to search another` + : source === 'env' ? ', from SIM_WORKSPACE; pass -w to search another' : source === 'config' ? `, the workspace of profile "${safeOneLine(profile.name)}"; pass -w or set SIM_WORKSPACE to search another` diff --git a/packages/sim-cli/src/terminal.test.ts b/packages/sim-cli/src/terminal.test.ts index 387a4b84baf..05a85481e07 100644 --- a/packages/sim-cli/src/terminal.test.ts +++ b/packages/sim-cli/src/terminal.test.ts @@ -1,4 +1,4 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' @@ -11,13 +11,17 @@ import { runTerminalCli } from './terminal' */ async function runAgainst( argv: string[], - response: Response + response: Response, + { workspace = 'ws_1', profileWorkspace }: { workspace?: string; profileWorkspace?: string } = {} ): Promise<{ stderr: string; exitCode: number }> { const configDir = mkdtempSync(join(tmpdir(), 'sim-cli-terminal-')) + if (profileWorkspace) { + writeFileSync(join(configDir, 'config'), `[default]\nworkspace = ${profileWorkspace}\n`) + } vi.stubEnv('SIM_CONFIG_DIR', configDir) vi.stubEnv('SIM_ENDPOINT', 'https://sim.example') vi.stubEnv('SIM_API_KEY', 'sk-test') - vi.stubEnv('SIM_WORKSPACE', 'ws_1') + vi.stubEnv('SIM_WORKSPACE', workspace) vi.stubEnv('SIM_NO_UPDATE_CHECK', '1') vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response)) @@ -177,3 +181,73 @@ describe('a refused source write in JSON output', () => { } }) }) + +describe('a command run inside a source directory', () => { + const notFound = () => + new Response(JSON.stringify({ error: { code: 'NOT_FOUND', message: 'Table not found' } }), { + status: 404, + headers: { 'content-type': 'application/json' }, + }) + const requestedUrl = () => String(vi.mocked(fetch).mock.calls[0]?.[0]) + + /** Runs `sim [...flags] tables rows list tbl_1` from `cwd`, answered with a 404. */ + async function listRowsIn( + cwd: string, + options: Parameters[2], + flags: string[] = [] + ): Promise<{ stderr: string; exitCode: number }> { + const previous = process.cwd() + process.chdir(cwd) + try { + return await runAgainst([...flags, 'tables', 'rows', 'list', 'tbl_1'], notFound(), options) + } finally { + process.chdir(previous) + } + } + + /** A directory holding `record` at `.sim/`, with a `workflows/triage` folder below it. */ + function sourceDirectory(file: string, record: unknown): { root: string; folder: string } { + const root = mkdtempSync(join(tmpdir(), 'sim-cli-source-dir-')) + mkdirSync(join(root, '.sim')) + writeFileSync(join(root, '.sim', file), JSON.stringify(record)) + const folder = join(root, 'workflows', 'triage') + mkdirSync(folder, { recursive: true }) + return { root, folder } + } + + it('acts on the workspace the nearest one names, below -w and SIM_WORKSPACE and above the profile', async () => { + const { root, folder } = sourceDirectory('base.json', { workspaceId: 'ws_dir' }) + try { + const inDirectory = await listRowsIn(folder, { + workspace: '', + profileWorkspace: 'ws_profile', + }) + expect(requestedUrl()).toContain('ws_dir') + expect(inDirectory.stderr).toContain( + `searched workspace ws_dir, the workspace of the source directory ${realpathSync(root)}` + ) + + await listRowsIn(folder, {}) + expect(requestedUrl()).toContain('ws_1') + expect(requestedUrl()).not.toContain('ws_dir') + + await listRowsIn(folder, { workspace: '' }, ['-w', 'ws_flag']) + expect(requestedUrl()).toContain('ws_flag') + + await listRowsIn(tmpdir(), { workspace: '', profileWorkspace: 'ws_profile' }) + expect(requestedUrl()).toContain('ws_profile') + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) + + it('acts on the workspace a starter was written for, as a create from it does', async () => { + const { root } = sourceDirectory('starter.json', { workspaceId: 'ws_starter' }) + try { + await listRowsIn(root, { workspace: '', profileWorkspace: 'ws_profile' }) + expect(requestedUrl()).toContain('ws_starter') + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) +}) diff --git a/packages/sim-cli/src/terminal.ts b/packages/sim-cli/src/terminal.ts index 1bd094917ed..f8caedde599 100644 --- a/packages/sim-cli/src/terminal.ts +++ b/packages/sim-cli/src/terminal.ts @@ -2,8 +2,9 @@ import type { Command } from 'commander' import { dump } from 'js-yaml' import { styles } from '#sim-cli/output/presentation' import { CliUpdateError } from '#sim-cli/update/install' +import { enclosingWorkspace } from './commands/protocol/source-dir' import { ProfileConfigError } from './config/index' -import { profileFrom } from './context' +import { profileFrom, setWorkingDirectoryWorkspace } from './context' import { CliExit } from './embed-context' import { formatApiErrorDetails, @@ -78,6 +79,12 @@ export async function runTerminalCli(suppliedProgram?: Command): Promise { const telemetry = suppliedProgram ? undefined : createCommandTelemetry() const program = suppliedProgram ?? buildProgram() telemetry?.observe(program) + // The working directory's workspace is read here, once, with the readers source commands use, + // because it is a terminal's alone: an embedded run has no working directory of its own. + program.hook('preAction', async () => { + const named = await enclosingWorkspace(process.cwd()) + if (named) setWorkingDirectoryWorkspace(program, named) + }) try { await program.parseAsync(process.argv) } catch (error) { diff --git a/packages/sim-cli/src/test/context-mock.ts b/packages/sim-cli/src/test/context-mock.ts index 0f80d1ef36e..dcb3df8380e 100644 --- a/packages/sim-cli/src/test/context-mock.ts +++ b/packages/sim-cli/src/test/context-mock.ts @@ -16,7 +16,10 @@ export const contextMockState: { workspaceSource: 'config', } -/** The resolved profile `clientFrom` and `profileFrom` return, built from {@link contextMockState}. */ +/** + * The resolved profile `clientFrom`, `profileFrom` and `actingProfileFrom` return, built from + * {@link contextMockState}. + */ export function mockedProfile() { return { workspaceId: contextMockState.workspaceId as string | null, @@ -63,5 +66,6 @@ export const contextMockFns = { export const contextMock = { globalsOf: contextMockFns.mockGlobalsOf, profileFrom: contextMockFns.mockProfileFrom, + actingProfileFrom: contextMockFns.mockProfileFrom, clientFrom: contextMockFns.mockClientFrom, } diff --git a/packages/workflow-code/src/agent-tools.ts b/packages/workflow-code/src/agent-tools.ts index acbcf3dbf77..b1c363f8d35 100644 --- a/packages/workflow-code/src/agent-tools.ts +++ b/packages/workflow-code/src/agent-tools.ts @@ -7,10 +7,9 @@ * of these types prints through its block builder or `raw(tool)`. */ -import { isRecordLike } from '@sim/utils/object' import { toolModes } from './canonicalize/modes' import type { BlockCatalog } from './catalog/types' -import type { CanonicalTool, Json, ResourceKind, ResourceNode, Value } from './model' +import { type CanonicalTool, isResource, type Json, type ResourceNode, type Value } from './model' import { deepEqual, setOwn } from './records' /** The stored type of an MCP server tool entry. */ @@ -95,15 +94,6 @@ function usageOf(tool: CanonicalTool): ToolUsage { } } -function isResource(value: Value | undefined, kind: ResourceKind): value is ResourceNode { - return ( - isRecordLike(value) && - value.$sim === 'resource' && - value.kind === kind && - typeof value.key === 'string' - ) -} - function optionalString(value: Value | undefined): value is string | undefined { return value === undefined || typeof value === 'string' } diff --git a/packages/workflow-code/src/child-results.ts b/packages/workflow-code/src/child-results.ts new file mode 100644 index 00000000000..67746c750de --- /dev/null +++ b/packages/workflow-code/src/child-results.ts @@ -0,0 +1,145 @@ +/** + * The result fields of a set of workflows that may call one another, each typed by the fields of + * the workflows it calls: a workspace check, an apply and a read all resolve them here, so a + * `>` is typed the same way by each. + */ + +import type { BlockCatalog } from './catalog/types' +import { type CompileInput, type CompileResult, compileWorkflow } from './compile' +import type { ChildResultFields } from './json-fields' +import { SOURCE_ENTRY_FILE } from './limits' +import type { WorkflowLockV1 } from './lock' +import type { CanonicalWorkflow } from './model' +import { calledWorkflowKeys, childResultFields } from './responds' + +/** By child workflow key, the result fields that type a call's `>`. */ +export type ChildResults = ReadonlyMap + +/** One workflow, as {@link resolveChildResults} reads it. */ +export interface ChildResultNode { + /** The keys of the workflows it calls. */ + calls: readonly string[] + /** Its result fields, its calls typed by `childResults` (of the workflows it calls). */ + fields(childResults: ChildResults): ChildResultFields | null +} + +/** + * What a workflow source folder compiles from offline, as a check and a parent's call typed by it + * read it: `entry` (its `workflow.ts`) and its code files against `catalog`, continuing the stored + * workflow its lock binds (`storedUnread`, so a `stored()` param of a bound block compiles unread). + */ +export function folderCompileInput( + entry: string, + files: Readonly>, + lock: WorkflowLockV1 | undefined, + catalog: BlockCatalog +): CompileInput { + return { + entry: { path: SOURCE_ENTRY_FILE, text: entry }, + files: new Map(Object.entries(files).filter(([path]) => path !== SOURCE_ENTRY_FILE)), + catalog, + sdkMajor: catalog.sdkMajor, + knownKeys: new Set(Object.keys(lock?.blocks ?? {})), + ...(lock ? { storedUnread: lock } : {}), + } +} + +/** + * The {@link ChildResultNode} of the source `input` compiles (`compiled`, its compile without + * child results), compiled again with its callees' fields when any types a call it makes. + */ +export function compiledResultNode( + input: CompileInput, + compiled: CompileResult = compileWorkflow(input) +): ChildResultNode | null { + const { workflow } = compiled + if (!workflow) return null + const calls = calledWorkflowKeys(workflow) + return { + calls, + fields: (childResults) => { + const typed = calls.some((key) => childResults.has(key)) + ? compileWorkflow({ ...input, childResults }).workflow + : workflow + return typed && childResultFields(typed, input.catalog, childResults) + }, + } +} + +/** The {@link ChildResultNode} of a stored workflow canonicalized as `workflow`. */ +export function canonicalResultNode( + workflow: CanonicalWorkflow, + catalog: BlockCatalog +): ChildResultNode { + return { + calls: calledWorkflowKeys(workflow), + fields: (childResults) => childResultFields(workflow, catalog, childResults), + } +} + +/** + * The result fields of each workflow of `nodes` that has any, by key, callees first: each is typed + * by the fields of the workflows it calls, so a field forwarding a grandchild's is typed through + * the chain. A call to a workflow `nodes` lacks is untyped, and so is a call within a cycle (to a + * workflow that calls back to the caller): its fields are not known before its own, so every + * workflow of a cycle is typed without the others, whichever is read first. + */ +export function resolveChildResults( + nodes: ReadonlyMap +): Map { + const resolved = new Map() + for (const component of stronglyConnected(nodes)) { + const members = new Set(component) + for (const key of component) { + const node = nodes.get(key) + if (!node) continue + const childResults = new Map() + for (const call of node.calls) { + const fields = members.has(call) ? undefined : resolved.get(call) + if (fields) childResults.set(call, fields) + } + const fields = node.fields(childResults) + if (fields) resolved.set(key, fields) + } + } + return resolved +} + +/** + * The strongly connected components of the call graph `nodes` holds (Tarjan's algorithm), each + * listed after every component it calls into. + */ +function stronglyConnected(nodes: ReadonlyMap): string[][] { + const index = new Map() + const low = new Map() + const stack: string[] = [] + const onStack = new Set() + const components: string[][] = [] + const visit = (key: string) => { + index.set(key, index.size) + low.set(key, index.size - 1) + stack.push(key) + onStack.add(key) + for (const call of nodes.get(key)?.calls ?? []) { + if (!nodes.has(call)) continue + if (!index.has(call)) { + visit(call) + low.set(key, Math.min(low.get(key) ?? 0, low.get(call) ?? 0)) + } else if (onStack.has(call)) { + low.set(key, Math.min(low.get(key) ?? 0, index.get(call) ?? 0)) + } + } + if (low.get(key) !== index.get(key)) return + const component: string[] = [] + let member: string | undefined + do { + member = stack.pop() + if (member === undefined) break + onStack.delete(member) + component.push(member) + } while (member !== key) + components.push(component) + } + for (const key of nodes.keys()) if (!index.has(key)) visit(key) + return components +} diff --git a/packages/workflow-code/src/compile/blocks.ts b/packages/workflow-code/src/compile/blocks.ts index 2ba78cd721f..7ae95ea851f 100644 --- a/packages/workflow-code/src/compile/blocks.ts +++ b/packages/workflow-code/src/compile/blocks.ts @@ -84,6 +84,7 @@ import { type CompileContext, catalogBlockOf, EDGE_METHODS, + lockBinds, type ResolvedBuilder, rangeOf, recordSpan, @@ -791,16 +792,24 @@ function pairMode(field: Extract, value: Compile /** * `stored()`: the param keeps what the stored block holds (`CompileInput.stored`), a pair its * members and mode, without the value ever appearing in source. Only a block the stored workflow - * already has under this key and type, holding a value for the param, can keep one. + * already has under this key and type, holding a value for the param, can keep one. Under + * `CompileInput.storedUnread` a block the lock binds may be such a block, which only the server + * can tell, so its param is left out unread (neither refused nor defaulted, nor required). */ function keepStored( ctx: CompileContext, - state: Pick, + state: Pick & + Partial>, members: ReadonlyArray<{ id: SubBlockId; password?: boolean }>, property: ObjectProperty, field: CatalogField | null ): void { const { decl, params, modes } = state + if (!ctx.stored && lockBinds(ctx, decl)) { + for (const member of members) state.unset.add(member.id) + if (field) state.explained?.add(field.name) + return + } const stored = ctx.stored ? getOwn(ctx.stored.blocks, decl.key) : undefined const name = field?.name ?? members[0]?.id ?? '' const type = @@ -2051,16 +2060,6 @@ export function compileBlock(ctx: CompileContext, decl: BlockDecl): CompiledBloc : compileRegularBlock(ctx, decl) } -/** Whether the lock of an unread stored workflow binds `decl`, by key or by ident. */ -function lockBinds(ctx: CompileContext, decl: BlockDecl): boolean { - const lock = ctx.storedUnread - return ( - lock !== undefined && - (Object.hasOwn(lock.blocks, decl.key) || - (decl.ident !== null && ctx.storedUnreadIdents.has(decl.ident))) - ) -} - /** * A new block of a type an apply cannot place: `W_UNKNOWN_BLOCK_TYPE` for a `block()` of a type the * catalog does not hold, `W_TYPE_NOT_ADDABLE` for one it keeps only for blocks already using it diff --git a/packages/workflow-code/src/compile/context.ts b/packages/workflow-code/src/compile/context.ts index 347b13a8e8a..4f28367608d 100644 --- a/packages/workflow-code/src/compile/context.ts +++ b/packages/workflow-code/src/compile/context.ts @@ -235,6 +235,16 @@ interface Located { end?: number | null } +/** Whether the lock of an unread stored workflow (`storedUnread`) binds `decl`, by key or ident. */ +export function lockBinds(ctx: CompileContext, decl: BlockDecl): boolean { + const lock = ctx.storedUnread + return ( + lock !== undefined && + (Object.hasOwn(lock.blocks, decl.key) || + (decl.ident !== null && ctx.storedUnreadIdents.has(decl.ident))) + ) +} + /** The range a node covers in the entry file. */ export function rangeOf(ctx: CompileContext, node: Located): Range { const start = node.start ?? 0 diff --git a/packages/workflow-code/src/compile/ergonomics.test.ts b/packages/workflow-code/src/compile/ergonomics.test.ts index c82d891effb..f0304d174e0 100644 --- a/packages/workflow-code/src/compile/ergonomics.test.ts +++ b/packages/workflow-code/src/compile/ergonomics.test.ts @@ -150,6 +150,36 @@ describe('stored()', () => { expect(secrets(envPrint.diagnostics)).toEqual([]) }) + it('leaves stored() unread offline on a block the lock binds, a tool param included', () => { + const lock = { + version: 1 as const, + blocks: { + m: { id: 'id-m', parent: null, ident: 'm', order: 0 }, + a: { id: 'id-a', parent: null, ident: 'a', order: 1 }, + }, + variables: {}, + } + const offline = (body: string) => + compileWorkflow({ + entry: { path: 'workflow.ts', text: source(body) }, + files: new Map(), + catalog: TEST_CATALOG, + sdkMajor: 1, + knownKeys: new Set(Object.keys(lock.blocks)), + storedUnread: lock, + }) + const block = offline(" mail.send('M', { apiKey: stored(), to: 'x@y.z' })") + expect(codes(block)).toEqual([]) + expect(block.workflow?.blocks.m?.params.apiKey).toBeUndefined() + const tool = offline( + " agent('A', { model: 'm', tools: [mail.tool.send({ credential: credential('ops'), apiKey: stored() })] })" + ) + expect(codes(tool)).toEqual([]) + const unbound = offline(" mail.send('Other', { apiKey: stored() })") + expect(unbound.workflow).toBeNull() + expect(codes(unbound)).toContain('E_STORED_VALUE_MISSING') + }) + it('refuses stored() inside a value', () => { expect(codes(run(source(" mail.send('M', { to: [stored()] })"), storedWorkflow))).toContain( 'E_UNSUPPORTED_SYNTAX' diff --git a/packages/workflow-code/src/compile/index.ts b/packages/workflow-code/src/compile/index.ts index 5febf8c5759..1b3478131a2 100644 --- a/packages/workflow-code/src/compile/index.ts +++ b/packages/workflow-code/src/compile/index.ts @@ -13,7 +13,12 @@ import { compareEdges } from '../canonicalize/edges' import type { BlockCatalog } from '../catalog/types' import type { CompileDiagnosticCode } from '../diagnostics/codes' import type { LocatedDiagnostic, SourceSpan } from '../diagnostics/frame' -import { jsonFieldText, type RefTypeScope, refValueKind } from '../json-fields' +import { + type ChildResultFields, + jsonFieldText, + type RefTypeScope, + refValueKind, +} from '../json-fields' import { lockIdentRenames, type SourceHints, type WorkflowLockV1 } from '../lock' import { renamedReferenceRewriter } from '../materialize/values' import type { @@ -27,6 +32,7 @@ import type { VarKey, } from '../model' import { getOwn, setOwn } from '../records' +import { childResultScope } from '../responds' import { SDK_MODULE } from '../sdk' import { compileBlock } from './blocks' import { checkStorableLiterals, checkStorableText } from './characters' @@ -103,6 +109,13 @@ export interface CompileInput { * `W_ENV_UNKNOWN` hint points at; absent, the hint points at the workspace's env variables. */ envDeclaredIn?: string + /** + * By child workflow key, the fields of the data that child responds with on every run + * (`childResultFields` of its compiled workflow). A call's `>` is then + * typed by that field, so a JSON field stores it quoted when it is text and bare otherwise + * instead of reporting `W_JSON_REF_UNTYPED`. Absent, such a reference is untyped. + */ + childResults?: ReadonlyMap } /** The compiled workflow (or `null` after an error) with its diagnostics, spans and lock hints. */ @@ -717,6 +730,7 @@ function compileEntry( catalog: input.catalog, block: (key) => compiled.get(key), variable: (key) => ctx.variables.get(key), + childResult: childResultScope((key) => compiled.get(key), input.childResults), } const isString = (token: string) => refValueKind(token, refTypes) === 'string' /** Bare references nothing types, reported once the unknown paths are known (see below). */ diff --git a/packages/workflow-code/src/compile/tools.ts b/packages/workflow-code/src/compile/tools.ts index e3c27bf0132..ea25867f79c 100644 --- a/packages/workflow-code/src/compile/tools.ts +++ b/packages/workflow-code/src/compile/tools.ts @@ -32,7 +32,7 @@ import { import { deepEqual, getOwn, setOwn } from '../records' import { CUSTOM_TOOL_TYPE, hasToolForm } from '../sdk' import { holdsSecret, literalSecretFinding } from '../secrets' -import { type CompileContext, lookup, rangeOf, unsupported } from './context' +import { type CompileContext, lockBinds, lookup, rangeOf, unsupported } from './context' import { didYouMean, hintForNode, nodeLabel, suggestBuilder } from './hints' import { calleePath, @@ -509,7 +509,11 @@ function matchStoredTools( return matches } -/** Fills each `stored()` param from the stored tool its tool matched; `false` after a refusal. */ +/** + * Fills each `stored()` param from the stored tool its tool matched; `false` after a refusal. A + * tool of a block the lock of an unread stored workflow binds leaves it out unread, as `stored()` + * on a block param does. + */ function resolveStoredParams( ctx: CompileContext, site: ValueSite, @@ -517,6 +521,7 @@ function resolveStoredParams( tools: readonly CanonicalTool[], storedTools: readonly CanonicalTool[] ): boolean { + if (!ctx.stored && lockBinds(ctx, site.decl)) return true const matches = matchStoredTools(calls, tools, storedTools) let ok = true calls.forEach((call, index) => { diff --git a/packages/workflow-code/src/index.ts b/packages/workflow-code/src/index.ts index 2bd77a84f44..08e51782f2b 100644 --- a/packages/workflow-code/src/index.ts +++ b/packages/workflow-code/src/index.ts @@ -29,6 +29,14 @@ export { catalogTrigger, expandBlockCatalog, } from './catalog/view' +export { + type ChildResultNode, + type ChildResults, + canonicalResultNode, + compiledResultNode, + folderCompileInput, + resolveChildResults, +} from './child-results' export { checkCodeFileBijection, createJsContextScanner, @@ -38,7 +46,12 @@ export { isIdentifierName, parseStoredPath, } from './code-files' -export { type CompileResult, compileWorkflow, type StoredEdgeRef } from './compile' +export { + type CompileInput, + type CompileResult, + compileWorkflow, + type StoredEdgeRef, +} from './compile' export { codePointLabel, scriptName } from './compile/characters' export { didYouMean, suggestBuilder } from './compile/hints' export { bracketDepthOverflow, sdkHeader, sourceDepthOverflow } from './compile/parse' @@ -68,7 +81,7 @@ export { export { executableView } from './equivalence/executable' export { sha256Hex, stableStringify } from './hash' export { readsIterationOutOfScope, type ScopeNode } from './iteration-scope' -export { parseJsonField } from './json-fields' +export { type ChildResultFields, parseJsonField } from './json-fields' export { type DefinedField, fieldNames, @@ -112,7 +125,11 @@ export { isResourceKind } from './model' export { assignIdentifiers, printWorkflow } from './print' export { hasSuspiciousCharacter, printKey, printNumber, quoteString } from './print/strings' export { getOwn, invertRecord, parseJsonContainer, setOrDelete, setOwn } from './records' -export { respondsOnEveryRun } from './responds' +export { + calledWorkflowKey, + calledWorkflowKeys, + respondsOnEveryRun, +} from './responds' export { JS_RESERVED_WORDS, RESPONSE_OUTPUTS, SDK_CORE_EXPORTS } from './sdk' export { holdsSecret, withoutAuthScheme } from './secrets' export { diff --git a/packages/workflow-code/src/json-fields.test.ts b/packages/workflow-code/src/json-fields.test.ts index 52d5718c0eb..bc87cd02c3b 100644 --- a/packages/workflow-code/src/json-fields.test.ts +++ b/packages/workflow-code/src/json-fields.test.ts @@ -1,9 +1,18 @@ import { describe, expect, it } from 'vitest' import type { BlockCatalog, CatalogBlock } from './catalog/types' -import { compileWorkflow } from './compile' +import { + type ChildResultNode, + canonicalResultNode, + compiledResultNode, + folderCompileInput, + resolveChildResults, +} from './child-results' +import { type CompileInput, compileWorkflow } from './compile' import { TEST_CATALOG } from './compile/catalog.test-helpers' import { refValueKind, valueTree } from './json-fields' import type { CanonicalBlock, CanonicalWorkflow } from './model' +import { printWorkflow } from './print' +import { childResultFields } from './responds' const IMPORTS = "import { agent, api, raw, table, trigger, workflow } from '@sim/workflow-sdk'" @@ -443,3 +452,331 @@ describe('W_JSON_REF_UNTYPED on the whole of an output that can hold text', () = }) }) }) + +describe("a reference into a child workflow's Response data, in a JSON field", () => { + const catalog: BlockCatalog = { + ...TEST_CATALOG, + builders: { + ...TEST_CATALOG.builders, + runWorkflow: { type: 'workflow_input' }, + response: { type: 'response' }, + }, + blocks: { + ...TEST_CATALOG.blocks, + workflow_input: { + ...TEST_CATALOG.blocks.api, + type: 'workflow_input', + subBlocks: [ + { id: 'workflowId', type: 'workflow-selector', valueKind: 'resource', storage: 'native' }, + { id: 'inputMapping', type: 'input-mapping', valueKind: 'object', storage: 'native' }, + ], + outputs: { success: { type: 'boolean' }, result: { type: 'json' } }, + } as CatalogBlock, + response: { + ...TEST_CATALOG.blocks.api, + type: 'response', + subBlocks: [ + { id: 'dataMode', type: 'dropdown', valueKind: 'string', storage: 'native' }, + { id: 'data', type: 'code', valueKind: 'json', storage: 'native', neverDecoded: true }, + { id: 'status', type: 'short-input', valueKind: 'string', storage: 'native' }, + ], + outputs: { data: { type: 'json' }, status: { type: 'number' }, headers: { type: 'json' } }, + } as CatalogBlock, + }, + } + const imports = + "import { api, childWorkflow, condition, js, response, runWorkflow, stored, table, trigger, workflow } from '@sim/workflow-sdk'" + + function compileText(body: string, childResults?: CompileInput['childResults']) { + const text = `// @sim-sdk 1\n${imports}\n\nexport default workflow('Test', {}, () => {\n ${body}\n})\n` + return compileWorkflow({ + entry: { path: 'workflow.ts', text }, + files: new Map(), + catalog, + sdkMajor: 1, + ...(childResults ? { childResults } : {}), + }) + } + + function childFields(body: string) { + const { workflow: child } = compileText(body) + if (!child) throw new Error('the child did not compile') + return childResultFields(child, catalog) + } + + const NORMALIZE = [ + "const start = trigger.start('Start', { inputFormat: { phone: 'string', n: 'number' } })", + "const lookup = api('Lookup', { url: 'https://x' })", + "const reply = response('Reply', { body: { mobile: start.phone, count: start.n, valid: true, label: 'ok', raw: lookup.data } })", + 'start.to(lookup)', + 'lookup.to(reply)', + ].join('\n ') + + function parent(read: string, childResults?: CompileInput['childResults']) { + const result = compileText( + [ + "const start = trigger.start('Start', { inputFormat: { phone: 'string' } })", + "const call = runWorkflow('Call', { workflowId: childWorkflow('normalize-phone'), inputMapping: { phone: start.phone } })", + `const row = table.insertRow('Row', { data: { v: ${read} } })`, + 'start.to(call)', + 'call.to(row)', + ].join('\n '), + childResults + ) + const param = result.workflow?.blocks.row?.params.data + return { + stored: param?.kind === 'value' ? param.value : undefined, + untyped: result.diagnostics.filter((d) => d.code === 'W_JSON_REF_UNTYPED'), + } + } + + it("reads the kinds of a responding child's top-level body keys, leaving an untyped one out", () => { + expect(childFields(NORMALIZE)).toEqual( + new Map([ + ['mobile', 'string'], + ['count', 'typed'], + ['valid', 'typed'], + ['label', 'string'], + ]) + ) + }) + + it('reads nothing from a child that can end without responding', () => { + expect( + childFields( + [ + "const start = trigger.start('Start', { inputFormat: { phone: 'string' } })", + "const gate = condition('Gate', { yes: js`${start.phone} === 'y'` })", + "const reply = response('Reply', { body: { mobile: start.phone } })", + 'start.to(gate)', + 'gate.yes.to(reply)', + ].join('\n ') + ) + ).toBeNull() + }) + + it('keeps only the keys every Response block types the same way', () => { + expect( + childFields( + [ + "const start = trigger.start('Start', { inputFormat: { phone: 'string', n: 'number' } })", + "const gate = condition('Gate', { yes: js`${start.phone} === 'y'`, else: true })", + "const a = response('A', { body: { mobile: start.phone, n: start.n, only: 1 } })", + "const b = response('B', { body: { mobile: 'none', n: 'many' } })", + 'start.to(gate)', + 'gate.yes.to(a)', + 'gate.else.to(b)', + ].join('\n ') + ) + ).toEqual(new Map([['mobile', 'string']])) + }) + + it('stores a string field quoted and a typed one bare, with no W_JSON_REF_UNTYPED', () => { + const fields = childFields(NORMALIZE) + if (!fields) throw new Error('the child does not respond') + const childResults = new Map([['normalize-phone', fields]]) + + const text = parent('call.result.data.mobile', childResults) + expect(JSON.parse(String(text.stored))).toEqual({ v: '' }) + expect(text.untyped).toEqual([]) + + const count = parent('call.result.data.count', childResults) + expect(count.stored).toBe('{\n "v": \n}') + expect(count.untyped).toEqual([]) + }) + + it('still warns on a key the child does not type, a deeper path, another child, or no input', () => { + const fields = childFields(NORMALIZE) + if (!fields) throw new Error('the child does not respond') + const childResults = new Map([['normalize-phone', fields]]) + expect(parent('call.result.data.raw', childResults).untyped).toHaveLength(1) + expect(parent('call.result.data.mobile.digits', childResults).untyped).toHaveLength(1) + expect(parent('call.result.data.mobile', new Map([['other', fields]])).untyped).toHaveLength(1) + expect(parent('call.result.data.mobile').untyped).toHaveLength(1) + }) + + it('prints a stored reference back in the form the same compile stores again', () => { + const fields = childFields(NORMALIZE) + if (!fields) throw new Error('the child does not respond') + const childResults = new Map([['normalize-phone', fields]]) + const read = 'call.result.data.mobile' + const { workflow } = compileText( + [ + "const start = trigger.start('Start', { inputFormat: { phone: 'string' } })", + "const call = runWorkflow('Call', { workflowId: childWorkflow('normalize-phone'), inputMapping: { phone: start.phone } })", + `const row = table.insertRow('Row', { data: { v: ${read}, n: call.result.data.count } })`, + 'start.to(call)', + 'call.to(row)', + ].join('\n '), + childResults + ) + if (!workflow) throw new Error('the parent did not compile') + const stored = workflow.blocks.row?.params.data + + const printed = (typed?: CompileInput['childResults']) => { + const { files } = printWorkflow({ + workflow, + catalog, + options: { functionCode: 'inline' }, + ...(typed ? { childResults: typed } : {}), + }) + return files[0].text + } + const typedText = printed(childResults) + expect(typedText).toContain('data: { v: call.result.data.mobile, n: call.result.data.count }') + const again = compileWorkflow({ + entry: { path: 'workflow.ts', text: typedText }, + files: new Map(), + catalog, + sdkMajor: 1, + childResults, + }) + expect(again.workflow?.blocks.row?.params.data).toEqual(stored) + expect(again.diagnostics.filter((d) => d.code === 'W_JSON_REF_UNTYPED')).toEqual([]) + + expect(printed()).toContain('v: t`${call.result.data.mobile}`') + }) + + function source(body: string) { + return `// @sim-sdk 1\n${imports}\n\nexport default workflow('Test', {}, () => {\n ${body}\n})\n` + } + + /** A lock binding `keys` in order, as a get writes one. */ + function lockOf(...keys: string[]) { + return { + version: 1 as const, + blocks: Object.fromEntries( + keys.map((key, order) => [key, { id: `id-${key}`, parent: null, ident: key, order }]) + ), + variables: {}, + } + } + + describe('a child whose blocks keep stored() values', () => { + const CHILD = [ + "const start = trigger.start('Start', { inputFormat: { phone: 'string' } })", + "const lookup = api('Lookup', { url: stored() })", + "const reply = response('Reply', { body: { mobile: start.phone } })", + 'start.to(lookup)', + 'lookup.to(reply)', + ].join('\n ') + + it('is typed when compiled under its lock, as a check and an apply read it', () => { + const input = folderCompileInput( + source(CHILD), + {}, + lockOf('start', 'lookup', 'reply'), + catalog + ) + const compiled = compileWorkflow(input) + expect(compiled.diagnostics.map((d) => d.code)).toEqual([]) + expect(compiled.workflow?.blocks.lookup?.params.url).toBeUndefined() + expect(compiledResultNode(input, compiled)?.fields(new Map())).toEqual( + new Map([['mobile', 'string']]) + ) + }) + + it('is refused for a block the lock does not bind, or without a lock', () => { + for (const lock of [lockOf('start', 'reply'), undefined]) { + const compiled = compileWorkflow(folderCompileInput(source(CHILD), {}, lock, catalog)) + expect(compiled.workflow).toBeNull() + expect(compiled.diagnostics.map((d) => d.code)).toContain('E_STORED_VALUE_MISSING') + } + }) + }) + + describe('a chain of calls', () => { + const C = [ + "const start = trigger.start('Start', { inputFormat: { phone: 'string', n: 'number' } })", + "const reply = response('Reply', { body: { text: start.phone, n: start.n } })", + 'start.to(reply)', + ].join('\n ') + const B = [ + "const start = trigger.start('Start', { inputFormat: { phone: 'string' } })", + "const callC = runWorkflow('Call C', { workflowId: childWorkflow('c'), inputMapping: { phone: start.phone } })", + "const reply = response('Reply', { body: { text: callC.result.data.text, n: callC.result.data.n, own: 1 } })", + 'start.to(callC)', + 'callC.to(reply)', + ].join('\n ') + const A = [ + "const start = trigger.start('Start', { inputFormat: { phone: 'string' } })", + "const callB = runWorkflow('Call B', { workflowId: childWorkflow('b'), inputMapping: { phone: start.phone } })", + "const row = table.insertRow('Row', { data: { text: callB.result.data.text, n: callB.result.data.n } })", + 'start.to(callB)', + 'callB.to(row)', + ].join('\n ') + + function node(body: string): ChildResultNode { + const compiled = compiledResultNode(folderCompileInput(source(body), {}, undefined, catalog)) + if (!compiled) throw new Error('the workflow did not compile') + return compiled + } + + it('types a field forwarded from a grandchild, whatever order the workflows are read in', () => { + const forward = resolveChildResults( + new Map([ + ['a', node(A)], + ['b', node(B)], + ['c', node(C)], + ]) + ) + const backward = resolveChildResults( + new Map([ + ['c', node(C)], + ['b', node(B)], + ['a', node(A)], + ]) + ) + const typed = new Map([ + ['text', 'string'], + ['n', 'typed'], + ['own', 'typed'], + ]) + expect(forward.get('b')).toEqual(typed) + expect(backward.get('b')).toEqual(typed) + }) + + it('reads the same fields from the stored workflow the typed compile writes', () => { + const resolved = resolveChildResults( + new Map([ + ['b', node(B)], + ['c', node(C)], + ]) + ) + const calls = new Map([['c', resolved.get('c') ?? new Map()]]) + const { workflow: stored } = compileText(B, calls) + if (!stored) throw new Error('b did not compile') + expect(canonicalResultNode(stored, catalog).fields(calls)).toEqual(resolved.get('b')) + + const { workflow: parent, diagnostics } = compileText(A, resolved) + const data = parent?.blocks.row?.params.data + expect(data?.kind === 'value' && data.value).toBe( + '{\n "text": "",\n "n": \n}' + ) + expect(diagnostics.filter((d) => d.code === 'W_JSON_REF_UNTYPED')).toEqual([]) + }) + + it('leaves a field forwarded around a cycle untyped, whichever workflow is read first', () => { + const calling = (child: string, body: string) => + [ + "const start = trigger.start('Start', { inputFormat: { phone: 'string' } })", + `const call = runWorkflow('Call', { workflowId: childWorkflow('${child}'), inputMapping: { phone: start.phone } })`, + `const reply = response('Reply', { body: ${body} })`, + 'start.to(call)', + 'call.to(reply)', + ].join('\n ') + const bodies: Record = { + x: calling('y', "{ text: call.result.data.text, own: 'x' }"), + y: calling('x', "{ text: 'y', back: call.result.data.own }"), + } + for (const order of [ + ['x', 'y'], + ['y', 'x'], + ]) { + const resolved = resolveChildResults(new Map(order.map((key) => [key, node(bodies[key])]))) + expect(resolved.get('x')).toEqual(new Map([['own', 'string']])) + expect(resolved.get('y')).toEqual(new Map([['text', 'string']])) + } + }) + }) +}) diff --git a/packages/workflow-code/src/json-fields.ts b/packages/workflow-code/src/json-fields.ts index ba5d0bc6a6f..0083fcd69af 100644 --- a/packages/workflow-code/src/json-fields.ts +++ b/packages/workflow-code/src/json-fields.ts @@ -53,11 +53,27 @@ export type JsonTree = /** How a reference's value is typed; only `string` is stored quoted. */ type RefValueKind = 'string' | 'typed' | 'untyped' +/** + * The top-level fields of the data a child workflow always responds with, each with how it is + * typed (`childResultFields`, responds.ts); a field missing is untyped. + */ +export type ChildResultFields = ReadonlyMap> + /** What {@link refValueKind} reads: the workflow's blocks and variables. */ export interface RefTypeScope { catalog: BlockCatalog block(key: BlockKey): CanonicalBlock | undefined variable(key: string): CanonicalVariable | undefined + /** For a block that runs a child workflow, the fields of the data that child responds with. */ + childResult?(key: BlockKey): ChildResultFields | undefined +} + +/** The field `>` names, for a path that is exactly that. */ +function childResultField(segments: readonly RefSegment[]): string | undefined { + const [result, data, field] = segments + if (segments.length !== 3 || result?.kind !== 'name' || result.name !== 'result') return undefined + if (data?.kind !== 'name' || data.name !== 'data') return undefined + return field?.kind === 'name' ? field.name : undefined } const STRING_VARIABLE_TYPES: ReadonlySet = new Set(['string', 'plain']) @@ -181,8 +197,10 @@ export function responseFormatFields(param: CanonicalParam | undefined): string[ * declares it (a path into untyped JSON, a loop item, an unknown block). An environment variable * is a string; a variable goes by its type; a block output by its declared output type, else by * the field its dynamic outputs declare, or for a Function's `result` by what its JavaScript - * certainly returns there. An `any` output, or one the catalog marks `mayBeText` (a Function's - * `result`, an HTTP `data`), is `untyped` unless the code says otherwise. + * certainly returns there; a child workflow call's `result.data.` by the field the child's + * Response data holds, when the scope knows it ({@link RefTypeScope.childResult}). An `any` + * output, or one the catalog marks `mayBeText` (a Function's `result`, an HTTP `data`), is + * `untyped` unless the code says otherwise. */ export function refValueKind(token: string, scope: RefTypeScope): RefValueKind { if (token.startsWith('{{')) return 'string' @@ -206,6 +224,10 @@ export function refValueKind(token: string, scope: RefTypeScope): RefValueKind { ? 'typed' : 'untyped' } + const childField = childResultField(segments) + const childKind = + childField === undefined ? undefined : scope.childResult?.(head.name)?.get(childField) + if (childKind) return childKind const declared = catalogBlock(scope.catalog, block.type) if (!declared) return 'untyped' const outputs = blockOutputSchemas(scope.catalog, declared, { diff --git a/packages/workflow-code/src/model.ts b/packages/workflow-code/src/model.ts index ca5d7e62804..93893b41fe0 100644 --- a/packages/workflow-code/src/model.ts +++ b/packages/workflow-code/src/model.ts @@ -185,6 +185,16 @@ export function isSimNode(value: unknown): value is SimNode { ) } +/** Whether `value` is a resource node of `kind` (a {@link ResourceNode} with a string key). */ +export function isResource(value: Value | undefined, kind: ResourceKind): value is ResourceNode { + return ( + isRecordLike(value) && + value.$sim === 'resource' && + value.kind === kind && + typeof value.key === 'string' + ) +} + /** Whether a value is an object literal: a record with no `$sim` key. */ export function isPlainRecord(value: Value): value is { [key: string]: Value } { return isRecordLike(value) && !('$sim' in value) diff --git a/packages/workflow-code/src/print/context.ts b/packages/workflow-code/src/print/context.ts index ceab13466fa..bf75ceabbe5 100644 --- a/packages/workflow-code/src/print/context.ts +++ b/packages/workflow-code/src/print/context.ts @@ -7,11 +7,12 @@ import type { BlockCatalog } from '../catalog/types' import type { PrintDiagnosticCode } from '../diagnostics/codes' import type { Diagnostic } from '../diagnostics/frame' -import type { RefTypeScope } from '../json-fields' +import type { ChildResultFields, RefTypeScope } from '../json-fields' import { isCodeFilePath } from '../limits' import type { SourceHints } from '../lock' import type { BlockKey, CanonicalBlock, CanonicalEdge, CanonicalWorkflow } from '../model' import { getOwn } from '../records' +import { childResultScope } from '../responds' import { CommentPlacer } from './comments' import { RefPrinter, type RefScope } from './refs' import { breakParentCycles, subflowScope, visibility } from './scope' @@ -28,6 +29,13 @@ export interface PrintInput { catalog: BlockCatalog hints?: SourceHints options: PrintOptions + /** + * By child workflow key, the fields of the data that child responds with: what the compile the + * printed source goes back through types `>` by + * (`CompileInput.childResults`), so a stored reference prints in the form that compile stores + * again. + */ + childResults?: ReadonlyMap } /** One print's shared state; see the module comment. */ @@ -120,6 +128,7 @@ export function createPrintContext(input: PrintInput): PrintContext { catalog, block: (key) => blocks.get(key), variable: (key) => getOwn(workflow.variables, key), + childResult: childResultScope((key) => blocks.get(key), input.childResults), }, } for (const key of blocks.keys()) { diff --git a/packages/workflow-code/src/responds.ts b/packages/workflow-code/src/responds.ts index d49676bb766..547ef075817 100644 --- a/packages/workflow-code/src/responds.ts +++ b/packages/workflow-code/src/responds.ts @@ -1,14 +1,31 @@ /** - * Whether a workflow, called as a child, always answers with its Response block's output. + * What a workflow called as a child answers with: whether it always answers with its Response + * block's output, and how the top-level fields of that output's data are typed. */ import { alwaysEndsAtResponse, isElseConditionTitle, + RESPONSE_BLOCK_TYPE, type ResponseGraphBlock, } from '@sim/workflow-types/workflow' import { storedTitle } from './canonicalize/branches' -import type { CanonicalBlock, CanonicalWorkflow, Port } from './model' -import { setOwn } from './records' +import type { BlockCatalog } from './catalog/types' +import { + type ChildResultFields, + JsonRef, + type JsonTree, + parseJsonField, + type RefTypeScope, + refValueKind, +} from './json-fields' +import { + type BlockKey, + type CanonicalBlock, + type CanonicalWorkflow, + isResource, + type Port, +} from './model' +import { getOwn, setOwn } from './records' /** * The branches `block` always takes one of (as `getAlwaysTakenBranchHandles` reads stored @@ -55,3 +72,90 @@ export function respondsOnEveryRun(workflow: CanonicalWorkflow): boolean { })) ) } + +/** How a value at a top-level key of Response data is typed, or `undefined` when nothing says. */ +function responseFieldKind(value: JsonTree, scope: RefTypeScope): 'string' | 'typed' | undefined { + if (value instanceof JsonRef) { + if (value.quoted) return 'string' + return refValueKind(value.token, scope) === 'typed' ? 'typed' : undefined + } + return typeof value === 'string' ? 'string' : 'typed' +} + +/** + * The top-level fields of the data `workflow` responds with when a Workflow block calls it, each + * typed as its JSON field stores it: a quoted reference or a string is text, a literal or a + * reference the workflow types otherwise is typed (a call of its own by `childResults`, the + * fields of the workflows it calls), and an untyped reference is left out. A field counts only + * when every enabled Response block holds it typed the same way. `null` when a run can end + * without responding ({@link respondsOnEveryRun}) or a Response block's data is not a JSON object + * in the editor's JSON mode (what `response(name, { body: { … } })` stores). + */ +export function childResultFields( + workflow: CanonicalWorkflow, + catalog: BlockCatalog, + childResults?: ReadonlyMap +): ChildResultFields | null { + if (!respondsOnEveryRun(workflow)) return null + const block = (key: BlockKey) => getOwn(workflow.blocks, key) + const scope: RefTypeScope = { + catalog, + block, + variable: (key) => getOwn(workflow.variables, key), + childResult: childResultScope(block, childResults), + } + let fields: Map | null = null + for (const block of Object.values(workflow.blocks)) { + if (block.type !== RESPONSE_BLOCK_TYPE || !block.enabled) continue + const mode = getOwn(block.params, 'dataMode') + const data = getOwn(block.params, 'data') + if (mode?.kind !== 'value' || mode.value !== 'json') return null + const tree = + data?.kind === 'value' && typeof data.value === 'string' + ? parseJsonField(data.value) + : undefined + if (!tree || typeof tree !== 'object' || tree instanceof JsonRef || Array.isArray(tree)) + return null + const own = new Map() + for (const [name, value] of Object.entries(tree)) { + const kind = responseFieldKind(value, scope) + if (kind && (fields === null || fields.get(name) === kind)) own.set(name, kind) + } + fields = own + } + return fields +} + +/** The key of the workflow `block` runs as a child (its `workflowId` names one), else `null`. */ +export function calledWorkflowKey(block: CanonicalBlock): string | null { + const param = getOwn(block.params, 'workflowId') + const child = param?.kind === 'value' ? param.value : undefined + return isResource(child, 'workflow') ? child.key : null +} + +/** The keys of the workflows `workflow` runs as children, each once, in block order. */ +export function calledWorkflowKeys(workflow: CanonicalWorkflow): string[] { + const keys = new Set() + for (const block of Object.values(workflow.blocks)) { + const key = calledWorkflowKey(block) + if (key !== null) keys.add(key) + } + return [...keys] +} + +/** + * The {@link RefTypeScope.childResult} of a workflow whose blocks `block` reads: for a block that + * runs a child, that child's fields in `childResults` (child workflow key to + * {@link childResultFields}). Compile and print type `>` through it alike. + */ +export function childResultScope( + block: (key: BlockKey) => CanonicalBlock | undefined, + childResults: ReadonlyMap | undefined +): NonNullable { + return (key) => { + if (!childResults || childResults.size === 0) return undefined + const called = block(key) + const child = called ? calledWorkflowKey(called) : null + return child === null ? undefined : childResults.get(child) + } +} diff --git a/packages/workflow-sdk/cookbook/examples/cookbook.ts b/packages/workflow-sdk/cookbook/examples/cookbook.ts index f13b1890758..ace44d11c9c 100644 --- a/packages/workflow-sdk/cookbook/examples/cookbook.ts +++ b/packages/workflow-sdk/cookbook/examples/cookbook.ts @@ -135,9 +135,29 @@ export default workflow('Cookbook', { description: 'One example of each common b text: report.content, }) + // Branches that rejoin: a block both lead to runs once, after whichever branch ran. A block + // that did not run reads as null in js`` code and as '' in t`` text, so a function picks the + // branch's value with ?? and one response replies for both. + const size = condition('Order Size', { large: js`${shape.result.cents} >= 100000`, else: true }) + const review = table.upsertRow('Keep Open', { + tableId: table('orders'), + data: { orderId: start.orderId, status: 'open' }, + conflictColumn: 'orderId', + }) + const accept = table.upsertRow('Mark Answered', { + tableId: table('orders'), + data: { orderId: start.orderId, status: 'answered' }, + conflictColumn: 'orderId', + }) + const status = fn('Pick Status', { + code: js`return ${review.row.data.status} ?? ${accept.row.data.status}`, + }) + // Response: the API reply body. Wrap an untyped value (fn.result.x) in t`` when it is text. // body is the short form of the editor's JSON mode: { dataMode: 'json', data } as below. - const reply = response('Respond', { body: { risk: check.risk, id: t`${shape.result.id}` } }) + const reply = response('Respond', { + body: { risk: check.risk, id: t`${shape.result.id}`, status: t`${status.result}` }, + }) const rejected = response('Respond Rejected', { dataMode: 'json', data: { status: 'rejected' }, @@ -158,7 +178,12 @@ export default workflow('Cookbook', { description: 'One example of each common b route.med.to(docs) docs.to(shape) route.else.to(shape) - shape.to(reply) + shape.to(size) + size.large.to(review) + size.else.to(accept) + review.to(status) + accept.to(status) + status.to(reply) shape.onError(invalid) nightly.to(recent) recent.to(each) diff --git a/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts b/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts index e183175d73c..c98ad976c20 100644 --- a/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts +++ b/packages/workflow-sdk/src/codegen/cookbook-text.generated.ts @@ -1,4 +1,4 @@ // Generated by scripts/generate-embedded-text.ts from cookbook/examples; do not edit. /** The example workflows, file name → text, written as `.sim/examples/`: together one correct example of each common block. */ -export const COOKBOOK_EXAMPLES: Readonly> = {"agents.ts":"// @sim-sdk 1\nimport {\n agent,\n childWorkflow,\n credential,\n customTool,\n env,\n mcp,\n parallel,\n response,\n router,\n runWorkflow,\n slack,\n t,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `lookup-order`, `linear`, `ops-slack`,\n// `enrich-lead` and ANTHROPIC_API_KEY stand in for this workspace\u0027s resources\n// (.sim/sdk/workspace.d.ts; `sim workflows source resources` lists the real keys).\nexport default workflow(\n \u0027Cookbook: agents and subflows\u0027,\n { description: \u0027Router, agent tools, a child workflow and a parallel fan-out.\u0027 },\n () => {\n const start = trigger.start(\u0027Start\u0027, {\n inputFormat: { message: \u0027string\u0027, email: \u0027string\u0027, domains: \u0027array\u0027 },\n })\n\n // Router: the model picks one route by its description; wire with triage..to(...).\n const triage = router(\u0027Triage\u0027, {\n context: start.message,\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n routes: {\n support: \u0027A customer asking about an existing order\u0027,\n sales: \u0027A prospect asking about pricing or a demo\u0027,\n },\n })\n\n // Agent tools: a workspace custom tool, one tool of an MCP server, an integration operation\n // (.tool.; the params given here are fixed, the model fills the rest) and\n // another workflow.\n const support = agent(\u0027Support Agent\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: \u0027Answer the customer. Use your tools when they help.\u0027 },\n { role: \u0027user\u0027, content: start.message },\n ],\n tools: [\n customTool(\u0027lookup-order\u0027),\n mcp(\u0027linear\u0027).tool(\u0027create_issue\u0027),\n slack.tool.sendMessage({ credential: credential(\u0027ops-slack\u0027), channel: \u0027support-urgent\u0027 }),\n childWorkflow(\u0027enrich-lead\u0027).asTool(),\n ],\n })\n\n // Child workflow: inputMapping is checked against the child\u0027s start inputs. Its output is\n // enrich.result (untyped JSON): the child\u0027s response block output, so a field of the child\u0027s\n // response body is enrich.result.data..\n const enrich = runWorkflow(\u0027Enrich Lead\u0027, {\n workflowId: childWorkflow(\u0027enrich-lead\u0027),\n inputMapping: { email: start.email },\n })\n\n // Parallel: one branch per item, run at once. p.currentItem is the item and p.index its\n // position; each.results lists every branch\u0027s output once all finish. (loop.forEach is the\n // sequential form.) In a function code file inside the body, the same values are\n // $ref.parallel.currentItem and $ref.parallel.index.\n const each = parallel.collection(\u0027Each Domain\u0027, { collection: start.domains }, (p) => {\n const brief = agent(\u0027Company Brief\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [{ role: \u0027user\u0027, content: t`Describe ${p.currentItem} in two sentences.` }],\n })\n p.to(brief)\n })\n\n const answer = response(\u0027Answer\u0027, { body: { answer: support.content } })\n const briefs = response(\u0027Briefs\u0027, {\n body: { lead: t`${enrich.result}`, briefs: t`${each.results}` },\n })\n\n start.to(triage)\n triage.support.to(support)\n support.to(answer)\n triage.sales.to(enrich)\n enrich.to(each)\n each.to(briefs)\n }\n)\n","cookbook.ts":"// @sim-sdk 1\nimport {\n agent,\n condition,\n credential,\n env,\n fn,\n human,\n js,\n knowledge,\n knowledgeBase,\n loop,\n response,\n slack,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `orders`, `policies`, `ops-slack` and\n// ANTHROPIC_API_KEY stand in for this workspace\u0027s resources. `sim workflows source resources`\n// lists the real keys, and .sim/sdk/workspace.d.ts types them.\nexport default workflow(\u0027Cookbook\u0027, { description: \u0027One example of each common block.\u0027 }, () => {\n // Triggers: trigger.start (API/manual input), trigger.schedule, trigger.webhook.\n const start = trigger.start(\u0027Start\u0027, { inputFormat: { orderId: \u0027string\u0027, amount: \u0027number\u0027 } })\n const nightly = trigger.schedule(\u0027Nightly\u0027, {\n scheduleType: \u0027daily\u0027,\n dailyTime: \u002702:00\u0027,\n timezone: \u0027UTC\u0027,\n })\n\n // Agent: structured output via responseFormat; its fields become outputs (check.risk).\n // apiKey: needed on self-hosted Sim; hosted Sim supplies one.\n const check = agent(\u0027Check Order\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: \u0027Rate the fraud risk of an order as low, med or high.\u0027 },\n { role: \u0027user\u0027, content: t`Order ${start.orderId} for ${start.amount}` },\n ],\n responseFormat: {\n name: \u0027risk\u0027,\n strict: true,\n schema: {\n type: \u0027object\u0027,\n properties: {\n risk: { type: \u0027string\u0027, enum: [\u0027low\u0027, \u0027med\u0027, \u0027high\u0027] },\n reason: { type: \u0027string\u0027 },\n },\n required: [\u0027risk\u0027, \u0027reason\u0027],\n additionalProperties: false,\n },\n },\n })\n\n // Condition: one branch per key, `else: true` last; wire with route..to(...).\n const route = condition(\u0027Route Risk\u0027, {\n high: js`${check.risk} === \u0027high\u0027`,\n med: js`${check.risk} === \u0027med\u0027`,\n else: true,\n })\n\n // Function: inline JavaScript; reference outputs with ${...}. Result is fn.result.\n const shape = fn(\u0027Shape\u0027, {\n code: js`return { id: ${start.orderId}, cents: Math.round(${start.amount} * 100) }`,\n })\n\n // Tables: query rows (each row is { id, data: { column } }) and write one.\n const recent = table.queryRows(\u0027Recent Orders\u0027, {\n tableId: table(\u0027orders\u0027),\n filterInput: { all: [{ field: \u0027status\u0027, op: \u0027eq\u0027, value: \u0027open\u0027 }] },\n limit: 50,\n })\n // Upsert: replaces the row whose conflictColumn (a unique column, by name) matches data, else\n // inserts one, so a second run for the same order rewrites it and a column missing from data\n // is cleared (table.updateRowsByFilter changes only the columns it names). table.insertRow\n // takes the same data without conflictColumn and adds a row every run. data is keyed by column\n // name: a column declared as `phone: column.string({ name: \u0027mobile\u0027 })` is written as\n // { mobile: ... }.\n const save = table.upsertRow(\u0027Save Order\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027open\u0027 },\n conflictColumn: \u0027orderId\u0027,\n })\n\n // Knowledge base search: results is the list of matching chunks.\n const docs = knowledge.search(\u0027Policy Search\u0027, {\n knowledgeBaseId: knowledgeBase(\u0027policies\u0027),\n query: check.reason,\n topK: 3,\n })\n\n // Slack: a saved credential by key (see .sim/sdk/workspace.d.ts).\n const alert = slack.sendMessage(\u0027Alert Ops\u0027, {\n credential: credential(\u0027ops-slack\u0027),\n destinationType: \u0027channel\u0027,\n channel: \u0027ops-alerts\u0027,\n messageFormat: \u0027text\u0027,\n text: t`High-risk order ${start.orderId}: ${check.reason}`,\n })\n\n // Human in the loop: inputFormat is the form; answers are approval.submission..\n const approval = human(\u0027Manager Review\u0027, {\n builderData: [{ name: \u0027orderId\u0027, type: \u0027string\u0027, value: start.orderId }],\n inputFormat: { approved: { type: \u0027boolean\u0027, required: true }, note: \u0027string\u0027 },\n })\n const decided = condition(\u0027Approved\u0027, {\n yes: js`${approval.submission.approved} === true`,\n else: true,\n })\n\n // Loop over a list: p.currentItem is one element and p.index its position; the loop\u0027s results\n // is the list of iteration outputs. In js`` code a reference is the value itself, not text\n // spliced in: write it where an expression goes, never inside quotes (\u0027${x}\u0027 would give the\n // JSON, quotes included). A function code file (code: codeFile(\u0027./functions/line.js\u0027)) reads\n // other blocks as $ref.. ($ref.recentorders.rows) and, inside the loop body,\n // the iteration as $ref.loop.currentItem and $ref.loop.index.\n const each = loop.forEach(\u0027Each Order\u0027, { collection: recent.rows }, (p) => {\n const line = fn(\u0027Line\u0027, {\n code: js`return ${p.currentItem.data.orderId} + \u0027: \u0027 + ${p.currentItem.data.status}`,\n })\n p.to(line)\n })\n const report = agent(\u0027Report\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [{ role: \u0027user\u0027, content: t`Summarize these orders in 3 lines:\\n${each.results}` }],\n })\n const post = slack.sendMessage(\u0027Post Report\u0027, {\n credential: credential(\u0027ops-slack\u0027),\n destinationType: \u0027channel\u0027,\n channel: \u0027ops-daily\u0027,\n messageFormat: \u0027text\u0027,\n text: report.content,\n })\n\n // Response: the API reply body. Wrap an untyped value (fn.result.x) in t`` when it is text.\n // body is the short form of the editor\u0027s JSON mode: { dataMode: \u0027json\u0027, data } as below.\n const reply = response(\u0027Respond\u0027, { body: { risk: check.risk, id: t`${shape.result.id}` } })\n const rejected = response(\u0027Respond Rejected\u0027, {\n dataMode: \u0027json\u0027,\n data: { status: \u0027rejected\u0027 },\n })\n // Error path: shape.onError(invalid) runs invalid when the code throws. shape.error leads with\n // the line and code that threw; shape.errorMessage is the thrown message alone, for the caller.\n const invalid = response(\u0027Respond Invalid\u0027, { body: { error: shape.errorMessage }, status: 422 })\n\n // Wiring: a.to(b) chains; a block can fan out to several targets.\n start.to(check)\n check.to(save)\n save.to(route)\n route.high.to(alert)\n alert.to(approval)\n approval.to(decided)\n decided.yes.to(shape)\n decided.else.to(rejected)\n route.med.to(docs)\n docs.to(shape)\n route.else.to(shape)\n shape.to(reply)\n shape.onError(invalid)\n nightly.to(recent)\n recent.to(each)\n each.to(report)\n report.to(post)\n})\n","integrations.ts":"// @sim-sdk 1\nimport {\n api,\n credential,\n env,\n gmail,\n response,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `leads`, `ops-gmail`, CLEARBIT_KEY and\n// LEADS_WEBHOOK_TOKEN stand in for this workspace\u0027s resources (.sim/sdk/workspace.d.ts).\n// Integration builders are named by service, not block type: `gmail_v2` is `gmail.*`, and a\n// hidden older version lives under `legacy.*`. .sim/sdk/INDEX.md lists every builder.\nexport default workflow(\n \u0027Cookbook: integrations\u0027,\n { description: \u0027Webhook, weekday schedule, HTTP with headers, table update, Gmail, error path.\u0027 },\n () => {\n // Webhook trigger: inputFormat types the posted JSON fields (hook.leadId). With requireAuth\n // the caller must send the token; keep it in an env var.\n const hook = trigger.webhook(\u0027Lead Webhook\u0027, {\n requireAuth: true,\n token: env.LEADS_WEBHOOK_TOKEN,\n inputFormat: { leadId: \u0027string\u0027, email: \u0027string\u0027, domain: \u0027string\u0027 },\n })\n\n // Schedule: no weekday preset exists, so scheduleType \u0027custom\u0027 takes a 5-field cron.\n const weekdays = trigger.schedule(\u0027Weekdays 8am\u0027, {\n scheduleType: \u0027custom\u0027,\n cronExpression: \u00270 8 * * 1-5\u0027,\n timezone: \u0027America/New_York\u0027,\n })\n\n // HTTP request: headers (and query params) are table rows, { cells: { Key, Value } }.\n const lookup = api(\u0027Company Lookup\u0027, {\n url: t`https://company.clearbit.com/v2/companies/find?domain=${hook.domain}`,\n method: \u0027GET\u0027,\n headers: [{ cells: { Key: \u0027Authorization\u0027, Value: t`Bearer ${env.CLEARBIT_KEY}` } }],\n })\n\n // Update one row by id: data holds only the columns to change. lookup.data is untyped JSON,\n // so a text field from it is wrapped in t``.\n const save = table.updateRowById(\u0027Save Company\u0027, {\n tableId: table(\u0027leads\u0027),\n rowId: hook.leadId,\n data: { company: t`${lookup.data.name}`, enriched: true },\n })\n\n // Gmail (gmail_v2): send one email with a saved Google credential.\n const welcome = gmail.sendEmail(\u0027Welcome Email\u0027, {\n credential: credential(\u0027ops-gmail\u0027),\n to: hook.email,\n subject: \u0027Welcome aboard\u0027,\n body: t`Thanks for signing up from ${hook.domain}.`,\n })\n\n // Query rows, then email them as one digest. A typed column filter: { field, op, value }.\n const pending = table.queryRows(\u0027Pending Leads\u0027, {\n tableId: table(\u0027leads\u0027),\n filterInput: { all: [{ field: \u0027enriched\u0027, op: \u0027eq\u0027, value: false }] },\n limit: 100,\n })\n const digest = gmail.sendEmail(\u0027Pending Digest\u0027, {\n credential: credential(\u0027ops-gmail\u0027),\n to: \u0027ops@example.com\u0027,\n subject: \u0027Leads still to enrich\u0027,\n body: t`${pending.rows}`,\n })\n\n // Error path: x.onError(y) runs y when x fails, instead of failing the run; y reads the\n // failure message as x.error.\n const failed = response(\u0027Lookup Failed\u0027, {\n body: { ok: false, error: lookup.error },\n status: 502,\n })\n const done = response(\u0027Done\u0027, { body: { ok: true, row: save.row } })\n\n hook.to(lookup)\n lookup.to(save)\n lookup.onError(failed)\n save.to(welcome)\n welcome.to(done)\n weekdays.to(pending)\n pending.to(digest)\n }\n)\n"} +export const COOKBOOK_EXAMPLES: Readonly> = {"agents.ts":"// @sim-sdk 1\nimport {\n agent,\n childWorkflow,\n credential,\n customTool,\n env,\n mcp,\n parallel,\n response,\n router,\n runWorkflow,\n slack,\n t,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `lookup-order`, `linear`, `ops-slack`,\n// `enrich-lead` and ANTHROPIC_API_KEY stand in for this workspace\u0027s resources\n// (.sim/sdk/workspace.d.ts; `sim workflows source resources` lists the real keys).\nexport default workflow(\n \u0027Cookbook: agents and subflows\u0027,\n { description: \u0027Router, agent tools, a child workflow and a parallel fan-out.\u0027 },\n () => {\n const start = trigger.start(\u0027Start\u0027, {\n inputFormat: { message: \u0027string\u0027, email: \u0027string\u0027, domains: \u0027array\u0027 },\n })\n\n // Router: the model picks one route by its description; wire with triage..to(...).\n const triage = router(\u0027Triage\u0027, {\n context: start.message,\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n routes: {\n support: \u0027A customer asking about an existing order\u0027,\n sales: \u0027A prospect asking about pricing or a demo\u0027,\n },\n })\n\n // Agent tools: a workspace custom tool, one tool of an MCP server, an integration operation\n // (.tool.; the params given here are fixed, the model fills the rest) and\n // another workflow.\n const support = agent(\u0027Support Agent\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: \u0027Answer the customer. Use your tools when they help.\u0027 },\n { role: \u0027user\u0027, content: start.message },\n ],\n tools: [\n customTool(\u0027lookup-order\u0027),\n mcp(\u0027linear\u0027).tool(\u0027create_issue\u0027),\n slack.tool.sendMessage({ credential: credential(\u0027ops-slack\u0027), channel: \u0027support-urgent\u0027 }),\n childWorkflow(\u0027enrich-lead\u0027).asTool(),\n ],\n })\n\n // Child workflow: inputMapping is checked against the child\u0027s start inputs. Its output is\n // enrich.result (untyped JSON): the child\u0027s response block output, so a field of the child\u0027s\n // response body is enrich.result.data..\n const enrich = runWorkflow(\u0027Enrich Lead\u0027, {\n workflowId: childWorkflow(\u0027enrich-lead\u0027),\n inputMapping: { email: start.email },\n })\n\n // Parallel: one branch per item, run at once. p.currentItem is the item and p.index its\n // position; each.results lists every branch\u0027s output once all finish. (loop.forEach is the\n // sequential form.) In a function code file inside the body, the same values are\n // $ref.parallel.currentItem and $ref.parallel.index.\n const each = parallel.collection(\u0027Each Domain\u0027, { collection: start.domains }, (p) => {\n const brief = agent(\u0027Company Brief\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [{ role: \u0027user\u0027, content: t`Describe ${p.currentItem} in two sentences.` }],\n })\n p.to(brief)\n })\n\n const answer = response(\u0027Answer\u0027, { body: { answer: support.content } })\n const briefs = response(\u0027Briefs\u0027, {\n body: { lead: t`${enrich.result}`, briefs: t`${each.results}` },\n })\n\n start.to(triage)\n triage.support.to(support)\n support.to(answer)\n triage.sales.to(enrich)\n enrich.to(each)\n each.to(briefs)\n }\n)\n","cookbook.ts":"// @sim-sdk 1\nimport {\n agent,\n condition,\n credential,\n env,\n fn,\n human,\n js,\n knowledge,\n knowledgeBase,\n loop,\n response,\n slack,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `orders`, `policies`, `ops-slack` and\n// ANTHROPIC_API_KEY stand in for this workspace\u0027s resources. `sim workflows source resources`\n// lists the real keys, and .sim/sdk/workspace.d.ts types them.\nexport default workflow(\u0027Cookbook\u0027, { description: \u0027One example of each common block.\u0027 }, () => {\n // Triggers: trigger.start (API/manual input), trigger.schedule, trigger.webhook.\n const start = trigger.start(\u0027Start\u0027, { inputFormat: { orderId: \u0027string\u0027, amount: \u0027number\u0027 } })\n const nightly = trigger.schedule(\u0027Nightly\u0027, {\n scheduleType: \u0027daily\u0027,\n dailyTime: \u002702:00\u0027,\n timezone: \u0027UTC\u0027,\n })\n\n // Agent: structured output via responseFormat; its fields become outputs (check.risk).\n // apiKey: needed on self-hosted Sim; hosted Sim supplies one.\n const check = agent(\u0027Check Order\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [\n { role: \u0027system\u0027, content: \u0027Rate the fraud risk of an order as low, med or high.\u0027 },\n { role: \u0027user\u0027, content: t`Order ${start.orderId} for ${start.amount}` },\n ],\n responseFormat: {\n name: \u0027risk\u0027,\n strict: true,\n schema: {\n type: \u0027object\u0027,\n properties: {\n risk: { type: \u0027string\u0027, enum: [\u0027low\u0027, \u0027med\u0027, \u0027high\u0027] },\n reason: { type: \u0027string\u0027 },\n },\n required: [\u0027risk\u0027, \u0027reason\u0027],\n additionalProperties: false,\n },\n },\n })\n\n // Condition: one branch per key, `else: true` last; wire with route..to(...).\n const route = condition(\u0027Route Risk\u0027, {\n high: js`${check.risk} === \u0027high\u0027`,\n med: js`${check.risk} === \u0027med\u0027`,\n else: true,\n })\n\n // Function: inline JavaScript; reference outputs with ${...}. Result is fn.result.\n const shape = fn(\u0027Shape\u0027, {\n code: js`return { id: ${start.orderId}, cents: Math.round(${start.amount} * 100) }`,\n })\n\n // Tables: query rows (each row is { id, data: { column } }) and write one.\n const recent = table.queryRows(\u0027Recent Orders\u0027, {\n tableId: table(\u0027orders\u0027),\n filterInput: { all: [{ field: \u0027status\u0027, op: \u0027eq\u0027, value: \u0027open\u0027 }] },\n limit: 50,\n })\n // Upsert: replaces the row whose conflictColumn (a unique column, by name) matches data, else\n // inserts one, so a second run for the same order rewrites it and a column missing from data\n // is cleared (table.updateRowsByFilter changes only the columns it names). table.insertRow\n // takes the same data without conflictColumn and adds a row every run. data is keyed by column\n // name: a column declared as `phone: column.string({ name: \u0027mobile\u0027 })` is written as\n // { mobile: ... }.\n const save = table.upsertRow(\u0027Save Order\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027open\u0027 },\n conflictColumn: \u0027orderId\u0027,\n })\n\n // Knowledge base search: results is the list of matching chunks.\n const docs = knowledge.search(\u0027Policy Search\u0027, {\n knowledgeBaseId: knowledgeBase(\u0027policies\u0027),\n query: check.reason,\n topK: 3,\n })\n\n // Slack: a saved credential by key (see .sim/sdk/workspace.d.ts).\n const alert = slack.sendMessage(\u0027Alert Ops\u0027, {\n credential: credential(\u0027ops-slack\u0027),\n destinationType: \u0027channel\u0027,\n channel: \u0027ops-alerts\u0027,\n messageFormat: \u0027text\u0027,\n text: t`High-risk order ${start.orderId}: ${check.reason}`,\n })\n\n // Human in the loop: inputFormat is the form; answers are approval.submission..\n const approval = human(\u0027Manager Review\u0027, {\n builderData: [{ name: \u0027orderId\u0027, type: \u0027string\u0027, value: start.orderId }],\n inputFormat: { approved: { type: \u0027boolean\u0027, required: true }, note: \u0027string\u0027 },\n })\n const decided = condition(\u0027Approved\u0027, {\n yes: js`${approval.submission.approved} === true`,\n else: true,\n })\n\n // Loop over a list: p.currentItem is one element and p.index its position; the loop\u0027s results\n // is the list of iteration outputs. In js`` code a reference is the value itself, not text\n // spliced in: write it where an expression goes, never inside quotes (\u0027${x}\u0027 would give the\n // JSON, quotes included). A function code file (code: codeFile(\u0027./functions/line.js\u0027)) reads\n // other blocks as $ref.. ($ref.recentorders.rows) and, inside the loop body,\n // the iteration as $ref.loop.currentItem and $ref.loop.index.\n const each = loop.forEach(\u0027Each Order\u0027, { collection: recent.rows }, (p) => {\n const line = fn(\u0027Line\u0027, {\n code: js`return ${p.currentItem.data.orderId} + \u0027: \u0027 + ${p.currentItem.data.status}`,\n })\n p.to(line)\n })\n const report = agent(\u0027Report\u0027, {\n model: \u0027claude-sonnet-4-6\u0027,\n apiKey: env.ANTHROPIC_API_KEY,\n messages: [{ role: \u0027user\u0027, content: t`Summarize these orders in 3 lines:\\n${each.results}` }],\n })\n const post = slack.sendMessage(\u0027Post Report\u0027, {\n credential: credential(\u0027ops-slack\u0027),\n destinationType: \u0027channel\u0027,\n channel: \u0027ops-daily\u0027,\n messageFormat: \u0027text\u0027,\n text: report.content,\n })\n\n // Branches that rejoin: a block both lead to runs once, after whichever branch ran. A block\n // that did not run reads as null in js`` code and as \u0027\u0027 in t`` text, so a function picks the\n // branch\u0027s value with ?? and one response replies for both.\n const size = condition(\u0027Order Size\u0027, { large: js`${shape.result.cents} >= 100000`, else: true })\n const review = table.upsertRow(\u0027Keep Open\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027open\u0027 },\n conflictColumn: \u0027orderId\u0027,\n })\n const accept = table.upsertRow(\u0027Mark Answered\u0027, {\n tableId: table(\u0027orders\u0027),\n data: { orderId: start.orderId, status: \u0027answered\u0027 },\n conflictColumn: \u0027orderId\u0027,\n })\n const status = fn(\u0027Pick Status\u0027, {\n code: js`return ${review.row.data.status} ?? ${accept.row.data.status}`,\n })\n\n // Response: the API reply body. Wrap an untyped value (fn.result.x) in t`` when it is text.\n // body is the short form of the editor\u0027s JSON mode: { dataMode: \u0027json\u0027, data } as below.\n const reply = response(\u0027Respond\u0027, {\n body: { risk: check.risk, id: t`${shape.result.id}`, status: t`${status.result}` },\n })\n const rejected = response(\u0027Respond Rejected\u0027, {\n dataMode: \u0027json\u0027,\n data: { status: \u0027rejected\u0027 },\n })\n // Error path: shape.onError(invalid) runs invalid when the code throws. shape.error leads with\n // the line and code that threw; shape.errorMessage is the thrown message alone, for the caller.\n const invalid = response(\u0027Respond Invalid\u0027, { body: { error: shape.errorMessage }, status: 422 })\n\n // Wiring: a.to(b) chains; a block can fan out to several targets.\n start.to(check)\n check.to(save)\n save.to(route)\n route.high.to(alert)\n alert.to(approval)\n approval.to(decided)\n decided.yes.to(shape)\n decided.else.to(rejected)\n route.med.to(docs)\n docs.to(shape)\n route.else.to(shape)\n shape.to(size)\n size.large.to(review)\n size.else.to(accept)\n review.to(status)\n accept.to(status)\n status.to(reply)\n shape.onError(invalid)\n nightly.to(recent)\n recent.to(each)\n each.to(report)\n report.to(post)\n})\n","integrations.ts":"// @sim-sdk 1\nimport {\n api,\n credential,\n env,\n gmail,\n response,\n t,\n table,\n trigger,\n workflow,\n} from \u0027@sim/workflow-sdk\u0027\n\n// An example to copy from, not a workflow of yours: `leads`, `ops-gmail`, CLEARBIT_KEY and\n// LEADS_WEBHOOK_TOKEN stand in for this workspace\u0027s resources (.sim/sdk/workspace.d.ts).\n// Integration builders are named by service, not block type: `gmail_v2` is `gmail.*`, and a\n// hidden older version lives under `legacy.*`. .sim/sdk/INDEX.md lists every builder.\nexport default workflow(\n \u0027Cookbook: integrations\u0027,\n { description: \u0027Webhook, weekday schedule, HTTP with headers, table update, Gmail, error path.\u0027 },\n () => {\n // Webhook trigger: inputFormat types the posted JSON fields (hook.leadId). With requireAuth\n // the caller must send the token; keep it in an env var.\n const hook = trigger.webhook(\u0027Lead Webhook\u0027, {\n requireAuth: true,\n token: env.LEADS_WEBHOOK_TOKEN,\n inputFormat: { leadId: \u0027string\u0027, email: \u0027string\u0027, domain: \u0027string\u0027 },\n })\n\n // Schedule: no weekday preset exists, so scheduleType \u0027custom\u0027 takes a 5-field cron.\n const weekdays = trigger.schedule(\u0027Weekdays 8am\u0027, {\n scheduleType: \u0027custom\u0027,\n cronExpression: \u00270 8 * * 1-5\u0027,\n timezone: \u0027America/New_York\u0027,\n })\n\n // HTTP request: headers (and query params) are table rows, { cells: { Key, Value } }.\n const lookup = api(\u0027Company Lookup\u0027, {\n url: t`https://company.clearbit.com/v2/companies/find?domain=${hook.domain}`,\n method: \u0027GET\u0027,\n headers: [{ cells: { Key: \u0027Authorization\u0027, Value: t`Bearer ${env.CLEARBIT_KEY}` } }],\n })\n\n // Update one row by id: data holds only the columns to change. lookup.data is untyped JSON,\n // so a text field from it is wrapped in t``.\n const save = table.updateRowById(\u0027Save Company\u0027, {\n tableId: table(\u0027leads\u0027),\n rowId: hook.leadId,\n data: { company: t`${lookup.data.name}`, enriched: true },\n })\n\n // Gmail (gmail_v2): send one email with a saved Google credential.\n const welcome = gmail.sendEmail(\u0027Welcome Email\u0027, {\n credential: credential(\u0027ops-gmail\u0027),\n to: hook.email,\n subject: \u0027Welcome aboard\u0027,\n body: t`Thanks for signing up from ${hook.domain}.`,\n })\n\n // Query rows, then email them as one digest. A typed column filter: { field, op, value }.\n const pending = table.queryRows(\u0027Pending Leads\u0027, {\n tableId: table(\u0027leads\u0027),\n filterInput: { all: [{ field: \u0027enriched\u0027, op: \u0027eq\u0027, value: false }] },\n limit: 100,\n })\n const digest = gmail.sendEmail(\u0027Pending Digest\u0027, {\n credential: credential(\u0027ops-gmail\u0027),\n to: \u0027ops@example.com\u0027,\n subject: \u0027Leads still to enrich\u0027,\n body: t`${pending.rows}`,\n })\n\n // Error path: x.onError(y) runs y when x fails, instead of failing the run; y reads the\n // failure message as x.error.\n const failed = response(\u0027Lookup Failed\u0027, {\n body: { ok: false, error: lookup.error },\n status: 502,\n })\n const done = response(\u0027Done\u0027, { body: { ok: true, row: save.row } })\n\n hook.to(lookup)\n lookup.to(save)\n lookup.onError(failed)\n save.to(welcome)\n welcome.to(done)\n weekdays.to(pending)\n pending.to(digest)\n }\n)\n"} diff --git a/packages/workflow-sdk/src/codegen/semantics.ts b/packages/workflow-sdk/src/codegen/semantics.ts index 2d8ade48263..e5c814d62b7 100644 --- a/packages/workflow-sdk/src/codegen/semantics.ts +++ b/packages/workflow-sdk/src/codegen/semantics.ts @@ -32,7 +32,7 @@ export const RUNTIME_SEMANTICS: readonly string[] = [ "- **Joins run once.** A block with several incoming edges runs once, after every one of them has fired or been ruled out (a condition or router branch not taken, the normal edge of a block that failed into `onError`). `a.to(join)`, `b.to(join)`, `c.to(join)` wait for all three; behind a condition only the taken branch fires, and the join runs once after it. A block never runs once per incoming branch. A reference to a block that did not run (on the branch not taken) resolves empty: `null` as a whole value, in function code or in a condition, `''` inside text.", '- **Loop and parallel results.** `x.results` holds one entry per iteration (a parallel: per branch), and each entry is the list of outputs of the body blocks that ran in it, in the order they finished. With one block in the body its output is `x.results[i][0]`; `x.results.flat()` lists every output.', "- **Outputs in function code.** In `fn` code, `\u0024{a.content}` inside js`` is not spliced in as text: it becomes an expression that evaluates to the output's value, a string as a string and an object as an object. Write it where an expression goes (`const reply = \u0024{a.content}`, `[\u0024{a.content}, \u0024{b.content}]`) and never wrap it in quotes. Written inside a JavaScript string or template literal it splices in as JSON, quotes included (`'Hi \u0024{a.content}'` gives `Hi \"hello\"`). Python code works the same way.", - "- **Child workflows.** `const c = runWorkflow('C', { workflowId: childWorkflow('k'), inputMapping })` outputs the child's run as `c.result`: the output of the first `response` block the child reaches, `{ data, status, headers }` (a field of its `body` is `c.result.data.field`), or, with no `response` block, the output of the last block it ran. `c.result` is untyped: wrap a value that should become text in `t`. A deployed run of the parent (API, webhook, schedule, chat) runs the child's deployed version and fails while the child is not deployed; a run from the editor runs the child's draft. A failed child fails `c` (`c.onError(...)` catches it).", + "- **Child workflows.** `const c = runWorkflow('C', { workflowId: childWorkflow('k'), inputMapping })` outputs the child's run as `c.result`: the output of the first `response` block the child reaches, `{ data, status, headers }` (a field of its `body` is `c.result.data.field`), or, with no `response` block, the output of the last block it ran. `c.result` is untyped, except `c.result.data.field` of a child in the workspace that responds on every run, typed by its `body` (a check reads the child only in a workspace directory): wrap any other value that should become text in `t`. A deployed run of the parent (API, webhook, schedule, chat) runs the child's deployed version and fails while the child is not deployed; a run from the editor runs the child's draft. A failed child fails `c` (`c.onError(...)` catches it).", "- **MCP headers** (`mcp/.ts`). A header value is plain text in which `{{NAME}}` names an env variable anywhere (`Authorization: 'Bearer {{GITHUB_TOKEN}}'`), `env.NAME` for a whole value, or `stored()` to keep the value the server holds. A `t` template or a template literal with `\u0024{}` is refused. A credential header (`Authorization`, `Cookie`, or a name with `key`, `token`, `secret`, `auth`, `password`, `session`, `signature` or `credential`) holds nothing but an optional scheme word (`Bearer`, `Basic`, `Token`, `Bot`, `Digest`, `ApiKey`, `Key`) and `{{NAME}}` references (`E_MCP_LITERAL_SECRET`). The variables resolve when the server connects, from the personal and workspace env (the workspace value wins); a missing one fails the connection.", "- **Table rows are keyed by column name.** A Table block's `data` (and `conflictColumn`, and a filter's `field`) names each column by its name: its key in `tables/.ts`, or the `name` set there (`phone: column.string({ name: 'mobile' })` is written `{ mobile: … }`). A key naming no column is dropped from the row at run time; `check` and `apply` warn on it (`W_TABLE_UNKNOWN_COLUMN`). A table's `rows.jsonl` is the exception: it is keyed by column key.", "- **MCP tool names are checked late.** `mcp('k').tool('name')` is type-checked only when `workspace.d.ts` lists that server's tools; a server that could not be listed, or one declared but not yet applied, takes any name. `sim workflows source check` and `sim workflows source apply` do not check tool names (the apply checks only that the server exists). `sim workspaces source apply` checks the tools of each workflow it changes against the server's live listing (`E_MCP_TOOL_UNKNOWN`, or `W_MCP_TOOLS_UNCHECKED` when it cannot list the server). Otherwise a wrong name surfaces at run time: the agent block fails before the model runs, `MCP operation \"name\" is missing or not permitted`.", diff --git a/packages/workspace-code/src/promote.ts b/packages/workspace-code/src/promote.ts index 40fe74d2147..f4f36f77b5c 100644 --- a/packages/workspace-code/src/promote.ts +++ b/packages/workspace-code/src/promote.ts @@ -175,7 +175,8 @@ function folderWorkflow( /** * Reads a promotion record for `workspaceId`; `undefined` for anything else (no record, another - * target's, an unreadable one), which makes the promotion take the target as it stands. + * target's, an unreadable one): the promotion then has no baseline, so it updates every resource + * to match the directory and refuses none as stale. */ export function parsePromotionRecord( input: unknown,