sim 2.3.0-preview.328.1 → 2.3.0-preview.330.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -23754,7 +23754,7 @@ class SimClient {
23754
23754
  this.resolveCredential(options.auth);
23755
23755
  const workspaceId = explicit ?? this.profile.workspaceId;
23756
23756
  if (!workspaceId) {
23757
- throw new SimApiError(`No workspace set for profile "${this.profile.name}". Pass --workspace, or run: sim configure --profile ${this.profile.name} --set-workspace <id>`, 0);
23757
+ throw new SimApiError(`No workspace set for profile "${this.profile.name}". Pass -w <workspaceId>, set SIM_WORKSPACE, or run: sim configure --profile ${this.profile.name} --set-workspace <id>`, 0);
23758
23758
  }
23759
23759
  return workspaceId;
23760
23760
  }
@@ -35167,7 +35167,36 @@ Source handles:
35167
35167
  parallel-start-source, parallel-end-source the same for a parallel
35168
35168
  Renames:
35169
35169
  An edit's {"name":"New name"} also rewrites every <old key.field> reference to the block, in
35170
- other blocks' inputs and in a loop's or parallel's collection and condition.`;
35170
+ other blocks' inputs and in a loop's or parallel's collection and condition.
35171
+ Inputs:
35172
+ inputs takes the field ids \`sim blocks get <type>\` lists (inputSchema, operationInputSchema),
35173
+ or the name a pair of them shares (inputDefinitions: tableId for tableSelector and
35174
+ manualTableId; a string goes to the typed field). Add the type it answers with: \`blocks get
35175
+ table\` answers table_v2, and an add of legacy table is refused.
35176
+ conditions (condition): [{"title":"if","value":"<start.n> > 3"},{"title":"else if","value":"…"},
35177
+ {"title":"else","value":""}]; the last entry is the else. Each entry's id comes from its
35178
+ position (<block id>-if, <block id>-else-if-0, …, <block id>-else): an id you pass is replaced.
35179
+ inputFormat (Start): [{"name":"email","type":"string"}]; types string, number, boolean,
35180
+ object, array, file[]; an optional default "value" as text.
35181
+ Block settings, beside inputs in an add's or edit's params:
35182
+ "retry":{"enabled":true,"maxTries":3,"waitBetweenTriesMs":1000} retries a failed block; null
35183
+ clears it. An api block's retries input repeats the request after a timeout, reset, 429 or
35184
+ 5xx, not when the host does not resolve or refuses the connection; "retry" covers that.
35185
+ Outputs:
35186
+ A block that fails outputs {"error":"<message>"}: connect its error handle and read
35187
+ <name.error> there (without one, the run fails). A Workflow block's result is the child's
35188
+ output; a child ending in a Response block gives {data, status, headers}, so read
35189
+ <call.result.data.x>.`;
35190
+ var BLOCK_DETAIL_GUIDE = `
35191
+ Reading it for \`sim workflows operations apply\`:
35192
+ id the type to add: \`blocks get table\` answers table_v2 (an add of legacy
35193
+ table is refused)
35194
+ inputSchema the field ids inputs takes; operationInputSchema, an operation's own
35195
+ inputDefinitions the block's inputs by name; one a pair of fields shares (tableId for
35196
+ tableSelector and manualTableId) is accepted in place of the pair
35197
+ outputs what it outputs on success; a failed block outputs {"error":"…"}
35198
+ instead, read on its error path as <name.error>
35199
+ Block settings such as retry are not fields: \`sim workflows operations apply --help\`.`;
35171
35200
  var WORKFLOW_SET_BLOCK_ENABLED_HELP = 'Blocks to enable or disable, applied after --operations: [{"block_id":"<uuid>","enabled":false}]. Disabling a loop or parallel cascades to its unlocked descendants; enabling a block whose container is disabled is declined';
35172
35201
  var WORKFLOW_VARIABLE_OPERATIONS_HELP = 'Variable changes to apply in order, keyed by operation: [{"operation":"add","name":"my_var","type":"string","value":"hello"},{"operation":"edit","name":"my_var","value":"updated"},{"operation":"delete","name":"my_var"}]';
35173
35202
  var MCP_PARAMETER_DESCRIPTIONS_HELP = 'Per-field description overrides applied to the schema generated from the deployed workflow inputs, as [{"name":"email","description":"Customer email address"}]. A name matching no input field is ignored';
@@ -35614,6 +35643,7 @@ var CLI_CONTRACT = {
35614
35643
  command: "workflows state replace",
35615
35644
  confirm: "This replaces the entire draft graph and cannot be undone."
35616
35645
  },
35646
+ getBlock: { helpText: BLOCK_DETAIL_GUIDE },
35617
35647
  applyWorkflowOperations: {
35618
35648
  command: "workflows operations apply",
35619
35649
  describe: "Edit a workflow’s blocks, connections and settings with a batch of operations",
@@ -35834,6 +35864,9 @@ var CLI_CONTRACT = {
35834
35864
  flags: { folderPath: FOLDER_PATH_FLAG }
35835
35865
  },
35836
35866
  createWorkflow: {
35867
+ helpText: `
35868
+ The new workflow's draft holds one Start block (start_trigger, named Start): connect the
35869
+ blocks you add from it.`,
35837
35870
  flags: {
35838
35871
  folderPath: {
35839
35872
  ...FOLDER_PATH_FLAG,
@@ -36956,6 +36989,10 @@ var CLI_CONTRACT = {
36956
36989
  },
36957
36990
  exportWorkflow: {
36958
36991
  describe: "Print a workflow as a portable JSON document",
36992
+ helpText: `
36993
+ Workspace bindings (a table, a child workflow, a knowledge base) print as null unless
36994
+ --include-workspace-bindings, and credentials always do: to read what a block is set to, use
36995
+ \`sim workflows state get\`.`,
36959
36996
  flags: {
36960
36997
  includeReferences: {
36961
36998
  boolean: true,
@@ -37962,7 +37999,7 @@ async function coerce(raw, field, flag, flagName) {
37962
37999
  return encodeFolderPath(raw);
37963
38000
  return raw;
37964
38001
  }
37965
- var NO_WORKSPACE_FALLBACK = "No workspace set. Pass --workspace, or run: sim configure --set-workspace <id>";
38002
+ var NO_WORKSPACE_FALLBACK = "No workspace set. Pass -w <workspaceId>, set SIM_WORKSPACE, or run: sim configure --set-workspace <id>";
37966
38003
  function asQueryValue(value) {
37967
38004
  if (value === null || value === undefined)
37968
38005
  return;
@@ -38457,6 +38494,14 @@ function foldOtherSpellings(operation, commandSpec, flags) {
38457
38494
  }
38458
38495
  }
38459
38496
  }
38497
+ function withSearchedWorkspace(error, profile) {
38498
+ if (!(error instanceof SimApiError) || error.status !== 404 || !profile.workspaceId)
38499
+ return error;
38500
+ const source = profile.sources.workspaceId;
38501
+ const from = source === "env" ? ", from SIM_WORKSPACE; pass -w <workspaceId> to search another" : source === "config" ? `, the workspace of profile "${safeOneLine(profile.name)}"; pass -w <workspaceId> or set SIM_WORKSPACE to search another` : "";
38502
+ const searched = `searched workspace ${safeOneLine(profile.workspaceId)}${from}`;
38503
+ return new SimApiError(`${error.message} (${searched})`, error.status, error.code, error.details, error.exitCode, error.requestId);
38504
+ }
38460
38505
  async function executeOperation(operation, commandSpec, operationSpec, invocation) {
38461
38506
  const host = invocation[invocation.length - 1];
38462
38507
  const inheritedFlags = host.optsWithGlobals();
@@ -38540,6 +38585,8 @@ async function executeOperation(operation, commandSpec, operationSpec, invocatio
38540
38585
  if (cursor && rows.length < limit)
38541
38586
  progress.advance(rows.length);
38542
38587
  } while (cursor && rows.length < limit);
38588
+ } catch (error) {
38589
+ throw needsWorkspace ? withSearchedWorkspace(error, profile) : error;
38543
38590
  } finally {
38544
38591
  progress.finish();
38545
38592
  }
@@ -38565,7 +38612,7 @@ async function executeOperation(operation, commandSpec, operationSpec, invocatio
38565
38612
  reconciliation: "Find the operation using this requestId, or retry identical inputs with the same requestId."
38566
38613
  }, failure.exitCode, failure.requestId);
38567
38614
  }
38568
- throw error;
38615
+ throw needsWorkspace ? withSearchedWorkspace(error, profile) : error;
38569
38616
  }
38570
38617
  let payload = result?.data ?? result;
38571
38618
  if (commandSpec.workspaceOperation && (Boolean(request.body?.requestId) || requestFlags.wait === true || payload && typeof payload === "object" && ("operationId" in payload))) {
@@ -40702,15 +40749,20 @@ export default workflow('Cookbook', { description: 'One example of each common b
40702
40749
  code: js\`return { id: \${start.orderId}, cents: Math.round(\${start.amount} * 100) }\`,
40703
40750
  })
40704
40751
 
40705
- // Tables: query rows (each row is { id, data: { column } }) and insert a row.
40752
+ // Tables: query rows (each row is { id, data: { column } }) and write one.
40706
40753
  const recent = table.queryRows('Recent Orders', {
40707
40754
  tableId: table('orders'),
40708
40755
  filterInput: { all: [{ field: 'status', op: 'eq', value: 'open' }] },
40709
40756
  limit: 50,
40710
40757
  })
40711
- const save = table.insertRow('Save Order', {
40758
+ // Upsert: updates the row whose conflictColumn (a unique column, by name) matches data, else
40759
+ // inserts one, so a second run for the same order updates it. table.insertRow takes the same
40760
+ // data without conflictColumn and adds a row every run. data is keyed by column name: a column
40761
+ // declared as \`phone: column.string({ name: 'mobile' })\` is written as { mobile: ... }.
40762
+ const save = table.upsertRow('Save Order', {
40712
40763
  tableId: table('orders'),
40713
- data: { orderId: start.orderId, status: 'open', risk: check.risk },
40764
+ data: { orderId: start.orderId, status: 'open' },
40765
+ conflictColumn: 'orderId',
40714
40766
  })
40715
40767
 
40716
40768
  // Knowledge base search: results is the list of matching chunks.
@@ -40765,8 +40817,12 @@ export default workflow('Cookbook', { description: 'One example of each common b
40765
40817
  })
40766
40818
 
40767
40819
  // Response: the API reply body. Wrap an untyped value (fn.result.x) in t\`\` when it is text.
40820
+ // body is the short form of the editor's JSON mode: { dataMode: 'json', data } as below.
40768
40821
  const reply = response('Respond', { body: { risk: check.risk, id: t\`\${shape.result.id}\` } })
40769
- const rejected = response('Respond Rejected', { body: { status: 'rejected' } })
40822
+ const rejected = response('Respond Rejected', {
40823
+ dataMode: 'json',
40824
+ data: { status: 'rejected' },
40825
+ })
40770
40826
 
40771
40827
  // Wiring: a.to(b) chains; a block can fan out to several targets.
40772
40828
  start.to(check)
@@ -40877,7 +40933,7 @@ export default workflow(
40877
40933
  )
40878
40934
  ` };
40879
40935
  // ../workflow-sdk/src/codegen/core-text.generated.ts
40880
- var CORE_DTS = "/**\n * The authoring surface for Sim workflows written as TypeScript.\n *\n * Nothing declared here runs. `@sim/workflow-code` compiles a workflow file statically, and every\n * runtime export of this package throws `SimSdkNotExecutable`. These declarations exist so an\n * editor, `tsc` (the type-check command `sim` prints) or an agent can check a workflow file before\n * the compiler sees it.\n *\n * Block builders (`slack.sendMessage`, `agent`, `trigger.gmail.poller`, ...) are not declared here:\n * they are generated from the block catalog into `blocks/{type}.d.ts`, which augment this module.\n * The generic `block(type, name, params)` covers any stored type without a builder.\n *\n * Every workflow file starts with the SDK header line, before any import:\n *\n * ```ts\n * // @sim-sdk 1\n * import { agent, trigger, workflow } from '@sim/workflow-sdk'\n * ```\n *\n * The number is the SDK major version the file is written against. A file without the header is\n * refused with `E_SDK_HEADER`, and one written for a newer major than the server supports with\n * `E_SDK_MAJOR`.\n */\n\n/** Plain JSON. */\nexport type Json = null | boolean | number | string | Json[] | { [key: string]: Json }\n\ndeclare const REF: unique symbol\ndeclare const TEMPLATE: unique symbol\ndeclare const ENV: unique symbol\ndeclare const RESOURCE: unique symbol\ndeclare const TOOL: unique symbol\ndeclare const NODE: unique symbol\ndeclare const CODE_FILE: unique symbol\ndeclare const RAW: unique symbol\ndeclare const UNTYPED: unique symbol\n\n/** Any reference, whatever it points at. */\nexport interface AnyRef {\n readonly [REF]: unknown\n}\n\n/** Marks a reference into untyped JSON, which any param accepts: its value is known only at run time. */\ninterface Untyped {\n readonly [UNTYPED]: true\n}\n\n/**\n * A reference into untyped JSON, where any path is allowed at any depth. An interface rather than\n * `Ref<Json>`, which TypeScript stops resolving after one step (`a.b.c` failed at `c`).\n */\ninterface UntypedRef extends Untyped {\n readonly [REF]: Json\n readonly [key: string]: UntypedRef\n}\n\ntype RefPaths<T> = [Json] extends [T]\n ? Untyped & { readonly [key: string]: UntypedRef }\n : T extends readonly (infer E)[]\n ? { readonly [index: number]: Ref<E>; readonly length: Ref<number> }\n : T extends object\n ? { readonly [K in keyof T]-?: Ref<T[K]> }\n : unknown\n\n/**\n * A typed reference to a block output, compiled to `<blockkey.path>`.\n * Paths map exactly: `.seg`, `['seg']` and `[n]`. Untyped JSON allows any path.\n */\nexport type Ref<T> = { readonly [REF]: T } & RefPaths<T>\n\n/** Text with references in it, written with one of the tags below. */\nexport type Template = string & { readonly [TEMPLATE]: true }\n\n/** A workspace environment variable, compiled to `{{NAME}}`. */\nexport interface EnvRef {\n readonly [ENV]: string\n}\n\n/**\n * What a reference must hold to fill a param of type `T`. A param taking some strings takes any\n * string (an option id computed at run time); `null` (an output a step left empty) fits anywhere.\n */\ntype RefValue<T> = [Extract<T, string>] extends [never] ? T | null : T | string | null\n\n/**\n * A reference that fits a param of type `T`: one whose value has that type, or one into untyped\n * JSON. A whole block is not a value: reference one of its outputs.\n */\nexport type RefTo<T> = ({ readonly [REF]: RefValue<T> } | (AnyRef & Untyped)) & {\n readonly [NODE]?: never\n}\n\n/** A param value: a literal, a reference of a fitting type, a template or an environment variable. */\nexport type Value<T> = T | RefTo<T> | Template | EnvRef\n\n/** JSON whose leaves may be references, templates or environment variables. */\nexport type JsonWithRefs =\n | null\n | boolean\n | number\n | string\n | AnyRef\n | Template\n | EnvRef\n | JsonWithRefs[]\n | { [key: string]: JsonWithRefs }\n\n/** A literal union that still accepts any other string (option ids read from values). */\nexport type LiteralUnion<T extends string> = T | (string & {})\n\n/** A `time-input` value, `HH:MM`. */\nexport type TimeString = `${number}:${number}`\n\n/** A reference written into text: any output or variable, but not a whole block. */\ntype InterpolatedRef = AnyRef & { readonly [NODE]?: never }\n\ntype Interpolation = InterpolatedRef | EnvRef | VarRef | string | number | boolean\n\n/** Text with interpolated references: `` t`New ${cls.category} ticket` ``. */\nexport declare function t(strings: TemplateStringsArray, ...values: Interpolation[]): Template\n/** JavaScript code (condition expressions, inline function code). */\nexport declare const js: typeof t\n/** Python code. */\nexport declare const py: typeof t\n/** Shell code. */\nexport declare const sh: typeof t\n/**\n * JSON text kept verbatim, for bodies an object literal cannot reproduce byte for byte. In a JSON\n * field an object literal is the usual form: a bare reference keeps its value's type (`n: score.value`\n * is a number), and a template is text.\n */\nexport declare const json: typeof t\n/** Markdown text (note content). */\nexport declare const md: typeof t\n\n/** A reference with a non-canonical spelling, such as `ref('Classify.content')`. */\nexport declare function ref(path: string): Ref<Json>\n\n/** A stored value outside the generated type (a legacy option id, say), kept verbatim. */\nexport declare function raw<T = never>(value: unknown): T & { readonly [RAW]: true }\n\n/** A required value that is still missing; compiles to absent, so canvas drafts type-check. */\nexport declare function todo(): never\n\n/**\n * Keeps the value the stored workflow holds for this param, without showing it: the printer writes\n * it for a secret pasted into a password field. Valid only on a param of a block the stored\n * workflow already has (same name and type) and holds a value for; anything else is\n * `E_STORED_VALUE_MISSING`.\n */\nexport declare function stored(): never\n\n/** Function code kept in a file next to the workflow (`.js`, `.py` or `.sh`), stored verbatim. */\nexport interface CodeFileRef {\n readonly [CODE_FILE]: string\n}\nexport declare function codeFile(path: `./${string}`): CodeFileRef\n\n/**\n * Environment variable names known to the workspace. `workspace.d.ts` adds one member per name;\n * until it exists `env` accepts any name.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceEnv {}\n\nexport declare const env: keyof WorkspaceEnv extends never\n ? { readonly [name: string]: EnvRef }\n : { readonly [K in keyof WorkspaceEnv]: EnvRef }\n\n/**\n * Workspace resources by stable key, filled in by the generated `workspace.d.ts`. Each map's\n * values describe the resource: a table's row type, a credential's provider, a workflow's inputs.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceTables {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceKnowledgeBases {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCredentials {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceWorkflows {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceSkills {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCustomTools {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceMcpServers {}\n\ntype KeyOf<M> = keyof M extends never ? string : Extract<keyof M, string>\n\nexport type TableKey = KeyOf<WorkspaceTables>\nexport type KnowledgeBaseKey = KeyOf<WorkspaceKnowledgeBases>\nexport type CredentialKey = KeyOf<WorkspaceCredentials>\nexport type WorkflowKey = KeyOf<WorkspaceWorkflows>\nexport type SkillKey = KeyOf<WorkspaceSkills>\nexport type CustomToolKey = KeyOf<WorkspaceCustomTools>\nexport type McpServerKey = KeyOf<WorkspaceMcpServers>\n/**\n * The tool names of MCP server `K`, as `workspace.d.ts` records them from the server's last\n * listing; any name for a server it could not list or does not know.\n */\nexport type McpToolName<K extends string> = K extends keyof WorkspaceMcpServers\n ? WorkspaceMcpServers[K] extends { tools: infer T extends string }\n ? T\n : string\n : string\n\n/** A workspace resource by stable key, compiled to the resource's internal id. */\nexport interface ResourceRef<Kind extends string, Key extends string = string> {\n readonly [RESOURCE]: Kind\n readonly key: Key\n}\n\n/** A saved credential: `credential('support-slack')`. */\nexport type CredentialRef<Key extends string = string> = ResourceRef<'credential', Key>\n\n/**\n * Keys of the saved credentials for one of `Providers`, as `workspace.d.ts` records each\n * credential's provider; any key until it exists.\n */\nexport type CredentialKeyFor<Providers extends string> = keyof WorkspaceCredentials extends never\n ? string\n : {\n [K in Extract<keyof WorkspaceCredentials, string>]: WorkspaceCredentials[K] extends {\n provider: Providers\n }\n ? K\n : never\n }[Extract<keyof WorkspaceCredentials, string>]\nexport declare function credential<K extends CredentialKey>(key: K): CredentialRef<K>\n\n/**\n * The other form a credential field takes beside `credential('key')`: a credential id produced at\n * run time by a reference, a template or an environment variable, stored in the field's advanced\n * twin (`manualCredential`). Literal text is not one, so a pasted token never type-checks; a\n * literal id the stored workflow already holds prints as `raw('…')`.\n */\nexport type CredentialIdValue = RefTo<string> | Template | EnvRef\n\n/** The columns of a workspace table, or loose JSON when `workspace.d.ts` does not know it. */\nexport type TableColumns<K extends string> = K extends keyof WorkspaceTables\n ? WorkspaceTables[K]\n : { [column: string]: Json }\n/**\n * One row as the table blocks output it: the row id, and its cells keyed by column name under\n * `data` (`row.data.status`). Times are ISO strings.\n */\nexport interface TableRow<K extends string> {\n id: string\n data: TableColumns<K>\n position: number\n createdAt: string\n updatedAt: string\n}\n/**\n * A value written to a field of type `T` (a table cell, a child workflow input): a JSON or JSON\n * array field takes JSON with references in it, and `null` leaves the field empty.\n */\ntype FieldValue<T> = [Json] extends [T]\n ? JsonWithRefs\n : [Json[]] extends [T]\n ? JsonWithRefs\n : Value<T> | null\n\n/** The columns of table `K` every row must hold: those whose cell type does not admit `null`. */\ntype RequiredColumns<K extends keyof WorkspaceTables> = {\n [C in keyof WorkspaceTables[K]]-?: null extends WorkspaceTables[K][C] ? never : C\n}[keyof WorkspaceTables[K]]\n\n/**\n * A whole row, as an insert, an upsert or a batch insert writes it, each value checked against\n * its column's type. A required column must be present and not `null`: the table refuses a row\n * without it (`Missing required field`), and an upsert checks the whole row before it looks for a\n * match.\n */\nexport type TableData<K extends string> = K extends keyof WorkspaceTables\n ? { [C in RequiredColumns<K>]-?: Exclude<FieldValue<WorkspaceTables[K][C]>, null> } & {\n [C in Exclude<keyof WorkspaceTables[K], RequiredColumns<K>>]?: FieldValue<\n WorkspaceTables[K][C]\n >\n }\n : { [column: string]: JsonWithRefs }\n\n/**\n * The cells an update writes, each checked against its column's type. Every column is optional:\n * an update merges these cells over the stored row.\n */\nexport type TableDataPatch<K extends string> = K extends keyof WorkspaceTables\n ? { [C in keyof WorkspaceTables[K]]?: FieldValue<WorkspaceTables[K][C]> }\n : { [column: string]: JsonWithRefs }\n\n/** A workspace table: `table('leads')`. Table block operations live on `table.*`. */\nexport type TableRef<Key extends string = string> = ResourceRef<'table', Key>\nexport declare function table<K extends TableKey>(key: K): TableRef<K>\n\n/** A knowledge base: `knowledgeBase('docs')`. */\nexport type KnowledgeBaseRef<Key extends string = string> = ResourceRef<'knowledge-base', Key>\nexport declare function knowledgeBase<K extends KnowledgeBaseKey>(key: K): KnowledgeBaseRef<K>\n\n/** A workspace skill: `skill('triage')`. */\nexport type SkillRef<Key extends string = string> = ResourceRef<'skill', Key>\nexport declare function skill<K extends SkillKey>(key: K): SkillRef<K>\n\n/** A workspace folder: `folder('reports')`. */\nexport type FolderRef = ResourceRef<'file-folder'>\nexport declare function folder(key: string): FolderRef\n\n/** A workspace file: `file('contracts/acme.pdf')`. File block operations live on `file.*`. */\nexport type FileRef = ResourceRef<'file'>\nexport declare function file(path: string): FileRef\n\n/**\n * A file a file-upload field holds, as the editor stores it: one uploaded in place, or a workspace\n * file chosen by `key` (written `file('path')` when the workspace resolves it).\n */\nexport interface UploadedFile {\n name: string\n path: string\n size?: number\n type?: string\n key?: string | FileRef\n id?: string\n folderPath?: string\n}\n\n/** A file produced at run time (`file` / `file[]` outputs). */\nexport interface SimFile {\n id: string\n name: string\n url: string\n size: number\n type: string\n key: string\n}\n\n// Agent tools\n\n/** One entry of an agent's `tools` list. */\nexport interface Tool {\n readonly [TOOL]: true\n}\n\n/** How the model may use a tool, and the stored tool fields a print carries. */\nexport interface ToolOpts {\n usageControl?: 'auto' | 'force' | 'none'\n usageControlExpression?: string\n title?: string\n /** The stored operation, when the method does not pin it. */\n operation?: string\n toolId?: string\n /** Pair modes of the tool's params, which pick the member the agent reads. */\n modes?: Record<string, 'basic' | 'advanced'>\n customTool?: JsonWithRefs\n operationPolicy?: Json\n /** Unknown stored tool keys, kept verbatim. */\n extra?: Json\n}\n\n/**\n * A workspace custom tool by key, as an agent tool: `customTool('lookup-order')`. A stored tool\n * whose definition was copied into the workflow (and may have drifted from the workspace tool)\n * prints as `raw(tool)` instead.\n */\nexport declare function customTool<K extends CustomToolKey>(key: K, options?: ToolUsage): Tool\n\n/** How the model may use a tool the SDK writes by name (`customTool`, `mcp().tool`, `asTool`). */\nexport type ToolUsage = Pick<ToolOpts, 'usageControl' | 'usageControlExpression'>\n\n/** An MCP tool's arguments and the editor's snapshot of its server. */\nexport interface McpToolOpts extends ToolUsage {\n /** Argument values the workflow fixes; the model fills in the rest. */\n args?: Record<string, JsonWithRefs>\n /**\n * What the editor saved about the server and the tool's input schema when the tool was picked.\n * Shown in the editor; never run.\n */\n snapshot?: { serverName?: string; serverUrl?: string; schema?: Json }\n}\n\n/** An MCP server by key: `mcp('linear')`. */\nexport interface McpServerRef<Key extends string = string> extends ResourceRef<'mcp-server', Key> {\n /** One of the server's tools, as an agent tool: `mcp('linear').tool('create_issue')`. */\n tool(name: McpToolName<Key>, options?: McpToolOpts): Tool\n}\nexport declare function mcp<K extends McpServerKey>(key: K): McpServerRef<K>\n\n// Graph\n\n/** Block-level fields (`BlockState`), written as the third builder argument. */\nexport interface BlockMeta {\n /**\n * A legacy key the display name cannot carry (a `name~n` collision key or a reserved name such\n * as `Loop`). Printed only for such a stored block; apply accepts it only for a key the stored\n * workflow already has, so it can never introduce one.\n */\n key?: string\n /** Stored as `enabled: false`. */\n disabled?: true\n /** Locked: apply refuses any change to this block. */\n locked?: true\n /** Exposes the error port without an `onError` edge. */\n errorPort?: boolean\n /** The block-level advanced toggle (`advancedMode`). */\n advancedMode?: boolean\n /**\n * Runs the block as its trigger (`triggerMode`). Trigger builders (`trigger.gmail.poller`) set\n * it themselves; write it on any other builder only for a block stored in trigger mode.\n */\n triggerMode?: boolean\n /** The stored retry policy, written whole. */\n retry?: BlockRetryConfig\n /**\n * Per branch key of a condition or router, the row's display `title` and any stored fields the\n * SDK has no syntax for (`extra`, plain JSON). `title: null` keeps a row stored with no title,\n * which the executor never takes for `else`.\n */\n branches?: Record<string, { title?: string | null; extra?: Record<string, Json> }>\n /**\n * Stored params that run but have no SDK syntax: a schema-agnostic custom block's inputs, the\n * agent's legacy prompt fields, a container's stored params. Values the block keeps but never\n * runs are not written; apply keeps them from the stored workflow.\n */\n extra?: Record<string, unknown>\n /**\n * A loop or parallel's `block.data` subflow keys the loader could not read as config, kept\n * verbatim (plain JSON).\n */\n subflowData?: Record<string, Json>\n}\n\n/** A block's retry policy, field for field the stored `BlockRetryConfig`. */\nexport interface BlockRetryConfig {\n /** Absent config and `false` mean the same thing: the block runs once. */\n enabled: boolean\n /** Total tries including the first. */\n maxTries: number\n /** Delay between tries. */\n waitBetweenTriesMs: number\n}\n\n/** Anything an edge can point at. */\nexport type Target = Node | Group\n\n/** A block or container in the graph. */\nexport interface Node {\n readonly [NODE]: true\n /** Wires this node's default port to each target. Returns the target, or a group of them. */\n to<const T extends Target[]>(...targets: T): T extends [infer One] ? One : Group\n /** Wires this node's error port to each target. */\n onError(...targets: Target[]): void\n}\n\n/** Several nodes; `.to()` wires every member (fan-in). */\nexport interface Group {\n to(...targets: Target[]): Group\n}\n\n/**\n * The failure message a block outputs when an error edge leaves it (`x.onError(y)` runs `y` with\n * `x.error`); a check refuses `x.error` on a block without one, which fails the run instead.\n */\ntype ErrorOutput<O> = [O] extends [{ error: unknown }] ? unknown : { readonly error: Ref<string> }\n\n/** A block: a node whose outputs can be referenced, and `error` after an `onError` edge. */\nexport type Block<O> = Node & Ref<O> & ErrorOutput<O>\n\n/** The named ports of a condition or router. */\nexport type Branches<K extends string> = { readonly [P in K]: Node }\n\n/** Trigger builders (`trigger.start`, `trigger.gmail.poller`, ...), generated from the catalog. */\nexport declare namespace trigger {}\n\n/** Builders for hidden legacy block versions (`legacy.slack.send`), generated from the catalog. */\nexport declare namespace legacy {}\n\n/** A raw edge from a handle the SDK has no name for (a legacy or unknown port). */\nexport declare function edge(from: Node, handle: string, to: Target): void\n\n/** Any stored block type without a builder (legacy, unknown or custom), with untyped outputs. */\nexport declare function block(\n type: string,\n name: string,\n params: Record<string, unknown>,\n meta?: BlockMeta\n): Block<Json>\n\n// Workflow and variables\n\nexport type VariableType = 'string' | 'number' | 'boolean' | 'object' | 'array' | 'plain'\n\n/** A workflow variable declared in `workflow(name, { variables })`: its type and initial value. */\nexport interface VariableDeclaration {\n /**\n * The display name, written only when it differs from the key. It must normalize to the key\n * (lowercased, spaces and dots removed), as `'Total Count'` does to `totalcount`.\n */\n name?: string\n type: VariableType\n value: Json\n}\n\n/** The variables a workflow declares, by name. */\nexport type VariableDeclarations = Record<string, VariableDeclaration>\n\ndeclare const VAR: unique symbol\n\n/** A workflow variable, compiled to `<variable.name>`. */\nexport interface VarRef {\n readonly [VAR]: string\n}\n\ntype VariableValue<T extends VariableType> = T extends 'number'\n ? number\n : T extends 'boolean'\n ? boolean\n : T extends 'string' | 'plain'\n ? string\n : Json\n\n/** `vars` in the workflow body: one typed reference per declared variable. */\nexport type VarRefs<V extends VariableDeclarations> = {\n readonly [K in keyof V]: VarRef & Ref<VariableValue<V[K]['type']>>\n}\n\n/**\n * Workflow variables by name, untyped. Prefer the `vars` the `workflow()` body receives, which is\n * typed from the declared variables.\n */\nexport declare const vars: { readonly [name: string]: VarRef & Ref<Json> }\n\ndeclare const WORKFLOW_DEF: unique symbol\n\n/** The default export of a workflow file. */\nexport interface WorkflowDef {\n readonly [WORKFLOW_DEF]: true\n}\n\n/** A child workflow by key, for `runWorkflow` or as an agent tool. */\nexport interface WorkflowRef<Key extends string = string> extends ResourceRef<'workflow', Key> {\n /**\n * The workflow as an agent tool, as the editor's tool picker adds it:\n * `childWorkflow('enrich-lead').asTool()`. A tool with fixed inputs is written `raw(tool)`.\n */\n asTool(options?: ToolUsage): Tool\n}\n\n/**\n * Declares a workflow. The body wires blocks; it never runs. With no description or variables the\n * options may be left out: `workflow('Name', () => { ... })`.\n */\nexport declare function workflow<const V extends VariableDeclarations = Record<never, never>>(\n name: string,\n options: { description?: string; variables?: V },\n body: (scope: { vars: VarRefs<V> }) => void\n): WorkflowDef\nexport declare function workflow(\n name: string,\n body: (scope: { vars: VarRefs<Record<never, never>> }) => void\n): WorkflowDef\n/** A child workflow by key: `childWorkflow('enrich-lead')`. */\nexport declare function childWorkflow<K extends WorkflowKey>(key: K): WorkflowRef<K>\n\n// Containers\n\ntype ItemOf<C> = C extends { readonly [REF]: readonly (infer E)[] }\n ? E\n : C extends readonly (infer E)[]\n ? E\n : Json\n\n/** Inside a loop or parallel body. As a node it is the container's start port: `p.to(first)`. */\nexport interface SubflowScope<Item> extends Node {\n readonly index: Ref<number>\n readonly currentItem: Ref<Item>\n readonly items: Ref<Item[]>\n}\n\n/**\n * A container's outputs, plus its iteration fields by name (`outer.index`), which a block inside\n * the container reads (in a nested container too: an outer loop's index or item). Outside the\n * container only `results` resolves: check reports `W_REF_OUT_OF_SCOPE` on `outer.index` there.\n */\nexport interface SubflowOutput {\n results: Json[]\n index: number\n currentItem: Json\n items: Json[]\n}\n\n/** A loop or parallel container. Its `.to()` wires the port taken after it finishes. */\nexport type Container = Block<SubflowOutput>\n\ntype Collection = AnyRef | Template | Json[] | string\n\nexport declare const loop: {\n for(\n name: string,\n params: { count?: number },\n body: (scope: SubflowScope<never>) => void,\n meta?: BlockMeta\n ): Container\n forEach<const C extends Collection>(\n name: string,\n params: { collection: C },\n body: (scope: SubflowScope<ItemOf<C>>) => void,\n meta?: BlockMeta\n ): Container\n while(\n name: string,\n params: { condition: Template | string },\n body: (scope: SubflowScope<never>) => void,\n meta?: BlockMeta\n ): Container\n doWhile(\n name: string,\n params: { condition?: Template | string; count?: number },\n body: (scope: SubflowScope<never>) => void,\n meta?: BlockMeta\n ): Container\n}\n\nexport declare const parallel: {\n /** A parallel with no stored type, which the loader runs as `count`. */\n (\n name: string,\n params: { count?: number; collection?: Collection; batchSize?: number },\n body: (scope: SubflowScope<Json>) => void,\n meta?: BlockMeta\n ): Container\n count(\n name: string,\n params: { count: number; batchSize?: number },\n body: (scope: SubflowScope<never>) => void,\n meta?: BlockMeta\n ): Container\n collection<const C extends Collection>(\n name: string,\n params: { collection: C; batchSize?: number },\n body: (scope: SubflowScope<ItemOf<C>>) => void,\n meta?: BlockMeta\n ): Container\n}\n\n// Blocks with a source form of their own\n\n/**\n * Params and outputs of the blocks below, generated from the catalog. Each entry is\n * `{ params; output }`; without generated types the params are loose.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface SpecialBuilderTypes {}\n\ntype SpecialParams<K extends string> = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { params: infer P }\n ? P\n : never\n : Record<string, unknown>\n\ntype SpecialOutput<K extends string> = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { output: infer O }\n ? O\n : never\n : Json\n\n/** A condition expression, or `true` for the `else` branch. */\nexport type BranchExpression = Template | string | true\n\ndeclare const ONLY_ELSE: unique symbol\n\n/** What a branch other than `else` written as `true` must be, which no value is: the error names it. */\ninterface OnlyElseMayBeTrue {\n readonly [ONLY_ELSE]: true\n}\n\n/**\n * A condition's branches: every key holds an expression, and only `else` may be `true`. Another\n * branch written as `true` is checked against {@link OnlyElseMayBeTrue}, so the error names that\n * branch alone.\n */\ntype ConditionBranches<B> = {\n [K in keyof B]: K extends 'else'\n ? BranchExpression\n : B[K] extends true\n ? OnlyElseMayBeTrue\n : Template | string\n}\n\n/**\n * Keys of a condition written with no rows (`condition('Name', {})`, the source form of rows\n * that were never persisted): the implicit `if` and `else` ports stay addressable.\n */\ntype ConditionKeys<B> = keyof B extends never ? 'if' | 'else' : Extract<keyof B, string>\ntype RouterKeys<R> = keyof R extends never ? 'route0' : Extract<keyof R, string>\n\n/** A condition: named branches, the last one `else` when there are two or more. */\nexport declare function condition<const B extends Record<string, BranchExpression>>(\n name: string,\n branches: B & ConditionBranches<B>,\n meta?: BlockMeta\n): Block<SpecialOutput<'condition'>> & Branches<ConditionKeys<B>>\n\n/** A router: named routes described for the model. */\nexport declare function router<const R extends Record<string, string | Template>>(\n name: string,\n params: SpecialParams<'router'> & { routes: R },\n meta?: BlockMeta\n): Block<SpecialOutput<'router'>> & Branches<RouterKeys<R>>\n\n/** A function block. `code` is inline (`` js`...` ``) or a code file (`codeFile('./functions/x.js')`). */\nexport declare function fn(\n name: string,\n params: SpecialParams<'fn'> & { code: Template | CodeFileRef | string },\n meta?: BlockMeta\n): Block<SpecialOutput<'fn'>>\n\n/**\n * The inputs of a child workflow by key, each checked against the input its start block\n * declares when `workspace.d.ts` knows the workflow; loose JSON otherwise.\n */\nexport type WorkflowInputMapping<K extends string> = K extends keyof WorkspaceWorkflows\n ? WorkspaceWorkflows[K] extends { inputs: infer I }\n ? { [N in keyof I]?: FieldValue<I[N]> }\n : InputMapping\n : InputMapping\n\n/**\n * Runs a child workflow. A `childWorkflow('key')` checks `inputMapping` against its inputs. Its\n * `result` is the child's output: its first response block's `{ data, status, headers }` (a body\n * field is `result.data.field`), else the output of the last block it ran.\n */\nexport declare function runWorkflow<K extends string = string>(\n name: string,\n params: Omit<SpecialParams<'runWorkflow'>, 'workflowId' | 'inputMapping'> & {\n workflowId: WorkflowRef<K> | Exclude<SpecialParams<'runWorkflow'>['workflowId'], WorkflowRef>\n inputMapping?: WorkflowInputMapping<K>\n },\n meta?: BlockMeta\n): Block<SpecialOutput<'runWorkflow'>>\n\n/**\n * Pauses for a person; the form in `inputFormat` types `submission`. A resumed block also holds\n * each form field at its top level (the runtime copies the submission up, over any output of the\n * same name), so `approval.approved` and `approval.submission.approved` both read it.\n */\nexport declare function human<const F extends InputFields = Record<never, never>>(\n name: string,\n params: SpecialParams<'human'> & { inputFormat?: F },\n meta?: BlockMeta\n): Block<\n Omit<SpecialOutput<'human'>, 'submission' | keyof F> & {\n submission: InputFieldsOutput<F>\n } & InputFieldsOutput<F>\n>\n\n/**\n * A response's body, status and headers: the editor's JSON mode. An object or array `body` is\n * JSON whose references keep their types; a template or reference is the body text as written.\n */\nexport interface ResponseBody {\n body: JsonWithRefs\n /** HTTP status; 200 when omitted. A template or reference must produce a number. */\n status?: number | RefTo<number> | Template | EnvRef\n /** Response headers by name. */\n headers?: Record<string, Value<string>>\n}\n\n/**\n * Ends the workflow with an API response: `response('Reply', { body: { ok: true }, status: 201 })`,\n * or the block's own params (`dataMode`, `builderData`, ...) when the body is built field by field.\n */\nexport declare function response(\n name: string,\n params: ResponseBody,\n meta?: BlockMeta\n): Block<SpecialOutput<'response'>>\nexport declare function response(\n name: string,\n params: SpecialParams<'response'>,\n meta?: BlockMeta\n): Block<SpecialOutput<'response'>>\n\n/** Assigns workflow variables. */\nexport declare function setVariables(\n name: string,\n params: SpecialParams<'setVariables'>,\n meta?: BlockMeta\n): Block<SpecialOutput<'setVariables'>>\n\ndeclare const ANNOTATION: unique symbol\n\n/** A canvas note: no edges, no outputs. */\nexport interface Annotation {\n readonly [ANNOTATION]: true\n}\nexport declare function note(\n name: string,\n params: SpecialParams<'note'>,\n meta?: BlockMeta\n): Annotation\n\n// Structured param shapes\n\n/** Type names an input-format field may declare. */\nexport type InputFieldType = 'string' | 'number' | 'boolean' | 'object' | 'array' | 'file[]'\n\n/** A structured input field: its type plus a default value, description or required flag. */\nexport interface InputFieldSpec {\n type: InputFieldType\n value?: JsonWithRefs\n description?: string\n required?: boolean\n}\n\n/** `input-format` fields by name: `{ subject: 'string', amount: { type: 'number', value: 0 } }`. */\nexport type InputFields = Record<string, InputFieldType | InputFieldSpec>\n\ntype InputFieldValue<T> = T extends 'string'\n ? string\n : T extends 'number'\n ? number\n : T extends 'boolean'\n ? boolean\n : T extends 'array'\n ? Json[]\n : T extends 'file[]'\n ? SimFile[]\n : Json\n\n/** The outputs an `input-format` declares. */\nexport type InputFieldsOutput<F> = {\n [K in keyof F]: F[K] extends { type: infer T } ? InputFieldValue<T> : InputFieldValue<F[K]>\n}\n\n/**\n * One `response-format` field as the editor's builder stores it. An `object` or `array` field's\n * `value` may hold nested fields. A response is usually written with `body` instead.\n */\nexport interface ResponseField {\n id?: string\n name: string\n type: string\n value?: JsonWithRefs\n collapsed?: boolean\n}\n\n/** `response-format` fields: `[{ name: 'ok', type: 'boolean', value: true }]`. */\nexport type ResponseFields = ResponseField[]\n\n/** An agent message. */\nexport interface Message {\n role: 'system' | 'user' | 'assistant'\n content: Value<string>\n}\n\n/** One `variables-input` assignment, with any other stored keys kept. */\nexport interface VariableAssignment {\n variableId: VarRef\n value?: JsonWithRefs\n [key: string]: JsonWithRefs | VarRef | undefined\n}\n\n/** Child workflow inputs by name (`input-mapping`, `workflow-input-mapper`). */\nexport type InputMapping = Record<string, JsonWithRefs>\n\n/** An operator a table filter condition or builder rule can use. */\nexport type FilterOperator = LiteralUnion<\n | 'eq'\n | 'ne'\n | 'gt'\n | 'gte'\n | 'lt'\n | 'lte'\n | 'in'\n | 'nin'\n | 'like'\n | 'ilike'\n | 'nlike'\n | 'nilike'\n | 'contains'\n | 'ncontains'\n | 'startsWith'\n | 'endsWith'\n | 'isNull'\n | 'isNotNull'\n | 'isEmpty'\n | 'isNotEmpty'\n>\n\n/** One row of the editor's filter builder, as it stores it. */\nexport interface FilterRule {\n id?: string\n /** How this row joins the rows before it; `and` when omitted. */\n logicalOperator?: 'and' | 'or'\n column: string\n operator: FilterOperator\n value: Value<string | number | boolean>\n collapsed?: boolean\n}\n\n/** A filter-builder value: the editor's rows, `[{ column: 'status', operator: 'eq', value: 'new' }]`. */\nexport type Filter = FilterRule[]\n\n/** One table filter condition: `{ field: 'status', op: 'eq', value: 'new' }`. */\nexport interface TableCondition {\n field: string\n op: FilterOperator\n value?: JsonWithRefs\n}\n\n/**\n * A table predicate: a condition, or an `all` (and) / `any` (or) group of predicates. The\n * `{ status: { $eq: 'new' } }` operator-object grammar is not one: the runtime refuses it.\n */\nexport type TablePredicate = TableCondition | { all: TablePredicate[] } | { any: TablePredicate[] }\n\n/** A table sort by column: `{ createdAt: 'desc' }`. */\nexport type Sort =\n | Record<string, 'asc' | 'desc'>\n | Array<{ column: string; direction: 'asc' | 'desc' }>\n\n/** One knowledge tag filter. */\nexport interface TagFilter {\n tagName: string\n tagValue: Value<string>\n [key: string]: JsonWithRefs\n}\n\n/** One document tag. */\nexport interface DocumentTag {\n tagName: string\n value: Value<string>\n [key: string]: JsonWithRefs\n}\n\n/** One `eval-input` metric. */\nexport interface EvalMetric {\n name: string\n description?: string\n range?: { min: number; max: number }\n [key: string]: JsonWithRefs | undefined\n}\n\n/** One `model-fallback-list` entry. */\nexport interface ModelFallback {\n model: LiteralUnion<Model>\n [key: string]: JsonWithRefs\n}\n\n/**\n * Model ids, generated into `models.d.ts` (which adds one member per model). Kept apart from the\n * block files so a model-list change touches one file.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface ModelIds {}\nexport type Model = Extract<keyof ModelIds, string>\n\n/** A JSON Schema `responseFormat`, or `{ name, strict, schema }` around one. */\nexport type ResponseFormat = JsonWithRefs\n\ntype Depth = [never, 0, 1, 2, 3, 4]\n\ntype FromSchema<S, D extends number> = [D] extends [never]\n ? Json\n : S extends { enum: readonly (infer E)[] }\n ? E\n : S extends { type: 'object'; properties: infer P }\n ? { [K in keyof P]: FromSchema<P[K], Depth[D]> }\n : S extends { type: 'array'; items: infer I }\n ? FromSchema<I, Depth[D]>[]\n : S extends { type: 'string' }\n ? string\n : S extends { type: 'number' | 'integer' }\n ? number\n : S extends { type: 'boolean' }\n ? boolean\n : Json\n\n/**\n * The outputs a literal `responseFormat` adds, read from its JSON Schema with recursion capped at\n * depth 4. A template or reference adds untyped JSON.\n */\nexport type ResponseFormatOutput<RF> = [RF] extends [undefined]\n ? unknown\n : RF extends { schema: infer S }\n ? FromSchema<S, 4>\n : RF extends { type: 'object'; properties: object }\n ? FromSchema<RF, 4>\n : { [key: string]: Json }\n";
40936
+ var CORE_DTS = "/**\n * The authoring surface for Sim workflows written as TypeScript.\n *\n * Nothing declared here runs. `@sim/workflow-code` compiles a workflow file statically, and every\n * runtime export of this package throws `SimSdkNotExecutable`. These declarations exist so an\n * editor, `tsc` (the type-check command `sim` prints) or an agent can check a workflow file before\n * the compiler sees it.\n *\n * Block builders (`slack.sendMessage`, `agent`, `trigger.gmail.poller`, ...) are not declared here:\n * they are generated from the block catalog into `blocks/{type}.d.ts`, which augment this module.\n * The generic `block(type, name, params)` covers any stored type without a builder.\n *\n * Every workflow file starts with the SDK header line, before any import:\n *\n * ```ts\n * // @sim-sdk 1\n * import { agent, trigger, workflow } from '@sim/workflow-sdk'\n * ```\n *\n * The number is the SDK major version the file is written against. A file without the header is\n * refused with `E_SDK_HEADER`, and one written for a newer major than the server supports with\n * `E_SDK_MAJOR`.\n */\n\n/** Plain JSON. */\nexport type Json = null | boolean | number | string | Json[] | { [key: string]: Json }\n\ndeclare const REF: unique symbol\ndeclare const TEMPLATE: unique symbol\ndeclare const ENV: unique symbol\ndeclare const RESOURCE: unique symbol\ndeclare const TOOL: unique symbol\ndeclare const NODE: unique symbol\ndeclare const CODE_FILE: unique symbol\ndeclare const RAW: unique symbol\ndeclare const UNTYPED: unique symbol\n\n/** Any reference, whatever it points at. */\nexport interface AnyRef {\n readonly [REF]: unknown\n}\n\n/** Marks a reference into untyped JSON, which any param accepts: its value is known only at run time. */\ninterface Untyped {\n readonly [UNTYPED]: true\n}\n\n/**\n * A reference into untyped JSON, where any path is allowed at any depth. An interface rather than\n * `Ref<Json>`, which TypeScript stops resolving after one step (`a.b.c` failed at `c`).\n */\ninterface UntypedRef extends Untyped {\n readonly [REF]: Json\n readonly [key: string]: UntypedRef\n}\n\ntype RefPaths<T> = [Json] extends [T]\n ? Untyped & { readonly [key: string]: UntypedRef }\n : T extends readonly (infer E)[]\n ? { readonly [index: number]: Ref<E>; readonly length: Ref<number> }\n : T extends object\n ? { readonly [K in keyof T]-?: Ref<T[K]> }\n : unknown\n\n/**\n * A typed reference to a block output, compiled to `<blockkey.path>`.\n * Paths map exactly: `.seg`, `['seg']` and `[n]`. Untyped JSON allows any path.\n */\nexport type Ref<T> = { readonly [REF]: T } & RefPaths<T>\n\n/** Text with references in it, written with one of the tags below. */\nexport type Template = string & { readonly [TEMPLATE]: true }\n\n/** A workspace environment variable, compiled to `{{NAME}}`. */\nexport interface EnvRef {\n readonly [ENV]: string\n}\n\n/**\n * What a reference must hold to fill a param of type `T`. A param taking some strings takes any\n * string (an option id computed at run time); `null` (an output a step left empty) fits anywhere.\n */\ntype RefValue<T> = [Extract<T, string>] extends [never] ? T | null : T | string | null\n\n/**\n * A reference that fits a param of type `T`: one whose value has that type, or one into untyped\n * JSON. A whole block is not a value: reference one of its outputs.\n */\nexport type RefTo<T> = ({ readonly [REF]: RefValue<T> } | (AnyRef & Untyped)) & {\n readonly [NODE]?: never\n}\n\n/** A param value: a literal, a reference of a fitting type, a template or an environment variable. */\nexport type Value<T> = T | RefTo<T> | Template | EnvRef\n\n/** JSON whose leaves may be references, templates or environment variables. */\nexport type JsonWithRefs =\n | null\n | boolean\n | number\n | string\n | AnyRef\n | Template\n | EnvRef\n | JsonWithRefs[]\n | { [key: string]: JsonWithRefs }\n\n/** A literal union that still accepts any other string (option ids read from values). */\nexport type LiteralUnion<T extends string> = T | (string & {})\n\n/** A `time-input` value, `HH:MM`. */\nexport type TimeString = `${number}:${number}`\n\n/** A reference written into text: any output or variable, but not a whole block. */\ntype InterpolatedRef = AnyRef & { readonly [NODE]?: never }\n\ntype Interpolation = InterpolatedRef | EnvRef | VarRef | string | number | boolean\n\n/** Text with interpolated references: `` t`New ${cls.category} ticket` ``. */\nexport declare function t(strings: TemplateStringsArray, ...values: Interpolation[]): Template\n/** JavaScript code (condition expressions, inline function code). */\nexport declare const js: typeof t\n/** Python code. */\nexport declare const py: typeof t\n/** Shell code. */\nexport declare const sh: typeof t\n/**\n * JSON text kept verbatim, for bodies an object literal cannot reproduce byte for byte. In a JSON\n * field an object literal is the usual form: a bare reference keeps its value's type (`n: score.value`\n * is a number), and a template is text.\n */\nexport declare const json: typeof t\n/** Markdown text (note content). */\nexport declare const md: typeof t\n\n/** A reference with a non-canonical spelling, such as `ref('Classify.content')`. */\nexport declare function ref(path: string): Ref<Json>\n\n/** A stored value outside the generated type (a legacy option id, say), kept verbatim. */\nexport declare function raw<T = never>(value: unknown): T & { readonly [RAW]: true }\n\n/** A required value that is still missing; compiles to absent, so canvas drafts type-check. */\nexport declare function todo(): never\n\n/**\n * Keeps the value the stored workflow holds for this param, without showing it: the printer writes\n * it for a secret pasted into a password field. Valid only on a param of a block the stored\n * workflow already has (same name and type) and holds a value for; anything else is\n * `E_STORED_VALUE_MISSING`.\n */\nexport declare function stored(): never\n\n/** Function code kept in a file next to the workflow (`.js`, `.py` or `.sh`), stored verbatim. */\nexport interface CodeFileRef {\n readonly [CODE_FILE]: string\n}\nexport declare function codeFile(path: `./${string}`): CodeFileRef\n\n/**\n * Environment variable names known to the workspace. `workspace.d.ts` adds one member per name;\n * until it exists `env` accepts any name.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceEnv {}\n\nexport declare const env: keyof WorkspaceEnv extends never\n ? { readonly [name: string]: EnvRef }\n : { readonly [K in keyof WorkspaceEnv]: EnvRef }\n\n/**\n * Workspace resources by stable key, filled in by the generated `workspace.d.ts`. Each map's\n * values describe the resource: a table's row type, a credential's provider, a workflow's inputs.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceTables {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceKnowledgeBases {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCredentials {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceWorkflows {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceSkills {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceCustomTools {}\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface WorkspaceMcpServers {}\n\ntype KeyOf<M> = keyof M extends never ? string : Extract<keyof M, string>\n\nexport type TableKey = KeyOf<WorkspaceTables>\nexport type KnowledgeBaseKey = KeyOf<WorkspaceKnowledgeBases>\nexport type CredentialKey = KeyOf<WorkspaceCredentials>\nexport type WorkflowKey = KeyOf<WorkspaceWorkflows>\nexport type SkillKey = KeyOf<WorkspaceSkills>\nexport type CustomToolKey = KeyOf<WorkspaceCustomTools>\nexport type McpServerKey = KeyOf<WorkspaceMcpServers>\n/**\n * The tool names of MCP server `K`, as `workspace.d.ts` records them from the server's last\n * listing; any name for a server it could not list or does not know.\n */\nexport type McpToolName<K extends string> = K extends keyof WorkspaceMcpServers\n ? WorkspaceMcpServers[K] extends { tools: infer T extends string }\n ? T\n : string\n : string\n\n/** A workspace resource by stable key, compiled to the resource's internal id. */\nexport interface ResourceRef<Kind extends string, Key extends string = string> {\n readonly [RESOURCE]: Kind\n readonly key: Key\n}\n\n/** A saved credential: `credential('support-slack')`. */\nexport type CredentialRef<Key extends string = string> = ResourceRef<'credential', Key>\n\n/**\n * Keys of the saved credentials for one of `Providers`, as `workspace.d.ts` records each\n * credential's provider; any key until it exists.\n */\nexport type CredentialKeyFor<Providers extends string> = keyof WorkspaceCredentials extends never\n ? string\n : {\n [K in Extract<keyof WorkspaceCredentials, string>]: WorkspaceCredentials[K] extends {\n provider: Providers\n }\n ? K\n : never\n }[Extract<keyof WorkspaceCredentials, string>]\nexport declare function credential<K extends CredentialKey>(key: K): CredentialRef<K>\n\n/**\n * The other form a credential field takes beside `credential('key')`: a credential id produced at\n * run time by a reference, a template or an environment variable, stored in the field's advanced\n * twin (`manualCredential`). Literal text is not one, so a pasted token never type-checks; a\n * literal id the stored workflow already holds prints as `raw('…')`.\n */\nexport type CredentialIdValue = RefTo<string> | Template | EnvRef\n\n/** The columns of a workspace table, or loose JSON when `workspace.d.ts` does not know it. */\nexport type TableColumns<K extends string> = K extends keyof WorkspaceTables\n ? WorkspaceTables[K]\n : { [column: string]: Json }\n/**\n * One row as the table blocks output it: the row id, and its cells keyed by column name under\n * `data` (`row.data.status`). Times are ISO strings.\n */\nexport interface TableRow<K extends string> {\n id: string\n data: TableColumns<K>\n position: number\n createdAt: string\n updatedAt: string\n}\n/**\n * A value written to a field of type `T` (a table cell, a child workflow input): a JSON or JSON\n * array field takes JSON with references in it, and `null` leaves the field empty.\n */\ntype FieldValue<T> = [Json] extends [T]\n ? JsonWithRefs\n : [Json[]] extends [T]\n ? JsonWithRefs\n : Value<T> | null\n\n/** The columns of table `K` every row must hold: those whose cell type does not admit `null`. */\ntype RequiredColumns<K extends keyof WorkspaceTables> = {\n [C in keyof WorkspaceTables[K]]-?: null extends WorkspaceTables[K][C] ? never : C\n}[keyof WorkspaceTables[K]]\n\n/**\n * A whole row, as an insert, an upsert or a batch insert writes it, each value checked against\n * its column's type. A required column must be present and not `null`: the table refuses a row\n * without it (`Missing required field`), and an upsert checks the whole row before it looks for a\n * match.\n */\nexport type TableData<K extends string> = K extends keyof WorkspaceTables\n ? { [C in RequiredColumns<K>]-?: Exclude<FieldValue<WorkspaceTables[K][C]>, null> } & {\n [C in Exclude<keyof WorkspaceTables[K], RequiredColumns<K>>]?: FieldValue<\n WorkspaceTables[K][C]\n >\n }\n : { [column: string]: JsonWithRefs }\n\n/**\n * The cells an update writes, each checked against its column's type. Every column is optional:\n * an update merges these cells over the stored row.\n */\nexport type TableDataPatch<K extends string> = K extends keyof WorkspaceTables\n ? { [C in keyof WorkspaceTables[K]]?: FieldValue<WorkspaceTables[K][C]> }\n : { [column: string]: JsonWithRefs }\n\n/** A workspace table: `table('leads')`. Table block operations live on `table.*`. */\nexport type TableRef<Key extends string = string> = ResourceRef<'table', Key>\nexport declare function table<K extends TableKey>(key: K): TableRef<K>\n\n/** A knowledge base: `knowledgeBase('docs')`. */\nexport type KnowledgeBaseRef<Key extends string = string> = ResourceRef<'knowledge-base', Key>\nexport declare function knowledgeBase<K extends KnowledgeBaseKey>(key: K): KnowledgeBaseRef<K>\n\n/** A workspace skill: `skill('triage')`. */\nexport type SkillRef<Key extends string = string> = ResourceRef<'skill', Key>\nexport declare function skill<K extends SkillKey>(key: K): SkillRef<K>\n\n/** A workspace folder: `folder('reports')`. */\nexport type FolderRef = ResourceRef<'file-folder'>\nexport declare function folder(key: string): FolderRef\n\n/** A workspace file: `file('contracts/acme.pdf')`. File block operations live on `file.*`. */\nexport type FileRef = ResourceRef<'file'>\nexport declare function file(path: string): FileRef\n\n/**\n * A file a file-upload field holds, as the editor stores it: one uploaded in place, or a workspace\n * file chosen by `key` (written `file('path')` when the workspace resolves it).\n */\nexport interface UploadedFile {\n name: string\n path: string\n size?: number\n type?: string\n key?: string | FileRef\n id?: string\n folderPath?: string\n}\n\n/** A file produced at run time (`file` / `file[]` outputs). */\nexport interface SimFile {\n id: string\n name: string\n url: string\n size: number\n type: string\n key: string\n}\n\n// Agent tools\n\n/** One entry of an agent's `tools` list. */\nexport interface Tool {\n readonly [TOOL]: true\n}\n\n/** How the model may use a tool, and the stored tool fields a print carries. */\nexport interface ToolOpts {\n usageControl?: 'auto' | 'force' | 'none'\n usageControlExpression?: string\n title?: string\n /** The stored operation, when the method does not pin it. */\n operation?: string\n toolId?: string\n /** Pair modes of the tool's params, which pick the member the agent reads. */\n modes?: Record<string, 'basic' | 'advanced'>\n customTool?: JsonWithRefs\n operationPolicy?: Json\n /** Unknown stored tool keys, kept verbatim. */\n extra?: Json\n}\n\n/**\n * A workspace custom tool by key, as an agent tool: `customTool('lookup-order')`. A stored tool\n * whose definition was copied into the workflow (and may have drifted from the workspace tool)\n * prints as `raw(tool)` instead.\n */\nexport declare function customTool<K extends CustomToolKey>(key: K, options?: ToolUsage): Tool\n\n/** How the model may use a tool the SDK writes by name (`customTool`, `mcp().tool`, `asTool`). */\nexport type ToolUsage = Pick<ToolOpts, 'usageControl' | 'usageControlExpression'>\n\n/** An MCP tool's arguments and the editor's snapshot of its server. */\nexport interface McpToolOpts extends ToolUsage {\n /** Argument values the workflow fixes; the model fills in the rest. */\n args?: Record<string, JsonWithRefs>\n /**\n * What the editor saved about the server and the tool's input schema when the tool was picked.\n * Shown in the editor; never run.\n */\n snapshot?: { serverName?: string; serverUrl?: string; schema?: Json }\n}\n\n/** An MCP server by key: `mcp('linear')`. */\nexport interface McpServerRef<Key extends string = string> extends ResourceRef<'mcp-server', Key> {\n /** One of the server's tools, as an agent tool: `mcp('linear').tool('create_issue')`. */\n tool(name: McpToolName<Key>, options?: McpToolOpts): Tool\n}\nexport declare function mcp<K extends McpServerKey>(key: K): McpServerRef<K>\n\n// Graph\n\n/** Block-level fields (`BlockState`), written as the third builder argument. */\nexport interface BlockMeta {\n /**\n * A legacy key the display name cannot carry (a `name~n` collision key or a reserved name such\n * as `Loop`). Printed only for such a stored block; apply accepts it only for a key the stored\n * workflow already has, so it can never introduce one.\n */\n key?: string\n /** Stored as `enabled: false`. */\n disabled?: true\n /** Locked: apply refuses any change to this block. */\n locked?: true\n /** Exposes the error port without an `onError` edge. */\n errorPort?: boolean\n /** The block-level advanced toggle (`advancedMode`). */\n advancedMode?: boolean\n /**\n * Runs the block as its trigger (`triggerMode`). Trigger builders (`trigger.gmail.poller`) set\n * it themselves; write it on any other builder only for a block stored in trigger mode.\n */\n triggerMode?: boolean\n /** The stored retry policy, written whole. */\n retry?: BlockRetryConfig\n /**\n * Per branch key of a condition or router, the row's display `title` and any stored fields the\n * SDK has no syntax for (`extra`, plain JSON). `title: null` keeps a row stored with no title,\n * which the executor never takes for `else`.\n */\n branches?: Record<string, { title?: string | null; extra?: Record<string, Json> }>\n /**\n * Stored params that run but have no SDK syntax: a schema-agnostic custom block's inputs, the\n * agent's legacy prompt fields, a container's stored params. Values the block keeps but never\n * runs are not written; apply keeps them from the stored workflow.\n */\n extra?: Record<string, unknown>\n /**\n * A loop or parallel's `block.data` subflow keys the loader could not read as config, kept\n * verbatim (plain JSON).\n */\n subflowData?: Record<string, Json>\n}\n\n/** A block's retry policy, field for field the stored `BlockRetryConfig`. */\nexport interface BlockRetryConfig {\n /** Absent config and `false` mean the same thing: the block runs once. */\n enabled: boolean\n /** Total tries including the first. */\n maxTries: number\n /** Delay between tries. */\n waitBetweenTriesMs: number\n}\n\n/** Anything an edge can point at. */\nexport type Target = Node | Group\n\n/** A block or container in the graph. */\nexport interface Node {\n readonly [NODE]: true\n /** Wires this node's default port to each target. Returns the target, or a group of them. */\n to<const T extends Target[]>(...targets: T): T extends [infer One] ? One : Group\n /** Wires this node's error port to each target. */\n onError(...targets: Target[]): void\n}\n\n/** Several nodes; `.to()` wires every member (fan-in). */\nexport interface Group {\n to(...targets: Target[]): Group\n}\n\n/**\n * The failure message a block outputs when an error edge leaves it (`x.onError(y)` runs `y` with\n * `x.error`); a check refuses `x.error` on a block without one, which fails the run instead.\n */\ntype ErrorOutput<O> = [O] extends [{ error: unknown }] ? unknown : { readonly error: Ref<string> }\n\n/** A block: a node whose outputs can be referenced, and `error` after an `onError` edge. */\nexport type Block<O> = Node & Ref<O> & ErrorOutput<O>\n\n/** The named ports of a condition or router. */\nexport type Branches<K extends string> = { readonly [P in K]: Node }\n\n/** Trigger builders (`trigger.start`, `trigger.gmail.poller`, ...), generated from the catalog. */\nexport declare namespace trigger {}\n\n/** Builders for hidden legacy block versions (`legacy.slack.send`), generated from the catalog. */\nexport declare namespace legacy {}\n\n/** A raw edge from a handle the SDK has no name for (a legacy or unknown port). */\nexport declare function edge(from: Node, handle: string, to: Target): void\n\n/** Any stored block type without a builder (legacy, unknown or custom), with untyped outputs. */\nexport declare function block(\n type: string,\n name: string,\n params: Record<string, unknown>,\n meta?: BlockMeta\n): Block<Json>\n\n// Workflow and variables\n\nexport type VariableType = 'string' | 'number' | 'boolean' | 'object' | 'array' | 'plain'\n\n/** A workflow variable declared in `workflow(name, { variables })`: its type and initial value. */\nexport interface VariableDeclaration {\n /**\n * The display name, written only when it differs from the key. It must normalize to the key\n * (lowercased, spaces and dots removed), as `'Total Count'` does to `totalcount`.\n */\n name?: string\n type: VariableType\n value: Json\n}\n\n/** The variables a workflow declares, by name. */\nexport type VariableDeclarations = Record<string, VariableDeclaration>\n\ndeclare const VAR: unique symbol\n\n/** A workflow variable, compiled to `<variable.name>`. */\nexport interface VarRef {\n readonly [VAR]: string\n}\n\ntype VariableValue<T extends VariableType> = T extends 'number'\n ? number\n : T extends 'boolean'\n ? boolean\n : T extends 'string' | 'plain'\n ? string\n : Json\n\n/** `vars` in the workflow body: one typed reference per declared variable. */\nexport type VarRefs<V extends VariableDeclarations> = {\n readonly [K in keyof V]: VarRef & Ref<VariableValue<V[K]['type']>>\n}\n\n/**\n * Workflow variables by name, untyped. Prefer the `vars` the `workflow()` body receives, which is\n * typed from the declared variables.\n */\nexport declare const vars: { readonly [name: string]: VarRef & Ref<Json> }\n\ndeclare const WORKFLOW_DEF: unique symbol\n\n/** The default export of a workflow file. */\nexport interface WorkflowDef {\n readonly [WORKFLOW_DEF]: true\n}\n\n/** A child workflow by key, for `runWorkflow` or as an agent tool. */\nexport interface WorkflowRef<Key extends string = string> extends ResourceRef<'workflow', Key> {\n /**\n * The workflow as an agent tool, as the editor's tool picker adds it:\n * `childWorkflow('enrich-lead').asTool()`. A tool with fixed inputs is written `raw(tool)`.\n */\n asTool(options?: ToolUsage): Tool\n}\n\n/**\n * Declares a workflow. The body wires blocks; it never runs. With no description or variables the\n * options may be left out: `workflow('Name', () => { ... })`.\n */\nexport declare function workflow<const V extends VariableDeclarations = Record<never, never>>(\n name: string,\n options: { description?: string; variables?: V },\n body: (scope: { vars: VarRefs<V> }) => void\n): WorkflowDef\nexport declare function workflow(\n name: string,\n body: (scope: { vars: VarRefs<Record<never, never>> }) => void\n): WorkflowDef\n/** A child workflow by key: `childWorkflow('enrich-lead')`. */\nexport declare function childWorkflow<K extends WorkflowKey>(key: K): WorkflowRef<K>\n\n// Containers\n\ntype ItemOf<C> = C extends { readonly [REF]: readonly (infer E)[] }\n ? E\n : C extends readonly (infer E)[]\n ? E\n : Json\n\n/** Inside a loop or parallel body. As a node it is the container's start port: `p.to(first)`. */\nexport interface SubflowScope<Item> extends Node {\n readonly index: Ref<number>\n readonly currentItem: Ref<Item>\n readonly items: Ref<Item[]>\n}\n\n/**\n * A container's outputs, plus its iteration fields by name (`outer.index`), which a block inside\n * the container reads (in a nested container too: an outer loop's index or item). Outside the\n * container only `results` resolves: check reports `W_REF_OUT_OF_SCOPE` on `outer.index` there.\n */\nexport interface SubflowOutput {\n results: Json[]\n index: number\n currentItem: Json\n items: Json[]\n}\n\n/** A loop or parallel container. Its `.to()` wires the port taken after it finishes. */\nexport type Container = Block<SubflowOutput>\n\ntype Collection = AnyRef | Template | Json[] | string\n\nexport declare const loop: {\n for(\n name: string,\n params: { count?: number },\n body: (scope: SubflowScope<never>) => void,\n meta?: BlockMeta\n ): Container\n forEach<const C extends Collection>(\n name: string,\n params: { collection: C },\n body: (scope: SubflowScope<ItemOf<C>>) => void,\n meta?: BlockMeta\n ): Container\n while(\n name: string,\n params: { condition: Template | string },\n body: (scope: SubflowScope<never>) => void,\n meta?: BlockMeta\n ): Container\n doWhile(\n name: string,\n params: { condition?: Template | string; count?: number },\n body: (scope: SubflowScope<never>) => void,\n meta?: BlockMeta\n ): Container\n}\n\nexport declare const parallel: {\n /** A parallel with no stored type, which the loader runs as `count`. */\n (\n name: string,\n params: { count?: number; collection?: Collection; batchSize?: number },\n body: (scope: SubflowScope<Json>) => void,\n meta?: BlockMeta\n ): Container\n count(\n name: string,\n params: { count: number; batchSize?: number },\n body: (scope: SubflowScope<never>) => void,\n meta?: BlockMeta\n ): Container\n collection<const C extends Collection>(\n name: string,\n params: { collection: C; batchSize?: number },\n body: (scope: SubflowScope<ItemOf<C>>) => void,\n meta?: BlockMeta\n ): Container\n}\n\n// Blocks with a source form of their own\n\n/**\n * Params and outputs of the blocks below, generated from the catalog. Each entry is\n * `{ params; output }`; without generated types the params are loose.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface SpecialBuilderTypes {}\n\ntype SpecialParams<K extends string> = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { params: infer P }\n ? P\n : never\n : Record<string, unknown>\n\ntype SpecialOutput<K extends string> = K extends keyof SpecialBuilderTypes\n ? SpecialBuilderTypes[K] extends { output: infer O }\n ? O\n : never\n : Json\n\n/** A condition expression, or `true` for the `else` branch. */\nexport type BranchExpression = Template | string | true\n\ndeclare const ONLY_ELSE: unique symbol\n\n/** What a branch other than `else` written as `true` must be, which no value is: the error names it. */\ninterface OnlyElseMayBeTrue {\n readonly [ONLY_ELSE]: true\n}\n\n/**\n * A condition's branches: every key holds an expression, and only `else` may be `true`. Another\n * branch written as `true` is checked against {@link OnlyElseMayBeTrue}, so the error names that\n * branch alone.\n */\ntype ConditionBranches<B> = {\n [K in keyof B]: K extends 'else'\n ? BranchExpression\n : B[K] extends true\n ? OnlyElseMayBeTrue\n : Template | string\n}\n\n/**\n * Keys of a condition written with no rows (`condition('Name', {})`, the source form of rows\n * that were never persisted): the implicit `if` and `else` ports stay addressable.\n */\ntype ConditionKeys<B> = keyof B extends never ? 'if' | 'else' : Extract<keyof B, string>\ntype RouterKeys<R> = keyof R extends never ? 'route0' : Extract<keyof R, string>\n\n/** A condition: named branches, the last one `else` when there are two or more. */\nexport declare function condition<const B extends Record<string, BranchExpression>>(\n name: string,\n branches: B & ConditionBranches<B>,\n meta?: BlockMeta\n): Block<SpecialOutput<'condition'>> & Branches<ConditionKeys<B>>\n\n/** A router: named routes described for the model. */\nexport declare function router<const R extends Record<string, string | Template>>(\n name: string,\n params: SpecialParams<'router'> & { routes: R },\n meta?: BlockMeta\n): Block<SpecialOutput<'router'>> & Branches<RouterKeys<R>>\n\n/** A function block. `code` is inline (`` js`...` ``) or a code file (`codeFile('./functions/x.js')`). */\nexport declare function fn(\n name: string,\n params: SpecialParams<'fn'> & { code: Template | CodeFileRef | string },\n meta?: BlockMeta\n): Block<SpecialOutput<'fn'>>\n\n/**\n * The inputs of a child workflow by key, each checked against the input its start block\n * declares when `workspace.d.ts` knows the workflow; loose JSON otherwise.\n */\nexport type WorkflowInputMapping<K extends string> = K extends keyof WorkspaceWorkflows\n ? WorkspaceWorkflows[K] extends { inputs: infer I }\n ? { [N in keyof I]?: FieldValue<I[N]> }\n : InputMapping\n : InputMapping\n\n/**\n * Runs a child workflow. A `childWorkflow('key')` checks `inputMapping` against its inputs. Its\n * `result` is the child's output: its first response block's `{ data, status, headers }` (a body\n * field is `result.data.field`), else the output of the last block it ran.\n */\nexport declare function runWorkflow<K extends string = string>(\n name: string,\n params: Omit<SpecialParams<'runWorkflow'>, 'workflowId' | 'inputMapping'> & {\n workflowId: WorkflowRef<K> | Exclude<SpecialParams<'runWorkflow'>['workflowId'], WorkflowRef>\n inputMapping?: WorkflowInputMapping<K>\n },\n meta?: BlockMeta\n): Block<SpecialOutput<'runWorkflow'>>\n\n/**\n * Pauses for a person; the form in `inputFormat` types `submission`. A resumed block also holds\n * each form field at its top level (the runtime copies the submission up, over any output of the\n * same name), so `approval.approved` and `approval.submission.approved` both read it.\n */\nexport declare function human<const F extends InputFields = Record<never, never>>(\n name: string,\n params: SpecialParams<'human'> & { inputFormat?: F },\n meta?: BlockMeta\n): Block<\n Omit<SpecialOutput<'human'>, 'submission' | keyof F> & {\n submission: InputFieldsOutput<F>\n } & InputFieldsOutput<F>\n>\n\n/**\n * A response's body, status and headers: the editor's JSON mode, `body` standing for\n * `{ dataMode: 'json', data }`. An object or array `body` is JSON whose references keep their\n * types; a template or reference is the body text as written.\n */\nexport interface ResponseBody {\n body: JsonWithRefs\n /** HTTP status; 200 when omitted. A template or reference must produce a number. */\n status?: number | RefTo<number> | Template | EnvRef\n /** Response headers by name. */\n headers?: Record<string, Value<string>>\n}\n\n/**\n * Ends the workflow with an API response: `response('Reply', { body: { ok: true }, status: 201 })`\n * (`body` is short for `dataMode: 'json'` with `data`), or the block's own params (`dataMode`,\n * `builderData`, ...) when the body is built field by field.\n */\nexport declare function response(\n name: string,\n params: ResponseBody,\n meta?: BlockMeta\n): Block<SpecialOutput<'response'>>\nexport declare function response(\n name: string,\n params: SpecialParams<'response'>,\n meta?: BlockMeta\n): Block<SpecialOutput<'response'>>\n\n/** Assigns workflow variables. */\nexport declare function setVariables(\n name: string,\n params: SpecialParams<'setVariables'>,\n meta?: BlockMeta\n): Block<SpecialOutput<'setVariables'>>\n\ndeclare const ANNOTATION: unique symbol\n\n/** A canvas note: no edges, no outputs. */\nexport interface Annotation {\n readonly [ANNOTATION]: true\n}\nexport declare function note(\n name: string,\n params: SpecialParams<'note'>,\n meta?: BlockMeta\n): Annotation\n\n// Structured param shapes\n\n/** Type names an input-format field may declare. */\nexport type InputFieldType = 'string' | 'number' | 'boolean' | 'object' | 'array' | 'file[]'\n\n/** A structured input field: its type plus a default value, description or required flag. */\nexport interface InputFieldSpec {\n type: InputFieldType\n value?: JsonWithRefs\n description?: string\n required?: boolean\n}\n\n/** `input-format` fields by name: `{ subject: 'string', amount: { type: 'number', value: 0 } }`. */\nexport type InputFields = Record<string, InputFieldType | InputFieldSpec>\n\ntype InputFieldValue<T> = T extends 'string'\n ? string\n : T extends 'number'\n ? number\n : T extends 'boolean'\n ? boolean\n : T extends 'array'\n ? Json[]\n : T extends 'file[]'\n ? SimFile[]\n : Json\n\n/** The outputs an `input-format` declares. */\nexport type InputFieldsOutput<F> = {\n [K in keyof F]: F[K] extends { type: infer T } ? InputFieldValue<T> : InputFieldValue<F[K]>\n}\n\n/**\n * One `response-format` field as the editor's builder stores it. An `object` or `array` field's\n * `value` may hold nested fields. A response is usually written with `body` instead.\n */\nexport interface ResponseField {\n id?: string\n name: string\n type: string\n value?: JsonWithRefs\n collapsed?: boolean\n}\n\n/** `response-format` fields: `[{ name: 'ok', type: 'boolean', value: true }]`. */\nexport type ResponseFields = ResponseField[]\n\n/** An agent message. */\nexport interface Message {\n role: 'system' | 'user' | 'assistant'\n content: Value<string>\n}\n\n/** One `variables-input` assignment, with any other stored keys kept. */\nexport interface VariableAssignment {\n variableId: VarRef\n value?: JsonWithRefs\n [key: string]: JsonWithRefs | VarRef | undefined\n}\n\n/** Child workflow inputs by name (`input-mapping`, `workflow-input-mapper`). */\nexport type InputMapping = Record<string, JsonWithRefs>\n\n/** An operator a table filter condition or builder rule can use. */\nexport type FilterOperator = LiteralUnion<\n | 'eq'\n | 'ne'\n | 'gt'\n | 'gte'\n | 'lt'\n | 'lte'\n | 'in'\n | 'nin'\n | 'like'\n | 'ilike'\n | 'nlike'\n | 'nilike'\n | 'contains'\n | 'ncontains'\n | 'startsWith'\n | 'endsWith'\n | 'isNull'\n | 'isNotNull'\n | 'isEmpty'\n | 'isNotEmpty'\n>\n\n/** One row of the editor's filter builder, as it stores it. */\nexport interface FilterRule {\n id?: string\n /** How this row joins the rows before it; `and` when omitted. */\n logicalOperator?: 'and' | 'or'\n column: string\n operator: FilterOperator\n value: Value<string | number | boolean>\n collapsed?: boolean\n}\n\n/** A filter-builder value: the editor's rows, `[{ column: 'status', operator: 'eq', value: 'new' }]`. */\nexport type Filter = FilterRule[]\n\n/** One table filter condition: `{ field: 'status', op: 'eq', value: 'new' }`. */\nexport interface TableCondition {\n field: string\n op: FilterOperator\n value?: JsonWithRefs\n}\n\n/**\n * A table predicate: a condition, or an `all` (and) / `any` (or) group of predicates. The\n * `{ status: { $eq: 'new' } }` operator-object grammar is not one: the runtime refuses it.\n */\nexport type TablePredicate = TableCondition | { all: TablePredicate[] } | { any: TablePredicate[] }\n\n/** A table sort by column: `{ createdAt: 'desc' }`. */\nexport type Sort =\n | Record<string, 'asc' | 'desc'>\n | Array<{ column: string; direction: 'asc' | 'desc' }>\n\n/** One knowledge tag filter. */\nexport interface TagFilter {\n tagName: string\n tagValue: Value<string>\n [key: string]: JsonWithRefs\n}\n\n/** One document tag. */\nexport interface DocumentTag {\n tagName: string\n value: Value<string>\n [key: string]: JsonWithRefs\n}\n\n/** One `eval-input` metric. */\nexport interface EvalMetric {\n name: string\n description?: string\n range?: { min: number; max: number }\n [key: string]: JsonWithRefs | undefined\n}\n\n/** One `model-fallback-list` entry. */\nexport interface ModelFallback {\n model: LiteralUnion<Model>\n [key: string]: JsonWithRefs\n}\n\n/**\n * Model ids, generated into `models.d.ts` (which adds one member per model). Kept apart from the\n * block files so a model-list change touches one file.\n */\n// biome-ignore lint/suspicious/noEmptyInterface: an empty interface is the merge target generated declarations augment\nexport interface ModelIds {}\nexport type Model = Extract<keyof ModelIds, string>\n\n/** A JSON Schema `responseFormat`, or `{ name, strict, schema }` around one. */\nexport type ResponseFormat = JsonWithRefs\n\ntype Depth = [never, 0, 1, 2, 3, 4]\n\ntype FromSchema<S, D extends number> = [D] extends [never]\n ? Json\n : S extends { enum: readonly (infer E)[] }\n ? E\n : S extends { type: 'object'; properties: infer P }\n ? { [K in keyof P]: FromSchema<P[K], Depth[D]> }\n : S extends { type: 'array'; items: infer I }\n ? FromSchema<I, Depth[D]>[]\n : S extends { type: 'string' }\n ? string\n : S extends { type: 'number' | 'integer' }\n ? number\n : S extends { type: 'boolean' }\n ? boolean\n : Json\n\n/**\n * The outputs a literal `responseFormat` adds, read from its JSON Schema with recursion capped at\n * depth 4. A template or reference adds untyped JSON.\n */\nexport type ResponseFormatOutput<RF> = [RF] extends [undefined]\n ? unknown\n : RF extends { schema: infer S }\n ? FromSchema<S, 4>\n : RF extends { type: 'object'; properties: object }\n ? FromSchema<RF, 4>\n : { [key: string]: Json }\n";
40881
40937
  // ../workflow-code/src/anchors.ts
40882
40938
  function portKey(port) {
40883
40939
  switch (port.kind) {
@@ -41884,6 +41940,16 @@ function findWorkflowReferenceTokens(source) {
41884
41940
  }
41885
41941
  return tokens.sort((left, right) => left.start - right.start);
41886
41942
  }
41943
+ function collectStringLeaves(value, out) {
41944
+ if (typeof value === "string")
41945
+ out.push(value);
41946
+ else if (Array.isArray(value))
41947
+ for (const item of value)
41948
+ collectStringLeaves(item, out);
41949
+ else if (typeof value === "object" && value !== null)
41950
+ for (const item of Object.values(value))
41951
+ collectStringLeaves(item, out);
41952
+ }
41887
41953
 
41888
41954
  // ../workflow-code/src/limits.ts
41889
41955
  var SOURCE_LIMITS = {
@@ -42366,6 +42432,7 @@ function parseWorkflowSourceHandle(handle, sourceType, branchKind) {
42366
42432
  var SIDE_ANCHORED_SOURCE_HANDLE_IDS = new Set(WORKFLOW_CARD_SIDES.map((side) => `source-${side}`));
42367
42433
  var SIDE_ANCHORED_TARGET_HANDLE_IDS = new Set(WORKFLOW_CARD_SIDES.map((side) => `target-${side}`));
42368
42434
  var WORKFLOW_CONTAINER_BLOCK_TYPES = new Set(["loop", "parallel"]);
42435
+ var WORKFLOW_ANNOTATION_ONLY_BLOCK_TYPE = "note";
42369
42436
  function getWorkflowEdgeScopeDropReason(edge, blocks) {
42370
42437
  const sourceBlock = blocks[edge.source];
42371
42438
  const targetBlock = blocks[edge.target];
@@ -42385,6 +42452,72 @@ function getWorkflowEdgeScopeDropReason(edge, blocks) {
42385
42452
  }
42386
42453
  return `blocks are in different scopes (${sourceParent ?? "root"} -> ${targetParent ?? "root"})`;
42387
42454
  }
42455
+ function isWorkflowAnnotationOnlyBlockType(blockType) {
42456
+ return blockType === WORKFLOW_ANNOTATION_ONLY_BLOCK_TYPE;
42457
+ }
42458
+ var RESPONSE_BLOCK_TYPE = "response";
42459
+ function isElseConditionTitle(title) {
42460
+ return typeof title === "string" && title.trim().toLowerCase() === "else";
42461
+ }
42462
+ function hasCycle(successors, pending) {
42463
+ const ready = [...successors.keys()].filter((id) => !pending.has(id));
42464
+ let visited = 0;
42465
+ for (let id = ready.pop();id !== undefined; id = ready.pop()) {
42466
+ visited += 1;
42467
+ for (const next of successors.get(id) ?? []) {
42468
+ const left = (pending.get(next) ?? 0) - 1;
42469
+ pending.set(next, left);
42470
+ if (left === 0)
42471
+ ready.push(next);
42472
+ }
42473
+ }
42474
+ const nodes = new Set([...successors.keys(), ...pending.keys()]);
42475
+ return visited < nodes.size;
42476
+ }
42477
+ function alwaysEndsAtResponse(blocks, edges) {
42478
+ const runs = (id) => {
42479
+ const block = Object.hasOwn(blocks, id) ? blocks[id] : undefined;
42480
+ return block?.enabled === true && !isWorkflowAnnotationOnlyBlockType(block.type);
42481
+ };
42482
+ const isRoot = (id) => blocks[id]?.parentId === null;
42483
+ const portsBySource = new Map;
42484
+ const successors = new Map;
42485
+ const pending = new Map;
42486
+ for (const edge of edges) {
42487
+ if (!runs(edge.source) || !runs(edge.target))
42488
+ continue;
42489
+ const ports = portsBySource.get(edge.source) ?? new Set;
42490
+ ports.add(edge.port);
42491
+ portsBySource.set(edge.source, ports);
42492
+ if (!isRoot(edge.source) || !isRoot(edge.target))
42493
+ continue;
42494
+ const next = successors.get(edge.source) ?? [];
42495
+ next.push(edge.target);
42496
+ successors.set(edge.source, next);
42497
+ pending.set(edge.target, (pending.get(edge.target) ?? 0) + 1);
42498
+ }
42499
+ if (hasCycle(successors, pending))
42500
+ return false;
42501
+ let responds = false;
42502
+ for (const [id, block] of Object.entries(blocks)) {
42503
+ if (!runs(id) || block.parentId !== null)
42504
+ continue;
42505
+ if (block.type === RESPONSE_BLOCK_TYPE) {
42506
+ responds = true;
42507
+ continue;
42508
+ }
42509
+ const ports = portsBySource.get(id);
42510
+ if (block.branches !== undefined) {
42511
+ const { branches } = block;
42512
+ if (branches.length === 0 || !branches.every((branch) => ports?.has(`branch:${branch}`))) {
42513
+ return false;
42514
+ }
42515
+ } else if (!ports?.has(isSubflowType(block.type) ? "subflowEnd" : "out")) {
42516
+ return false;
42517
+ }
42518
+ }
42519
+ return responds;
42520
+ }
42388
42521
  var RESERVED_WORKFLOW_BLOCK_NAMES = ["loop", "parallel", "variable"];
42389
42522
  function isReservedWorkflowBlockName(name) {
42390
42523
  return RESERVED_WORKFLOW_BLOCK_NAMES.includes(name);
@@ -42789,8 +42922,8 @@ function valueTree(value) {
42789
42922
  var SDK_MODULE = "@sim/workflow-sdk";
42790
42923
  var GENERIC_BUILDER = "block";
42791
42924
  var CUSTOM_TOOL_TYPE = "custom-tool";
42792
- var RESPONSE_BLOCK_TYPE = "response";
42793
42925
  var RESPONSE_BODY_KEYS = ["body", "status", "headers"];
42926
+ var RESPONSE_OUTPUTS = ["data", "status", "headers"];
42794
42927
  var TEMPLATE_TAGS = [
42795
42928
  "t",
42796
42929
  "js",
@@ -43670,6 +43803,9 @@ function renamedReferenceRewriter(renames) {
43670
43803
  }) : text;
43671
43804
  }
43672
43805
 
43806
+ // ../workflow-code/src/compile/blocks.ts
43807
+ var import_parser3 = __toESM(require_lib(), 1);
43808
+
43673
43809
  // ../workflow-code/src/canonicalize/values.ts
43674
43810
  var REFERENCE_CANDIDATE = /<([^<>]+)>/g;
43675
43811
  var VARIABLE_PREFIX = "variable";
@@ -43764,6 +43900,20 @@ var MODELED_ROW_KEYS = new Set(["id", "title", "value", "key"]);
43764
43900
  function isBranchExtraField(field) {
43765
43901
  return !MODELED_ROW_KEYS.has(field) && !UI_ROW_KEYS.has(field);
43766
43902
  }
43903
+ function storedTitle(kind, row, index, count) {
43904
+ if (row.titleOverride !== undefined)
43905
+ return row.titleOverride;
43906
+ return row.titleMissing ? undefined : positionalTitle(kind, index, count);
43907
+ }
43908
+ function positionalTitle(kind, index, count) {
43909
+ if (kind === "router")
43910
+ return `Route ${index + 1}`;
43911
+ if (index === 0)
43912
+ return "if";
43913
+ if (index === count - 1)
43914
+ return "else";
43915
+ return "else if";
43916
+ }
43767
43917
 
43768
43918
  // ../workflow-code/src/canonicalize/subflows.ts
43769
43919
  var PARALLEL_BATCH_MIN = 1;
@@ -47710,6 +47860,48 @@ function textField(value) {
47710
47860
  function jsonField(value) {
47711
47861
  return isJson(value) ? value : undefined;
47712
47862
  }
47863
+ function checkLoopCondition(ctx, decl, text, property) {
47864
+ if (text.trim() === "")
47865
+ return;
47866
+ const at = rangeOf(ctx, property.value);
47867
+ const selfReads = new Set;
47868
+ const ownName = normalizeWorkflowBlockName(decl.name);
47869
+ const runnable = text.replace(REFERENCE_CANDIDATE, (match, inner) => {
47870
+ if (!isLikelyWorkflowReferenceSegment(match))
47871
+ return match;
47872
+ const segments = parseStoredPath(inner);
47873
+ const [head, field] = segments ?? [];
47874
+ if (head?.kind === "name" && normalizeWorkflowBlockName(head.name) === ownName && field?.kind === "name" && LOOP_PROPERTIES.includes(field.name)) {
47875
+ selfReads.add(field.name);
47876
+ }
47877
+ return "(0)";
47878
+ });
47879
+ for (const field of selfReads) {
47880
+ ctx.reporter.report("W_REF_OUT_OF_SCOPE", `${decl.name}'s condition reads its own ${field} by the loop's name. The run evaluates the condition outside the loop's body, where the loop outputs only results, so the run fails.`, at, {
47881
+ hint: `Write <loop.${field}>: the bare loop prefix reads the iteration the condition is evaluated for.`,
47882
+ blockKey: decl.key
47883
+ });
47884
+ }
47885
+ let failure = null;
47886
+ try {
47887
+ const file = import_parser3.parse(`return Boolean(${runnable})`, {
47888
+ sourceType: "script",
47889
+ allowReturnOutsideFunction: true,
47890
+ errorRecovery: true
47891
+ });
47892
+ failure = file.errors?.[0] ?? null;
47893
+ } catch (error) {
47894
+ failure = error;
47895
+ }
47896
+ if (failure === null)
47897
+ return;
47898
+ const { message: raw } = babelErrorShape(failure);
47899
+ const message = typeof raw === "string" ? raw : "Invalid JavaScript";
47900
+ ctx.reporter.report("W_LOOP_CONDITION_SYNTAX", `${decl.name}'s condition is not a JavaScript expression (${message.replace(/\s*\(\d+:\d+\)$/, "")}), so the run fails when it evaluates it.`, at, {
47901
+ hint: "Write one JavaScript expression the loop repeats while it is true, e.g. condition: '<loop.index> < 3'.",
47902
+ blockKey: decl.key
47903
+ });
47904
+ }
47713
47905
  function compileContainer(ctx, decl) {
47714
47906
  const builder = decl.builder;
47715
47907
  if (builder.kind !== "container")
@@ -47741,6 +47933,12 @@ function compileContainer(ctx, decl) {
47741
47933
  ...doWhileCondition !== undefined && { doWhileCondition }
47742
47934
  };
47743
47935
  reportUnreadConfig(ctx, decl, form, written, loop);
47936
+ for (const field of ["whileCondition", "doWhileCondition"]) {
47937
+ const text = loop[field];
47938
+ const property = written.get(field);
47939
+ if (text !== undefined && property)
47940
+ checkLoopCondition(ctx, decl, text, property);
47941
+ }
47744
47942
  subflow = loop;
47745
47943
  } else {
47746
47944
  const { fields } = compileConfig(ctx, site, "parallel", parallelForm(builder.method), config);
@@ -48390,7 +48588,7 @@ function stronglyConnected(keys, successors) {
48390
48588
  }
48391
48589
 
48392
48590
  // ../workflow-code/src/compile/function-returns.ts
48393
- var import_parser3 = __toESM(require_lib(), 1);
48591
+ var import_parser4 = __toESM(require_lib(), 1);
48394
48592
  var FUNCTION_TYPE = "function";
48395
48593
  var NUMBER_FUNCTIONS = new Set(["Number", "parseInt", "parseFloat"]);
48396
48594
  var BOOLEAN_FUNCTIONS = new Set(["Boolean", "isNaN", "isFinite"]);
@@ -48726,7 +48924,7 @@ function returnedFields(object, inference) {
48726
48924
  function readReturns(code) {
48727
48925
  let program;
48728
48926
  try {
48729
- const file = import_parser3.parse(toCodeFile(code, "javascript"), {
48927
+ const file = import_parser4.parse(toCodeFile(code, "javascript"), {
48730
48928
  sourceType: "unambiguous",
48731
48929
  allowReturnOutsideFunction: true,
48732
48930
  allowAwaitOutsideFunction: true,
@@ -48826,6 +49024,7 @@ var COMPILE_SCOPE_CODES = [
48826
49024
  "W_ENV_UNKNOWN",
48827
49025
  "W_CHILD_INPUT_UNKNOWN",
48828
49026
  "W_CHILD_NO_START",
49027
+ "W_CHILD_RESULT_PATH",
48829
49028
  "E_UNKNOWN_SUBFLOW_PROPERTY",
48830
49029
  "W_FORWARD_REF",
48831
49030
  "W_REF_NOT_NORMALIZED",
@@ -48871,7 +49070,8 @@ var COMPILE_CATALOG_CODES = [
48871
49070
  "W_SUBFLOW_COUNT",
48872
49071
  "W_UNKNOWN_OUTPUT_PATH",
48873
49072
  "W_OUTPUT_PATH_UNDECLARED",
48874
- "W_JSON_REF_UNTYPED"
49073
+ "W_JSON_REF_UNTYPED",
49074
+ "W_LOOP_CONDITION_SYNTAX"
48875
49075
  ];
48876
49076
  var CODE_FILE_CODES = [
48877
49077
  "E_CODE_FILE_MISSING",
@@ -48975,6 +49175,7 @@ var APPLY_DIAGNOSTIC_CODES = [
48975
49175
  "E_APPLY_UNRESOLVED_REF",
48976
49176
  "E_APPLY_REF_OUT_OF_SCOPE",
48977
49177
  "E_APPLY_CODE_FILE_REF_SYNTAX",
49178
+ "E_APPLY_LOOP_CONDITION_SYNTAX",
48978
49179
  "W_APPLY_LINT",
48979
49180
  "W_TABLE_UNKNOWN_COLUMN",
48980
49181
  "E_APPLY_INVALID_SCHEDULE",
@@ -49016,7 +49217,8 @@ function refusalClassifier(extra = {}) {
49016
49217
  }
49017
49218
  var refusalClass = refusalClassifier();
49018
49219
  var CHANGED_BLOCK_REFUSALS = new Map([
49019
- ["W_REF_OUT_OF_SCOPE", "E_APPLY_REF_OUT_OF_SCOPE"]
49220
+ ["W_REF_OUT_OF_SCOPE", "E_APPLY_REF_OUT_OF_SCOPE"],
49221
+ ["W_LOOP_CONDITION_SYNTAX", "E_APPLY_LOOP_CONDITION_SYNTAX"]
49020
49222
  ]);
49021
49223
  var PARAM_REFUSALS = new Map([
49022
49224
  ["W_UNKNOWN_OPTION", "E_APPLY_INVALID_SUBBLOCK_FIELD"]
@@ -49035,6 +49237,7 @@ var CODE_FILE_REFUSALS = new Map([
49035
49237
  var REFUSABLE_WARNING_CODES = new Set([
49036
49238
  "W_UNKNOWN_OPTION",
49037
49239
  "W_REF_OUT_OF_SCOPE",
49240
+ "W_LOOP_CONDITION_SYNTAX",
49038
49241
  "W_UNKNOWN_OUTPUT_PATH",
49039
49242
  "W_UNRESOLVED_REF",
49040
49243
  "W_CODE_FILE_REF_SYNTAX",
@@ -50568,6 +50771,37 @@ function stableStringify(value) {
50568
50771
  function sha256Hex(text) {
50569
50772
  return bytesToHex(sha256(utf8ToBytes(text)));
50570
50773
  }
50774
+ // ../workflow-code/src/responds.ts
50775
+ function alwaysTakenBranches(block) {
50776
+ const branches = block.branches;
50777
+ if (!branches)
50778
+ return;
50779
+ const rows = branches.rows ?? [];
50780
+ if (branches.kind === "router")
50781
+ return rows.map((row) => row.key);
50782
+ const elseAt = rows.findIndex((row, index) => isElseConditionTitle(storedTitle(branches.kind, row, index, rows.length)));
50783
+ return elseAt === -1 ? [] : rows.slice(0, elseAt + 1).map((row) => row.key);
50784
+ }
50785
+ function portName(port) {
50786
+ return port.kind === "branch" ? `branch:${port.key}` : port.kind;
50787
+ }
50788
+ function respondsOnEveryRun(workflow) {
50789
+ const blocks = {};
50790
+ for (const [key, block] of Object.entries(workflow.blocks)) {
50791
+ const branches = alwaysTakenBranches(block);
50792
+ setOwn(blocks, key, {
50793
+ type: block.type,
50794
+ enabled: block.enabled,
50795
+ parentId: block.parent,
50796
+ ...branches !== undefined && { branches }
50797
+ });
50798
+ }
50799
+ return alwaysEndsAtResponse(blocks, workflow.edges.map((edge) => ({
50800
+ source: edge.from,
50801
+ target: edge.to,
50802
+ port: portName(edge.port)
50803
+ })));
50804
+ }
50571
50805
  // ../workflow-sdk/src/codegen/emit.ts
50572
50806
  function literal(value) {
50573
50807
  return typeof value === "string" ? quoteString(value) : String(value);
@@ -51238,12 +51472,14 @@ function dynamicOutputPlan(spec, outputs, operation) {
51238
51472
  var RUNTIME_SEMANTICS = [
51239
51473
  "## How it runs",
51240
51474
  "",
51241
- "- **Two retries, nested.** An `api` block's `retries`, `retryDelayMs` and `retryMaxDelayMs` repeat the HTTP request inside one run of the block: only after a timeout, a connection reset, a 429 or a 5xx, only for GET, HEAD, PUT and DELETE unless `retryNonIdempotent: true`, with jittered exponential backoff capped at `retryMaxDelayMs` (a `Retry-After` beyond the cap ends the retries). `meta.retry` (`{ enabled, maxTries, waitBetweenTriesMs }`) reruns the whole block, request retries included, after any failure but a stop or a failed child workflow; `maxTries` counts every try. So `retries: 2` under `maxTries: 3` sends up to 9 requests. Only the last try's failure reaches `onError`. Triggers and `human` never retry.",
51475
+ "- **Two retries, nested.** An `api` block's `retries`, `retryDelayMs` and `retryMaxDelayMs` repeat the HTTP request inside one run of the block: only after a timeout, a connection reset, a 429 or a 5xx (a host that does not resolve or refuses the connection fails at once), only for GET, HEAD, PUT and DELETE unless `retryNonIdempotent: true`, with jittered exponential backoff capped at `retryMaxDelayMs` (a `Retry-After` beyond the cap ends the retries). `meta.retry` (`{ enabled, maxTries, waitBetweenTriesMs }`) reruns the whole block, request retries included, after any failure but a stop or a failed child workflow; `maxTries` counts every try. So `retries: 2` under `maxTries: 3` sends up to 9 requests. Only the last try's failure reaches `onError`. Triggers and `human` never retry.",
51242
51476
  "- **`onError`.** `x.onError(y)` makes a failure of `x` an output, `{ error: '<message>' }`, and runs `y` instead of `x`'s other targets; the run goes on. `y` reads the message as `x.error` (only a block with an `onError` edge has it). In a loop or parallel body (`y` must be in the same body) the iteration ends normally and the loop moves to the next item, with that error output as `x`'s entry for the iteration. Without `onError`, a failure in any iteration fails the run and stops the loop.",
51243
- "- **Joins run once.** A block with several incoming edges runs once, after every one of them has fired or been ruled out (a condition or router branch not taken, the normal edge of a block that failed into `onError`). `a.to(join)`, `b.to(join)`, `c.to(join)` wait for all three; behind a condition only the taken branch fires, and the join runs once after it. A block never runs once per incoming branch.",
51477
+ "- **Joins run once.** A block with several incoming edges runs once, after every one of them has fired or been ruled out (a condition or router branch not taken, the normal edge of a block that failed into `onError`). `a.to(join)`, `b.to(join)`, `c.to(join)` wait for all three; behind a condition only the taken branch fires, and the join runs once after it. A block never runs once per incoming branch. A reference to a block that did not run (on the branch not taken) resolves empty: `null` as a whole value, in function code or in a condition, `''` inside text.",
51478
+ "- **Loop and parallel results.** `x.results` holds one entry per iteration (a parallel: per branch), and each entry is the list of outputs of the body blocks that ran in it, in the order they finished. With one block in the body its output is `x.results[i][0]`; `x.results.flat()` lists every output.",
51244
51479
  "- **Outputs in function code.** In `fn` code, `${a.content}` inside js`` is not spliced in as text: it becomes an expression that evaluates to the output's value, a string as a string and an object as an object. Write it where an expression goes (`const reply = ${a.content}`, `[${a.content}, ${b.content}]`) and never wrap it in quotes. Written inside a JavaScript string or template literal it splices in as JSON, quotes included (`'Hi ${a.content}'` gives `Hi \"hello\"`). Python code works the same way.",
51245
51480
  "- **Child workflows.** `const c = runWorkflow('C', { workflowId: childWorkflow('k'), inputMapping })` outputs the child's run as `c.result`: the output of the first `response` block the child reaches, `{ data, status, headers }` (a field of its `body` is `c.result.data.field`), or, with no `response` block, the output of the last block it ran. `c.result` is untyped: wrap a value that should become text in `t`. A deployed run of the parent (API, webhook, schedule, chat) runs the child's deployed version and fails while the child is not deployed; a run from the editor runs the child's draft. A failed child fails `c` (`c.onError(...)` catches it).",
51246
51481
  "- **MCP headers** (`mcp/<key>.ts`). A header value is plain text in which `{{NAME}}` names an env variable anywhere (`Authorization: 'Bearer {{GITHUB_TOKEN}}'`), `env.NAME` for a whole value, or `stored()` to keep the value the server holds. A `t` template or a template literal with `${}` is refused. A credential header (`Authorization`, `Cookie`, or a name with `key`, `token`, `secret`, `auth`, `password`, `session`, `signature` or `credential`) holds nothing but an optional scheme word (`Bearer`, `Basic`, `Token`, `Bot`, `ApiKey`) and `{{NAME}}` references (`E_MCP_LITERAL_SECRET`). The variables resolve when the server connects, from the personal and workspace env (the workspace value wins); a missing one fails the connection.",
51482
+ "- **Table rows are keyed by column name.** A Table block's `data` (and `conflictColumn`, and a filter's `field`) names each column by its name: its key in `tables/<key>.ts`, or the `name` set there (`phone: column.string({ name: 'mobile' })` is written `{ mobile: … }`). A key naming no column is dropped from the row at run time; `check` and `apply` warn on it (`W_TABLE_UNKNOWN_COLUMN`). A table's `rows.jsonl` is the exception: it is keyed by column key.",
51247
51483
  "- **MCP tool names are checked late.** `mcp('k').tool('name')` is type-checked only when `workspace.d.ts` lists that server's tools; a server that could not be listed, or one declared but not yet applied, takes any name. `sim workflows source check` and `sim workflows source apply` do not check tool names (the apply checks only that the server exists). `sim workspaces source apply` checks the tools of each workflow it changes against the server's live listing (`E_MCP_TOOL_UNKNOWN`, or `W_MCP_TOOLS_UNCHECKED` when it cannot list the server). Otherwise a wrong name surfaces at run time: the agent block fails before the model runs, `MCP operation \"name\" is missing or not permitted`.",
51248
51484
  ""
51249
51485
  ];
@@ -51833,6 +52069,7 @@ function describeBuilder(catalog, key) {
51833
52069
  summary: types.summary,
51834
52070
  ...entry.builder.operation ? { operation: entry.builder.operation } : {},
51835
52071
  legacy: isLegacyBuilder(key),
52072
+ ...entry.special ? docOf(key) : {},
51836
52073
  signature,
51837
52074
  tool,
51838
52075
  paramsName: types.paramsName,
@@ -51856,28 +52093,47 @@ function lookupBuilder(catalog, query) {
51856
52093
  if (SDK_CORE_EXPORTS.includes(root)) {
51857
52094
  return { kind: "core", name: key, declaration: coreDeclaration(root) };
51858
52095
  }
52096
+ const ofBlockType = paths.filter((path) => catalogBuilder(catalog, path)?.type === key);
52097
+ const only = ofBlockType.length === 1 ? describeBuilder(catalog, ofBlockType[0]) : null;
52098
+ if (only)
52099
+ return { kind: "builder", reference: only };
52100
+ if (ofBlockType.length > 1) {
52101
+ return {
52102
+ kind: "namespace",
52103
+ namespace: key,
52104
+ builders: ofBlockType.map((path) => ({ key: path, summary: summaryOf(catalog, path) }))
52105
+ };
52106
+ }
51859
52107
  const hint = suggestBuilder(key, paths.filter((path) => !isLegacyBuilder(path)));
51860
52108
  return hint ? { kind: "missing", hint } : { kind: "missing" };
51861
52109
  }
51862
52110
  var MAX_CORE_LINES = 80;
51863
- function coreDeclarationRanges(name) {
51864
- const lines = CORE_DTS.split(`
52111
+ var CORE_LINES = CORE_DTS.split(`
51865
52112
  `);
52113
+ function docCommentStart(start) {
52114
+ if (!CORE_LINES[start - 1]?.trim().endsWith("*/"))
52115
+ return start;
52116
+ let first = start - 1;
52117
+ while (first > 0 && !CORE_LINES[first].trim().startsWith("/**"))
52118
+ first--;
52119
+ return first;
52120
+ }
52121
+ function coreDeclarationRanges(name) {
51866
52122
  const start = new RegExp(`^export (?:declare )?(?:const|function|namespace|interface|type) ${escapeRegExp(name)}\\b`);
51867
52123
  const declarations = [];
51868
- for (let index = 0;index < lines.length; index++) {
51869
- if (!start.test(lines[index]))
52124
+ for (let index = 0;index < CORE_LINES.length; index++) {
52125
+ if (!start.test(CORE_LINES[index]))
51870
52126
  continue;
51871
52127
  let depth = 0;
51872
52128
  let end = index;
51873
- for (;end < lines.length; end++) {
51874
- for (const char of lines[end]) {
52129
+ for (;end < CORE_LINES.length; end++) {
52130
+ for (const char of CORE_LINES[end]) {
51875
52131
  if ("({[".includes(char))
51876
52132
  depth++;
51877
52133
  else if (")}]".includes(char))
51878
52134
  depth--;
51879
52135
  }
51880
- const continues = /[=:,|&]\s*$/.test(lines[end]) || /^\s+[?:|&]/.test(lines[end + 1] ?? "");
52136
+ const continues = /[=:,|&]\s*$/.test(CORE_LINES[end]) || /^\s+[?:|&]/.test(CORE_LINES[end + 1] ?? "");
51881
52137
  if (depth <= 0 && !continues)
51882
52138
  break;
51883
52139
  }
@@ -51887,28 +52143,26 @@ function coreDeclarationRanges(name) {
51887
52143
  return declarations;
51888
52144
  }
51889
52145
  function coreSignatures(name) {
51890
- const lines = CORE_DTS.split(`
51891
- `);
51892
- return coreDeclarationRanges(name).map(({ start, end }) => lines.slice(start, end).join(" ").replace(/^export (?:declare )?function /, "").replace(/\s+/g, " ").replace(/([(<]) /g, "$1").replace(/,? ([)>])/g, "$1").trim()).join(`
52146
+ return coreDeclarationRanges(name).map(({ start, end }) => CORE_LINES.slice(start, end).join(" ").replace(/^export (?:declare )?function /, "").replace(/\s+/g, " ").replace(/([(<]) /g, "$1").replace(/,? ([)>])/g, "$1").trim()).join(`
51893
52147
  `);
51894
52148
  }
51895
52149
  function coreDeclaration(name) {
51896
- const lines = CORE_DTS.split(`
51897
- `);
51898
52150
  const out = [];
51899
52151
  for (const { start, end } of coreDeclarationRanges(name)) {
51900
- let first = start;
51901
- if (lines[start - 1]?.trim().endsWith("*/")) {
51902
- while (first > 0 && !lines[first].trim().startsWith("/**"))
51903
- first--;
51904
- }
51905
52152
  if (out.length > 0)
51906
52153
  out.push("");
51907
- out.push(...lines.slice(first, end));
52154
+ out.push(...CORE_LINES.slice(docCommentStart(start), end));
51908
52155
  }
51909
52156
  return out.slice(0, MAX_CORE_LINES).join(`
51910
52157
  `);
51911
52158
  }
52159
+ function docOf(name) {
52160
+ const range = coreDeclarationRanges(name)[0];
52161
+ if (!range)
52162
+ return {};
52163
+ const doc = CORE_LINES.slice(docCommentStart(range.start), range.start).map((line) => line.trim().replace(/^\/\*\*\s?|\s?\*\/$|^\*\s?/g, "")).join(" ").replace(/\s+/g, " ").trim();
52164
+ return doc ? { doc } : {};
52165
+ }
51912
52166
  var MAX_SNIPPET_TYPE = 60;
51913
52167
  var MAX_SNIPPET_OPTIONAL = 12;
51914
52168
  function shortType(type) {
@@ -51999,6 +52253,8 @@ function renderBuilderReference(reference) {
51999
52253
  if (reference.legacy) {
52000
52254
  lines.push("Legacy: an older block version. Write the current builder instead.");
52001
52255
  }
52256
+ if (reference.doc)
52257
+ lines.push("", reference.doc);
52002
52258
  lines.push("", reference.signature);
52003
52259
  if (reference.tool)
52004
52260
  lines.push(`${reference.tool} (as an agent tool)`);
@@ -52246,12 +52502,13 @@ Write like a person, not a policy. Lead with the answer, then the one detail tha
52246
52502
  import { column, defineTable } from '@sim/workflow-sdk/workspace'
52247
52503
 
52248
52504
  // tables/<key>.ts: the key (\`orders\`) is how a workflow names it: table('orders'). Its rows stay
52249
- // out of source (see plans.ts to opt in). To rename a column keep its key and set \`name\`.
52505
+ // out of source (see plans.ts to opt in). To rename a column keep its key and set \`name\`: a
52506
+ // workflow's row data (\`data\`, \`conflictColumn\`, filters) names a column by that name, not its key.
52250
52507
  export default defineTable({
52251
52508
  name: 'orders',
52252
52509
  description: 'Order questions the support workflow answered',
52253
52510
  columns: {
52254
- orderId: column.string({ required: true }),
52511
+ orderId: column.string({ required: true, unique: true }),
52255
52512
  status: column.select({ options: ['open', 'answered'] }),
52256
52513
  total: column.number(),
52257
52514
  },
@@ -52330,9 +52587,10 @@ export default workflow('Support', { description: 'Answers an order question.' }
52330
52587
  tools: [customTool('lookup-order')],
52331
52588
  skills: [skill('tone')],
52332
52589
  })
52333
- const log = table.insertRow('Log Question', {
52590
+ const log = table.upsertRow('Log Question', {
52334
52591
  tableId: table('orders'),
52335
52592
  data: { orderId: start.orderId, status: 'answered' },
52593
+ conflictColumn: 'orderId',
52336
52594
  })
52337
52595
 
52338
52596
  start.to(policy)
@@ -53845,7 +54103,7 @@ async function withSourceCommandLock(dir, run, options = {}) {
53845
54103
  return withSourceDirLock(folder ? folder.root : dir, run, options);
53846
54104
  }
53847
54105
  // ../workflow-code/src/code-files/references.ts
53848
- var import_parser4 = __toESM(require_lib(), 1);
54106
+ var import_parser5 = __toESM(require_lib(), 1);
53849
54107
  var CODE_FILE_EXPORT = "codeFile";
53850
54108
  function codeFileReferences(text) {
53851
54109
  if (utf8Bytes(text, SOURCE_LIMITS.maxTotalBytes) > SOURCE_LIMITS.maxTotalBytes)
@@ -53854,7 +54112,7 @@ function codeFileReferences(text) {
53854
54112
  return [];
53855
54113
  let program;
53856
54114
  try {
53857
- program = import_parser4.parse(text, PARSER_OPTIONS).program;
54115
+ program = import_parser5.parse(text, PARSER_OPTIONS).program;
53858
54116
  } catch {
53859
54117
  return [];
53860
54118
  }
@@ -54070,6 +54328,10 @@ function loopRows(rows) {
54070
54328
  return rows.map(([command, what]) => ` ${command.padEnd(width)}${what}`.trimEnd()).join(`
54071
54329
  `);
54072
54330
  }
54331
+ var WORKSPACE_LINE = `Workspace: a directory records it (.sim/base.json, or a starter's .sim/starter.json); any other
54332
+ command takes -w <id>, SIM_WORKSPACE or the profile's (export SIM_WORKSPACE once, or keep only the
54333
+ ID in a variable: one holding "--workspace <id>" is one argument, an unknown option alone and the
54334
+ whole ID after -w).`;
54073
54335
  function statusLine(group, dir) {
54074
54336
  return `\`${group} status --dir ${dir}\` shows what applying would do and
54075
54337
  whether the server changed since the get (exit 0 clean, ${SOURCE_LOCAL_CHANGES_EXIT_CODE} your edits only, ${SOURCE_DRIFT_EXIT_CODE} the server changed).
@@ -54088,6 +54350,7 @@ ${loopRows([
54088
54350
  A new workflow: \`sim workflows source create --dir ./new --workspace <workspaceId>\` writes a
54089
54351
  starter that records its workspace; edit and check it, then \`create --dir ./new --yes\` creates the
54090
54352
  workflow there, and the loop above goes on from there.
54353
+ ${WORKSPACE_LINE}
54091
54354
 
54092
54355
  Flags the loop needs: --allow-delete (apply: an edit that removes a block or variable is refused
54093
54356
  without it), --deploy (apply, create: also deploy the saved draft), --force (get: replace another
@@ -54105,6 +54368,7 @@ ${loopRows([
54105
54368
  ])}
54106
54369
  Promote dev to prod: \`sim workspaces source apply --dir ./ws --to <workspaceId> --dry-run\`, then
54107
54370
  --yes.
54371
+ ${WORKSPACE_LINE}
54108
54372
 
54109
54373
  Flags the loop needs: --allow-delete (apply: removing a resource, a column, rows or a document,
54110
54374
  or a workflow's block or variable, is refused without it), --force (get: replace edits no apply
@@ -54398,6 +54662,112 @@ async function printRunFailureSite(dir, workflowId, error) {
54398
54662
  ]);
54399
54663
  }
54400
54664
 
54665
+ // src/commands/protocol/workflow-run-get.ts
54666
+ var BLOCK_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
54667
+ var SELECT_OUTPUT_FLAG = "select-output";
54668
+ function normalizeBlockName(name) {
54669
+ return name.toLowerCase().replace(/\s+/g, "").replace(/\./g, "");
54670
+ }
54671
+ async function loadWorkflowBlocks(client, workflowId) {
54672
+ const raw = await client.request("getWorkflowState", { params: { workflowId } });
54673
+ const state = isRecordLike(raw) && isRecordLike(raw.data) ? raw.data : raw;
54674
+ const blocks = isRecordLike(state) && isRecordLike(state.blocks) ? Object.entries(state.blocks) : [];
54675
+ return blocks.map(([key, block]) => ({
54676
+ id: isRecordLike(block) && typeof block.id === "string" ? block.id : key,
54677
+ name: isRecordLike(block) && typeof block.name === "string" ? block.name : ""
54678
+ }));
54679
+ }
54680
+ function splitSelector(selector) {
54681
+ const dot = selector.indexOf(".");
54682
+ return dot === -1 ? { head: selector, path: "" } : { head: selector.slice(0, dot), path: selector.slice(dot) };
54683
+ }
54684
+ function isIdHeaded(selector) {
54685
+ return BLOCK_ID.test(splitSelector(selector).head);
54686
+ }
54687
+ function resolveSelection(typed, blocks, workflowId) {
54688
+ const resolved = [];
54689
+ const typedBy = new Map;
54690
+ const unresolved = [];
54691
+ for (const selector of typed) {
54692
+ const { head, path } = splitSelector(selector);
54693
+ let blockId = head;
54694
+ if (!BLOCK_ID.test(head)) {
54695
+ const wanted = normalizeBlockName(head);
54696
+ const matches = blocks.filter((block) => block.id === head || normalizeBlockName(block.name) === wanted);
54697
+ if (matches.length === 0) {
54698
+ unresolved.push(selector);
54699
+ continue;
54700
+ }
54701
+ if (matches.length > 1) {
54702
+ throw new SimApiError(`--${SELECT_OUTPUT_FLAG} ${selector} names ${matches.length} blocks (${matches.map((block) => block.id).join(", ")}); pass the block id instead`, 0);
54703
+ }
54704
+ blockId = matches[0].id;
54705
+ }
54706
+ const rewritten = `${blockId}${path}`;
54707
+ resolved.push(rewritten);
54708
+ if (!typedBy.has(rewritten))
54709
+ typedBy.set(rewritten, selector);
54710
+ }
54711
+ if (unresolved.length > 0) {
54712
+ const names = blocks.map((block) => block.name).filter((name) => name !== "");
54713
+ throw new SimApiError(`--${SELECT_OUTPUT_FLAG} did not resolve to any block on this run: ${unresolved.join(", ")}. Pass a block id or its name — "blockId", "blockId.path", "blockName" or "blockName.path"; names match ignoring case, spaces and dots. Blocks on workflow ${workflowId}: ${names.length > 0 ? names.join(", ") : "none"}.`, 0);
54714
+ }
54715
+ return { resolved, typedBy };
54716
+ }
54717
+ function keyByTyped(payload, typedBy) {
54718
+ if (!isRecordLike(payload) || !isRecordLike(payload.blockOutputs))
54719
+ return payload;
54720
+ const blockOutputs = {};
54721
+ for (const [key, value] of Object.entries(payload.blockOutputs)) {
54722
+ blockOutputs[typedBy.get(key) ?? key] = value;
54723
+ }
54724
+ return { ...payload, blockOutputs };
54725
+ }
54726
+ async function readRunByName(runId, typed, command, { client, profile }) {
54727
+ const flags = command.optsWithGlobals();
54728
+ const operation = V2_OPERATIONS.getWorkflowRun;
54729
+ const spec = CLI_CONTRACT.getWorkflowRun ?? {};
54730
+ await buildRequest("getWorkflowRun", [runId], flags, profile.workspaceId);
54731
+ const workflowId = String(flags.workflow);
54732
+ const selection = resolveSelection(typed, await loadWorkflowBlocks(client, workflowId), workflowId);
54733
+ const request = await buildRequest("getWorkflowRun", [runId], { ...flags, selectOutput: selection.resolved }, profile.workspaceId);
54734
+ let result;
54735
+ try {
54736
+ result = await client.request("getWorkflowRun", {
54737
+ params: request.params,
54738
+ headers: request.headers,
54739
+ query: request.query,
54740
+ body: request.body
54741
+ });
54742
+ } catch (error) {
54743
+ throw retypeApiError(error, "getWorkflowRun", spec, operation);
54744
+ }
54745
+ renderResult("getWorkflowRun", profile.output, keyByTyped(result?.data ?? result, selection.typedBy), spec, {}, result);
54746
+ }
54747
+ function attachWorkflowRunGet(runs) {
54748
+ const get = runs.commands.find((command) => command.name() === "get");
54749
+ const held = get?._actionHandler;
54750
+ if (!get || typeof held !== "function") {
54751
+ throw new Error("workflows runs get must be registered before block names can be attached to it");
54752
+ }
54753
+ const previous = held;
54754
+ const connectGet = callsOperations(get, ["getWorkflowRun", "getWorkflowState"]);
54755
+ get.action(async (runId, _options, command) => {
54756
+ const raw = command.optsWithGlobals().selectOutput;
54757
+ if (raw === undefined) {
54758
+ await previous(command.processedArgs);
54759
+ return;
54760
+ }
54761
+ const typed = await readListValues(raw, SELECT_OUTPUT_FLAG);
54762
+ command.setOptionValue("selectOutput", typed);
54763
+ if (typed.every(isIdHeaded)) {
54764
+ await previous(command.processedArgs);
54765
+ return;
54766
+ }
54767
+ await readRunByName(runId, typed, command, connectGet());
54768
+ });
54769
+ }
54770
+
54401
54771
  // src/commands/protocol/workflow-run-wait.ts
54402
54772
  var TERMINAL_STATUSES = new Set(["completed", "failed", "cancelled"]);
54403
54773
  var WAIT_EXIT_CODES = {
@@ -54831,6 +55201,14 @@ async function followRun(workflowId, command) {
54831
55201
  throw new SimApiError(safeOneLine(typeof final.error === "string" ? final.error : "The workflow run failed."), 0);
54832
55202
  }
54833
55203
  }
55204
+ function stopBlockSelection(selection, flags) {
55205
+ const stopAfter = selection?.stopAfterBlockId;
55206
+ if (stopAfter === undefined)
55207
+ return null;
55208
+ if (Array.isArray(flags.selectOutput) && flags.selectOutput.length > 0)
55209
+ return null;
55210
+ return [BLOCK_ID.test(stopAfter) ? stopAfter : normalizeBlockName(stopAfter)];
55211
+ }
54834
55212
  function followOrDelegate(previous) {
54835
55213
  return async (workflowId, _options, command) => {
54836
55214
  const initialFlags = command.optsWithGlobals();
@@ -54848,6 +55226,9 @@ function followOrDelegate(previous) {
54848
55226
  if (selection)
54849
55227
  command.setOptionValue("run", selection);
54850
55228
  const flags = command.optsWithGlobals();
55229
+ const stopBlock = stopBlockSelection(selection, flags);
55230
+ if (stopBlock)
55231
+ command.setOptionValue("selectOutput", stopBlock);
54851
55232
  if (flags.follow !== true) {
54852
55233
  if (Array.isArray(flags.selectOutput) && flags.selectOutput.length > 0 && flags.async === true) {
54853
55234
  throw new SimApiError("--select-output names outputs of a completed run, and --async returns as soon as the run is queued. Drop one of them, or read the finished run with: sim workflows runs get <runId> --workflow <workflowId> --select-output <blockName|blockId>[.path] — that resource takes the same selectors --select-output takes here.", 0);
@@ -54869,6 +55250,18 @@ function followOrDelegate(previous) {
54869
55250
  await followRun(workflowId, command);
54870
55251
  };
54871
55252
  }
55253
+ var RUN_HELP = `
55254
+ Without --manual (or a flag that implies it) this runs the active deployment; a workflow never
55255
+ deployed has none. --manual runs the saved draft, as the source loop leaves it.
55256
+
55257
+ The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the
55258
+ workflow's final output) and blockOutputs (what --select-output named). It has no success field:
55259
+ branch on status, or on the exit code. With --follow it is the stream's final frame
55260
+ instead: success and output.
55261
+
55262
+ Exit codes: 0 completed or paused (--async: queued); 1 failed or cancelled (the result is printed
55263
+ first, then the error on stderr), or the command failed; ${STILL_RUNNING_EXIT_CODE} still running when --wait-timeout
55264
+ elapsed.`;
54872
55265
  function attachWorkflowRunFollow(workflows) {
54873
55266
  const run = workflows.commands.find((command) => command.name() === "run");
54874
55267
  if (!run) {
@@ -54877,113 +55270,7 @@ function attachWorkflowRunFollow(workflows) {
54877
55270
  const held = run._actionHandler;
54878
55271
  const previous = typeof held === "function" ? held : null;
54879
55272
  callsOperations(run, ["executeWorkflow", "getWorkflowRun"], { runs: "executeWorkflow" });
54880
- run.option("--manual", "Run the current saved workflow state instead of the active deployment").option("--trigger <blockId>", "Enter the run through this runnable trigger, by its block id; runs the current saved workflow state (implies --manual)").option("--mock-payload", "Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual)").option("--from-block <block>", "Run manually from this saved workflow block: its id, display name or key").option("--source-run <runId>", "Prior run whose persisted state supplies upstream outputs (requires --from-block)").option("--stop-after <block>", "Stop the run after this saved block (its id, display name or key), failing it if the run takes a path that skips the block; with --from-block on the same block, re-runs only that block (implies --manual)").option("--dir <dir>", "This workflow's source directory: a failed run names the source file and line of the block that failed, read through its .sim/lock.json. Not with --async or --follow, and not for a run --wait-timeout leaves running").option(WAIT_TIMEOUT_FLAG, "Wait at most this many seconds for a synchronous run (0 waits until it settles). A run still going then continues in the background under async limits: the command prints its run record and exits 4, and `sim workflows runs wait` keeps waiting. Not with --async or --follow").option("--follow", "Stream the run as it happens; progress on stderr, result on stdout. The stream reports only success and output, so the result omits the run id and timings a non-streaming run returns").option("--include-thinking", "Show model reasoning while following (requires --follow)").option("--include-tool-calls", "Show tool calls while following (requires --follow)").action(followOrDelegate(previous));
54881
- }
54882
-
54883
- // src/commands/protocol/workflow-run-get.ts
54884
- var BLOCK_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
54885
- var SELECT_OUTPUT_FLAG = "select-output";
54886
- function normalizeBlockName(name) {
54887
- return name.toLowerCase().replace(/\s+/g, "").replace(/\./g, "");
54888
- }
54889
- async function loadWorkflowBlocks(client, workflowId) {
54890
- const raw = await client.request("getWorkflowState", { params: { workflowId } });
54891
- const state = isRecordLike(raw) && isRecordLike(raw.data) ? raw.data : raw;
54892
- const blocks = isRecordLike(state) && isRecordLike(state.blocks) ? Object.entries(state.blocks) : [];
54893
- return blocks.map(([key, block]) => ({
54894
- id: isRecordLike(block) && typeof block.id === "string" ? block.id : key,
54895
- name: isRecordLike(block) && typeof block.name === "string" ? block.name : ""
54896
- }));
54897
- }
54898
- function splitSelector(selector) {
54899
- const dot = selector.indexOf(".");
54900
- return dot === -1 ? { head: selector, path: "" } : { head: selector.slice(0, dot), path: selector.slice(dot) };
54901
- }
54902
- function isIdHeaded(selector) {
54903
- return BLOCK_ID.test(splitSelector(selector).head);
54904
- }
54905
- function resolveSelection(typed, blocks, workflowId) {
54906
- const resolved = [];
54907
- const typedBy = new Map;
54908
- const unresolved = [];
54909
- for (const selector of typed) {
54910
- const { head, path } = splitSelector(selector);
54911
- let blockId = head;
54912
- if (!BLOCK_ID.test(head)) {
54913
- const wanted = normalizeBlockName(head);
54914
- const matches = blocks.filter((block) => block.id === head || normalizeBlockName(block.name) === wanted);
54915
- if (matches.length === 0) {
54916
- unresolved.push(selector);
54917
- continue;
54918
- }
54919
- if (matches.length > 1) {
54920
- throw new SimApiError(`--${SELECT_OUTPUT_FLAG} ${selector} names ${matches.length} blocks (${matches.map((block) => block.id).join(", ")}); pass the block id instead`, 0);
54921
- }
54922
- blockId = matches[0].id;
54923
- }
54924
- const rewritten = `${blockId}${path}`;
54925
- resolved.push(rewritten);
54926
- if (!typedBy.has(rewritten))
54927
- typedBy.set(rewritten, selector);
54928
- }
54929
- if (unresolved.length > 0) {
54930
- const names = blocks.map((block) => block.name).filter((name) => name !== "");
54931
- throw new SimApiError(`--${SELECT_OUTPUT_FLAG} did not resolve to any block on this run: ${unresolved.join(", ")}. Pass a block id or its name — "blockId", "blockId.path", "blockName" or "blockName.path"; names match ignoring case, spaces and dots. Blocks on workflow ${workflowId}: ${names.length > 0 ? names.join(", ") : "none"}.`, 0);
54932
- }
54933
- return { resolved, typedBy };
54934
- }
54935
- function keyByTyped(payload, typedBy) {
54936
- if (!isRecordLike(payload) || !isRecordLike(payload.blockOutputs))
54937
- return payload;
54938
- const blockOutputs = {};
54939
- for (const [key, value] of Object.entries(payload.blockOutputs)) {
54940
- blockOutputs[typedBy.get(key) ?? key] = value;
54941
- }
54942
- return { ...payload, blockOutputs };
54943
- }
54944
- async function readRunByName(runId, typed, command, { client, profile }) {
54945
- const flags = command.optsWithGlobals();
54946
- const operation = V2_OPERATIONS.getWorkflowRun;
54947
- const spec = CLI_CONTRACT.getWorkflowRun ?? {};
54948
- await buildRequest("getWorkflowRun", [runId], flags, profile.workspaceId);
54949
- const workflowId = String(flags.workflow);
54950
- const selection = resolveSelection(typed, await loadWorkflowBlocks(client, workflowId), workflowId);
54951
- const request = await buildRequest("getWorkflowRun", [runId], { ...flags, selectOutput: selection.resolved }, profile.workspaceId);
54952
- let result;
54953
- try {
54954
- result = await client.request("getWorkflowRun", {
54955
- params: request.params,
54956
- headers: request.headers,
54957
- query: request.query,
54958
- body: request.body
54959
- });
54960
- } catch (error) {
54961
- throw retypeApiError(error, "getWorkflowRun", spec, operation);
54962
- }
54963
- renderResult("getWorkflowRun", profile.output, keyByTyped(result?.data ?? result, selection.typedBy), spec, {}, result);
54964
- }
54965
- function attachWorkflowRunGet(runs) {
54966
- const get = runs.commands.find((command) => command.name() === "get");
54967
- const held = get?._actionHandler;
54968
- if (!get || typeof held !== "function") {
54969
- throw new Error("workflows runs get must be registered before block names can be attached to it");
54970
- }
54971
- const previous = held;
54972
- const connectGet = callsOperations(get, ["getWorkflowRun", "getWorkflowState"]);
54973
- get.action(async (runId, _options, command) => {
54974
- const raw = command.optsWithGlobals().selectOutput;
54975
- if (raw === undefined) {
54976
- await previous(command.processedArgs);
54977
- return;
54978
- }
54979
- const typed = await readListValues(raw, SELECT_OUTPUT_FLAG);
54980
- command.setOptionValue("selectOutput", typed);
54981
- if (typed.every(isIdHeaded)) {
54982
- await previous(command.processedArgs);
54983
- return;
54984
- }
54985
- await readRunByName(runId, typed, command, connectGet());
54986
- });
55273
+ run.option("--manual", "Run the current saved workflow state instead of the active deployment").option("--trigger <blockId>", "Enter the run through this runnable trigger, by its block id; runs the current saved workflow state (implies --manual)").option("--mock-payload", "Use the selected trigger's server-derived mock payload; runs the current saved workflow state (implies --manual)").option("--from-block <block>", "Run manually from this saved workflow block: its id, display name or key").option("--source-run <runId>", "Prior run whose persisted state supplies upstream outputs (requires --from-block)").option("--stop-after <block>", "Stop the run after this saved block (its id, display name or key), failing it if the run takes a path that skips the block; with --from-block on the same block, re-runs only that block (implies --manual). Unless --select-output names others, blockOutputs holds the output of that block under its key (or id); output stays empty").option("--dir <dir>", "This workflow's source directory: a failed run names the source file and line of the block that failed, read through its .sim/lock.json. Not with --async or --follow, and not for a run --wait-timeout leaves running").option(WAIT_TIMEOUT_FLAG, "Wait at most this many seconds for a synchronous run (0 waits until it settles). A run still going then continues in the background under async limits: the command prints its run record and exits 4, and `sim workflows runs wait` keeps waiting. Not with --async or --follow").option("--follow", "Stream the run as it happens; progress on stderr, result on stdout. The stream reports only success and output, so the result omits the run id and timings a non-streaming run returns").option("--include-thinking", "Show model reasoning while following (requires --follow)").option("--include-tool-calls", "Show tool calls while following (requires --follow)").addHelpText("after", RUN_HELP).action(followOrDelegate(previous));
54987
55274
  }
54988
55275
 
54989
55276
  // ../../node_modules/minisearch/dist/es/index.js
@@ -56199,7 +56486,7 @@ function sourceExitCodeRows(prefix) {
56199
56486
  "workflows source apply": "the source has errors (each printed as file:line:column with its frame and hint) or the command failed",
56200
56487
  "workflows source create": "the source has errors (each printed as file:line:column with its frame and hint), the workflow name is taken (SOURCE_NAME_TAKEN: pass --name), or the command failed (a starter is created in the workspace its types were written for unless --workspace names another)",
56201
56488
  "workflows source get": "the command failed, the directory is a workspace source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or it holds another workflow's source (SOURCE_WORKFLOW_MISMATCH) or edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force)",
56202
- "workspaces source apply": "the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run that would hold changes back exits 1 too), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed",
56489
+ "workspaces source apply": "the source has errors (each printed as file:line:column with its frame and hint), or every change it would write was held back because it uses a declared secret the workspace has no value for or a declared credential key nothing binds to (nothing was written; a dry run of such an apply exits 1 too), the directory was read from another workspace than the one --workspace names (SOURCE_OTHER_WORKSPACE: drop --workspace, or promote it with --to; without --workspace an apply targets the workspace the directory was read from), its base records binary files no get downloaded (SOURCE_BLOBS_NOT_FETCHED: get again first), or the command failed",
56203
56490
  "workspaces source get": "the command failed, the directory holds edits no apply has saved (SOURCE_LOCAL_EDITS: apply them, get into another directory, or pass --force), --workspace names another workspace than the one the directory was read from (SOURCE_OTHER_WORKSPACE), the directory is a workflow source directory (SOURCE_DIR_KIND_MISMATCH, even with --force), or a downloaded binary file does not match its listing (SOURCE_BLOB_MISMATCH: nothing was written)"
56204
56491
  }
56205
56492
  },
@@ -56299,10 +56586,10 @@ function sourceExitCodeRows(prefix) {
56299
56586
  },
56300
56587
  {
56301
56588
  code: SOURCE_HELD_EXIT_CODE,
56302
- meaning: "`sim workspaces source apply` (or `--to`) wrote part of its plan and held the rest back: a change that uses a declared secret the workspace has no value for, or a credential key nothing binds to",
56589
+ meaning: "`sim workspaces source apply` (or `--to`) wrote part of its plan and held the rest back: a change that uses a declared secret the workspace has no value for, or a credential key nothing binds to. Its dry run exits 15 too, so a script can tell beforehand that the apply would write only part",
56303
56590
  next: "Set the secret (`sim secrets set`) or connect the credential, then apply again",
56304
56591
  help: {
56305
- "workspaces source apply": "written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again)"
56592
+ "workspaces source apply": "written in part: changes that use a declared secret the workspace has no value for, or a declared credential key nothing binds to, were held back and the rest was applied and saved (set the secret or connect the credential, then apply again); a dry run that would do so exits 15 too, having written nothing"
56306
56593
  }
56307
56594
  },
56308
56595
  {
@@ -56381,14 +56668,14 @@ var WORKFLOW_PRIMER = `# Sim workflow source: primer
56381
56668
  - **Deploy**: apply saves a draft; \`apply --deploy\` also deploys it, or \`sim workflows deploy <workflowId>\` publishes the saved draft later.
56382
56669
  ${sharedRules("sim workflows source")}
56383
56670
  `;
56384
- var WORKSPACE_RENAMES = " A column: change its `name`, keep its key (cells stay); Table blocks using the old name are not rewritten (`W_TABLE_COLUMN_RENAMED_IN_USE`). A file's key never changes (`E_KEY_RENAMED`): rename by `name`.";
56671
+ var WORKSPACE_RENAMES = " A column: change its `name`, keep its key (cells stay). Table blocks (`data`, `conflictColumn`, filters) use the name, not the key, and keep old names (`W_TABLE_COLUMN_RENAMED_IN_USE`). A file's key never changes (`E_KEY_RENAMED`): rename by `name`.";
56385
56672
  var WORKSPACE_PRIMER = `# Sim workspace source: primer
56386
56673
 
56387
- This directory is a Sim workspace as files (\`tables/\`, \`workflows/<key>/workflow.ts\`, …); read statically; nothing runs. Commands read the workspace id from \`${SOURCE_BASE_FILE}\`; run them from this directory.
56674
+ This directory is a Sim workspace as files (\`tables/\`, \`workflows/<key>/workflow.ts\`, …); nothing in it runs. Commands read the workspace id from \`${SOURCE_BASE_FILE}\`; run them from this directory.
56388
56675
 
56389
56676
  **Edit loop**: edit the files → \`sim workspaces source check --dir .\` (offline; refreshes \`workspace.d.ts\` and \`tsconfig.json\`) → \`${typecheckCommand()}\` → \`sim workspaces source apply --dir . --dry-run\` → \`--yes\`. Rerun each step until it exits 0. Apply rewrites the directory from what it stored: read a file again before the next edit.
56390
56677
 
56391
- - **Deletes**: a removed file (a resource this directory managed), table column, workflow block or workflow variable is deleted only with \`apply --allow-delete\` (else refused), and cannot be undone. A kind is managed only when its folder exists.
56678
+ - **Deletes**: a removed file (a resource this directory managed), table column, workflow block or variable is deleted only with \`apply --allow-delete\` and cannot be undone. A kind is managed only when its folder exists.
56392
56679
  - **Deploy**: \`deployments/<workflow key>.ts\` (\`defineDeployment({ live: 'draft' })\`) deploys that workflow on apply, which prints its webhook URLs; without one, apply never deploys.
56393
56680
  - **Promote** (dev → prod): \`sim workspaces source apply --dir . --to <workspaceId> --dry-run\`, then \`--yes\`.
56394
56681
  - **Exit ${SOURCE_HELD_EXIT_CODE}**: written in part; changes using an unset secret or unbound credential were held back: set it, apply again.
@@ -57067,7 +57354,7 @@ async function runSourceWrite(flow) {
57067
57354
  preview = await flow.preview();
57068
57355
  flow.show(preview);
57069
57356
  if (preview.diagnostics.some((finding) => finding.severity === "error")) {
57070
- setSoftExitCode(refusedExitCode(preview.diagnostics));
57357
+ setSoftExitCode(flow.previewExitCode?.(preview) ?? refusedExitCode(preview.diagnostics));
57071
57358
  }
57072
57359
  if (flow.mode === "dry-run" || flow.refuses(preview)) {
57073
57360
  flow.report(preview);
@@ -57267,12 +57554,18 @@ async function readBase(directory, workflowId) {
57267
57554
  }
57268
57555
  return base;
57269
57556
  }
57557
+ var WORKFLOW_GET = `\`sim workflows source get <workflowId> --dir <new dir>\`, with the id from ${SOURCE_BASE_FILE}`;
57558
+ function lockRecoveryHint(get = WORKFLOW_GET) {
57559
+ return `Restore ${SOURCE_LOCK_FILE} from version control, or write the source into a fresh directory (${get}) and carry your edits across.`;
57560
+ }
57561
+ function lockProblem(finding) {
57562
+ return `${finding.path ? `${finding.path}: ` : ""}${finding.message}`;
57563
+ }
57270
57564
  async function readLock(directory) {
57271
57565
  const parsed = parseWorkflowLock(await readJson(directory, SOURCE_LOCK_FILE, GET_HINT));
57272
57566
  if (parsed.lock)
57273
57567
  return parsed.lock;
57274
- const problems = parsed.diagnostics.map((finding) => `${finding.path === "" ? "" : `${finding.path}: `}${finding.message}`);
57275
- throw new SourceDirError(`${SOURCE_LOCK_FILE} in ${directory} is not a valid lock: ${problems.join("; ")}`);
57568
+ throw new SourceDirError(`${SOURCE_LOCK_FILE} in ${directory} is not a valid lock: ${parsed.diagnostics.map(lockProblem).join("; ")}. ${lockRecoveryHint()}`);
57276
57569
  }
57277
57570
  function requireEntry(directory) {
57278
57571
  return requireText(directory, SOURCE_ENTRY_FILE, GET_HINT);
@@ -57311,7 +57604,7 @@ The primer above is enough to edit; read a section here when a step needs it.
57311
57604
 
57312
57605
  ## Edit loop in detail
57313
57606
 
57314
- 1. Edit \`${SOURCE_ENTRY_FILE}\` (and \`functions/*\`). \`${SOURCE_EXAMPLES_DIR}/\` holds correct examples to copy from: \`cookbook.ts\` (agent with structured output, condition, function, table query and insert, knowledge search, Slack, human in the loop, loop, response), \`integrations.ts\` (webhook trigger, weekday cron schedule, HTTP request with headers, table update by row id, Gmail, an error path) and \`agents.ts\` (router, agent tools: custom tool, MCP tool, integration operation, child workflow; run a child workflow; parallel). Their resource keys are examples; this workspace's are in \`${WORKSPACE_TYPES_FILE}\`.
57607
+ 1. Edit \`${SOURCE_ENTRY_FILE}\` (and \`functions/*\`). \`${SOURCE_EXAMPLES_DIR}/\` holds correct examples to copy from: \`cookbook.ts\` (agent with structured output, condition, function, table query and upsert, knowledge search, Slack, human in the loop, loop, response), \`integrations.ts\` (webhook trigger, weekday cron schedule, HTTP request with headers, table update by row id, Gmail, an error path) and \`agents.ts\` (router, agent tools: custom tool, MCP tool, integration operation, child workflow; run a child workflow; parallel). Their resource keys are examples; this workspace's are in \`${WORKSPACE_TYPES_FILE}\`.
57315
57608
  2. \`sim workflows source check --dir .\`: compiles offline with the server's compiler, in milliseconds. It catches what \`tsc\` cannot (duplicate names, cycles, literal secrets), and fails (exit 1) on a missing required field, an unknown option or output path, a wrong value kind, an out-of-range value, an unwired condition or router branch or a literal secret in a block you added (\`--strict\`: in every block). It also adds the blocks the source now uses to \`tsconfig.json\`.
57316
57609
  3. \`${typecheckCommand()}\`: about a second; catches what step 2 and the dry run do not (such as a reference to a start input the trigger does not declare). It runs the TypeScript release the declarations are built for (the directory has no \`package.json\`; plain \`bunx tsc\` would run whatever version it finds). \`tsconfig.json\` includes only the blocks the source used at the last check, get or apply: a builder from another block fails with \`has no exported member\` until you run step 2 (or use \`${typecheckCommand(TSCONFIG_FULL_FILE)}\`, every current block). The dry run is the authority: a printed line you did not edit that \`tsc\` flags and the dry run accepts is fine.
57317
57610
  4. \`sim workflows source status --dir .\`: the files you changed (\`sim workflows source diff --dir .\` shows the edits), whether the workflow changed on the server since the get, and the command to run next (\`--offline\`: skip the server). Then \`sim workflows source apply --dir . --dry-run\` until it exits 0.
@@ -57783,7 +58076,7 @@ function summarize(data, creating, machine) {
57783
58076
  import { join as join9 } from "node:path";
57784
58077
 
57785
58078
  // ../workspace-code/src/declaration/read.ts
57786
- var import_parser5 = __toESM(require_lib(), 1);
58079
+ var import_parser6 = __toESM(require_lib(), 1);
57787
58080
 
57788
58081
  // ../workspace-code/src/limits.ts
57789
58082
  var WORKSPACE_SOURCE_LIMITS = {
@@ -57907,7 +58200,7 @@ function readDeclaration(file, raw, options) {
57907
58200
  }
57908
58201
  let program;
57909
58202
  try {
57910
- program = import_parser5.parse(text, PARSER_OPTIONS2).program;
58203
+ program = import_parser6.parse(text, PARSER_OPTIONS2).program;
57911
58204
  } catch (error) {
57912
58205
  if (error instanceof RangeError) {
57913
58206
  diagnostics.push(diagnostic2("E_LIMIT_EXCEEDED", "The file is nested too deeply to parse.", { ...at(0, 0) }));
@@ -62267,7 +62560,7 @@ var ZodRealError = $constructor("ZodError", initializer2, {
62267
62560
  });
62268
62561
 
62269
62562
  // ../../node_modules/zod/v4/classic/parse.js
62270
- var parse8 = /* @__PURE__ */ _parse(ZodRealError);
62563
+ var parse9 = /* @__PURE__ */ _parse(ZodRealError);
62271
62564
  var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError);
62272
62565
  var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError);
62273
62566
  var safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError);
@@ -62310,7 +62603,7 @@ var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
62310
62603
  reg.add(inst, meta);
62311
62604
  return inst;
62312
62605
  };
62313
- inst.parse = (data, params) => parse8(inst, data, params, { callee: inst.parse });
62606
+ inst.parse = (data, params) => parse9(inst, data, params, { callee: inst.parse });
62314
62607
  inst.safeParse = (data, params) => safeParse2(inst, data, params);
62315
62608
  inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync });
62316
62609
  inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params);
@@ -64127,6 +64420,7 @@ function declaredColumns(decl) {
64127
64420
  return new Map(Object.entries(decl.columns).map(([columnKey, column]) => [
64128
64421
  columnName(columnKey, column),
64129
64422
  {
64423
+ key: columnKey,
64130
64424
  ...column.options ? { options: column.options } : {},
64131
64425
  ...column.multiple ? { multiple: true } : {}
64132
64426
  }
@@ -64329,9 +64623,11 @@ var STRICT_CODES = new Set([
64329
64623
  "W_LITERAL_SECRET",
64330
64624
  "W_TABLE_UNKNOWN_COLUMN",
64331
64625
  "W_CHILD_INPUT_UNKNOWN",
64626
+ "W_CHILD_RESULT_PATH",
64332
64627
  "W_BRANCH_UNWIRED",
64333
64628
  "W_UNRESOLVED_REF",
64334
- "W_REF_OUT_OF_SCOPE"
64629
+ "W_REF_OUT_OF_SCOPE",
64630
+ "W_LOOP_CONDITION_SYNTAX"
64335
64631
  ]);
64336
64632
  var STORED_EXEMPT_CODES = new Set(["W_BRANCH_UNWIRED"]);
64337
64633
  var EDIT_SCOPED_CODES = new Set(["W_JSON_REF_UNTYPED"]);
@@ -64420,25 +64716,29 @@ function inputMappingOf(canonical) {
64420
64716
  const value = rowJson(mapping.value);
64421
64717
  return toRecord(value);
64422
64718
  }
64423
- function childInputFindings(block, canonical, declarations) {
64719
+ function calledWorkflowKey(canonical) {
64424
64720
  const ref = canonical.params.workflowId;
64425
64721
  const child = ref?.kind === "value" ? resourceNode(ref.value) : null;
64426
- if (child?.kind !== "workflow")
64722
+ return child?.kind === "workflow" ? child.key : null;
64723
+ }
64724
+ function childInputFindings(block, canonical, declarations) {
64725
+ const childKey = calledWorkflowKey(canonical);
64726
+ if (childKey === null)
64427
64727
  return [];
64428
- const inputs = declarations.workflowInputs?.get(child.key);
64728
+ const inputs = declarations.workflowInputs?.get(childKey);
64429
64729
  if (inputs === undefined)
64430
64730
  return [];
64431
- const entry = `${KIND_DIRS.workflow}/${child.key}/${SOURCE_ENTRY_FILE}`;
64731
+ const entry = `${KIND_DIRS.workflow}/${childKey}/${SOURCE_ENTRY_FILE}`;
64432
64732
  if (inputs === null) {
64433
64733
  return [
64434
64734
  {
64435
64735
  code: "W_CHILD_NO_START",
64436
64736
  severity: "warning",
64437
- message: `Workflow "${child.key}" has no Start trigger, so it takes no inputs and a call cannot run it.`,
64737
+ message: `Workflow "${childKey}" has no Start trigger, so it takes no inputs and a call cannot run it.`,
64438
64738
  hint: `Add trigger.start('Start', { inputFormat: { … } }) to ${entry}, or call a workflow that has one.`,
64439
64739
  block,
64440
64740
  param: "workflowId",
64441
- names: child.key
64741
+ names: childKey
64442
64742
  }
64443
64743
  ];
64444
64744
  }
@@ -64446,12 +64746,81 @@ function childInputFindings(block, canonical, declarations) {
64446
64746
  return Object.keys(inputMappingOf(canonical)).filter((field) => !names.includes(field)).map((field) => ({
64447
64747
  code: "W_CHILD_INPUT_UNKNOWN",
64448
64748
  severity: "warning",
64449
- message: `inputMapping sets ${field}, which is not an input of workflow "${child.key}"; the child never receives it.`,
64749
+ message: `inputMapping sets ${field}, which is not an input of workflow "${childKey}"; the child never receives it.`,
64450
64750
  hint: names.length > 0 ? `${didYouMean(field, names) ?? ""} Inputs (the Start trigger's inputFormat in ${entry}): ${listed2(names)}.`.trimStart() : `The Start trigger of ${entry} declares no inputs: add ${field} to its inputFormat.`,
64451
64751
  block,
64452
64752
  param: "inputMapping"
64453
64753
  }));
64454
64754
  }
64755
+ function childResultFindings(workflow, declarations) {
64756
+ const responding = declarations.respondingWorkflows;
64757
+ if (!responding || responding.size === 0)
64758
+ return [];
64759
+ const calls = new Map;
64760
+ for (const [key, block] of Object.entries(workflow.blocks)) {
64761
+ const child = calledWorkflowKey(block);
64762
+ if (child !== null && responding.has(child))
64763
+ calls.set(key, child);
64764
+ }
64765
+ if (calls.size === 0)
64766
+ return [];
64767
+ const findings = [];
64768
+ for (const [block, canonical] of Object.entries(workflow.blocks)) {
64769
+ for (const [param, value] of Object.entries(canonical.params)) {
64770
+ if (value.kind !== "value")
64771
+ continue;
64772
+ const reported = new Set;
64773
+ const leaves = [];
64774
+ collectStringLeaves(value.value, leaves);
64775
+ for (const text of leaves) {
64776
+ for (const token of findWorkflowReferenceTokens(text)) {
64777
+ if (token.kind !== "workflow" || reported.has(token.value))
64778
+ continue;
64779
+ const segments = parseStoredPath(token.value.slice(1, -1));
64780
+ const [head, output, field, ...rest] = segments ?? [];
64781
+ const child = head?.kind === "name" ? calls.get(head.name) : undefined;
64782
+ if (child === undefined || output?.kind !== "name" || output.name !== "result")
64783
+ continue;
64784
+ if (field?.kind !== "name" || RESPONSE_OUTPUTS.includes(field.name))
64785
+ continue;
64786
+ reported.add(token.value);
64787
+ const meant = formatStoredPath([
64788
+ head,
64789
+ output,
64790
+ { kind: "name", name: "data" },
64791
+ field,
64792
+ ...rest
64793
+ ]);
64794
+ findings.push({
64795
+ code: "W_CHILD_RESULT_PATH",
64796
+ severity: "warning",
64797
+ message: `${token.value} reads ${field.name} from the result of workflow "${child}", which responds: its result is the Response output ({ data, status, headers }), so the path reads nothing.`,
64798
+ hint: `Did you mean <${meant}>? A field of the child's Response data is result.data.${field.name}.`,
64799
+ block,
64800
+ param
64801
+ });
64802
+ }
64803
+ }
64804
+ }
64805
+ }
64806
+ return findings;
64807
+ }
64808
+ function unknownColumnFinding(table, columns, field, block, param) {
64809
+ const finding = { code: "W_TABLE_UNKNOWN_COLUMN", severity: "warning", block, param };
64810
+ const renamed = [...columns].find(([, column]) => column.key === field)?.[0];
64811
+ if (renamed) {
64812
+ return {
64813
+ ...finding,
64814
+ message: `${param} writes ${field}, the key of column "${renamed}" of table "${table}": row data is keyed by column name, so the run drops it.`,
64815
+ hint: `Did you mean ${renamed}?`
64816
+ };
64817
+ }
64818
+ return {
64819
+ ...finding,
64820
+ message: `${param} writes ${field}, which is not a column of table "${table}"; the run drops it.`,
64821
+ hint: `${didYouMean(field, columns.keys()) ?? ""} Columns: ${listed2(columns.keys())}.`.trimStart()
64822
+ };
64823
+ }
64455
64824
  function declarationFindings(workflow, declarations) {
64456
64825
  const findings = [];
64457
64826
  for (const [block, canonical] of Object.entries(workflow.blocks)) {
@@ -64493,14 +64862,7 @@ function declarationFindings(workflow, declarations) {
64493
64862
  for (const [field, cell] of Object.entries(row)) {
64494
64863
  const column = columns.get(field);
64495
64864
  if (!column) {
64496
- findings.push({
64497
- code: "W_TABLE_UNKNOWN_COLUMN",
64498
- severity: "warning",
64499
- message: `${param} writes ${field}, which is not a column of table "${table}"; the run drops it.`,
64500
- hint: `${didYouMean(field, columns.keys()) ?? ""} Columns: ${listed2(columns.keys())}.`.trimStart(),
64501
- block,
64502
- param
64503
- });
64865
+ findings.push(unknownColumnFinding(table, columns, field, block, param));
64504
64866
  continue;
64505
64867
  }
64506
64868
  const { options } = column;
@@ -64520,10 +64882,13 @@ function declarationFindings(workflow, declarations) {
64520
64882
  }
64521
64883
  }
64522
64884
  }
64885
+ findings.push(...childResultFindings(workflow, declarations));
64523
64886
  return findings;
64524
64887
  }
64525
64888
  async function compileWorkflowDir(dir, workspaceCatalog, declarations) {
64526
- const { lock } = parseWorkflowLock(await readSourceJson(dir, SOURCE_LOCK_FILE));
64889
+ const lockText = await readSourceText(dir, SOURCE_LOCK_FILE);
64890
+ const parsedLock = lockText === null ? null : parseWorkflowLock(lockText);
64891
+ const lock = parsedLock?.lock;
64527
64892
  const [files, storedEdges, storedBlocks, printedWith] = await Promise.all([
64528
64893
  readSourceFiles(dir, lock ?? null),
64529
64894
  readStoredEdges(dir),
@@ -64542,16 +64907,35 @@ async function compileWorkflowDir(dir, workspaceCatalog, declarations) {
64542
64907
  ...storedEdges ? { storedUnreadEdges: storedEdges } : {},
64543
64908
  ...envNames ? { envNames, envDeclaredIn: KIND_DIRS.secret } : {}
64544
64909
  });
64545
- return { lock, files, compiled, storedBlocks, printedWith, catalog };
64910
+ return {
64911
+ lock,
64912
+ lockProblems: parsedLock?.diagnostics ?? [],
64913
+ files,
64914
+ compiled,
64915
+ storedBlocks,
64916
+ printedWith,
64917
+ catalog
64918
+ };
64919
+ }
64920
+ async function readCheckDeclarations(root, catalog) {
64921
+ const [declared, workflows] = await Promise.all([
64922
+ readWorkspaceDeclarations(root),
64923
+ compileWorkspaceWorkflows(root, catalog)
64924
+ ]);
64925
+ return { ...declared, ...workflows };
64546
64926
  }
64547
- async function workspaceWorkflowInputs(root, catalog) {
64548
- const inputs = new Map;
64927
+ async function compileWorkspaceWorkflows(root, catalog) {
64928
+ const workflowInputs = new Map;
64929
+ const respondingWorkflows = new Set;
64549
64930
  for (const key of await workspaceWorkflowKeys(root)) {
64550
64931
  const { compiled } = await compileWorkflowDir(join9(root, KIND_DIRS.workflow, key), catalog);
64551
- if (compiled.workflow)
64552
- inputs.set(key, startInputs(compiled.workflow));
64932
+ if (!compiled.workflow)
64933
+ continue;
64934
+ workflowInputs.set(key, startInputs(compiled.workflow));
64935
+ if (respondsOnEveryRun(compiled.workflow))
64936
+ respondingWorkflows.add(key);
64553
64937
  }
64554
- return inputs;
64938
+ return { workflowInputs, respondingWorkflows };
64555
64939
  }
64556
64940
  function withWorkflowInputs(local, inputs) {
64557
64941
  const workflows = { ...local.workflows };
@@ -64564,7 +64948,7 @@ function withWorkflowInputs(local, inputs) {
64564
64948
  }
64565
64949
  async function checkWorkflowDir(dir, catalog, options) {
64566
64950
  const compiledDir = await compileWorkflowDir(dir, catalog, options.declarations);
64567
- const { lock, files, compiled, storedBlocks, printedWith } = compiledDir;
64951
+ const { lock, lockProblems, files, compiled, storedBlocks, printedWith } = compiledDir;
64568
64952
  const entryText = files[SOURCE_ENTRY_FILE];
64569
64953
  const locate = (block, param, names) => {
64570
64954
  const prefix = encodeAnchor({ kind: "param", block, param: "" });
@@ -64644,6 +65028,14 @@ async function checkWorkflowDir(dir, catalog, options) {
64644
65028
  }, { changed, codeEdited }),
64645
65029
  ...compiled.diagnostics.filter(exempt)
64646
65030
  ];
65031
+ const lockFindings = lockProblems.map((problem) => ({
65032
+ code: problem.code,
65033
+ severity: "error",
65034
+ message: `${problem.message} Every apply and status refuses this lock.`,
65035
+ hint: lockRecoveryHint(options.declarations ? "`sim workspaces source get --dir <new dir>`, from the workspace directory" : undefined),
65036
+ file: `${prefix}${SOURCE_LOCK_FILE}`,
65037
+ ...problem.path ? { path: problem.path } : {}
65038
+ }));
64647
65039
  const findings = [
64648
65040
  ...refused.filter((diagnostic) => reported(diagnostic.code, diagnostic.blockKey)),
64649
65041
  ...declared
@@ -64691,7 +65083,7 @@ async function checkWorkflowDir(dir, catalog, options) {
64691
65083
  else
64692
65084
  unlisted.warnings += count;
64693
65085
  }
64694
- return { findings, entry: entryText, unlisted };
65086
+ return { findings: [...lockFindings, ...findings], entry: entryText, unlisted };
64695
65087
  }
64696
65088
  function reportCheck(output, findings, result, options = {}) {
64697
65089
  const shown = findingsOutput(output, options.verbose, options.dir);
@@ -64744,10 +65136,7 @@ function attachWorkflowSourceCheck(source) {
64744
65136
  throw new CliUsageError(`${options.dir} has no ${SOURCE_BASE_FILE} and no workspace is selected: pass --workspace <workspaceId>.`);
64745
65137
  }
64746
65138
  const catalog = cachedOrRefuse(await cachedSourceCatalog(options.dir) ?? cachedCatalog(workspaceId), workspaceId, workspace ? `\`sim workspaces source get --dir ${workspace.root}\`` : `\`sim workflows source get <workflowId> --dir ${options.dir}\` (or \`create\`)`);
64747
- const declarations = workspace ? {
64748
- ...await readWorkspaceDeclarations(workspace.root),
64749
- workflowInputs: await workspaceWorkflowInputs(workspace.root, catalog)
64750
- } : undefined;
65139
+ const declarations = workspace ? await readCheckDeclarations(workspace.root, catalog) : undefined;
64751
65140
  const { findings, entry, unlisted } = await checkWorkflowDir(options.dir, catalog, {
64752
65141
  strict: strictMode(options),
64753
65142
  ...declarations ? { declarations } : {}
@@ -64848,8 +65237,9 @@ Prints a builder's params (required first, with enums and defaults), the gate fi
64848
65237
  which others apply, and its outputs, from the block catalog the last get, create or check cached.
64849
65238
  No request is made. <builder> is the dotted builder path as source writes it: table.upsertRow,
64850
65239
  agent, trigger.schedule, slack.sendMessage (slack.tool.sendMessage names the same builder). A
64851
- namespace (gmail, trigger.gmail) lists its builders; a construct core.d.ts declares (loop,
64852
- parallel, t, env) prints its declaration. Run it from a workflow or workspace source directory,
65240
+ namespace (gmail, trigger.gmail) lists its builders; a block type prints the builder written for
65241
+ it (function is fn) or lists them (table_v2); a construct core.d.ts declares (loop, parallel, t,
65242
+ env) prints its declaration. Run it from a workflow or workspace source directory,
64853
65243
  or pass --dir.
64854
65244
 
64855
65245
  Exit codes: 0 printed; 1 no builder or namespace of that name (the closest one is named), or no
@@ -65516,10 +65906,14 @@ function splitLines2(text) {
65516
65906
  return result;
65517
65907
  }
65518
65908
  // src/commands/protocol/source-status.ts
65519
- function planFindings(diagnostics, listed) {
65520
- return diagnostics.filter((finding) => (finding.severity === "error" || finding.severity === "warning" || finding.code === "I_FINDINGS_TRUNCATED") && !listed(finding.code));
65909
+ function planFindings(diagnostics) {
65910
+ return diagnostics.filter((finding) => finding.severity === "error" || finding.severity === "warning" || finding.code === "I_FINDINGS_TRUNCATED");
65521
65911
  }
65522
65912
  var STATUS_EXIT_CODES_HELP = `
65913
+ With --json, \`plan\` is what applying would do as \`apply --dry-run --allow-delete\` reports it
65914
+ (its errors and warnings counted the same, a conflict as an error), and \`next\` the command to
65915
+ run (with --allow-delete only when the plan deletes something).
65916
+
65523
65917
  Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was
65524
65918
  read); ${SOURCE_LOCAL_CHANGES_EXIT_CODE} local changes only (applying writes them); ${SOURCE_DRIFT_EXIT_CODE} the server changed since the
65525
65919
  directory was read: drift (a resource edited, added or deleted there that the directory leaves
@@ -65792,7 +66186,7 @@ async function readLocalWorkflow(dir) {
65792
66186
  };
65793
66187
  }
65794
66188
  function workflowPlanFindings(data) {
65795
- return planFindings(data.diagnostics, (code) => code === "E_APPLY_STALE");
66189
+ return planFindings(data.diagnostics).filter((finding) => finding.code !== "E_APPLY_STALE");
65796
66190
  }
65797
66191
  function planSummary(data) {
65798
66192
  const planned = workflowPlanFindings(data);
@@ -65803,12 +66197,14 @@ function planSummary(data) {
65803
66197
  blocksModified: data.diff.blocks.modified.length,
65804
66198
  edgesAdded: data.diff.edges.added,
65805
66199
  edgesRemoved: data.diff.edges.removed,
66200
+ variablesRemoved: data.diff.variables.removed.length,
65806
66201
  errors: findings("error"),
65807
66202
  warnings: findings("warning")
65808
66203
  };
65809
66204
  }
65810
66205
  function planLine(plan) {
65811
- return `Applying would: blocks +${plan.blocksAdded} -${plan.blocksRemoved} ~${plan.blocksModified}, connections +${plan.edgesAdded} -${plan.edgesRemoved}; ${plan.errors} error(s), ${plan.warnings} warning(s).`;
66206
+ const variables = plan.variablesRemoved > 0 ? `, variables -${plan.variablesRemoved}` : "";
66207
+ return `Applying would: blocks +${plan.blocksAdded} -${plan.blocksRemoved} ~${plan.blocksModified}, connections +${plan.edgesAdded} -${plan.edgesRemoved}${variables}; ${plan.errors} error(s), ${plan.warnings} warning(s).`;
65812
66208
  }
65813
66209
  function attachWorkflowSourceStatus(source) {
65814
66210
  const [command, connect] = apiCommand(source, "status", [
@@ -65886,7 +66282,7 @@ function attachWorkflowSourceStatus(source) {
65886
66282
  getArgs: `${workflowId} `,
65887
66283
  server,
65888
66284
  errors: plan?.errors ?? 0,
65889
- deletes: (plan?.blocksRemoved ?? 0) > 0,
66285
+ deletes: (plan?.blocksRemoved ?? 0) + (plan?.variablesRemoved ?? 0) > 0,
65890
66286
  scope: "",
65891
66287
  login
65892
66288
  })
@@ -66164,11 +66560,19 @@ function failedExitCode(failed) {
66164
66560
  return failed.code === "E_APPLY_FAILED" ? SOURCE_PARTIAL_EXIT_CODE : refusedExitCode([{ code: failed.code, severity: "error" }]);
66165
66561
  }
66166
66562
  function isHeldFinding(plan, finding) {
66167
- return plan.some((change) => change.held && change.kind === finding.kind && change.key === finding.key);
66563
+ return finding.code !== "E_PLAN_REF_DELETED" && plan.some((change) => change.held && change.kind === finding.kind && change.key === finding.key);
66168
66564
  }
66169
66565
  function refusesApply(data) {
66566
+ if (data.refuses !== undefined)
66567
+ return data.refuses;
66170
66568
  return data.diagnostics.some((finding) => finding.severity === "error" && !isHeldFinding(data.plan, finding));
66171
66569
  }
66570
+ function previewExitCode(data) {
66571
+ if (refusesApply(data))
66572
+ return refusedExitCode(data.diagnostics);
66573
+ const writesSome = data.plan.some((change) => change.action !== "noop" && !change.held);
66574
+ return writesSome ? SOURCE_HELD_EXIT_CODE : 1;
66575
+ }
66172
66576
  var sameChange = (a, b) => a.kind === b.kind && a.key === b.key;
66173
66577
  function wasWritten(change, outcome) {
66174
66578
  return outcome.applied.some((written) => sameChange(written, change));
@@ -66602,6 +67006,7 @@ function attachWorkspaceSourceApply(source) {
66602
67006
  findings.print(preview.diagnostics);
66603
67007
  },
66604
67008
  refuses: refusesApply,
67009
+ previewExitCode,
66605
67010
  beforeCommit: (preview) => stage(submission, preview ? new Set(preview.needBlobs) : blobsToStage(submission)),
66606
67011
  commit: async () => {
66607
67012
  const answer = reported(await send(submission, false));
@@ -66814,11 +67219,7 @@ ${SOURCE_DIR_BUSY_HELP}`).action(async (options, command) => {
66814
67219
  }
66815
67220
  await withSourceDirLock(options.dir, async () => {
66816
67221
  const catalog = cachedCatalog(workspaceId) ?? await fetchedCatalog(connect, workspaceId, options.dir);
66817
- const workflowInputs = await workspaceWorkflowInputs(options.dir, catalog);
66818
- const declarations = {
66819
- ...await readWorkspaceDeclarations(options.dir),
66820
- workflowInputs
66821
- };
67222
+ const declarations = await readCheckDeclarations(options.dir, catalog);
66822
67223
  const keys = await workspaceWorkflowKeys(options.dir);
66823
67224
  const findings = [];
66824
67225
  const unlisted = { errors: 0, warnings: 0 };
@@ -66851,7 +67252,7 @@ ${SOURCE_DIR_BUSY_HELP}`).action(async (options, command) => {
66851
67252
  column
66852
67253
  });
66853
67254
  }
66854
- await refreshWorkspaceTypes(options.dir, withWorkflowInputs(declarations.local, workflowInputs));
67255
+ await refreshWorkspaceTypes(options.dir, withWorkflowInputs(declarations.local, declarations.workflowInputs));
66855
67256
  await refreshWorkspaceTsconfigs(options.dir, workspaceId);
66856
67257
  reportCheck(profile.output, findings, { workflows: keys.length, catalogHash: catalog.hash }, {
66857
67258
  verbose: options.verbose === true,
@@ -67123,8 +67524,8 @@ function aboutWorkflowSentByBase(item, byBase) {
67123
67524
  function planAsApplied(plan, byBase) {
67124
67525
  return plan.map((change) => aboutWorkflowSentByBase(change, byBase) && change.action !== "noop" ? { kind: change.kind, key: change.key, action: "noop" } : change);
67125
67526
  }
67126
- function workspacePlanFindings(data, byBase) {
67127
- return planFindings(data.diagnostics, isServerChangeFinding).filter((finding) => !(aboutWorkflowSentByBase(finding, byBase) && isFolderEvaluationFinding(finding)));
67527
+ function dryRunFindings(data, byBase) {
67528
+ return planFindings(data.diagnostics).filter((finding) => !(aboutWorkflowSentByBase(finding, byBase) && (isFolderEvaluationFinding(finding) || finding.code === "E_APPLY_STALE")));
67128
67529
  }
67129
67530
  function planSummary2(findings, plan, conflicts) {
67130
67531
  const count = (...actions) => plan.filter((change) => actions.includes(change.action)).length;
@@ -67142,7 +67543,7 @@ function planSummary2(findings, plan, conflicts) {
67142
67543
  }
67143
67544
  function planLine2(plan) {
67144
67545
  const counts = `${plan.create} create, ${plan.update} update, ${plan.delete} delete (${plan.unchanged} unchanged); ${plan.errors} error(s), ${plan.warnings} warning(s)`;
67145
- return plan.conflicts > 0 ? `Applying would be refused as stale (exit ${SOURCE_STALE_EXIT_CODE}): ${plan.conflicts} conflict(s) above. Without them it would: ${counts}.` : `Applying would: ${counts}.`;
67546
+ return plan.conflicts > 0 ? `Applying would be refused as stale (exit ${SOURCE_STALE_EXIT_CODE}): the ${plan.conflicts} conflict(s) above. Its dry run: ${counts}.` : `Applying would: ${counts}.`;
67146
67547
  }
67147
67548
  function fitsWhole(files) {
67148
67549
  const paths = Object.keys(files).filter((path) => kindOfPath(path) === "workflow");
@@ -67229,8 +67630,9 @@ ${SOURCE_DIR_BUSY_HELP}`).action(async (options, invoked) => {
67229
67630
  }
67230
67631
  const skipped = data ? await skippedResources(options.dir) : new Set;
67231
67632
  const status = sourceStatus(locals, data ? serverResourceChanges(data.diagnostics).filter((change) => !(change.server === "added" && skipped.has(`${change.kind}:${change.key}`))) : []);
67232
- const planned = data ? workspacePlanFindings(data, byBase) : [];
67233
- const plan = data ? planSummary2(planned, applyPlan, status.conflicts.length) : null;
67633
+ const dryRun = data ? dryRunFindings(data, byBase) : [];
67634
+ const planned = dryRun.filter((finding) => !isServerChangeFinding(finding.code));
67635
+ const plan = data ? planSummary2(dryRun, applyPlan, status.conflicts.length) : null;
67234
67636
  const report = {
67235
67637
  workspaceId,
67236
67638
  dir: options.dir,
@@ -69077,7 +69479,7 @@ class Parser extends Transform2 {
69077
69479
  callback(err);
69078
69480
  }
69079
69481
  }
69080
- var parse10 = function() {
69482
+ var parse11 = function() {
69081
69483
  let data, options, callback;
69082
69484
  for (const i in arguments) {
69083
69485
  const argument = arguments[i];
@@ -69242,7 +69644,7 @@ async function stagePermissionCsvs(provider, paths, signal) {
69242
69644
  parts.push({ field, path: partPath });
69243
69645
  totalBytes += partBytes;
69244
69646
  };
69245
- const parser = parse10({
69647
+ const parser = parse11({
69246
69648
  bom: true,
69247
69649
  trim: true,
69248
69650
  skip_empty_lines: true,
@@ -69606,6 +70008,15 @@ Profiles work like the AWS CLI: settings live in ~/.sim/config, keys in
69606
70008
  ~/.sim/credentials (0600), or under SIM_CONFIG_DIR when it is set. Select one
69607
70009
  with -P, --profile, or SIM_PROFILE.
69608
70010
 
70011
+ A command targets the profile's workspace unless -w <id> (--workspace <id>) or
70012
+ SIM_WORKSPACE names another. A source directory records its own: a workflow
70013
+ directory acts on the workflow its .sim/base.json names, a workspace directory
70014
+ on the workspace its base names (refusing a -w naming another), and a starter
70015
+ on the one .sim/starter.json names unless -w names another. In a script, export
70016
+ SIM_WORKSPACE=<id> once, or keep only the ID in a variable and write -w "$WS".
70017
+ A variable holding "--workspace <id>" is one argument: alone it is an unknown
70018
+ option, and after -w all of it is taken as the ID.
70019
+
69609
70020
  Workflow, knowledge-base and workspace IDs are bare UUIDs. Table IDs carry a
69610
70021
  tbl_ prefix and file IDs a wf_ one, so wf_ never names a workflow. An audit-log
69611
70022
  or custom-tool ID can open with a dash, which reads as a flag; put -- in front