From 34fcb0c509151e9667c501a10859dff34c37aef9 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 15:09:56 -0800 Subject: [PATCH 1/3] improvement(workflow-code): one primer for coding agents and Mothership, pre-installed TypeScript - source-primer: a cli/chat surface; the chat primer stops the shell loop at apply and tests and deploys through sim_cli, with no workspace source or --run; print-source-primers emits chat.workflow - the CLI serves the chat primer and source help where its host is Mothership: SIM_CLI_HOST=mothership in the workbench env (sandbox-session) or host on runEmbeddedCli (sim_cli) - command inventory: workspaces source check is mothershipUnavailable with the rest of its group - source check reads the pinned TypeScript from SIM_TYPESCRIPT_DIR before installing it, and a failed check ends stderr with its first error --- apps/docs/content/docs/cli/configuration.mdx | 1 + apps/docs/content/docs/cli/reference.mdx | 4 +- apps/docs/content/docs/cli/workflows.mdx | 2 +- apps/docs/content/docs/cli/workspaces.mdx | 2 +- .../docs/content/docs/workflows/code/edit.mdx | 2 +- apps/sim/lib/mothership/agent-cli/run-cli.ts | 2 + .../mothership/tools/sandbox-session.test.ts | 1 + .../lib/mothership/tools/sandbox-session.ts | 6 +- packages/sim-cli/README.md | 1 + packages/sim-cli/package.json | 4 + .../scripts/print-command-inventory.ts | 24 ++++- .../sim-cli/scripts/print-source-primers.ts | 14 ++- .../sim-cli/src/commands/protocol/index.ts | 9 +- .../src/commands/protocol/source-check.ts | 7 +- .../src/commands/protocol/source-loop-help.ts | 63 ++++++++--- .../src/commands/protocol/source-primer.ts | 98 +++++++++++++---- .../src/commands/protocol/source-tree.ts | 13 ++- .../src/commands/protocol/source-types.ts | 37 +++++-- .../src/commands/protocol/source-ui.ts | 7 ++ .../protocol/workflow-source-check.test.ts | 36 ++++++- .../protocol/workflow-source-get.test.ts | 100 +++++++++++++++--- .../protocol/workspace-source-get.test.ts | 27 ++++- packages/sim-cli/src/embed-context.ts | 5 + packages/sim-cli/src/embed.ts | 2 + packages/sim-cli/src/host.ts | 13 +++ packages/sim-cli/src/test/typescript.ts | 16 ++- 26 files changed, 412 insertions(+), 84 deletions(-) create mode 100644 packages/sim-cli/src/host.ts diff --git a/apps/docs/content/docs/cli/configuration.mdx b/apps/docs/content/docs/cli/configuration.mdx index b11e660fd2d..f6559c12ea1 100644 --- a/apps/docs/content/docs/cli/configuration.mdx +++ b/apps/docs/content/docs/cli/configuration.mdx @@ -130,6 +130,7 @@ To select an accessible workspace interactively, omit `--workspace` from `sim pr | `SIM_TIMEOUT_SECONDS` | Per-request timeout, default `3600` seconds; `0` removes the CLI timeout | | `SIM_DEBUG` | Write request method, URL, status, and duration to stderr | | `SIM_NO_UPDATE_CHECK` | Disable automatic update checks and notices | +| `SIM_TYPESCRIPT_DIR` | A directory of TypeScript releases installed ahead of time (`//node_modules/typescript`); `source check` reads the pinned one there instead of installing it into the cache | | `SIM_TELEMETRY_DISABLED` | Disable anonymous usage reporting | | `DO_NOT_TRACK` | Cross-tool usage-reporting opt-out; takes precedence over the CLI setting | diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 6513b966498..e719c6ca84d 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8737,7 +8737,7 @@ sim workflows source check [options] -Compiles workflow.ts (and the function files it names) with the compiler the server runs, against the workspace's block catalog the last get or create cached, and prints the findings as the dry run does. No request is made to Sim. It covers the source itself (syntax, builders, params, references, wiring). In a workflow folder of a workspace directory (workflows/<key>), it reads the workspace's .sim/base.json and also checks env names, resource keys and table columns against what the directory declares. The dry run still checks what only the server knows (stored values, deployment), so run it before applying. A check also adds the blocks the source now uses to the CLI's tsconfig.json, so a block the edit added is typed; in a workspace directory it also regenerates .sim/sdk/workspace.d.ts from the files, so each key and workflow input they declare is. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code. One is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them). The first check installs that release with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. +Compiles workflow.ts (and the function files it names) with the compiler the server runs, against the workspace's block catalog the last get or create cached, and prints the findings as the dry run does. No request is made to Sim. It covers the source itself (syntax, builders, params, references, wiring). In a workflow folder of a workspace directory (workflows/<key>), it reads the workspace's .sim/base.json and also checks env names, resource keys and table columns against what the directory declares. The dry run still checks what only the server knows (stored values, deployment), so run it before applying. A check also adds the blocks the source now uses to the CLI's tsconfig.json, so a block the edit added is typed; in a workspace directory it also regenerates .sim/sdk/workspace.d.ts from the files, so each key and workflow input they declare is. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code. One is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them). The first check installs that release with npm into the CLI's cache, once (none when SIM_TYPESCRIPT_DIR already holds it); when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. @@ -10154,7 +10154,7 @@ sim workspaces source check [options] -Compiles every workflows/<key>/workflow.ts (and the function files each names) with the compiler the server runs, against the workspace's block catalog the last get cached (in a fresh clone with no cache, such as CI, it downloads the catalog once with the profile's credentials). No other request is made to Sim. It checks, against what the directory declares: - env names (secrets.ts), with a did-you-mean - credential keys (credentials.ts) - the keys of tables, knowledge bases, skills, custom tools, MCP servers and workflows, with a did-you-mean, and a key holding a look-alike letter (a Cyrillic а) named by its code point - the columns and select options of a table row write - a child workflow call: an inputMapping key the child's Start trigger does not declare, and a child with no Start trigger - each tables/<key>.rows.jsonl: a malformed line, an undeclared column, a managed key two lines share, an empty required cell, a repeated unique value, a value its column's type or options cannot hold - block names whose words mix Latin with Cyrillic, Greek, Armenian or Cherokee letters The dry run still checks what only the server knows (stored values, MCP tool names, model ids, deployments, credential bindings), so run it before applying. A check also regenerates .sim/sdk/workspace.d.ts from the declarations (so a key added since the get is typed, and each workflow's inputs) and adds the blocks the workflows now use to the CLI's tsconfig.json. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code. One is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them). The first check installs that release with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. +Compiles every workflows/<key>/workflow.ts (and the function files each names) with the compiler the server runs, against the workspace's block catalog the last get cached (in a fresh clone with no cache, such as CI, it downloads the catalog once with the profile's credentials). No other request is made to Sim. It checks, against what the directory declares: - env names (secrets.ts), with a did-you-mean - credential keys (credentials.ts) - the keys of tables, knowledge bases, skills, custom tools, MCP servers and workflows, with a did-you-mean, and a key holding a look-alike letter (a Cyrillic а) named by its code point - the columns and select options of a table row write - a child workflow call: an inputMapping key the child's Start trigger does not declare, and a child with no Start trigger - each tables/<key>.rows.jsonl: a malformed line, an undeclared column, a managed key two lines share, an empty required cell, a repeated unique value, a value its column's type or options cannot hold - block names whose words mix Latin with Cyrillic, Greek, Armenian or Cherokee letters The dry run still checks what only the server knows (stored values, MCP tool names, model ids, deployments, credential bindings), so run it before applying. A check also regenerates .sim/sdk/workspace.d.ts from the declarations (so a key added since the get is typed, and each workflow's inputs) and adds the blocks the workflows now use to the CLI's tsconfig.json. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code. One is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them). The first check installs that release with npm into the CLI's cache, once (none when SIM_TYPESCRIPT_DIR already holds it); when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog that could not be downloaded (a check downloads it once when none is cached, with the profile's credentials; 13 when there is no login to download it with). With --output json, stdout is one document that also lists every finding under diagnostics. diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index 2c7111d150e..e11f158af59 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1531,7 +1531,7 @@ sim workflows source check [options] -Compiles workflow.ts (and the function files it names) with the compiler the server runs, against the workspace's block catalog the last get or create cached, and prints the findings as the dry run does. No request is made to Sim. It covers the source itself (syntax, builders, params, references, wiring). In a workflow folder of a workspace directory (workflows/<key>), it reads the workspace's .sim/base.json and also checks env names, resource keys and table columns against what the directory declares. The dry run still checks what only the server knows (stored values, deployment), so run it before applying. A check also adds the blocks the source now uses to the CLI's tsconfig.json, so a block the edit added is typed; in a workspace directory it also regenerates .sim/sdk/workspace.d.ts from the files, so each key and workflow input they declare is. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code. One is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them). The first check installs that release with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. +Compiles workflow.ts (and the function files it names) with the compiler the server runs, against the workspace's block catalog the last get or create cached, and prints the findings as the dry run does. No request is made to Sim. It covers the source itself (syntax, builders, params, references, wiring). In a workflow folder of a workspace directory (workflows/<key>), it reads the workspace's .sim/base.json and also checks env names, resource keys and table columns against what the directory declares. The dry run still checks what only the server knows (stored values, deployment), so run it before applying. A check also adds the blocks the source now uses to the CLI's tsconfig.json, so a block the edit added is typed; in a workspace directory it also regenerates .sim/sdk/workspace.d.ts from the files, so each key and workflow input they declare is. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code. One is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them). The first check installs that release with npm into the CLI's cache, once (none when SIM_TYPESCRIPT_DIR already holds it); when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog (run the get once). With --output json, stdout is one document that also lists every finding under diagnostics. diff --git a/apps/docs/content/docs/cli/workspaces.mdx b/apps/docs/content/docs/cli/workspaces.mdx index ced64883970..9718d573495 100644 --- a/apps/docs/content/docs/cli/workspaces.mdx +++ b/apps/docs/content/docs/cli/workspaces.mdx @@ -786,7 +786,7 @@ sim workspaces source check [options] -Compiles every workflows/<key>/workflow.ts (and the function files each names) with the compiler the server runs, against the workspace's block catalog the last get cached (in a fresh clone with no cache, such as CI, it downloads the catalog once with the profile's credentials). No other request is made to Sim. It checks, against what the directory declares: - env names (secrets.ts), with a did-you-mean - credential keys (credentials.ts) - the keys of tables, knowledge bases, skills, custom tools, MCP servers and workflows, with a did-you-mean, and a key holding a look-alike letter (a Cyrillic а) named by its code point - the columns and select options of a table row write - a child workflow call: an inputMapping key the child's Start trigger does not declare, and a child with no Start trigger - each tables/<key>.rows.jsonl: a malformed line, an undeclared column, a managed key two lines share, an empty required cell, a repeated unique value, a value its column's type or options cannot hold - block names whose words mix Latin with Cyrillic, Greek, Armenian or Cherokee letters The dry run still checks what only the server knows (stored values, MCP tool names, model ids, deployments, credential bindings), so run it before applying. A check also regenerates .sim/sdk/workspace.d.ts from the declarations (so a key added since the get is typed, and each workflow's inputs) and adds the blocks the workflows now use to the CLI's tsconfig.json. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code. One is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them). The first check installs that release with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. +Compiles every workflows/<key>/workflow.ts (and the function files each names) with the compiler the server runs, against the workspace's block catalog the last get cached (in a fresh clone with no cache, such as CI, it downloads the catalog once with the profile's credentials). No other request is made to Sim. It checks, against what the directory declares: - env names (secrets.ts), with a did-you-mean - credential keys (credentials.ts) - the keys of tables, knowledge bases, skills, custom tools, MCP servers and workflows, with a did-you-mean, and a key holding a look-alike letter (a Cyrillic а) named by its code point - the columns and select options of a table row write - a child workflow call: an inputMapping key the child's Start trigger does not declare, and a child with no Start trigger - each tables/<key>.rows.jsonl: a malformed line, an undeclared column, a managed key two lines share, an empty required cell, a repeated unique value, a value its column's type or options cannot hold - block names whose words mix Latin with Cyrillic, Greek, Armenian or Cherokee letters The dry run still checks what only the server knows (stored values, MCP tool names, model ids, deployments, credential bindings), so run it before applying. A check also regenerates .sim/sdk/workspace.d.ts from the declarations (so a key added since the get is typed, and each workflow's inputs) and adds the blocks the workflows now use to the CLI's tsconfig.json. Then it type-checks the directory with TypeScript 7.0.2 (the release the declarations are built for) over tsconfig.json. Each type error is an E_TYPE error, its message starting with TypeScript's code. One is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them). The first check installs that release with npm into the CLI's cache, once (none when SIM_TYPESCRIPT_DIR already holds it); when it cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check. Exit codes: 0 no errors; 1 errors (each printed as file:line:column with its frame and hint), or no cached catalog that could not be downloaded (a check downloads it once when none is cached, with the profile's credentials; 13 when there is no login to download it with). With --output json, stdout is one document that also lists every finding under diagnostics. diff --git a/apps/docs/content/docs/workflows/code/edit.mdx b/apps/docs/content/docs/workflows/code/edit.mdx index 853237a8973..4ca4c981e70 100644 --- a/apps/docs/content/docs/workflows/code/edit.mdx +++ b/apps/docs/content/docs/workflows/code/edit.mdx @@ -31,7 +31,7 @@ sim workflows source check --dir ./support-triage `check` makes no request. It needs the block catalog the last `get` cached in `~/.sim/cache/source-catalog/`; with none cached it exits `1` and tells you to run `get` once. It exits `1` on an error, and on the warnings `sim workflows source check --help` lists (a missing required field, an unknown option, an unwired condition or router branch, a literal secret and more) in a block you added since the get. `--strict` fails on these in every block, except an unwired branch on a block the get printed; `--no-strict` never fails on a warning. -Then it adds the blocks the workflow now uses to `tsconfig.json` and type-checks the directory with it, using the TypeScript release the generated declarations are built for, as your editor does. Each type error is an `E_TYPE` error at its line, with TypeScript's own code (`TS2339: …`) at the start of the message. A type error is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them), where the dry run decides; one that another file's edit causes there is reported. The first check installs that release with `npm` into `~/.sim/cache/typescript/`, once; offline before then, `check` warns `W_TYPES_UNCHECKED` and passes or fails on the compile alone. `--no-types` skips the type check. `tsconfig.full.json` includes every block, for an editor. +Then it adds the blocks the workflow now uses to `tsconfig.json` and type-checks the directory with it, using the TypeScript release the generated declarations are built for, as your editor does. Each type error is an `E_TYPE` error at its line, with TypeScript's own code (`TS2339: …`) at the start of the message. A type error is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them), where the dry run decides; one that another file's edit causes there is reported. The first check installs that release with `npm` into `~/.sim/cache/typescript/`, once (none when `SIM_TYPESCRIPT_DIR` already holds it); offline before then, `check` warns `W_TYPES_UNCHECKED` and passes or fails on the compile alone. `--no-types` skips the type check. `tsconfig.full.json` includes every block, for an editor. ## 3. See what changed diff --git a/apps/sim/lib/mothership/agent-cli/run-cli.ts b/apps/sim/lib/mothership/agent-cli/run-cli.ts index 17cbc1baf43..64d33bd2ec6 100644 --- a/apps/sim/lib/mothership/agent-cli/run-cli.ts +++ b/apps/sim/lib/mothership/agent-cli/run-cli.ts @@ -1,4 +1,5 @@ import { type EmbeddedCliIdentity, runEmbeddedCli } from 'sim/embed' +import { MOTHERSHIP_CLI_HOST } from 'sim/host' import { importDurableSecretProvenance } from '@/lib/execution/durable-secret-provenance' import { isBinarySandboxPath } from '@/lib/execution/remote-sandbox/encoding' import type { SessionFileObserver } from '@/lib/execution/remote-sandbox/session-file-observer' @@ -53,6 +54,7 @@ export async function runCli( identity.signal?.throwIfAborted() return runEmbeddedCli(argv, identity, { workingDirectory: SESSION_SANDBOX_HOME, + host: MOTHERSHIP_CLI_HOST, ...(readFile ? { readFile } : {}), ...(openFile ? { openFile } : {}), ...(writeFile ? { writeFile } : {}), diff --git a/apps/sim/lib/mothership/tools/sandbox-session.test.ts b/apps/sim/lib/mothership/tools/sandbox-session.test.ts index 896b3f2b5cf..5c77a2e767c 100644 --- a/apps/sim/lib/mothership/tools/sandbox-session.test.ts +++ b/apps/sim/lib/mothership/tools/sandbox-session.test.ts @@ -93,6 +93,7 @@ describe('deployment-owned workbench tooling', () => { SIM_API_KEY: expect.stringMatching(/^mothership-sandbox:[0-9a-f-]{36}$/), SIM_WORKSPACE: 'workspace', SIM_ENDPOINT: 'https://sim.test/api/mothership/sandbox/owned-token', + SIM_CLI_HOST: 'mothership', }) }) diff --git a/apps/sim/lib/mothership/tools/sandbox-session.ts b/apps/sim/lib/mothership/tools/sandbox-session.ts index 98ffb6ae0d0..aeff0d70f7b 100644 --- a/apps/sim/lib/mothership/tools/sandbox-session.ts +++ b/apps/sim/lib/mothership/tools/sandbox-session.ts @@ -6,6 +6,7 @@ import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' import { generateId } from '@sim/utils/id' import { toRecord } from '@sim/utils/object' +import { CLI_HOST_ENV, MOTHERSHIP_CLI_HOST } from 'sim/host' import { env } from '@/lib/core/config/env' import { encryptSecret } from '@/lib/core/security/encryption' import { getBaseUrl } from '@/lib/core/utils/urls' @@ -179,8 +180,8 @@ async function sandboxEntitlements(args: { * Builds the session request for a Mothership chat's persistent sandbox: the * per-chat identity, the sim-CLI bootstrap, and the CLI's headless auth * environment (`SIM_API_KEY`/`SIM_WORKSPACE`/`SIM_ENDPOINT`, the CLI's - * documented CI path), plus the owner's `SIM_ENTITLEMENTS` so entitlement-gated - * CLI commands are visible. Only an opaque callback credential enters the workbench; + * documented CI path), `SIM_CLI_HOST` so the CLI gives its chat primer and help, + * plus the owner's `SIM_ENTITLEMENTS` so entitlement-gated CLI commands are visible. Only an opaque callback credential enters the workbench; * the active tool lease resolves the real user credential on the server. The * opaque credential cannot authenticate directly to ordinary v2 routes. * @@ -231,6 +232,7 @@ export async function buildMothershipSandboxSession(args: { ? { SIM_ORGANIZATION_ID: args.organizationId } : { SIM_WORKSPACE: args.workspaceId! }), SIM_ENDPOINT: scopedEndpoint, + [CLI_HOST_ENV]: MOTHERSHIP_CLI_HOST, ...(activeSandboxFileOwnerProtocol() === 1 ? { SIM_FILE_OWNER_PROTOCOL: '1' } : {}), ...(activeSandboxWorkspaceFileCopy() ? { SIM_WORKSPACE_FILE_COPY: '1' } : {}), ...(entitlements ? { SIM_ENTITLEMENTS: entitlements } : {}), diff --git a/packages/sim-cli/README.md b/packages/sim-cli/README.md index d45b92ec052..fccb1c94fba 100644 --- a/packages/sim-cli/README.md +++ b/packages/sim-cli/README.md @@ -385,6 +385,7 @@ The main environment variables are: | `SIM_TIMEOUT_SECONDS` | Per-request timeout; `0` waits indefinitely | | `SIM_DEBUG` | Print request diagnostics to stderr | | `SIM_NO_UPDATE_CHECK` | Turn off update notices | +| `SIM_TYPESCRIPT_DIR` | Pre-installed TypeScript releases (`//node_modules/typescript`) that `source check` reads before installing one | | `SIM_TELEMETRY_DISABLED` | Turn off anonymous usage reporting (`DO_NOT_TRACK=1` also works) | On eligible interactive invocations, `sim` uses a daily cache before asking diff --git a/packages/sim-cli/package.json b/packages/sim-cli/package.json index 4c33f12fa54..a62ff8ce8c0 100644 --- a/packages/sim-cli/package.json +++ b/packages/sim-cli/package.json @@ -77,6 +77,10 @@ "types": "./src/embed.ts", "default": "./src/embed.ts" }, + "./host": { + "types": "./src/host.ts", + "default": "./src/host.ts" + }, "./runtime": { "types": "./dist/runtime.d.ts", "default": "./dist/runtime.js" diff --git a/packages/sim-cli/scripts/print-command-inventory.ts b/packages/sim-cli/scripts/print-command-inventory.ts index 44900ff2efa..48e9cd26da1 100644 --- a/packages/sim-cli/scripts/print-command-inventory.ts +++ b/packages/sim-cli/scripts/print-command-inventory.ts @@ -6,7 +6,8 @@ * read — so the model's card can never describe a command the CLI does not have. Each * leaf carries its positionals and options as commander declares them, plus the top-level * shape of its JSON response resolved from the v2 OpenAPI documents, - * `mothershipUnavailable` when Sim refuses a Mothership caller any operation it calls, and + * `mothershipUnavailable` when Sim refuses a Mothership caller any operation it calls (or the + * get that writes the directory it works on), and * `entitlement` when an operation it calls exists only where a rollout flag is on. * * bun run packages/sim-cli/scripts/print-command-inventory.ts > inventory.json @@ -55,8 +56,8 @@ interface InventoryCommand extends CommandReference { args: InventoryArgument[] options: InventoryOption[] /** - * Sim refuses Mothership for an operation this command calls, so chat cannot run it. - * Absent when every call is admitted or the command calls no known operation. + * Sim refuses Mothership for an operation this command calls, or for the `get` that writes the + * directory it works on, so chat cannot run it. Absent otherwise. */ mothershipUnavailable?: true /** In a group hidden from `--help` until launch; the worker exposes it only when Sim enables it. */ @@ -246,6 +247,23 @@ const inventory: InventoryCommand[] = collectLeaves(program, []).map( } ) +const groupOf = (entry: InventoryCommand) => entry.path.slice(0, -1).join(' ') +const takesDir = (entry: InventoryCommand) => entry.options.some((option) => option.name === 'dir') +const refusedDirectoryGroups = new Set( + inventory + .filter( + (entry) => entry.path.at(-1) === 'get' && entry.mothershipUnavailable && takesDir(entry) + ) + .map(groupOf) +) +// A --dir command works only on what its group's get writes, so a refused get refuses it too +// (`workspaces source check` calls no refused operation but checks a refused get's directory). +for (const entry of inventory) { + if (takesDir(entry) && refusedDirectoryGroups.has(groupOf(entry))) { + entry.mothershipUnavailable = true + } +} + const gatedGroups = new Map( inventory.flatMap((entry) => entry.entitlement && entry.path.length > 1 diff --git a/packages/sim-cli/scripts/print-source-primers.ts b/packages/sim-cli/scripts/print-source-primers.ts index 911bd54f640..a93c71b93a9 100644 --- a/packages/sim-cli/scripts/print-source-primers.ts +++ b/packages/sim-cli/scripts/print-source-primers.ts @@ -1,8 +1,9 @@ /** - * 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. + * Prints the source primers as JSON: `workflow` and `workspace`, the ones `sim workflows source + * get` and `sim workspaces source get` write atop `.sim/AGENTS.md` for a coding agent, and + * `chat.workflow`, the one a get writes inside Mothership, which the mothership worker takes + * verbatim as its `workflow-source` skill. Mothership has no workspace source, so `chat` holds + * the workflow primer alone. * * bun run packages/sim-cli/scripts/print-source-primers.ts > primers.json */ @@ -10,6 +11,9 @@ import { type PrimerKind, sourcePrimer } from '#sim-cli/commands/protocol/source const KINDS: readonly PrimerKind[] = ['workflow', 'workspace'] -const primers = Object.fromEntries(KINDS.map((kind) => [kind, sourcePrimer(kind)])) +const primers = { + ...Object.fromEntries(KINDS.map((kind) => [kind, sourcePrimer(kind, 'cli')])), + chat: { workflow: sourcePrimer('workflow', 'chat') }, +} process.stdout.write(`${JSON.stringify(primers, null, 2)}\n`) diff --git a/packages/sim-cli/src/commands/protocol/index.ts b/packages/sim-cli/src/commands/protocol/index.ts index 96fc7f0415a..6a5b72a897e 100644 --- a/packages/sim-cli/src/commands/protocol/index.ts +++ b/packages/sim-cli/src/commands/protocol/index.ts @@ -15,10 +15,11 @@ import { attachKnowledgeImport } from './knowledge-import' import { attachLogsFollow } from './logs-follow' import { attachResourceDirectoryCommands } from './resource-directory' import { - WORKFLOW_SOURCE_LOOP_HELP, - WORKFLOW_SOURCE_SCOPE_HELP, WORKSPACE_SOURCE_LOOP_HELP, + workflowSourceLoopHelp, + workflowSourceScopeHelp, } from './source-loop-help' +import { primerSurface } from './source-primer' import { attachTableImport } from './tables-import' import { attachWorkflowRunFollow } from './workflow-run-follow' import { attachWorkflowRunGet } from './workflow-run-get' @@ -99,8 +100,8 @@ export function attachProtocolCommands(program: Command): void { const source = group(workflows, 'source').description( 'Read and apply a workflow as TypeScript source (preview)' ) - source.addHelpText('before', WORKFLOW_SOURCE_SCOPE_HELP) - source.addHelpText('after', WORKFLOW_SOURCE_LOOP_HELP) + source.addHelpText('before', () => workflowSourceScopeHelp(primerSurface())) + source.addHelpText('after', () => workflowSourceLoopHelp(primerSurface())) attachWorkflowSourceGet(source) attachWorkflowSourceApply(source) attachWorkflowSourceCreate(source) diff --git a/packages/sim-cli/src/commands/protocol/source-check.ts b/packages/sim-cli/src/commands/protocol/source-check.ts index 007101dad74..a3a8669dce4 100644 --- a/packages/sim-cli/src/commands/protocol/source-check.ts +++ b/packages/sim-cli/src/commands/protocol/source-check.ts @@ -45,6 +45,7 @@ import { KIND_DIRS } from '@sim/workspace-code' import { KIND_LAYOUTS } from '@sim/workspace-code/kinds/registry' import type { Command } from 'commander' import { setSoftExitCode } from '../../embed-context' +import { printError } from '../../output/io' import { SourceDirError } from './local-errors' import { printProtocolResult } from './result' import { @@ -65,7 +66,7 @@ import { workspaceTypesText, } from './source-tree' import { type TypeCheck, typeCheck } from './source-types' -import { type Diagnostic, findingsOutput } from './source-ui' +import { type Diagnostic, findingLine, findingsOutput } from './source-ui' import { blockDigest, compiledWithChildResults, readStoredRecord } from './stored-edges' import { lockRecoveryHint, readSourceFiles, resourceNodes } from './workflow-dir' import { @@ -911,6 +912,10 @@ export function reportCheck( ...result, ...shown.result(listed), }) + // A failed check's stderr ends with its first error, so a caller that reads the last stderr + // line as the failure reads the mistake, never a notice (the TypeScript install's) or a warning. + const first = findings.find((finding) => finding.severity === 'error') + if (first) printError(`Error: ${findingLine(first)}`) } /** The catalog a cache read found, or a refusal naming `get`, the command that caches one. */ diff --git a/packages/sim-cli/src/commands/protocol/source-loop-help.ts b/packages/sim-cli/src/commands/protocol/source-loop-help.ts index bcf25b792a9..33b7699cd41 100644 --- a/packages/sim-cli/src/commands/protocol/source-loop-help.ts +++ b/packages/sim-cli/src/commands/protocol/source-loop-help.ts @@ -4,6 +4,7 @@ */ import { SOURCE_DRIFT_EXIT_CODE, SOURCE_LOCAL_CHANGES_EXIT_CODE } from '../../exit-codes' import { SOURCE_AGENTS_FILE } from './source-dir' +import type { PrimerSurface } from './source-primer' /** Where the commands of either group find their workspace. */ const WORKSPACE_LINE = `Workspace: a directory records it (.sim/base.json, or a starter's .sim/starter.json); other @@ -23,33 +24,69 @@ function statusLine(group: string, dir: string): string { } /** - * The top of `sim workflows source --help`, above the usage line: what a workflow's source leaves - * out, so a task that changes a table starts in the directory that holds it. + * The top of `sim workflows source --help` on `surface`, above the usage line: what a workflow's + * source leaves out, so a task that changes a table starts in the command that changes it. */ -export const WORKFLOW_SOURCE_SCOPE_HELP = `A workflow's source holds that workflow alone: edit a table's columns and rows with +export function workflowSourceScopeHelp(surface: PrimerSurface): string { + const tables = + surface === 'chat' + ? `change a table's columns with +\`sim tables columns create|update\` before the get (the table types it writes miss a later +change), its rows with \`sim tables rows\`` + : `edit a table's columns and rows with \`sim workspaces source get --dir \` (tables/.ts), read rows with \`sim tables rows -list \`. \`workflows source get\` names the tables a workflow uses (\`tables\`). +list
\`` + return `A workflow's source holds that workflow alone: ${tables}. \`workflows source get\` names the tables a workflow uses (\`tables\`). ` +} + +const GET_LINE = ` sim workflows source get --dir ./wf && cat ./wf/${SOURCE_AGENTS_FILE}` + +const WORKFLOW_LOOP = + 'sim workflows source check --dir ./wf && sim workflows source apply --dir ./wf --yes' + +const CHAIN_STOPS = + 'A non-zero exit stops the chain at the first failure; fix what it reported and run it again.' /** - * `sim workflows source --help`, after the command list. The get reads the primer in the same - * shell call, so the agent edits without a turn spent opening it. + * The loop lines of `sim workflows source --help` on each surface: a coding agent chains the test + * run and the deploy onto the apply, while the chat's shell refuses a synchronous run, so it tests + * and deploys through `sim_cli`. */ -export const WORKFLOW_SOURCE_LOOP_HELP = ` -The loop, two shell calls (: its id or exact name): - sim workflows source get --dir ./wf && cat ./wf/${SOURCE_AGENTS_FILE} - edit every file, then: sim workflows source check --dir ./wf && sim workflows source apply --dir ./wf --yes --run '{…}' --deploy -A non-zero exit stops the chain at the first failure; fix what it reported and run it again. check +const WORKFLOW_LOOP_LINES: Record = { + cli: `The loop, two shell calls (: its id or exact name): +${GET_LINE} + edit every file, then: ${WORKFLOW_LOOP} --run '{…}' --deploy +${CHAIN_STOPS} check compiles and type-checks (TypeScript installs on first run; --no-types skips it); apply re-checks, saves the draft and rewrites the files; --run dry-runs that input on the saved draft (writes stubbed, listed under run.sideEffects); --deploy deploys only if that run completed (without it the -draft stays undeployed). --allow-delete lets an edit remove a block or variable; apply --dry only +draft stays undeployed).`, + chat: `The loop, two calls in run_code's shell (: its id or exact name): +${GET_LINE} + edit every file, then: ${WORKFLOW_LOOP} +then test the saved draft with sim_cli (the shell refuses a synchronous run): + workflows run --dry --input '{…}' --dir ./wf +and once it completes, deploy it with sim_cli: workflows deploy . +${CHAIN_STOPS} check +compiles and type-checks (--no-types skips it); apply re-checks, saves the draft and rewrites the +files.`, +} + +/** + * \`sim workflows source --help\` on \`surface\`, after the command list. The get reads the primer + * in the same shell call, so the agent edits without a turn spent opening it. + */ +export function workflowSourceLoopHelp(surface: PrimerSurface): string { + return ` +${WORKFLOW_LOOP_LINES[surface]} --allow-delete lets an edit remove a block or variable; apply --dry only prints the plan; get --force replaces unapplied edits or another workflow's source. A new workflow: \`sim workflows source create --dir ./new --workspace \` writes a -starter; edit and check it, then \`create --dir ./new --yes --run '{…}' --deploy\`. +starter; edit and check it, then \`create --dir ./new --yes${surface === 'chat' ? '' : " --run '{…}' --deploy"}\`. ${WORKSPACE_LINE} ${RUN_LOGS_LINE} ${statusLine('sim workflows source', './wf')}` +} /** `sim workspaces source --help`, after the command list. */ export const WORKSPACE_SOURCE_LOOP_HELP = ` diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index 337f365299f..fae9154d440 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -7,6 +7,7 @@ import type { BlockCatalog } from '@sim/workflow-code' import { SOURCE_BASE_FILE, SOURCE_ENTRY_FILE, SOURCE_LOCK_FILE } from '@sim/workflow-code/limits' import { SDK_MAJOR, SDK_SPECIAL_BUILDERS } from '@sim/workflow-code/sdk' import { builderSnippet, describeBuilder, referencedBuilders } from '@sim/workflow-sdk/codegen' +import { embedStore } from '../../embed-context' import { RATE_LIMITED_EXIT_CODE, SOURCE_BUSY_EXIT_CODE, @@ -15,11 +16,29 @@ import { SOURCE_LOCAL_CHANGES_EXIT_CODE, SOURCE_STALE_EXIT_CODE, } from '../../exit-codes' +import { CLI_HOST_ENV, MOTHERSHIP_CLI_HOST } from '../../host' import { SOURCE_AGENTS_FILE, SOURCE_STARTER_FILE } from './source-dir' /** Which directory a primer is for. */ export type PrimerKind = 'workflow' | 'workspace' +/** + * Who reads a primer: a coding agent with a shell of its own (`cli`), or Mothership's chat + * (`chat`), whose workbench shell refuses a synchronous run (it tests through its `sim_cli` tool) + * and which Sim refuses workspace source. A workspace directory has the `cli` primer alone. + */ +export type PrimerSurface = 'cli' | 'chat' + +/** + * The surface this CLI serves: `chat` where its host is Mothership, named by the embedding call + * (Mothership's `sim_cli` tool) or by {@link CLI_HOST_ENV} (its workbench), else `cli`. + */ +export function primerSurface(): PrimerSurface { + const embedded = embedStore.getStore() + const host = embedded ? embedded.host : process.env[CLI_HOST_ENV] + return host === MOTHERSHIP_CLI_HOST ? 'chat' : 'cli' +} + /** * The primer without its builder snippets stays within this many bytes: about one screen, room for * the rules agents otherwise spend a lookup on (renames, failures, test runs). @@ -38,7 +57,6 @@ export const PATTERNS_HEADING = '- **Patterns**' /** The rules every source directory shares, after the kind's own edit loop. */ function sharedRules( - group: string, extra: { renames?: string; patterns?: string; debug?: string } = {} ): string { return `- **Renames**: rename any number of blocks' display names (first argument) or consts, with other edits: \`${SOURCE_LOCK_FILE}\` keeps each block and apply rewrites every reference, \`$ref.\` too. Changing both on one block keeps it only if its settings or neighbours match, else a delete (\`E_APPLY_BLOCK_DELETE\`). One workflow variable per apply.${extra.renames ?? ''} @@ -52,21 +70,46 @@ ${PATTERNS_HEADING} (\`.sim/examples/\`, indexed atop \`cookbook.ts\`; any build - Tables: \`table.queryRows\` outputs \`rows\` (\`recent.rows[0].data.status\`), not \`row\`; \`table.upsertRow\` takes \`conflictColumn: 'orderId'\`. - Rejoin: before one \`response\`, a Function picks the branch that ran with \`??\`.${extra.patterns ?? ''} - **Credentials**: \`sim credentials connect --name ""\`, send the owner its link, then \`credential('')\`. -- **Run**: \`sim workflows run \` runs the active deployment (\`--deployment-version \`: that version); \`--draft\` runs the draft for real (use test resources); \`--dry\` runs it stubbing writes and MCP tools (even read-only: \`mcp-read-only\`), listed in \`sideEffects\` (\`dry_run_*\` placeholders; a read given one too: \`placeholder\`); GET \`api\` calls and plain-JS GET fetches run; sandboxed code (Python, shell, imports): \`unchecked\`. \`--allow \` sends its writes (use test resources); \`--mock ='{…}'\` fixes its output (bare, with \`--mock-from \`: that run's); a child's block: \`.\`. -- **Debug**: \`--dir .\` maps a failure to file:line; \`sim logs get --trace --no-include-workflow-state\`; rows: \`sim tables rows list
\`; rerun: \`--from-block --source-run \`; \`--stop-after \`.${extra.debug ?? ''} -- **Exit codes**: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (redo in a fresh \`${group} get\`), ${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.` +- **Run**: \`sim workflows run \` runs the active deployment; \`--draft\` runs the draft for real (use test resources); \`--dry\` runs it stubbing writes and MCP tools (even read-only: \`mcp-read-only\`), listed in \`sideEffects\` (\`dry_run_*\` placeholders; a read given one too: \`placeholder\`); GET \`api\` calls and plain-JS GET fetches run; sandboxed code (Python, shell, imports): \`unchecked\`. \`--allow \` sends its writes; \`--mock ='{…}'\` fixes its output (bare, with \`--mock-from \`: that run's); a child's block: \`.\`. +- **Debug**: \`--dir \` maps a failure to file:line; \`sim logs get --trace --no-include-workflow-state\`; rows: \`sim tables rows list
\`; rerun: \`--from-block --source-run \`; \`--stop-after \`.${extra.debug ?? ''} +- **Exit codes**: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (redo in a fresh get), ${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 +const WORKFLOW_LOOP = + 'sim workflows source check --dir . && sim workflows source apply --dir . --yes' + +const WORKSPACE_LOOP = + 'sim workspaces source check --dir . && sim workspaces source apply --dir . --yes' + +/** What a coding agent chains onto a workflow apply: the test run, then the deploy. */ +const RUN_AND_DEPLOY = " --run '{…}' --deploy" -\`${SOURCE_ENTRY_FILE}\` is a Sim workflow as TypeScript; the server compiles it statically and nothing in it runs. Commands here (table ones too) act on the workflow \`${SOURCE_BASE_FILE}\` names and its workspace (a starter's \`${SOURCE_STARTER_FILE}\` names the workspace, and its loop runs \`create\` in place of \`apply\`: no workflow exists yet). +const EDIT_LOOP_LEAD = '**Edit loop**: write every file, then run one chained command' -**Edit loop**: write every file, then run one chained command; fix what it reports: \`sim workflows source check --dir . && sim workflows source apply --dir . --yes --run '{…}' --deploy\` applies, dry-runs that input on the draft, and deploys only if it completed (no \`--deploy\`: stays a draft). \`check\` also type-checks (no \`tsc\`). Apply re-checks (\`apply --dry\` only plans) and rewrites \`${SOURCE_ENTRY_FILE}\`: reread it before editing. +const APPLY_REWRITES = `\`check\` also type-checks (no \`tsc\`). Apply re-checks (\`apply --dry\` only plans) and rewrites \`${SOURCE_ENTRY_FILE}\`: reread it before editing.` -- **Scope**: the workflow alone. Table columns and rows: \`sim tables columns update
--column-name --updates '{…}'\`, \`sim tables rows update
--data '{…}'\`. +/** + * The workflow edit loop of each surface. A coding agent chains the test run and the deploy onto + * the apply; the chat's shell refuses a synchronous run, so its loop stops at the apply and the + * test runs through `sim_cli`, whose `--dir` reads the same workbench. + */ +const WORKFLOW_EDIT_LOOP: Record = { + cli: `${EDIT_LOOP_LEAD}; fix what it reports: \`${WORKFLOW_LOOP}${RUN_AND_DEPLOY}\` applies, dry-runs that input, and deploys only if it completed (no \`--deploy\`: stays a draft). ${APPLY_REWRITES}`, + chat: `${EDIT_LOOP_LEAD} in run_code's shell; fix what it reports: \`${WORKFLOW_LOOP}\`. ${APPLY_REWRITES} Test the draft with sim_cli (the shell refuses synchronous runs): \`workflows run --dry --input '{…}' --dir \` (from /home/user); once it completes, \`workflows deploy \`.`, +} + +function workflowPrimer(surface: PrimerSurface): string { + return `# Sim workflow source: primer + +\`${SOURCE_ENTRY_FILE}\` is a Sim workflow as TypeScript; the server compiles it; nothing in it runs. Commands here (table ones too) act on the workflow \`${SOURCE_BASE_FILE}\` names and its workspace (a starter's \`${SOURCE_STARTER_FILE}\` names the workspace; its loop runs \`create\` in place of \`apply\`). + +${WORKFLOW_EDIT_LOOP[surface]} + +- **Scope**: the workflow alone. Tables: \`sim tables columns create
--column '{…}'\` (or \`update\`), \`sim tables rows update
--data '{…}'\`; change columns before the get (its table types go stale). - **Deletes**: removing a block or variable needs \`apply --allow-delete\`. -${sharedRules('sim workflows source')} +${sharedRules()} ` +} /** What a workspace directory adds to the shared rules. */ const WORKSPACE_EXTRA = { @@ -84,7 +127,7 @@ A Sim workspace as files (\`tables/\`, \`workflows//\`); nothing here runs. - **Deletes**: removing a file, folder, column, block or variable needs \`apply --allow-delete\` and is permanent. - **Exit ${SOURCE_HELD_EXIT_CODE}**: partly written: what needs an unset secret or unbound credential waits; set it, reapply. -${sharedRules('sim workspaces source', WORKSPACE_EXTRA)} +${sharedRules(WORKSPACE_EXTRA)} ` /** @@ -94,29 +137,42 @@ ${sharedRules('sim workspaces source', WORKSPACE_EXTRA)} export const AGENTS_POINTER_MARKER = '' +const STARTER_LOOP = ` A starter (\`${SOURCE_STARTER_FILE}\`, no workflow yet) runs \`create\` in place of \`apply\`.` + +const WORKSPACE_POINTER_LOOP = `\`${WORKSPACE_LOOP}\`; fix what it reports next.` + +/** The loop line of the pointer, after its lead, by directory kind and surface. */ +const POINTER_LOOPS: Record> = { + workflow: { + cli: `\`${WORKFLOW_LOOP}${RUN_AND_DEPLOY}\`; fix what it reports next.${STARTER_LOOP}`, + chat: `\`${WORKFLOW_LOOP}\`; fix what it reports next. Then test the draft with sim_cli as \`${SOURCE_AGENTS_FILE}\` says.${STARTER_LOOP}`, + }, + workspace: { cli: WORKSPACE_POINTER_LOOP, chat: WORKSPACE_POINTER_LOOP }, +} + /** * The root `AGENTS.md` pointer: an agent that opens `workflow.ts` loads the nearest `AGENTS.md` * above it, and `.sim/` is a sibling of the source, so without this file the guide is never found. */ -export function agentsPointer(kind: PrimerKind): string { - const group = kind === 'workflow' ? 'sim workflows source' : 'sim workspaces source' +export function agentsPointer(kind: PrimerKind, surface: PrimerSurface = 'cli'): string { return `${AGENTS_POINTER_MARKER} # Sim ${kind} source ${kind === 'workflow' ? '`workflow.ts` is a Sim workflow as TypeScript that Sim compiles' : 'This directory is a Sim workspace as files that Sim applies'}; nothing in it runs. Read \`${SOURCE_AGENTS_FILE}\` before editing: the rules, the edit loop, patterns and exit codes. -Loop: write every file, then one chained command: \`${group} check --dir . && ${group} apply --dir . --yes${kind === 'workflow' ? " --run '{…}' --deploy" : ''}\`; fix what it reports next.${kind === 'workflow' ? ` A starter (\`${SOURCE_STARTER_FILE}\`, no workflow yet) runs \`create\` in place of \`apply\`.` : ''} +Loop: write every file, then one chained command: ${POINTER_LOOPS[kind][surface]} Exit codes: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (get a fresh copy and redo the edit), ${SOURCE_DRIFT_EXIT_CODE} \`status\`: the server changed. ` } /** - * 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. + * The primer for a `kind` directory read on `surface`, without builder snippets. The mothership + * worker preloads the `chat` workflow primer verbatim 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 +export function sourcePrimer(kind: PrimerKind, surface: PrimerSurface = 'cli'): string { + return kind === 'workflow' ? workflowPrimer(surface) : WORKSPACE_PRIMER } /** @@ -150,12 +206,14 @@ function builderSnippets(catalog: BlockCatalog, sources: Iterable): stri return `## Builders this source uses\n\n${snippets.join('\n')}\n${rest}` } -/** The primer with the snippets of the builders `sources` call. */ +/** The `surface` primer with the snippets of the builders `sources` call. */ export function primerFor( kind: PrimerKind, + surface: PrimerSurface, catalog: BlockCatalog, sources: Iterable ): string { + const primer = sourcePrimer(kind, surface) const snippets = builderSnippets(catalog, sources) - return snippets ? `${sourcePrimer(kind)}\n${snippets}` : sourcePrimer(kind) + return snippets ? `${primer}\n${snippets}` : primer } diff --git a/packages/sim-cli/src/commands/protocol/source-tree.ts b/packages/sim-cli/src/commands/protocol/source-tree.ts index 24c275329a8..d078b94f023 100644 --- a/packages/sim-cli/src/commands/protocol/source-tree.ts +++ b/packages/sim-cli/src/commands/protocol/source-tree.ts @@ -53,7 +53,13 @@ import { updateSourceDir, withMissingLines, } from './source-dir' -import { AGENTS_POINTER_MARKER, agentsPointer, type PrimerKind, primerFor } from './source-primer' +import { + AGENTS_POINTER_MARKER, + agentsPointer, + type PrimerKind, + primerFor, + primerSurface, +} from './source-primer' import { shellWord } from './source-ui' /** The CLI's `tsconfig.json`, which a check type-checks the directory with. */ @@ -830,7 +836,8 @@ export async function sourceTreeChange( options: { incremental?: boolean } = {} ): Promise<{ change: SourceDirChange; ownsTsconfig: boolean; primer: string }> { const sources = [...use.sources] - const primer = primerFor(profile.kind, catalog, sources) + const surface = primerSurface() + const primer = primerFor(profile.kind, surface, catalog, sources) const write: Array = [ [SOURCE_AGENTS_FILE, `${primer}\n${profile.agents}`], ...(profile.guides ?? []), @@ -853,7 +860,7 @@ export async function sourceTreeChange( readUserOwnedText(dir, ROOT_AGENTS_FILE), ]) if (rootAgents === null || rootAgents.startsWith(AGENTS_POINTER_MARKER)) { - write.push([ROOT_AGENTS_FILE, agentsPointer(profile.kind)]) + write.push([ROOT_AGENTS_FILE, agentsPointer(profile.kind, surface)]) } const kept = options.incremental ? includedBlockTypes(tsconfig) : [] const used = usedBlockTypes(catalog, { diff --git a/packages/sim-cli/src/commands/protocol/source-types.ts b/packages/sim-cli/src/commands/protocol/source-types.ts index 5cbce967139..83a38b8ce15 100644 --- a/packages/sim-cli/src/commands/protocol/source-types.ts +++ b/packages/sim-cli/src/commands/protocol/source-types.ts @@ -4,8 +4,9 @@ * declarations are built for) over the directory's `tsconfig.json`, each error a finding. * * A source directory has no `package.json`, so the release is installed once with `npm` into the - * CLI's cache and reused from there. When it cannot be installed (offline, no `npm`) or does not - * start, the check reports `W_TYPES_UNCHECKED` and the compile's findings still decide the exit. + * CLI's cache and reused from there, unless {@link TYPESCRIPT_DIR_ENV} names a directory that + * already holds it. When it cannot be installed (offline, no `npm`) or does not start, the check + * reports `W_TYPES_UNCHECKED` and the compile's findings still decide the exit. */ import { spawn } from 'node:child_process' import { existsSync } from 'node:fs' @@ -45,8 +46,9 @@ declarations are built for) over tsconfig.json. Each type error is an E_TYPE err starting with TypeScript's code. One is left out on a line the compile already reports an error on, and in a file still as the last get or apply wrote it when that file had the same error then (against the declarations as that get or apply left them). The first check installs that release -with npm into the CLI's cache, once; when it cannot (offline, no npm), the check warns -W_TYPES_UNCHECKED and passes or fails on the compile alone. --no-types skips the type check.` +with npm into the CLI's cache, once (none when SIM_TYPESCRIPT_DIR already holds it); when it +cannot (offline, no npm), the check warns W_TYPES_UNCHECKED and passes or fails on the compile +alone. --no-types skips the type check.` /** Adds `--no-types` to a check command. */ export function typesFlag(command: Command): Command { @@ -72,9 +74,22 @@ const PROCESS_TIMEOUT_MS = 5 * 60_000 /** At most this much of a process's output is kept: tsc's findings, npm's error lines. */ const MAX_OUTPUT_BYTES = 1024 * 1024 +/** + * Names a directory of TypeScript releases installed ahead of time, one per version as the cache + * lays them out (`//node_modules/typescript`), such as a sandbox image bakes in + * with `npm install --prefix / typescript@`. A check reads the pinned + * release there before the cache and never writes there; without it, the cache installs as usual. + */ +const TYPESCRIPT_DIR_ENV = 'SIM_TYPESCRIPT_DIR' + +/** The pinned release's folder in `releases`, a directory laid out one folder per version. */ +function releaseRoot(releases: string): string { + return join(releases, SOURCE_TYPESCRIPT_VERSION) +} + /** Where the pinned release is installed: cache, safe to delete, so it follows `SIM_CONFIG_DIR`. */ function typescriptRoot(): string { - return join(configDir(), 'cache', 'typescript', SOURCE_TYPESCRIPT_VERSION) + return releaseRoot(join(configDir(), 'cache', 'typescript')) } function tscPath(root: string): string { @@ -143,11 +158,17 @@ function npmReason(stderr: string): string { } /** - * The pinned release's `tsc`, installed on first use: into a fresh folder beside its place, then - * renamed there, so a check interrupted mid-install or two checks installing at once never leave - * a partial install behind. The install reads the person's npm configuration (registry, proxy). + * The pinned release's `tsc`: the one {@link TYPESCRIPT_DIR_ENV} holds, else the cache's, installed + * on first use into a fresh folder beside its place, then renamed there, so a check interrupted + * mid-install or two checks installing at once never leave a partial install behind. The install + * reads the person's npm configuration (registry, proxy). */ async function installedTsc(): Promise { + const preinstalled = process.env[TYPESCRIPT_DIR_ENV]?.trim() + if (preinstalled) { + const tsc = tscPath(releaseRoot(preinstalled)) + if (existsSync(tsc)) return tsc + } const root = typescriptRoot() const tsc = tscPath(root) if (existsSync(tsc)) return tsc diff --git a/packages/sim-cli/src/commands/protocol/source-ui.ts b/packages/sim-cli/src/commands/protocol/source-ui.ts index 4c66524e4ba..b9d78493bfa 100644 --- a/packages/sim-cli/src/commands/protocol/source-ui.ts +++ b/packages/sim-cli/src/commands/protocol/source-ui.ts @@ -85,6 +85,13 @@ function formatDiagnostic(diagnostic: Diagnostic): string { return lines.join('\n') } +/** A finding as one line, without its frame or hint: where it is, its code and its message. */ +export function findingLine(diagnostic: Diagnostic): string { + return safeOneLine( + formatDiagnostic({ ...boundFindingText(diagnostic), frame: undefined, hint: undefined }) + ) +} + /** How many other locations a collapsed line lists before counting the rest. */ const COLLAPSED_LOCATIONS = 8 diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts index ebb0fa6f105..28ed6586f13 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-check.test.ts @@ -376,7 +376,7 @@ describe('sim workflows source check', () => { }) }) - it('with --output json, prints each finding in the JSON only, not again as a frame on stderr', async () => { + it('with --output json, prints each finding in the JSON, ending stderr with the first error on one line and no frame', async () => { cacheCatalog() writeFileSync( join(dir, 'workflow.ts'), @@ -386,7 +386,34 @@ describe('sim workflows source check', () => { await check() expect(stdoutJson()).toMatchObject({ diagnostics: [{ code: 'E_UNKNOWN_PARAM' }] }) - expect(vi.mocked(console.error)).not.toHaveBeenCalled() + const stderr = vi.mocked(console.error).mock.calls.map((call) => call.join(' ')) + expect(stderr).toEqual([ + expect.stringMatching(/^Error: workflow\.ts:6:\d+ error E_UNKNOWN_PARAM: /), + ]) + }) + + it('ends stderr with the first error, not a warning printed after it', async () => { + cacheCatalog() + contextMockFns.mockProfileFrom.mockReturnValue({ + ...mockedProfile(), + workspaceId: 'ws_other', + output: 'table', + }) + writeFileSync( + join(dir, 'workflow.ts'), + UNKNOWN_METHOD.replace( + '{ body: { received: start.message } }', + '{ bdy: { received: start.message } }' + ) + ) + writeLock(['start', 'done', 'call']) + + await check() + + const stderr = vi.mocked(console.error).mock.calls.map((call) => call.join(' ')) + expect(stderr.some((line) => / warning W_/.test(line))).toBe(true) + expect(stderr.at(-1)).toMatch(/^Error: workflow\.ts:6:\d+ error E_UNKNOWN_PARAM: /) + expect(process.exitCode).toBe(1) }) it('with --output json in a GitHub Actions job, still annotates each finding on stderr, as a workflow command only', async () => { @@ -401,7 +428,10 @@ describe('sim workflows source check', () => { expect(stdoutJson()).toMatchObject({ diagnostics: [{ code: 'E_UNKNOWN_PARAM' }] }) const stderr = vi.mocked(console.error).mock.calls.map((call) => call.join(' ')) - expect(stderr).toEqual([expect.stringMatching(/^::error file=.*,title=E_UNKNOWN_PARAM::/)]) + expect(stderr).toEqual([ + expect.stringMatching(/^::error file=.*,title=E_UNKNOWN_PARAM::/), + expect.stringMatching(/^Error: workflow\.ts:6:\d+ error E_UNKNOWN_PARAM: /), + ]) }) it('leaves stored() to the server, which holds the stored values', async () => { 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 77374e8cee5..452a9914f3b 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 @@ -14,6 +14,7 @@ import { escapeRegExp } from '@sim/utils/string' import { COOKBOOK_EXAMPLES, WORKSPACE_COOKBOOK } from '@sim/workflow-sdk/codegen' import { Command } from 'commander' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { runEmbeddedCli } from '../../embed' import { SimApiError } from '../../http/client' import { buildProgram } from '../../program' import { buildGeneratedCommands } from '../../runtime/build' @@ -431,18 +432,29 @@ describe('sim workflows source get --dir', () => { expect(existsSync(join(outDir, '.sim/AGENTS.md'))).toBe(true) }) - it.each(['workflow', 'workspace'] as const)( - 'names in the %s primer only commands and flags this CLI has', - (kind) => { + /** Each primer there is: the workspace directory has the `cli` one alone. */ + const PRIMERS = [ + ['workflow', 'cli'], + ['workflow', 'chat'], + ['workspace', 'cli'], + ] as const + + it.each(PRIMERS)( + 'names in the %s %s primer only commands and flags this CLI has', + (kind, surface) => { const program = buildProgram() + const roots = new Set(program.commands.map((command) => command.name())) + // A `sim_cli` command is named without `sim`, as that tool takes it. const named = [ - ...`${sourcePrimer(kind)}${agentsPointer(kind)}`.matchAll(/`(sim [^`]+)`/g), - ].flatMap((match) => match[1].split(' && ')) + ...`${sourcePrimer(kind, surface)}${agentsPointer(kind, surface)}`.matchAll(/`([^`]+)`/g), + ] + .flatMap((match) => match[1].split(' && ')) + .map((line) => line.replace(/^sim /, '')) + .filter((line) => roots.has(line.split(' ')[0]) && line.includes(' ')) expect(named.length).toBeGreaterThan(0) for (const line of named) { let command: Command = program - const words = line.split(/\s+/).slice(1) - for (const word of words) { + for (const word of line.split(/\s+/)) { if (word.startsWith('-') || word.startsWith('<') || /^['"{.]/.test(word)) break const next = command.commands.find( (child) => child.name() === word || child.aliases().includes(word) @@ -466,20 +478,33 @@ describe('sim workflows source get --dir', () => { } ) - it('keeps the primer without snippets within its byte budget for both directory kinds', () => { - for (const kind of ['workflow', 'workspace'] as const) { - expect(Buffer.byteLength(sourcePrimer(kind))).toBeLessThanOrEqual(PRIMER_MAX_BYTES) + it('keeps every primer without snippets within its byte budget', () => { + for (const [kind, surface] of PRIMERS) { + expect( + Buffer.byteLength(sourcePrimer(kind, surface)), + `${kind} ${surface}` + ).toBeLessThanOrEqual(PRIMER_MAX_BYTES) } }) - it.each(['workflow', 'workspace'] as const)( - 'quotes in the %s primer patterns only code the type-checked examples hold', - (kind) => { + it('teaches the chat no command its workbench or Sim refuses it, and the test run through sim_cli', () => { + const chat = `${sourcePrimer('workflow', 'chat')}${agentsPointer('workflow', 'chat')}` + expect(chat).not.toMatch(/workspaces source/) + expect(chat).not.toMatch(/ --run(?![\w-])/) + expect(chat).not.toMatch(/&& sim workflows run\b/) + expect(chat).toMatch(/sim_cli[^\n]*`workflows run --dry\b/) + expect(chat).toContain('`workflows deploy `') + expect(sourcePrimer('workflow', 'cli')).toContain("--run '{…}' --deploy") + }) + + it.each(PRIMERS)( + 'quotes in the %s %s primer patterns only code the type-checked examples hold', + (kind, surface) => { const examples = [ ...Object.values(COOKBOOK_EXAMPLES), ...Object.values(WORKSPACE_COOKBOOK), ].join('\n') - const lines = sourcePrimer(kind).split('\n') + const lines = sourcePrimer(kind, surface).split('\n') const start = lines.findIndex((line) => line.startsWith(PATTERNS_HEADING)) const end = lines.findIndex((line, index) => index > start && !line.startsWith(' - ')) const spans = lines @@ -493,6 +518,53 @@ describe('sim workflows source get --dir', () => { } ) + it('writes the chat primer and pointer inside Mothership, and the coding-agent ones elsewhere', async () => { + const guides = () => + ['.sim/AGENTS.md', 'AGENTS.md'].map((file) => readFileSync(join(outDir, file), 'utf8')) + serve() + await get('--dir', outDir) + for (const guide of guides()) { + expect(guide).toContain("--yes --run '{…}' --deploy") + expect(guide).not.toContain('sim_cli') + } + + vi.stubEnv('SIM_CLI_HOST', 'mothership') + await get('--dir', outDir, '--force') + + for (const guide of guides()) { + expect(guide).not.toMatch(/ --run(?![\w-])/) + expect(guide).toContain('with sim_cli') + } + }) + + it('gives the chat loop in the source help inside Mothership and to an embedded run', async () => { + const render = () => { + const source = buildProgram() + .commands.find((command) => command.name() === 'workflows') + ?.commands.find((command) => command.name() === 'source') + let text = '' + source?.configureOutput({ writeOut: (chunk) => (text += chunk) }) + source?.outputHelp() + return text + } + expect(render()).toContain("--yes --run '{…}' --deploy") + expect(render()).toContain('sim workspaces source get') + + const embedded = (host?: string) => + runEmbeddedCli( + ['workflows', 'source', '--help'], + { endpoint: 'https://sim.test', apiKey: 'key' }, + { host } + ) + expect((await embedded()).stdout).toContain("--yes --run '{…}' --deploy") + const mothership = (await embedded('mothership')).stdout + vi.stubEnv('SIM_CLI_HOST', 'mothership') + for (const chat of [mothership, render()]) { + expect(chat).not.toMatch(/ --run(?![\w-])|workspaces source/) + expect(chat).toContain("workflows run --dry --input '{…}' --dir ./wf") + } + }) + it('type-checks a builder of a block the directory does not hold: through the cache at once, and locally after a check', async () => { const workflow = [ '// @sim-sdk 1', 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 5678ebc7b04..2ce6014df4b 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 @@ -19,7 +19,7 @@ import { knowledgeCodec } from '@sim/workspace-code/kinds/knowledge' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { SimApiError } from '../../http/client' import { contextMockFns, contextMockState, mockedProfile } from '../../test/context-mock' -import { provideTscPrinting, provideTypescript } from '../../test/typescript' +import { provideTscPrinting, provideTypescript, provideTypescriptIn } from '../../test/typescript' import { runWorkflowSourceCheck, runWorkspaceSource } from '../../test/workspace-source-command' import { blobBytes, blobDigests } from './workspace-source-blobs' import { kindFolders } from './workspace-source-dir' @@ -1385,6 +1385,31 @@ describe('the type check of workspaces source check', () => { expect(env).not.toContain('sk-sim-secret') }) + it('type-checks with the release SIM_TYPESCRIPT_DIR holds, installing nothing', async () => { + serve({ 'tables/leads.ts': LEADS }) + await get() + writeInserting( + 'leads', + " const done = response('Done', { body: { email: start.emial } })\n save.to(done)" + ) + rmSync(join(rootDir, 'config/cache/typescript'), { recursive: true }) + const bin = join(rootDir, 'bin') + mkdirSync(bin) + writeFileSync(join(bin, 'npm'), `#!/bin/sh\ntouch "${join(rootDir, 'npm-ran')}"\nexit 1\n`, { + mode: 0o755, + }) + vi.stubEnv('PATH', `${bin}:${process.env.PATH}`) + provideTypescriptIn(join(rootDir, 'preinstalled')) + vi.stubEnv('SIM_TYPESCRIPT_DIR', join(rootDir, 'preinstalled')) + + await runWorkspaceSource('check', dir) + + expect(result().checked).toEqual(['compile', 'types']) + expect(result().diagnostics).toContainEqual(expect.objectContaining({ code: 'E_TYPE' })) + expect(existsSync(join(rootDir, 'npm-ran'))).toBe(false) + expect(existsSync(join(rootDir, 'config/cache/typescript'))).toBe(false) + }) + it('warns and passes on the compile alone when the TypeScript cache cannot be written', async () => { serve({ 'tables/leads.ts': LEADS }) await get() diff --git a/packages/sim-cli/src/embed-context.ts b/packages/sim-cli/src/embed-context.ts index df7999d046e..fc61152c7c4 100644 --- a/packages/sim-cli/src/embed-context.ts +++ b/packages/sim-cli/src/embed-context.ts @@ -36,6 +36,11 @@ export interface EmbedContext { identity: EmbeddedCliIdentity /** Absolute caller filesystem working directory; never inherited from the embedding server. */ workingDirectory?: string + /** + * Who embeds the CLI, as `SIM_CLI_HOST` names it for an installed one (`host.ts`); an embedded + * run never reads the host process env. + */ + host?: string stdout: EmbeddedOutput stderr: EmbeddedOutput /** diff --git a/packages/sim-cli/src/embed.ts b/packages/sim-cli/src/embed.ts index be26c306f55..9fd323d757d 100644 --- a/packages/sim-cli/src/embed.ts +++ b/packages/sim-cli/src/embed.ts @@ -84,6 +84,7 @@ export async function runEmbeddedCli( identity: EmbeddedCliIdentity, options?: { workingDirectory?: string + host?: string readFile?: EmbedContext['readFile'] openFile?: EmbedContext['openFile'] writeFile?: EmbedContext['writeFile'] @@ -97,6 +98,7 @@ export async function runEmbeddedCli( const ctx: EmbedContext = { identity, ...(options?.workingDirectory ? { workingDirectory: options.workingDirectory } : {}), + ...(options?.host ? { host: options.host } : {}), stdout: new EmbeddedOutput(), stderr: new EmbeddedOutput(), ...(reader diff --git a/packages/sim-cli/src/host.ts b/packages/sim-cli/src/host.ts new file mode 100644 index 00000000000..6b464831bea --- /dev/null +++ b/packages/sim-cli/src/host.ts @@ -0,0 +1,13 @@ +/** + * How a host that runs the CLI for an agent tells it so. Kept free of imports, so a host's server + * code reads these names without loading the CLI. + */ + +/** + * Set to {@link MOTHERSHIP_CLI_HOST} in the environment of the CLI that Mothership's workbench + * runs (an embedding call passes it as `host` instead), so the source primer and help it gives + * are the chat ones (`PrimerSurface`). + */ +export const CLI_HOST_ENV = 'SIM_CLI_HOST' + +export const MOTHERSHIP_CLI_HOST = 'mothership' diff --git a/packages/sim-cli/src/test/typescript.ts b/packages/sim-cli/src/test/typescript.ts index 8818cd02cf2..4e8aa09b545 100644 --- a/packages/sim-cli/src/test/typescript.ts +++ b/packages/sim-cli/src/test/typescript.ts @@ -10,13 +10,25 @@ const REPO_TYPESCRIPT = join(__dirname, '../../../../node_modules/typescript') * by linking the repository's copy, so a check type-checks without reaching npm. */ export function provideTypescript(configDir: string): void { - const installed = installedPath(configDir) + provideTypescriptIn(join(configDir, 'cache/typescript')) +} + +/** + * Lays the pinned TypeScript out under `releases` as the cache does + * (`/node_modules/typescript`), by linking the repository's copy. + */ +export function provideTypescriptIn(releases: string): void { + const installed = releasePath(releases) mkdirSync(dirname(installed), { recursive: true }) symlinkSync(REPO_TYPESCRIPT, installed, 'dir') } +function releasePath(releases: string): string { + return join(releases, SOURCE_TYPESCRIPT_VERSION, 'node_modules/typescript') +} + function installedPath(configDir: string): string { - return join(configDir, 'cache/typescript', SOURCE_TYPESCRIPT_VERSION, 'node_modules/typescript') + return releasePath(join(configDir, 'cache/typescript')) } /** From 86faf7f9a2a609e787543c4467956f2e1c749bf9 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 15:43:47 -0800 Subject: [PATCH 2/3] fix(workflow-code): deploy only the tested draft from chat, resolve SIM_TYPESCRIPT_DIR, drop ./host from the published manifest --- .github/workflows/publish-sim-cli.yml | 4 ++-- packages/sim-cli/src/commands/protocol/source-check.ts | 1 + packages/sim-cli/src/commands/protocol/source-loop-help.ts | 3 ++- packages/sim-cli/src/commands/protocol/source-primer.ts | 6 +++--- packages/sim-cli/src/commands/protocol/source-types.ts | 5 +++-- .../src/commands/protocol/workflow-source-get.test.ts | 4 +++- .../src/commands/protocol/workspace-source-get.test.ts | 7 ++++--- 7 files changed, 18 insertions(+), 12 deletions(-) diff --git a/.github/workflows/publish-sim-cli.yml b/.github/workflows/publish-sim-cli.yml index 2d77a608bdf..cc1a9978700 100644 --- a/.github/workflows/publish-sim-cli.yml +++ b/.github/workflows/publish-sim-cli.yml @@ -114,14 +114,14 @@ jobs: echo "tag=$TAG" } >> "$GITHUB_OUTPUT" - # `./embed` and the `#sim-cli/*` imports point at TypeScript source, which + # `./embed`, `./host` and the `#sim-cli/*` imports point at TypeScript source, which # only the monorepo's own Next.js app consumes (it transpiles the package). # The tarball ships `dist` alone, so published they would be dead entry # points; the smoke test below fails on any export that does not exist. - name: Drop source-only entry points working-directory: packages/sim-cli run: | - jq 'del(.imports, .exports["./embed"])' package.json > "$RUNNER_TEMP/package.json" + jq 'del(.imports, .exports["./embed"], .exports["./host"])' package.json > "$RUNNER_TEMP/package.json" mv "$RUNNER_TEMP/package.json" package.json # Bun packs because it rewrites `workspace:` ranges to real versions, diff --git a/packages/sim-cli/src/commands/protocol/source-check.ts b/packages/sim-cli/src/commands/protocol/source-check.ts index a3a8669dce4..1787f9b6fbe 100644 --- a/packages/sim-cli/src/commands/protocol/source-check.ts +++ b/packages/sim-cli/src/commands/protocol/source-check.ts @@ -916,6 +916,7 @@ export function reportCheck( // line as the failure reads the mistake, never a notice (the TypeScript install's) or a warning. const first = findings.find((finding) => finding.severity === 'error') if (first) printError(`Error: ${findingLine(first)}`) + else if (errors > 0) printError(`Error: ${errors} errors past the findings a check lists.`) } /** The catalog a cache read found, or a refusal naming `get`, the command that caches one. */ diff --git a/packages/sim-cli/src/commands/protocol/source-loop-help.ts b/packages/sim-cli/src/commands/protocol/source-loop-help.ts index 33b7699cd41..039fc33ec83 100644 --- a/packages/sim-cli/src/commands/protocol/source-loop-help.ts +++ b/packages/sim-cli/src/commands/protocol/source-loop-help.ts @@ -67,7 +67,8 @@ ${GET_LINE} edit every file, then: ${WORKFLOW_LOOP} then test the saved draft with sim_cli (the shell refuses a synchronous run): workflows run --dry --input '{…}' --dir ./wf -and once it completes, deploy it with sim_cli: workflows deploy . +and once it completes, deploy that draft with sim_cli: + workflows deploy --expected-draft-fingerprint ${CHAIN_STOPS} check compiles and type-checks (--no-types skips it); apply re-checks, saves the draft and rewrites the files.`, diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index fae9154d440..f7ea3f54a04 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -59,7 +59,7 @@ export const PATTERNS_HEADING = '- **Patterns**' function sharedRules( extra: { renames?: string; patterns?: string; debug?: string } = {} ): string { - return `- **Renames**: rename any number of blocks' display names (first argument) or consts, with other edits: \`${SOURCE_LOCK_FILE}\` keeps each block and apply rewrites every reference, \`$ref.\` too. Changing both on one block keeps it only if its settings or neighbours match, else a delete (\`E_APPLY_BLOCK_DELETE\`). One workflow variable per apply.${extra.renames ?? ''} + return `- **Renames**: rename blocks' display names (first argument) or consts, with other edits: \`${SOURCE_LOCK_FILE}\` keeps each block and apply rewrites every reference, \`$ref.\` too. Changing both on one block keeps it only if its settings or neighbours match, else a delete (\`E_APPLY_BLOCK_DELETE\`). One workflow variable per apply.${extra.renames ?? ''} - **References**: \`${SOURCE_ENTRY_FILE}\` reads \`x.content\`, text as \`\` t\`…\` \`\`, env as \`env.NAME\`. A function file (\`codeFile('./functions/x.js')\`) reads \`$ref..\` (key: display name lowercased, no spaces or dots), \`$ref.loop.currentItem\` / \`.index\` in a body (\`parallel\` too), \`$env.NAME\`; \`.py\`/\`.sh\` files \`\`, \`{{NAME}}\`. A block that never ran reads \`null\` (\`''\` in text). ${PATTERNS_HEADING} (\`.sim/examples/\`, indexed atop \`cookbook.ts\`; any builder: \`${PARAMS_COMMAND} \`): - Condition: keys test in order, first true wins, \`else: true\` last; wire \`route.high.to(alert)\`. @@ -70,7 +70,7 @@ ${PATTERNS_HEADING} (\`.sim/examples/\`, indexed atop \`cookbook.ts\`; any build - Tables: \`table.queryRows\` outputs \`rows\` (\`recent.rows[0].data.status\`), not \`row\`; \`table.upsertRow\` takes \`conflictColumn: 'orderId'\`. - Rejoin: before one \`response\`, a Function picks the branch that ran with \`??\`.${extra.patterns ?? ''} - **Credentials**: \`sim credentials connect --name ""\`, send the owner its link, then \`credential('')\`. -- **Run**: \`sim workflows run \` runs the active deployment; \`--draft\` runs the draft for real (use test resources); \`--dry\` runs it stubbing writes and MCP tools (even read-only: \`mcp-read-only\`), listed in \`sideEffects\` (\`dry_run_*\` placeholders; a read given one too: \`placeholder\`); GET \`api\` calls and plain-JS GET fetches run; sandboxed code (Python, shell, imports): \`unchecked\`. \`--allow \` sends its writes; \`--mock ='{…}'\` fixes its output (bare, with \`--mock-from \`: that run's); a child's block: \`.\`. +- **Run**: \`sim workflows run \` runs the active deployment; \`--draft\` runs the draft for real (use test resources); \`--dry\` runs it stubbing writes and MCP tools (even read-only: \`mcp-read-only\`), listed in \`sideEffects\` (\`dry_run_*\` placeholders); GET \`api\` calls and plain-JS GET fetches run; sandboxed code (Python, shell, imports): \`unchecked\`. \`--allow \` sends its writes; \`--mock ='{…}'\` fixes its output (bare, with \`--mock-from \`: that run's); a child's block: \`.\`. - **Debug**: \`--dir \` maps a failure to file:line; \`sim logs get --trace --no-include-workflow-state\`; rows: \`sim tables rows list
\`; rerun: \`--from-block --source-run \`; \`--stop-after \`.${extra.debug ?? ''} - **Exit codes**: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (redo in a fresh get), ${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.` } @@ -95,7 +95,7 @@ const APPLY_REWRITES = `\`check\` also type-checks (no \`tsc\`). Apply re-checks */ const WORKFLOW_EDIT_LOOP: Record = { cli: `${EDIT_LOOP_LEAD}; fix what it reports: \`${WORKFLOW_LOOP}${RUN_AND_DEPLOY}\` applies, dry-runs that input, and deploys only if it completed (no \`--deploy\`: stays a draft). ${APPLY_REWRITES}`, - chat: `${EDIT_LOOP_LEAD} in run_code's shell; fix what it reports: \`${WORKFLOW_LOOP}\`. ${APPLY_REWRITES} Test the draft with sim_cli (the shell refuses synchronous runs): \`workflows run --dry --input '{…}' --dir \` (from /home/user); once it completes, \`workflows deploy \`.`, + chat: `${EDIT_LOOP_LEAD} in run_code's shell; fix what it reports: \`${WORKFLOW_LOOP}\`. ${APPLY_REWRITES} Test the draft with sim_cli (the shell refuses sync runs): \`workflows run --dry --input '{…}' --dir \` (from /home/user); once it passes, \`workflows deploy --expected-draft-fingerprint \` (from \`.sim/base.json\`).`, } function workflowPrimer(surface: PrimerSurface): string { diff --git a/packages/sim-cli/src/commands/protocol/source-types.ts b/packages/sim-cli/src/commands/protocol/source-types.ts index 83a38b8ce15..46866a423bf 100644 --- a/packages/sim-cli/src/commands/protocol/source-types.ts +++ b/packages/sim-cli/src/commands/protocol/source-types.ts @@ -11,7 +11,7 @@ import { spawn } from 'node:child_process' import { existsSync } from 'node:fs' import { mkdir, mkdtemp, rename, rm, writeFile } from 'node:fs/promises' -import { dirname, join, posix } from 'node:path' +import { dirname, join, posix, resolve } from 'node:path' import { mapWithConcurrency } from '@sim/utils/concurrency' import { getErrorMessage } from '@sim/utils/errors' import { generateShortId } from '@sim/utils/id' @@ -166,7 +166,8 @@ function npmReason(stderr: string): string { async function installedTsc(): Promise { const preinstalled = process.env[TYPESCRIPT_DIR_ENV]?.trim() if (preinstalled) { - const tsc = tscPath(releaseRoot(preinstalled)) + // Resolved here: tsc runs from the source directory, not the caller's. + const tsc = tscPath(releaseRoot(resolve(preinstalled))) if (existsSync(tsc)) return tsc } const root = typescriptRoot() 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 452a9914f3b..24a1fadde01 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 @@ -493,7 +493,9 @@ describe('sim workflows source get --dir', () => { expect(chat).not.toMatch(/ --run(?![\w-])/) expect(chat).not.toMatch(/&& sim workflows run\b/) expect(chat).toMatch(/sim_cli[^\n]*`workflows run --dry\b/) - expect(chat).toContain('`workflows deploy `') + expect(chat).toContain( + '`workflows deploy --expected-draft-fingerprint `' + ) expect(sourcePrimer('workflow', 'cli')).toContain("--run '{…}' --deploy") }) 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 2ce6014df4b..d74fb43360d 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 @@ -13,7 +13,7 @@ import { writeFileSync, } from 'node:fs' import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { join, relative } from 'node:path' import { fingerprintOf } from '@sim/workspace-code' import { knowledgeCodec } from '@sim/workspace-code/kinds/knowledge' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -1385,7 +1385,7 @@ describe('the type check of workspaces source check', () => { expect(env).not.toContain('sk-sim-secret') }) - it('type-checks with the release SIM_TYPESCRIPT_DIR holds, installing nothing', async () => { + it('type-checks with the release a relative SIM_TYPESCRIPT_DIR holds, installing nothing', async () => { serve({ 'tables/leads.ts': LEADS }) await get() writeInserting( @@ -1400,7 +1400,8 @@ describe('the type check of workspaces source check', () => { }) vi.stubEnv('PATH', `${bin}:${process.env.PATH}`) provideTypescriptIn(join(rootDir, 'preinstalled')) - vi.stubEnv('SIM_TYPESCRIPT_DIR', join(rootDir, 'preinstalled')) + // Relative to the caller, as an env var usually is; tsc itself runs from the source directory. + vi.stubEnv('SIM_TYPESCRIPT_DIR', relative(process.cwd(), join(rootDir, 'preinstalled'))) await runWorkspaceSource('check', dir) From ca491cca19ab86dc1644948b942b82d1772657fd Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 16:13:36 -0800 Subject: [PATCH 3/3] fix(workflow-code): keep the test-resource warning on --allow, concrete table commands in the chat help --- .../sim-cli/src/commands/protocol/source-loop-help.ts | 7 ++++--- packages/sim-cli/src/commands/protocol/source-primer.ts | 8 +++----- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/packages/sim-cli/src/commands/protocol/source-loop-help.ts b/packages/sim-cli/src/commands/protocol/source-loop-help.ts index 039fc33ec83..8088eda05e8 100644 --- a/packages/sim-cli/src/commands/protocol/source-loop-help.ts +++ b/packages/sim-cli/src/commands/protocol/source-loop-help.ts @@ -30,9 +30,10 @@ function statusLine(group: string, dir: string): string { export function workflowSourceScopeHelp(surface: PrimerSurface): string { const tables = surface === 'chat' - ? `change a table's columns with -\`sim tables columns create|update\` before the get (the table types it writes miss a later -change), its rows with \`sim tables rows\`` + ? `change a table's columns before the get, whose +table types miss a later change: \`sim tables columns create
--column '{…}'\` or \`sim +tables columns update
--column-name --updates '{…}'\`; its rows with \`sim tables +rows update
--data '{…}'\`` : `edit a table's columns and rows with \`sim workspaces source get --dir \` (tables/.ts), read rows with \`sim tables rows list
\`` diff --git a/packages/sim-cli/src/commands/protocol/source-primer.ts b/packages/sim-cli/src/commands/protocol/source-primer.ts index f7ea3f54a04..41f31524e4e 100644 --- a/packages/sim-cli/src/commands/protocol/source-primer.ts +++ b/packages/sim-cli/src/commands/protocol/source-primer.ts @@ -56,9 +56,7 @@ const PARAMS_COMMAND = 'sim workflows source params' export const PATTERNS_HEADING = '- **Patterns**' /** The rules every source directory shares, after the kind's own edit loop. */ -function sharedRules( - extra: { renames?: string; patterns?: string; debug?: string } = {} -): string { +function sharedRules(extra: { renames?: string; patterns?: string; debug?: string } = {}): string { return `- **Renames**: rename blocks' display names (first argument) or consts, with other edits: \`${SOURCE_LOCK_FILE}\` keeps each block and apply rewrites every reference, \`$ref.\` too. Changing both on one block keeps it only if its settings or neighbours match, else a delete (\`E_APPLY_BLOCK_DELETE\`). One workflow variable per apply.${extra.renames ?? ''} - **References**: \`${SOURCE_ENTRY_FILE}\` reads \`x.content\`, text as \`\` t\`…\` \`\`, env as \`env.NAME\`. A function file (\`codeFile('./functions/x.js')\`) reads \`$ref..\` (key: display name lowercased, no spaces or dots), \`$ref.loop.currentItem\` / \`.index\` in a body (\`parallel\` too), \`$env.NAME\`; \`.py\`/\`.sh\` files \`\`, \`{{NAME}}\`. A block that never ran reads \`null\` (\`''\` in text). ${PATTERNS_HEADING} (\`.sim/examples/\`, indexed atop \`cookbook.ts\`; any builder: \`${PARAMS_COMMAND} \`): @@ -70,7 +68,7 @@ ${PATTERNS_HEADING} (\`.sim/examples/\`, indexed atop \`cookbook.ts\`; any build - Tables: \`table.queryRows\` outputs \`rows\` (\`recent.rows[0].data.status\`), not \`row\`; \`table.upsertRow\` takes \`conflictColumn: 'orderId'\`. - Rejoin: before one \`response\`, a Function picks the branch that ran with \`??\`.${extra.patterns ?? ''} - **Credentials**: \`sim credentials connect --name ""\`, send the owner its link, then \`credential('')\`. -- **Run**: \`sim workflows run \` runs the active deployment; \`--draft\` runs the draft for real (use test resources); \`--dry\` runs it stubbing writes and MCP tools (even read-only: \`mcp-read-only\`), listed in \`sideEffects\` (\`dry_run_*\` placeholders); GET \`api\` calls and plain-JS GET fetches run; sandboxed code (Python, shell, imports): \`unchecked\`. \`--allow \` sends its writes; \`--mock ='{…}'\` fixes its output (bare, with \`--mock-from \`: that run's); a child's block: \`.\`. +- **Run**: \`sim workflows run \` runs the active deployment; \`--draft\` runs the draft for real and \`--allow \` sends that block's writes (use test resources); \`--dry\` runs it stubbing writes and MCP tools (even read-only: \`mcp-read-only\`), listed in \`sideEffects\` (\`dry_run_*\` placeholders); GET \`api\` calls and plain-JS GET fetches run; sandboxed code (Python, shell, imports): \`unchecked\`. \`--mock ='{…}'\` fixes its output (bare, with \`--mock-from \`: that run's); a child's block: \`.\`. - **Debug**: \`--dir \` maps a failure to file:line; \`sim logs get --trace --no-include-workflow-state\`; rows: \`sim tables rows list
\`; rerun: \`--from-block --source-run \`; \`--stop-after \`.${extra.debug ?? ''} - **Exit codes**: 0 ok, 1 errors, ${SOURCE_STALE_EXIT_CODE} stale (redo in a fresh get), ${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.` } @@ -95,7 +93,7 @@ const APPLY_REWRITES = `\`check\` also type-checks (no \`tsc\`). Apply re-checks */ const WORKFLOW_EDIT_LOOP: Record = { cli: `${EDIT_LOOP_LEAD}; fix what it reports: \`${WORKFLOW_LOOP}${RUN_AND_DEPLOY}\` applies, dry-runs that input, and deploys only if it completed (no \`--deploy\`: stays a draft). ${APPLY_REWRITES}`, - chat: `${EDIT_LOOP_LEAD} in run_code's shell; fix what it reports: \`${WORKFLOW_LOOP}\`. ${APPLY_REWRITES} Test the draft with sim_cli (the shell refuses sync runs): \`workflows run --dry --input '{…}' --dir \` (from /home/user); once it passes, \`workflows deploy --expected-draft-fingerprint \` (from \`.sim/base.json\`).`, + chat: `${EDIT_LOOP_LEAD} in run_code's shell; fix what it reports: \`${WORKFLOW_LOOP}\`. ${APPLY_REWRITES} Test the draft with sim_cli, as the shell refuses runs: \`workflows run --dry --input '{…}' --dir \` (from /home/user), then \`workflows deploy --expected-draft-fingerprint \` (from \`.sim/base.json\`).`, } function workflowPrimer(surface: PrimerSurface): string {