diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 9bd9351dd87..059624a490b 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8622,6 +8622,7 @@ sim workflows source get [options] | `--function-code ` | No | Where function-block code goes: `files` (default) writes it to `functions/*` files referenced with `codeFile()`; `inline` prints it in tagged templates. Accepted values: `inline`, `files`. | | `--dir ` | No | Write the source, its lock and SDK type declarations into this directory instead of printing them. | | `--force` | No | With --dir: replace another workflow's source or edits no apply has saved. | +| `--primer` | No | Also print the primer written atop .sim/AGENTS.md (a `primer` field in JSON). | @@ -8809,10 +8810,11 @@ sim workflows source params [options] | Option | Required | Description | | --- | --- | --- | | `--dir ` | No | Source directory whose catalog to read. Defaults to `.`. | +| `--full` | No | Print every param with its type, enum, default and doc, not the brief form. | -Prints a builder's params (required first, with enums and defaults), the gate field that picks which others apply, and its outputs, from the block catalog the last get, create or check cached. No request is made. <builder> is the dotted builder path as source writes it: table.upsertRow, agent, trigger.schedule, slack.sendMessage (slack.tool.sendMessage names the same builder). A namespace (gmail, trigger.gmail) lists its builders; a block type prints the builder written for it (function is fn) or lists them (table_v2); a construct core.d.ts declares (loop, parallel, t, env) prints its declaration. Run it from a workflow or workspace source directory, or pass --dir. +Prints a builder in brief (an example call, the required params with types, the optional ones by name, the gate field that picks which others apply, and the outputs), from the block catalog the last get, create or check cached. --full prints every param with its type, enum, default and doc. A legacy builder names the one that replaces it. No request is made. <builder> is the dotted builder path as source writes it: table.upsertRow, agent, trigger.schedule, slack.sendMessage (slack.tool.sendMessage names the same builder). A namespace (gmail, trigger.gmail) lists its builders; a block type prints the builder written for it (function is fn) or lists them (table_v2); a construct core.d.ts declares (loop, parallel, t, env) prints its declaration. Run it from a workflow or workspace source directory, or pass --dir. Exit codes: 0 printed; 1 no builder or namespace of that name (the closest one is named), or no cached catalog (run a get once). @@ -10035,6 +10037,7 @@ sim workspaces source get [options] | Option | Required | Description | | --- | --- | --- | +| `--primer` | No | Also print the primer written atop .sim/AGENTS.md (a `primer` field in JSON). | | `--dir ` | Yes | Directory to write the workspace source into. | | `--only ` | No | Read only these kinds (comma-separated folders: secrets.ts, credentials.ts, tools, skills, mcp, tables, knowledge, files, workflows, deployments). | | `--force` | No | Replace files with edits no apply has saved. | diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index b58981fcf39..8760141181e 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1379,6 +1379,7 @@ sim workflows source get [options] | `--function-code ` | No | Where function-block code goes: `files` (default) writes it to `functions/*` files referenced with `codeFile()`; `inline` prints it in tagged templates. Accepted values: `inline`, `files`. | | `--dir ` | No | Write the source, its lock and SDK type declarations into this directory instead of printing them. | | `--force` | No | With --dir: replace another workflow's source or edits no apply has saved. | +| `--primer` | No | Also print the primer written atop .sim/AGENTS.md (a `primer` field in JSON). | @@ -1574,10 +1575,11 @@ sim workflows source params [options] | Option | Required | Description | | --- | --- | --- | | `--dir ` | No | Source directory whose catalog to read. Defaults to `.`. | +| `--full` | No | Print every param with its type, enum, default and doc, not the brief form. | -Prints a builder's params (required first, with enums and defaults), the gate field that picks which others apply, and its outputs, from the block catalog the last get, create or check cached. No request is made. <builder> is the dotted builder path as source writes it: table.upsertRow, agent, trigger.schedule, slack.sendMessage (slack.tool.sendMessage names the same builder). A namespace (gmail, trigger.gmail) lists its builders; a block type prints the builder written for it (function is fn) or lists them (table_v2); a construct core.d.ts declares (loop, parallel, t, env) prints its declaration. Run it from a workflow or workspace source directory, or pass --dir. +Prints a builder in brief (an example call, the required params with types, the optional ones by name, the gate field that picks which others apply, and the outputs), from the block catalog the last get, create or check cached. --full prints every param with its type, enum, default and doc. A legacy builder names the one that replaces it. No request is made. <builder> is the dotted builder path as source writes it: table.upsertRow, agent, trigger.schedule, slack.sendMessage (slack.tool.sendMessage names the same builder). A namespace (gmail, trigger.gmail) lists its builders; a block type prints the builder written for it (function is fn) or lists them (table_v2); a construct core.d.ts declares (loop, parallel, t, env) prints its declaration. Run it from a workflow or workspace source directory, or pass --dir. Exit codes: 0 printed; 1 no builder or namespace of that name (the closest one is named), or no cached catalog (run a get once). diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index ccaae1e1758..619562b560f 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -700,6 +700,7 @@ sim workspaces source get [options] | Option | Required | Description | | --- | --- | --- | +| `--primer` | No | Also print the primer written atop .sim/AGENTS.md (a `primer` field in JSON). | | `--dir ` | Yes | Directory to write the workspace source into. | | `--only ` | No | Read only these kinds (comma-separated folders: secrets.ts, credentials.ts, tools, skills, mcp, tables, knowledge, files, workflows, deployments). | | `--force` | No | Replace files with edits no apply has saved. | diff --git a/apps/docs/content/docs/workflows/code/coding-agents.mdx b/apps/docs/content/docs/workflows/code/coding-agents.mdx index 77dd28d4c37..e96084c2b55 100644 --- a/apps/docs/content/docs/workflows/code/coding-agents.mdx +++ b/apps/docs/content/docs/workflows/code/coding-agents.mdx @@ -7,7 +7,7 @@ Claude Code, Cursor, Codex and other coding agents work from a directory that `g ## What get gives an agent -- A **primer**: `get` prints it (in JSON output, its `primer` field), and it opens `.sim/AGENTS.md`. It covers the edit loop, how block identity, references and renames work, failures and retries, test runs, deletes, deploy, exit codes, and the params of each builder the workflow already uses. +- A **primer**, which opens `.sim/AGENTS.md`. `get` prints a short summary instead (the files written, the guide, and the `editLoop` commands to run); `get --primer` also prints the primer (in JSON output, its `primer` field). It covers the edit loop, how block identity, references and renames work, failures and retries, test runs, deletes, deploy, exit codes, and the params of each builder the workflow already uses. - **`.sim/AGENTS.md`**: the primer followed by a reference, by task. A workspace directory also gets `.sim/GUIDE-advanced.md`. - **`.sim/examples/`**: one correct example of each common block to copy from. - **`.sim/sdk/`**: the type declarations, with `.sim/sdk/INDEX.md` listing the builders. @@ -26,7 +26,7 @@ For a whole workspace, use `sim workspaces source` with the same steps; see [Man ## Look things up -- `sim workflows source params ` prints a builder's params and outputs from the cached block catalog without a request. A namespace such as `gmail` lists its builders. +- `sim workflows source params ` prints a builder in brief (an example call, the required params with types, the optional ones by name and the outputs) from the cached block catalog without a request. `--full` prints every param with its type, options, default and doc. A legacy builder names the one that replaces it, and a namespace such as `gmail` lists its builders. - `sim workflows source resources` lists the tables, knowledge bases, credentials, workflows, skills, custom tools, MCP servers and environment variable names the file can name. - `sim workflows source catalog` shows the block catalog the source is checked against. diff --git a/apps/docs/content/docs/workflows/code/directory.mdx b/apps/docs/content/docs/workflows/code/directory.mdx index 321679afdb3..7b363e138f8 100644 --- a/apps/docs/content/docs/workflows/code/directory.mdx +++ b/apps/docs/content/docs/workflows/code/directory.mdx @@ -18,7 +18,7 @@ description: Every file a workflow directory and a workspace directory holds, wh | `.sim/written.json` | A digest of each file as the CLI last wrote it, so `status` and `get` tell your edits from the CLI's | Commit | | `.sim/stored-edges.json` | The connections the stored workflow held when it was printed, so an offline `check` tells them from connections you added. The CLI's own record, never sent | Commit | | `.sim/starter.json` | The workspace a starter was written for, before `create` | Not kept: removed once the workflow exists | -| `.sim/AGENTS.md` | The guide for coding agents: the primer `get` prints, then a reference | Optional, written again by `get` | +| `.sim/AGENTS.md` | The guide for coding agents: the primer, then a reference | Optional, written again by `get` | | `.sim/examples/` | Example workflows to copy from | Optional, written again by `get` | | `.sim/sdk/` | Type declarations for the blocks the workflow uses, and your workspace's tables, credentials, knowledge bases and environment variable names. `.sim/sdk/INDEX.md` lists the builders | Optional, written again by `get` and `check` | | `tsconfig.json` | Resolves the declarations and type-checks the blocks the workflow uses. Left as it is if you already have one | Commit | diff --git a/apps/docs/content/docs/workflows/code/edit.mdx b/apps/docs/content/docs/workflows/code/edit.mdx index 5a9fb5d89c5..69625fd3440 100644 --- a/apps/docs/content/docs/workflows/code/edit.mdx +++ b/apps/docs/content/docs/workflows/code/edit.mdx @@ -19,7 +19,7 @@ This writes `workflow.ts`, any function code under `functions/`, type declaratio `get` into a directory that already holds source refuses to overwrite edits you have not applied, and refuses a directory that holds a different workflow. Pass `--force` to replace them. A workspace directory is always refused, `--force` included. -To write a block the workflow does not use yet, `sim workflows source params ` (for example `table.upsertRow` or `trigger.schedule`) prints its params, required ones first with their options and defaults, and its outputs, from the cached block catalog without a request. A namespace such as `gmail` lists its builders. +To write a block the workflow does not use yet, `sim workflows source params ` (for example `table.upsertRow` or `trigger.schedule`) prints an example call, its required params with their types, its optional params by name and its outputs, from the cached block catalog without a request (`--full` adds every param's options, default and doc). A namespace such as `gmail` lists its builders. ## 2. Edit and check diff --git a/apps/docs/content/docs/workflows/code/index.mdx b/apps/docs/content/docs/workflows/code/index.mdx index 2a7cb5bc8d7..e9012034dc0 100644 --- a/apps/docs/content/docs/workflows/code/index.mdx +++ b/apps/docs/content/docs/workflows/code/index.mdx @@ -44,7 +44,7 @@ sim workflows source apply --dir ./support-triage --yes ## For coding agents [#for-coding-agents] -Claude Code, Cursor, Codex and other coding agents work from a directory that `get` writes. `get` prints a primer and writes the full guide to `.sim/AGENTS.md`. See [Use with coding agents](/workflows/code/coding-agents). +Claude Code, Cursor, Codex and other coding agents work from a directory that `get` writes. `get` prints a summary with the edit loop and writes the primer and full guide to `.sim/AGENTS.md`. See [Use with coding agents](/workflows/code/coding-agents). ## Related docs diff --git a/apps/docs/content/docs/workflows/code/syntax.mdx b/apps/docs/content/docs/workflows/code/syntax.mdx index 42bf9e2a800..a4776d4dfe2 100644 --- a/apps/docs/content/docs/workflows/code/syntax.mdx +++ b/apps/docs/content/docs/workflows/code/syntax.mdx @@ -196,7 +196,7 @@ A secret is never printed. A literal value in a password field prints as `stored ### JSON fields -A field that holds JSON text, such as `responseFormat`, a table row's `data` or a response body, takes an object or array literal and stores it as formatted JSON. Each bare reference inside is quoted when the output is a string and left bare otherwise, because the run splices a string raw and any other value as JSON. A reference no output type is known for is stored bare with `W_JSON_REF_UNTYPED`. A template is a JSON string, which is how a value becomes text on purpose. A resource helper inside the literal is `E_UNSUPPORTED_SYNTAX`. +A field that holds JSON text, such as `responseFormat`, a table row's `data` or a response body, takes an object or array literal and stores it as formatted JSON. Each bare reference inside is quoted when the output is a string and left bare otherwise, because the run splices a string raw and any other value as JSON. A field of a Function's `result` has the type its JavaScript certainly returns there (a string literal, `String(…)`, `.toISOString().slice(…)` and the like are text; arithmetic, comparisons and literals are not). A reference no output type is known for is stored bare with `W_JSON_REF_UNTYPED`. A template is a JSON string, which is how a value becomes text on purpose. A resource helper inside the literal is `E_UNSUPPORTED_SYNTAX`. ### Input formats and tools diff --git a/apps/docs/content/docs/workflows/code/workspace.mdx b/apps/docs/content/docs/workflows/code/workspace.mdx index be03a344d3f..20b2e3ae0d0 100644 --- a/apps/docs/content/docs/workflows/code/workspace.mdx +++ b/apps/docs/content/docs/workflows/code/workspace.mdx @@ -32,7 +32,7 @@ const log = table.insertRow('Log Question', { }) ``` -`get` prints a short primer for coding agents (in JSON output, its `primer` field) and writes it atop `.sim/AGENTS.md`, the guide, with deletes in depth, Git and CI, and promoting to another workspace in `.sim/GUIDE-advanced.md`. It also writes `.sim/examples/workspace/`, a complete example of every kind and the workflow that uses them. +`get` writes a short primer for coding agents atop `.sim/AGENTS.md` (`get --primer` also prints it, in JSON output as its `primer` field), the guide, with deletes in depth, Git and CI, and promoting to another workspace in `.sim/GUIDE-advanced.md`. It also writes `.sim/examples/workspace/`, a complete example of every kind and the workflow that uses them. ## Edit a workspace diff --git a/packages/sim-cli/src/commands/protocol/source-tree.ts b/packages/sim-cli/src/commands/protocol/source-tree.ts index 407de0def5f..e591bb6aab5 100644 --- a/packages/sim-cli/src/commands/protocol/source-tree.ts +++ b/packages/sim-cli/src/commands/protocol/source-tree.ts @@ -27,8 +27,10 @@ import { SDK_MAJOR, SDK_MODELS_FILE, sdkIndexHeader, + typecheckCommand, type WorkspaceManifest, } from '@sim/workflow-sdk/codegen' +import type { Command } from 'commander' import { printError, printLine } from '#sim-cli/output/io' import type { OutputFormat } from '../../config/index' import { readJsonFile, writeJsonFile } from '../../config/json-file' @@ -55,6 +57,7 @@ import { withMissingLines, } from './source-dir' import { AGENTS_POINTER_MARKER, agentsPointer, type PrimerKind, primerFor } from './source-primer' +import { shellWord } from './source-ui' const TSCONFIG_FILE = 'tsconfig.json' /** Where agents look first: the nearest `AGENTS.md` above the file they edit. */ @@ -572,12 +575,13 @@ export function finishTree( } /** - * Prints a tree write's result: in JSON or YAML one document with the primer as its `primer` - * field, otherwise the fields and then the primer as text, so it reads as written. + * Prints a tree write's result: the fields, then the primer as text when the result carries one + * (in JSON or YAML it is the document's `primer` field). A get leaves the primer out unless + * `--primer` asks for it: it is already the top of `.sim/AGENTS.md`. */ export function printTreeResult( format: OutputFormat, - result: Record & { primer: string } + result: Record & { primer?: string } ): void { if (format === 'json' || format === 'yaml') { printProtocolResult(format, result) @@ -585,7 +589,29 @@ export function printTreeResult( } const { primer, ...fields } = result printProtocolResult(format, fields) - printLine(`\n${primer}`) + if (primer !== undefined) printLine(`\n${primer}`) +} + +/** Adds `--primer` to a get command: it prints the primer the get writes atop `.sim/AGENTS.md`. */ +export function primerOption(command: Command): void { + command.option( + '--primer', + 'Also print the primer written atop .sim/AGENTS.md (a `primer` field in JSON)' + ) +} + +/** + * The commands of a directory's edit loop, in order, for a get's result: what the primer's loop + * says, runnable from anywhere because each names the directory. + */ +export function editLoop(kind: PrimerKind, dir: string): string[] { + const group = kind === 'workflow' ? 'sim workflows source' : 'sim workspaces source' + const at = shellWord(dir) + return [ + `${group} check --dir ${at}`, + typecheckCommand(at), + `${group} apply --dir ${at} --dry-run`, + ] } /** What a directory's editable tree holds beside the printed source. */ diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts index 9d8dce81924..91c0fe7a7bd 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.test.ts @@ -184,7 +184,7 @@ describe('sim workflows source get --dir', () => { expect(callsTo(CATALOG_PATH)[0][1].query).toBeUndefined() }) - it('prints the primer, which opens the guide, with a snippet for each builder the source calls and no other', async () => { + it('writes the primer atop the guide with a snippet for each builder the source calls and no other, printing it only with --primer', async () => { serve({ [SOURCE_PATH]: () => source({ 'workflow.ts': "// @sim-sdk 1\nconst mail = gmail.sendEmail('Mail', {})\n" }), @@ -192,10 +192,23 @@ describe('sim workflows source get --dir', () => { await get('--dir', outDir) + const printed = JSON.parse(vi.mocked(console.log).mock.calls.at(-1)?.join(' ') ?? '{}') + expect(printed).not.toHaveProperty('primer') + expect(printed.guide).toBe('.sim/AGENTS.md') + expect(printed.editLoop).toEqual([ + expect.stringMatching(/^sim workflows source check --dir /), + expect.stringMatching(/^bunx -p typescript@[\d.]+ tsc -p /), + expect.stringMatching(/^sim workflows source apply --dir .* --dry-run$/), + ]) + const agents = readFileSync(join(outDir, '.sim/AGENTS.md'), 'utf8') + expect(agents).toContain('- `gmail.sendEmail` (Gmail: Send Email)') + expect(agents).not.toContain('`slack.sendMessage`') + + vi.mocked(console.log).mockClear() + await get('--dir', outDir, '--primer') + const { primer } = JSON.parse(vi.mocked(console.log).mock.calls.at(-1)?.join(' ') ?? '{}') - expect(readFileSync(join(outDir, '.sim/AGENTS.md'), 'utf8').startsWith(primer)).toBe(true) - expect(primer).toContain('- `gmail.sendEmail` (Gmail: Send Email)') - expect(primer).not.toContain('`slack.sendMessage`') + expect(agents.startsWith(primer)).toBe(true) }) it('writes a root AGENTS.md pointing at the guide, and never replaces one it did not write', async () => { 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 28c6ec7cf27..4a9d147e2d3 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-get.ts @@ -15,7 +15,7 @@ import { withSourceCommandLock, } from './source-dir' import { sourceExitCodesHelp } from './source-exit-codes' -import { printTreeResult, withSourceExitCode } from './source-tree' +import { editLoop, primerOption, printTreeResult, withSourceExitCode } from './source-tree' import { findingsOutput } from './source-ui' import { type PrintedSource, writeSourceDirectory } from './workflow-dir' @@ -60,7 +60,8 @@ async function assertNoLocalEdits(dir: string, source: PrintedSource): Promise => { @@ -122,7 +124,7 @@ export function attachWorkflowSourceGet(source: Command): void { ) assertPrintedSourcePaths(workflowSource.files) if (!force) await assertNoLocalEdits(dir, workflowSource) - const tree = await writeSourceDirectory( + const { primer, ...tree } = await writeSourceDirectory( client, dir, workflowSource, @@ -134,6 +136,8 @@ export function attachWorkflowSourceGet(source: Command): void { workflowId: workflowSource.workflowId, dir, ...tree, + editLoop: editLoop('workflow', dir), + ...(flags.primer === true ? { primer } : {}), fingerprint: workflowSource.base.fingerprint, ...findings.result(workflowSource.diagnostics), }) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-params.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-params.test.ts index 1b3f69941dc..e0b6ff5fc86 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-params.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-params.test.ts @@ -84,7 +84,7 @@ describe('sim workflows source params', () => { cacheCatalogText(join(dir, 'config'), WORKSPACE_ID, catalogWithoutUpsert()) writeBase(printedWith) - await params('table.upsertRow') + await params('table.upsertRow', '--full') const { builder } = stdoutJson() as { builder: { key: string; params: { common: Array<{ key: string; required: boolean }> } } @@ -144,4 +144,94 @@ describe('sim workflows source params', () => { expect(error.code).toBe('CATALOG_NOT_CACHED') expect(contextMockFns.mockRequest).not.toHaveBeenCalled() }) + + it('prints a brief builder by default and every param with its docs under --full', async () => { + cacheCatalogText(join(dir, 'config'), WORKSPACE_ID, FIXTURE_TEXT) + writeBase() + + await params('table.upsertRow') + const brief = stdoutJson() as { + builder: { + required: Array<{ key: string; type: string }> + optional: string[] + outputs: string[] + } + } + expect(brief.builder.required.map((param) => param.key)).toEqual(['tableId', 'data']) + expect(brief.builder).not.toHaveProperty('params') + expect(brief.builder.outputs.length).toBeGreaterThan(0) + + vi.mocked(console.log).mockClear() + await params('table.upsertRow', '--full') + const full = stdoutJson() as { builder: { params: { common: unknown[] } } } + expect(full.builder.params.common.length).toBeGreaterThan(brief.builder.required.length) + expect(JSON.stringify(full).length).toBeGreaterThan(JSON.stringify(brief).length * 2) + }) + + it('keeps the call signature of a builder whose required params core.d.ts types', async () => { + cacheCatalogText(join(dir, 'config'), WORKSPACE_ID, FIXTURE_TEXT) + writeBase() + + await params('fn') + + const { builder } = stdoutJson() as { builder: { coreParams: string[]; signature?: string } } + expect(builder.coreParams).toContain('code') + expect(builder.signature).toContain('code:') + }) + + it('names the builder that replaces a legacy block type, by either name', async () => { + const catalog = JSON.parse(FIXTURE_TEXT) + catalog.blocks.human_in_the_loop = { + ...catalog.blocks.human_in_the_loop_v2, + type: 'human_in_the_loop', + lifecycle: { hidden: true, sunset: { status: 'legacy', replacedBy: 'human_in_the_loop_v2' } }, + } + catalog.builders['legacy.humanInTheLoop'] = { type: 'human_in_the_loop' } + cacheCatalogText( + join(dir, 'config'), + WORKSPACE_ID, + JSON.stringify({ ...catalog, hash: 'e'.repeat(64) }) + ) + writeBase() + + await params('human_in_the_loop') + + expect(stdoutJson()).toMatchObject({ + builder: { + key: 'legacy.humanInTheLoop', + legacy: true, + replacement: { blockType: 'human_in_the_loop_v2', builders: ['human'] }, + }, + }) + }) + + it('names only the replacement builders for the same operation, and few of them', async () => { + const catalog = JSON.parse(FIXTURE_TEXT) + catalog.blocks.old_block = { + ...catalog.blocks.human_in_the_loop_v2, + type: 'old_block', + lifecycle: { hidden: true, sunset: { status: 'legacy', replacedBy: 'new_block' } }, + } + catalog.blocks.new_block = { ...catalog.blocks.human_in_the_loop_v2, type: 'new_block' } + catalog.builders['legacy.old.send'] = { type: 'old_block', operation: 'send' } + for (let index = 0; index < 20; index++) { + catalog.builders[`next.op${index}`] = { type: 'new_block', operation: `op${index}` } + } + catalog.builders['next.send'] = { type: 'new_block', operation: 'send' } + cacheCatalogText( + join(dir, 'config'), + WORKSPACE_ID, + JSON.stringify({ ...catalog, hash: 'd'.repeat(64) }) + ) + writeBase() + + await params('legacy.old.send') + + const { builder } = stdoutJson() as { builder: { replacement: { builders: string[] } } } + expect(builder.replacement.builders).toEqual(['next.send']) + + vi.mocked(console.log).mockClear() + await params('legacy.old.send', '--full') + expect(stdoutJson()).toMatchObject({ builder: { replacement: { builders: ['next.send'] } } }) + }) }) 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 491d774aa59..8e0f226918f 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-params.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-params.ts @@ -1,7 +1,12 @@ import { toRecord } from '@sim/utils/object' import type { BlockCatalog } from '@sim/workflow-code' import { SOURCE_BASE_FILE } from '@sim/workflow-code/limits' -import { lookupBuilder, renderBuilderReference } from '@sim/workflow-sdk/codegen' +import { + compactBuilder, + lookupBuilder, + renderBuilderReference, + renderCompactBuilder, +} from '@sim/workflow-sdk/codegen' import type { Command } from 'commander' import { printLine } from '#sim-cli/output/io' import { profileFrom } from '../../context' @@ -12,9 +17,10 @@ import { cachedCatalog, cachedSourceCatalog } from './source-tree' import { isMachine } from './source-ui' const PARAMS_HELP = ` -Prints a builder's params (required first, with enums and defaults), the gate field that picks -which others apply, and its outputs, from the block catalog the last get, create or check cached. -No request is made. is the dotted builder path as source writes it: table.upsertRow, +Prints a builder in brief (an example call, the required params with types, the optional ones by +name, the gate field that picks which others apply, and the outputs), from the block catalog the +last get, create or check cached. --full prints every param with its type, enum, default and doc. +A legacy builder names the one that replaces it. No request is made. is the dotted builder path as source writes it: table.upsertRow, agent, trigger.schedule, slack.sendMessage (slack.tool.sendMessage names the same builder). A namespace (gmail, trigger.gmail) lists its builders; a block type prints the builder written for it (function is fn) or lists them (table_v2); a construct core.d.ts declares (loop, parallel, t, @@ -47,7 +53,8 @@ async function lookupCatalog(dir: string, profileWorkspace: string | null): Prom } /** - * `sim workflows source params [--dir ]`: one builder's params and outputs from the + * `sim workflows source params [--dir ] [--full]`: one builder in brief, or with + * every param's docs under `--full`, from the * cached catalog, so an agent reads the shape of a block it is about to write in one command * instead of searching the declarations. */ @@ -56,18 +63,25 @@ export function attachWorkflowSourceParams(source: Command): void { .command('params') .argument('', 'Builder path (table.upsertRow, agent, trigger.schedule) or namespace') .option('--dir ', 'Source directory whose catalog to read', '.') + .option('--full', 'Print every param with its type, enum, default and doc, not the brief form') .allowExcessArguments(false) .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 }, command: Command) => { + .action(async (query: string, options: { dir: string; full?: boolean }, command: Command) => { const profile = profileFrom(command) const catalog = await lookupCatalog(options.dir, profile.workspaceId) const found = lookupBuilder(catalog, query) const machine = isMachine(profile.output) switch (found.kind) { case 'builder': - if (machine) printProtocolResult(profile.output, { builder: found.reference }) - else printLine(renderBuilderReference(found.reference)) + if (machine) { + const builder = options.full ? found.reference : compactBuilder(found.reference) + printProtocolResult(profile.output, { builder }) + } else { + printLine( + (options.full ? renderBuilderReference : renderCompactBuilder)(found.reference) + ) + } return case 'namespace': if (machine) printProtocolResult(profile.output, found) diff --git a/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts b/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts index 1cfd254017d..a63e7fbb08d 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-get.test.ts @@ -186,6 +186,22 @@ describe('workspaces source get', () => { expect(readFileSync(join(dir, 'AGENTS.md'), 'utf8')).toBe('# Our rules\n') }) + it('names the edit loop instead of printing the primer, which --primer prints', async () => { + serve({ 'tables/leads.ts': LEADS }) + + await get() + + const printed = JSON.parse(vi.mocked(console.log).mock.calls.at(-1)?.join(' ') ?? '{}') + expect(printed).not.toHaveProperty('primer') + expect(printed.editLoop[0]).toMatch(/^sim workspaces source check --dir /) + + vi.mocked(console.log).mockClear() + await get('--primer') + + const { primer } = JSON.parse(vi.mocked(console.log).mock.calls.at(-1)?.join(' ') ?? '{}') + expect(readFileSync(join(dir, '.sim/AGENTS.md'), 'utf8').startsWith(primer)).toBe(true) + }) + it('writes the workspace primer atop the guide, and the deep dives to the advanced guide it names', async () => { serve({ 'tables/leads.ts': LEADS }) 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 14f69a4794d..601ee73deb8 100644 --- a/packages/sim-cli/src/commands/protocol/workspace-source-get.ts +++ b/packages/sim-cli/src/commands/protocol/workspace-source-get.ts @@ -33,9 +33,11 @@ import { import { sourceExitCodesHelp } from './source-exit-codes' import { assertSdkMajor, + editLoop, finishTree, loadCatalog, loadWorkspaceTypes, + primerOption, printTreeResult, sourceTreeChange, withSourceExitCode, @@ -333,6 +335,7 @@ export function attachWorkspaceSourceGet(source: Command): void { 'downloadKnowledgeDocument', ]) absoluteDirOption(command) + primerOption(command) searchTasks(command, [ 'change the model in every agent block', 'bulk edit every workflow in the workspace', @@ -345,7 +348,7 @@ export function attachWorkspaceSourceGet(source: Command): void { .allowExcessArguments(false) .description('Write a workspace as a source directory') .addHelpText('after', GET_HELP) - .action(async (options: { dir: string; only?: string; force?: boolean }) => { + .action(async (options: { dir: string; only?: string; force?: boolean; primer?: boolean }) => { const kinds = parseKinds(options.only) const { client, profile } = connect() await withSourceDirLock(options.dir, async () => { @@ -388,7 +391,8 @@ export function attachWorkspaceSourceGet(source: Command): void { removed: result.removed, skipped: data.skipped.length, guide: result.guide, - primer: result.primer, + editLoop: editLoop('workspace', options.dir), + ...(options.primer === true ? { primer: result.primer } : {}), ...findings.result(data.diagnostics), }) }) diff --git a/packages/sim-cli/src/commands/search.test.ts b/packages/sim-cli/src/commands/search.test.ts index b129ed9730a..f48f106c94d 100644 --- a/packages/sim-cli/src/commands/search.test.ts +++ b/packages/sim-cli/src/commands/search.test.ts @@ -135,4 +135,12 @@ describe('the agent discovery note', () => { it('is never shown to a person', () => { expect(helpOf(['--help'], {})).not.toContain('AGENT COMMAND DISCOVERY') }) + + it('leaves the worked examples to a person, keeping the notes an agent needs', () => { + const agent = helpOf(['--help'], { CLAUDECODE: '1' }) + const person = helpOf(['--help'], {}) + expect(person).toContain('\nExamples:\n') + expect(agent).not.toContain('\nExamples:\n') + expect(agent).toContain('A command targets the profile') + }) }) diff --git a/packages/sim-cli/src/program.ts b/packages/sim-cli/src/program.ts index 2ea6725298b..c50c32992e0 100644 --- a/packages/sim-cli/src/program.ts +++ b/packages/sim-cli/src/program.ts @@ -22,7 +22,7 @@ import { cliVersion } from './version' /** Root program description, shared by `--help` and the generated docs. */ export const PROGRAM_DESCRIPTION = 'Talk to the Sim API from your terminal' -export const HELP_EPILOGUE = ` +const HELP_NOTES = ` 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. @@ -40,7 +40,10 @@ Workflow, knowledge-base and workspace IDs are bare UUIDs. Table IDs carry a tbl_ prefix and file IDs a wf_ one, so wf_ never names a workflow. An audit-log or custom-tool ID can open with a dash, which reads as a flag; put -- in front of it, as in sim audit-logs get -- -HlDcD1z76nK6R4crsUp0. +` +/** The worked examples a person reads; a coding agent is pointed at `sim cli search` instead. */ +const HELP_EXAMPLES = ` Examples: $ sim cli search "cancel a workflow run" Find the command for a task $ sim login Authorize the default profile @@ -59,6 +62,8 @@ Examples: $ sim whoami --profile dev ` +export const HELP_EPILOGUE = `${HELP_NOTES}${HELP_EXAMPLES}` + /** * Printed above group-level help when a coding agent runs the CLI. * @@ -218,7 +223,10 @@ export function buildProgram( attachSecretCommands(program) attachSourcePermissionCommands(program) - program.addHelpText('after', options.helpText ?? HELP_EPILOGUE) + program.addHelpText('after', () => { + if (options.helpText !== undefined) return options.helpText + return detectCodingAgent(env) !== undefined ? HELP_NOTES : HELP_EPILOGUE + }) program.addHelpText('beforeAll', ({ command }) => detectCodingAgent(env) !== undefined && command.commands.length > 0 ? AGENT_DISCOVERY_NOTE : '' ) diff --git a/packages/workflow-code/DESIGN.md b/packages/workflow-code/DESIGN.md index 65e7d51c018..a3463565c12 100644 --- a/packages/workflow-code/DESIGN.md +++ b/packages/workflow-code/DESIGN.md @@ -401,7 +401,11 @@ A JSON code field (a `code` subBlock holding JSON text: an agent's `responseForm splices a reference's value into such text raw for a string and as JSON otherwise, so a bare reference in a literal is stored by its output type: quoted (`""`) when the catalog or the workflow types it `string`, bare (``) otherwise, and bare with `W_JSON_REF_UNTYPED` when -nothing types it. A string in the literal (a template or plain string) is always a JSON string. The +nothing types it. A Function's `result.` is typed by what its JavaScript certainly returns +there (`refValueKind` reads `function-returns.ts`), so a text field is quoted at compile and +printed back as the bare reference. The runtime splice is not changed: a bare token outside a +string is spliced raw by design (a string holding JSON text is nested on purpose), and the text is +not valid JSON until the splice, so the resolver cannot tell where a value should be encoded. A string in the literal (a template or plain string) is always a JSON string. The printer writes stored text back as a literal only when serializing that literal reproduces the text byte for byte; print and compile decide each token's form through the same `refValueKind`. In a pair, a list or object literal never lands in the JSON code member when the other member takes it diff --git a/packages/workflow-code/src/compile/SYNTAX.md b/packages/workflow-code/src/compile/SYNTAX.md index fe465bce4e7..d9ab8226974 100644 --- a/packages/workflow-code/src/compile/SYNTAX.md +++ b/packages/workflow-code/src/compile/SYNTAX.md @@ -223,8 +223,9 @@ A JSON code field (subBlock type `code`: `responseFormat`, table row `data`, a r written as an object or array literal compiles to `JSON.stringify(value, null, 2)` text. Each bare reference is stored by its output type: quoted (`""`) when the catalog or the workflow types it `string`, bare (``) otherwise, because the executor splices a string raw and any other value as -JSON. A reference nothing types is stored bare with `W_JSON_REF_UNTYPED`, which is not raised for a -Function `result` field its JavaScript returns as a non-string literal (`return { total: a + b }`), +JSON. A Function `result` field its JavaScript certainly returns as text (`return { tier: 'gold' }`) is +quoted too, and one it returns as a non-string (`return { total: a + b }`) is bare. A reference +nothing types is stored bare with `W_JSON_REF_UNTYPED`, which is not raised for those, nor, against a stored workflow, for a field the source left as stored. A template is a JSON string, which is how a value becomes text on purpose. A resource (`table('x')`, `credential()`, `file()`) or `raw(node)` is not data, so inside the literal it is `E_UNSUPPORTED_SYNTAX`. The printer writes a field's text back as the diff --git a/packages/workflow-code/src/compile/function-returns.ts b/packages/workflow-code/src/compile/function-returns.ts index 6fa5e4372ef..e52e5ce30f2 100644 --- a/packages/workflow-code/src/compile/function-returns.ts +++ b/packages/workflow-code/src/compile/function-returns.ts @@ -66,6 +66,8 @@ const NUMBER_METHODS: ReadonlySet = new Set([ 'getTime', 'charCodeAt', ]) +/** Methods that return their receiver's kind: a string's `slice` is a string, an array's an array. */ +const SAME_KIND_METHODS: ReadonlySet = new Set(['slice', 'concat']) const ARRAY_METHODS: ReadonlySet = new Set(['map', 'filter', 'split', 'flat', 'flatMap']) const STATIC_KINDS: Readonly> = { 'Number.isFinite': 'boolean', @@ -157,6 +159,12 @@ function collectBindings(program: Node): Bindings { const name = boundName(node.id) if (name !== null) declare(name, node.init ?? null) else for (const child of childNodes(node.id)) walkPatternNames(child, (n) => declare(n, null)) + } else if ( + node.type === 'ImportSpecifier' || + node.type === 'ImportDefaultSpecifier' || + node.type === 'ImportNamespaceSpecifier' + ) { + declare(node.local.name, null) } else if (node.type === 'FunctionDeclaration' && node.id) { declare(node.id.name, null) } else if (isFunctionNode(node) && 'params' in node) { @@ -271,7 +279,8 @@ class Inference { private call(callee: Node): JsKind | undefined { if (callee.type === 'Identifier') { - if (callee.name === 'String') return 'string' + if (callee.name === 'String') return this.isBuiltin(callee.name) ? 'string' : undefined + if (!this.isBuiltin(callee.name)) return undefined if (NUMBER_FUNCTIONS.has(callee.name)) return 'number' if (BOOLEAN_FUNCTIONS.has(callee.name)) return 'boolean' return undefined @@ -279,38 +288,84 @@ class Inference { const method = memberName(callee) if (method === null || !('object' in callee)) return undefined if (callee.object.type === 'Identifier') { - if (callee.object.name === 'Math') return 'number' + if (callee.object.name === 'Math') return this.isBuiltin('Math') ? 'number' : undefined const known = STATIC_KINDS[`${callee.object.name}.${method}`] - if (known) return known + if (known) return this.isBuiltin(callee.object.name) ? known : undefined + } + if (STRING_METHODS.has(method)) + return this.producesString(method, callee.object) ? 'string' : undefined + if (SAME_KIND_METHODS.has(method)) { + if (this.kind(callee.object) === 'string') return 'string' + return this.isArray(callee.object, true) ? 'typed' : undefined } - if (STRING_METHODS.has(method)) return 'string' if (BOOLEAN_METHODS.has(method)) return 'boolean' if (NUMBER_METHODS.has(method)) return 'number' if (ARRAY_METHODS.has(method)) return 'typed' return undefined } + /** Whether a global is the built-in: no local declaration or assignment shadows it. */ + private isBuiltin(name: string): boolean { + return !this.bindings.initial.has(name) && !this.bindings.writes.has(name) + } + + /** + * Whether `receiver.method()` certainly yields text. A method name alone proves nothing (an + * object can define its own `toString`), so the receiver's kind must: a string for the string + * methods, a number for `toFixed`, an array for `join`, a built-in `Date` for `toISOString`. + */ + private producesString(method: string, receiver: Node): boolean { + const kind = this.kind(receiver) + if (method === 'toString') { + return kind === 'string' || kind === 'number' || kind === 'boolean' || this.isDate(receiver) + } + if (method === 'toFixed' || method === 'toPrecision') return kind === 'number' + if (method === 'join') return this.isArray(receiver, true) + if (method === 'toISOString') return this.isDate(receiver) + if (method === 'toLocaleString') { + return kind === 'number' || kind === 'string' || kind === 'boolean' || this.isDate(receiver) + } + return kind === 'string' + } + + private isDate(node: Node): boolean { + return ( + node.type === 'NewExpression' && + node.callee.type === 'Identifier' && + node.callee.name === 'Date' && + this.isBuiltin('Date') + ) + } + /** * Whether `node` is certainly an array: a literal, an array method's result, `Object.keys` * (`values`, `entries`), or a local variable set to one and never reassigned. Any other object - * can hold anything under `length`. + * can hold anything under `length`. `strict` accepts only what the code proves: a call named + * like an array method (`map`) may be any object's own, so it proves nothing there. */ - private isArray(node: Node): boolean { + private isArray(node: Node, strict = false): boolean { if (node.type === 'ArrayExpression') return true if (node.type === 'CallExpression' || node.type === 'OptionalCallExpression') { const method = memberName(node.callee) if (method === null || !('object' in node.callee)) return false if (node.callee.object.type === 'Identifier' && node.callee.object.name === 'Object') { - return method === 'keys' || method === 'values' || method === 'entries' + return ( + this.isBuiltin('Object') && + (method === 'keys' || method === 'values' || method === 'entries') + ) } - return ARRAY_METHODS.has(method) + if (!ARRAY_METHODS.has(method)) return false + if (!strict) return true + return method === 'split' + ? this.kind(node.callee.object) === 'string' + : this.isArray(node.callee.object, true) } if (node.type !== 'Identifier') return false const init = this.bindings.initial.get(node.name) if (!init || this.bindings.writes.has(node.name) || this.resolving.has(node.name)) return false this.resolving.add(node.name) try { - return this.isArray(init) + return this.isArray(init, strict) } finally { this.resolving.delete(node.name) } diff --git a/packages/workflow-code/src/compile/index.ts b/packages/workflow-code/src/compile/index.ts index 67f41a030f3..3850a53547f 100644 --- a/packages/workflow-code/src/compile/index.ts +++ b/packages/workflow-code/src/compile/index.ts @@ -731,13 +731,12 @@ function compileEntry( setOwn(params, id, { kind: 'value', value }) for (const ref of refs) { if (refValueKind(ref.token, refTypes) !== 'untyped') continue - const returned = referencedResultKind(ref.token, refTypes.block) - if (returned === 'typed') continue // An unchanged field stays quiet only while what it reads is too: a Function that now - // returns text where it returned a number makes the same bare token break the JSON. + // returns something unreadable where it returned a number makes the same bare token break + // the JSON. if ( stored.holds(ref.blockKey, id, value) && - referencedResultKind(ref.token, stored.block) === returned + referencedResultKind(ref.token, stored.block) === undefined ) { continue } diff --git a/packages/workflow-code/src/json-fields.test.ts b/packages/workflow-code/src/json-fields.test.ts index f749ea97517..96db98018aa 100644 --- a/packages/workflow-code/src/json-fields.test.ts +++ b/packages/workflow-code/src/json-fields.test.ts @@ -182,10 +182,44 @@ describe('W_JSON_REF_UNTYPED on a Function block output', () => { } }) - it('keeps the warning on a field returned as text, which stored bare breaks the JSON', () => { - const code = "return { tier: 'gold', label: String(1) + 'x' }" - expect(untyped(code, 'tier')).toHaveLength(1) - expect(untyped(code, 'label')).toHaveLength(1) + it('stores a field the code returns as text quoted, so a string value cannot break the JSON', () => { + const code = + "return { tier: 'gold', label: String(1) + 'x', day: new Date().toISOString().slice(0, 10) }" + for (const field of ['tier', 'label', 'day']) { + const result = compile(code, field) + expect(untyped(code, field), field).toEqual([]) + const body = result.workflow?.blocks.next?.params.body + expect(body, field).toEqual({ + kind: 'value', + value: `{\n "v": ""\n}`, + }) + } + }) + + it('does not read a method name as proof of text when the receiver can define it', () => { + // A user-defined `toString` or `join` can return anything, and a shadowed `String` is not the built-in. + expect( + untyped('const o = { toString: () => 42 }\nreturn { v: o.toString() }', 'v') + ).toHaveLength(1) + expect(untyped('const o = { join: () => 42 }\nreturn { v: o.join(",") }', 'v')).toHaveLength(1) + expect(untyped('const String = (x) => 1\nreturn { v: String(2) }', 'v')).toHaveLength(1) + expect( + untyped("const Object = { keys: () => 'oops' }\nreturn { v: Object.keys({}).slice(0) }", 'v') + ).toHaveLength(1) + expect(untyped("import String from 'x'\nreturn { v: String(2) }", 'v')).toHaveLength(1) + expect(untyped('const parseInt = () => "x"\nreturn { v: parseInt("1") }', 'v')).toHaveLength(1) + expect( + untyped("const o = { map: () => 'text' }\nreturn { v: o.map().slice(0) }", 'v') + ).toHaveLength(1) + expect( + untyped("const o = { map: () => 'text' }\nreturn { v: o.map().join(',') }", 'v') + ).toHaveLength(1) + expect(untyped("return { v: 'a,b'.split(',').join('-') }", 'v')).toEqual([]) + expect(untyped('return { v: [1, 2].map((n) => n * 2).join(",") }', 'v')).toEqual([]) + expect(untyped('return { v: new Date().toString() }', 'v')).toEqual([]) + expect(untyped("return { v: 'a'.toLocaleString() }", 'v')).toEqual([]) + expect(untyped('return { v: (5).toFixed(2) }', 'v')).toEqual([]) + expect(untyped("return { v: ['a'].join(',') }", 'v')).toEqual([]) }) it('keeps the warning when nothing certain says what the field holds', () => { @@ -263,11 +297,23 @@ describe('W_JSON_REF_UNTYPED on a Function block output', () => { expect(renamed(printed, new Map())).toHaveLength(1) }) - it('on an apply, warns on an unchanged JSON field when the Function it reads now returns text there', () => { + it('on an apply, warns on an unchanged JSON field when the Function it reads no longer says what it returns', () => { const printed = compile('return { v: 1 }', 'v').workflow if (!printed) throw new Error('the source did not compile') expect(untyped('return { v: 2 }', 'v', printed)).toEqual([]) - expect(untyped("return { v: 'one' }", 'v', printed)).toHaveLength(1) + expect(untyped('return { v: $ref.start.v }', 'v', printed)).toHaveLength(1) + }) + + it('on an apply, requotes an unchanged JSON field when the Function it reads now returns text there', () => { + const printed = compile('return { v: 1 }', 'v').workflow + if (!printed) throw new Error('the source did not compile') + + const next = compile("return { v: 'one' }", 'v', printed) + expect(next.workflow?.blocks.next?.params.body).toEqual({ + kind: 'value', + value: '{\n "v": ""\n}', + }) + expect(untyped("return { v: 'one' }", 'v', printed)).toEqual([]) }) }) diff --git a/packages/workflow-code/src/json-fields.ts b/packages/workflow-code/src/json-fields.ts index 7893963d73c..471ca3e2e57 100644 --- a/packages/workflow-code/src/json-fields.ts +++ b/packages/workflow-code/src/json-fields.ts @@ -21,6 +21,7 @@ import { blockOutputSchemas, errorOutputOf } from './catalog/activity' import type { BlockCatalog, CatalogOutput } from './catalog/types' import { catalogBlock } from './catalog/view' import { parseStoredPath, type RefSegment } from './code-files/ref-path' +import { referencedResultKind } from './compile/function-returns' import { type BlockKey, type CanonicalBlock, @@ -179,7 +180,8 @@ export function responseFormatFields(param: CanonicalParam | undefined): string[ * and the workflow say: `string`, `typed` (any other declared type), or `untyped` when nothing * 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. + * the field its dynamic outputs declare, or for a Function's `result.` by what its + * JavaScript certainly returns there. */ export function refValueKind(token: string, scope: RefTypeScope): RefValueKind { if (token.startsWith('{{')) return 'string' @@ -214,6 +216,9 @@ export function refValueKind(token: string, scope: RefTypeScope): RefValueKind { }) const found = outputAt(outputs, segments) if (found) return found.type === 'string' ? 'string' : 'typed' + // A Function's `result.` is typed by the object literal its JavaScript returns. + const returned = referencedResultKind(token, scope.block) + if (returned) return returned if (declared.dynamicOutputs) { const { source, param } = declared.dynamicOutputs const field = dynamicFieldName(source, segments) diff --git a/packages/workflow-code/src/print/round-trip.test.ts b/packages/workflow-code/src/print/round-trip.test.ts index 7999982f425..f3b1ea4bb49 100644 --- a/packages/workflow-code/src/print/round-trip.test.ts +++ b/packages/workflow-code/src/print/round-trip.test.ts @@ -8,7 +8,7 @@ import { TEST_CATALOG } from '../compile/catalog.test-helpers' import type { CanonicalWorkflow } from '../model' import { printWorkflow } from './printer' -const IMPORTS = "import { agent, api, customTool, js, workflow } from '@sim/workflow-sdk'" +const IMPORTS = "import { agent, api, customTool, fn, js, workflow } from '@sim/workflow-sdk'" function compile(text: string) { return compileWorkflow({ @@ -47,6 +47,23 @@ describe('printWorkflow round trip', () => { expect(again.diagnostics.filter((d) => d.severity === 'error')).toEqual([]) }) + it('prints a quoted reference to a text field a Function returns as the bare reference, not a template', () => { + const body = [ + ` const score = fn('Score', { code: ${JSON.stringify("return { tier: 'gold' }")} })`, + " const next = api('Next', { url: 'https://x', body: { tier: score.result.tier } })", + ].join('\n') + const workflow = compiled(body) + expect(workflow.blocks.next?.params.body).toEqual({ + kind: 'value', + value: '{\n "tier": ""\n}', + }) + const entry = printed(workflow).files[0]?.text ?? '' + expect(entry).toContain('body: { tier: score.result.tier }') + expect(compile(entry).workflow?.blocks.next?.params.body).toEqual( + workflow.blocks.next?.params.body + ) + }) + it('prints a literal credential id as raw() and compiles it back into the advanced member', () => { const text = "// @sim-sdk 1\nimport { mail, raw, workflow } from '@sim/workflow-sdk'\n\n" + diff --git a/packages/workflow-sdk/src/codegen/index.ts b/packages/workflow-sdk/src/codegen/index.ts index 57668009355..fdc2aef763a 100644 --- a/packages/workflow-sdk/src/codegen/index.ts +++ b/packages/workflow-sdk/src/codegen/index.ts @@ -22,9 +22,12 @@ export { type BuilderLookup, type BuilderReference, builderSnippet, + type CompactBuilderReference, + compactBuilder, describeBuilder, lookupBuilder, renderBuilderReference, + renderCompactBuilder, } from './reference' export { SOURCE_COMPILER_OPTIONS, typecheckCommand } from './tsconfig' export { diff --git a/packages/workflow-sdk/src/codegen/reference.ts b/packages/workflow-sdk/src/codegen/reference.ts index bf83af41a17..b451a489276 100644 --- a/packages/workflow-sdk/src/codegen/reference.ts +++ b/packages/workflow-sdk/src/codegen/reference.ts @@ -8,7 +8,12 @@ import { compareStrings, escapeRegExp } from '@sim/utils/string' import type { BlockCatalog } from '@sim/workflow-code' import { suggestBuilder } from '@sim/workflow-code' -import { catalogBlock, catalogBuilder, catalogBuilderPaths } from '@sim/workflow-code/catalog/view' +import { + catalogBlock, + catalogBuilder, + catalogBuilderPaths, + catalogBuildersOfType, +} from '@sim/workflow-code/catalog/view' import { SDK_CORE_EXPORTS } from '@sim/workflow-code/sdk' import { CORE_DTS } from './core-text.generated' import { builderTypes, operationLabel, type ParamFact, type ParamFacts } from './generate' @@ -25,6 +30,8 @@ export interface BuilderReference { operation?: string /** An older block version's builder, kept so stored workflows print; write the current one. */ legacy: boolean + /** The block type that replaces a legacy block's, and the builders written for it. */ + replacement?: { blockType: string; builders: string[] } /** What `core.d.ts` says of a builder it declares itself (`response`, `fn`), as prose. */ doc?: string /** The call, as the declarations type it. */ @@ -70,6 +77,31 @@ function withoutToolSegment(query: string): string { return path.join('.') } +/** At most this many replacement builders are named; a namespace is looked up for the rest. */ +const MAX_REPLACEMENT_BUILDERS = 6 + +/** + * The block type that replaces a sunset block type, with the current builders written for it: + * the ones for the same `operation` when the replacement has them, else its first few. + */ +function replacementOf( + catalog: BlockCatalog, + blockType: string, + operation: string | undefined +): BuilderReference['replacement'] { + const replacedBy = catalogBlock(catalog, blockType)?.lifecycle?.sunset?.replacedBy + if (!replacedBy) return undefined + const current = catalogBuildersOfType(catalog, replacedBy) + .filter(([path]) => !isLegacyBuilder(path)) + .map(([path, builder]) => ({ path, operation: builder.operation })) + const sameOperation = operation ? current.filter((entry) => entry.operation === operation) : [] + const builders = (sameOperation.length > 0 ? sameOperation : current) + .map((entry) => entry.path) + .sort(compareStrings) + .slice(0, MAX_REPLACEMENT_BUILDERS) + return { blockType: replacedBy, builders } +} + /** The reference of the catalog builder `key`, or `null` when the catalog has none. */ export function describeBuilder(catalog: BlockCatalog, key: string): BuilderReference | null { const entry = builderEntry(catalog, key) @@ -84,12 +116,14 @@ export function describeBuilder(catalog: BlockCatalog, key: string): BuilderRefe const tool = types.tool ? `${entry.path.slice(0, -1).join('.')}.${TOOL_NAMESPACE}.${(types.tool.at(-1) ?? '').replace(/^export function /, '')}` : null + const replacement = replacementOf(catalog, entry.builder.type, entry.builder.operation) return { key, blockType: entry.builder.type, summary: types.summary, ...(entry.builder.operation ? { operation: entry.builder.operation } : {}), legacy: isLegacyBuilder(key), + ...(replacement ? { replacement } : {}), ...(entry.special ? docOf(key) : {}), signature, tool, @@ -255,13 +289,9 @@ function paramLine(param: ParamFact): string { return `${param.key}: ${shortType(param.type)}${fallback}` } -/** - * A few lines for the source primer: the call with its required params filled in, the required - * params with their types, the optional ones by name, and the outputs. - */ -export function builderSnippet(reference: BuilderReference): string { +/** An example call of the builder with its required params filled in (`gate` first when it has no default). */ +function builderCall(reference: BuilderReference): string { const required = reference.params.common.filter((param) => param.required) - const optional = reference.params.common.filter((param) => !param.required) const gate = reference.params.gate const variant = gate ? (gate.variants.find((v) => gate.default !== undefined && v.values.includes(gate.default)) ?? @@ -276,7 +306,21 @@ export function builderSnippet(reference: BuilderReference): string { .filter((param) => param.required) .map((param) => `${param.key}: ${exampleValue(param.type)}`), ] - const call = `${reference.key}('Name', ${args.length > 0 ? `{ ${args.join(', ')} }` : '{}'})` + return `${reference.key}('Name', ${args.length > 0 ? `{ ${args.join(', ')} }` : '{}'})` +} + +/** + * A few lines for the source primer: the call with its required params filled in, the required + * params with their types, the optional ones by name, and the outputs. + */ +export function builderSnippet( + reference: BuilderReference, + maxOptional = MAX_SNIPPET_OPTIONAL +): string { + const required = reference.params.common.filter((param) => param.required) + const optional = reference.params.common.filter((param) => !param.required) + const gate = reference.params.gate + const call = builderCall(reference) const lines = [`- \`${reference.key}\` (${reference.summary}): \`const x = ${call}\``] if (required.length > 0) lines.push(` required: ${required.map(paramLine).join('; ')}`) if (gate) { @@ -288,7 +332,7 @@ export function builderSnippet(reference: BuilderReference): string { lines.push(` ${gate.key}${fallback} picks the rest: ${variants.join('; ')}`) } if (optional.length > 0) { - const shown = optional.slice(0, MAX_SNIPPET_OPTIONAL).map((param) => param.key) + const shown = optional.slice(0, maxOptional).map((param) => param.key) const more = optional.length > shown.length ? `, +${optional.length - shown.length} more` : '' lines.push(` optional: ${shown.join(', ')}${more}`) } @@ -315,9 +359,7 @@ export function renderBuilderReference(reference: BuilderReference): string { .filter(Boolean) .join(', ') const lines = [`${reference.key} — ${reference.summary} (${where})`] - if (reference.legacy) { - lines.push('Legacy: an older block version. Write the current builder instead.') - } + if (reference.legacy) lines.push(legacyNote(reference)) if (reference.doc) lines.push('', reference.doc) lines.push('', reference.signature) if (reference.tool) lines.push(`${reference.tool} (as an agent tool)`) @@ -344,3 +386,87 @@ export function renderBuilderReference(reference: BuilderReference): string { lines.push(...(reference.outputs.length > 0 ? reference.outputs : [' (none)'])) return lines.join('\n') } + +/** The note on a legacy builder: it is an older block version, and which builder replaces it. */ +function legacyNote(reference: BuilderReference): string { + const { replacement } = reference + const instead = + replacement && replacement.builders.length > 0 + ? `Write ${replacement.builders.map((key) => `\`${key}\``).join(' or ')} (block ${replacement.blockType}) instead.` + : 'Write the current builder instead.' + return `Legacy: an older block version. ${instead}` +} + +/** What `sim workflows source params ` prints by default for one builder, and its JSON. */ +export interface CompactBuilderReference + extends Pick< + BuilderReference, + 'key' | 'blockType' | 'summary' | 'operation' | 'legacy' | 'replacement' | 'doc' + > { + /** An example call with the required params filled in. */ + call: string + required: Array<{ key: string; type: string; default?: unknown }> + /** The param that picks which others apply, with the ones each choice requires. */ + gate?: { + key: string + default?: unknown + variants: Array<{ values: unknown[]; required: string[] }> + } + /** Optional params by name; `params --full` lists their types, docs and defaults. */ + optional: string[] + coreParams: string[] + /** The call as `core.d.ts` types it, for a builder with required params the list above omits. */ + signature?: string + /** The output type's top-level members, by name. */ + outputs: string[] +} + +/** The few hundred bytes of a builder an agent needs to write a call: see {@link CompactBuilderReference}. */ +export function compactBuilder(reference: BuilderReference): CompactBuilderReference { + const required = reference.params.common.filter((param) => param.required) + const gate = reference.params.gate + return { + key: reference.key, + blockType: reference.blockType, + summary: reference.summary, + ...(reference.operation ? { operation: reference.operation } : {}), + legacy: reference.legacy, + ...(reference.replacement ? { replacement: reference.replacement } : {}), + ...(reference.doc ? { doc: reference.doc } : {}), + call: builderCall(reference), + required: required.map((param) => ({ + key: param.key, + type: shortType(param.type), + ...(param.default !== undefined ? { default: param.default } : {}), + })), + ...(gate + ? { + gate: { + key: gate.key, + ...(gate.default !== undefined ? { default: gate.default } : {}), + variants: gate.variants.map((variant) => ({ + values: variant.values, + required: variant.params.filter((param) => param.required).map((param) => param.key), + })), + }, + } + : {}), + optional: reference.params.common.filter((param) => !param.required).map((param) => param.key), + coreParams: [...reference.coreParams], + ...(reference.coreParams.length > 0 ? { signature: reference.signature } : {}), + outputs: outputNames(reference.outputs), + } +} + +/** The text `params` prints by default: the legacy note, the snippet, and where the rest is. */ +export function renderCompactBuilder(reference: BuilderReference): string { + const lines = [] + if (reference.legacy) lines.push(legacyNote(reference)) + if (reference.doc) lines.push(reference.doc) + lines.push(builderSnippet(reference, Number.POSITIVE_INFINITY)) + if (reference.coreParams.length > 0) lines.push(` signature: ${reference.signature}`) + lines.push( + `Every param's type, enum, default and doc: \`sim workflows source params ${reference.key} --full\`.` + ) + return lines.join('\n') +}