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/runtime.js CHANGED
@@ -20273,7 +20273,7 @@ class SimClient {
20273
20273
  this.resolveCredential(options.auth);
20274
20274
  const workspaceId = explicit ?? this.profile.workspaceId;
20275
20275
  if (!workspaceId) {
20276
- 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);
20276
+ 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);
20277
20277
  }
20278
20278
  return workspaceId;
20279
20279
  }
@@ -35216,7 +35216,36 @@ Source handles:
35216
35216
  parallel-start-source, parallel-end-source the same for a parallel
35217
35217
  Renames:
35218
35218
  An edit's {"name":"New name"} also rewrites every <old key.field> reference to the block, in
35219
- other blocks' inputs and in a loop's or parallel's collection and condition.`;
35219
+ other blocks' inputs and in a loop's or parallel's collection and condition.
35220
+ Inputs:
35221
+ inputs takes the field ids \`sim blocks get <type>\` lists (inputSchema, operationInputSchema),
35222
+ or the name a pair of them shares (inputDefinitions: tableId for tableSelector and
35223
+ manualTableId; a string goes to the typed field). Add the type it answers with: \`blocks get
35224
+ table\` answers table_v2, and an add of legacy table is refused.
35225
+ conditions (condition): [{"title":"if","value":"<start.n> > 3"},{"title":"else if","value":"…"},
35226
+ {"title":"else","value":""}]; the last entry is the else. Each entry's id comes from its
35227
+ position (<block id>-if, <block id>-else-if-0, …, <block id>-else): an id you pass is replaced.
35228
+ inputFormat (Start): [{"name":"email","type":"string"}]; types string, number, boolean,
35229
+ object, array, file[]; an optional default "value" as text.
35230
+ Block settings, beside inputs in an add's or edit's params:
35231
+ "retry":{"enabled":true,"maxTries":3,"waitBetweenTriesMs":1000} retries a failed block; null
35232
+ clears it. An api block's retries input repeats the request after a timeout, reset, 429 or
35233
+ 5xx, not when the host does not resolve or refuses the connection; "retry" covers that.
35234
+ Outputs:
35235
+ A block that fails outputs {"error":"<message>"}: connect its error handle and read
35236
+ <name.error> there (without one, the run fails). A Workflow block's result is the child's
35237
+ output; a child ending in a Response block gives {data, status, headers}, so read
35238
+ <call.result.data.x>.`;
35239
+ var BLOCK_DETAIL_GUIDE = `
35240
+ Reading it for \`sim workflows operations apply\`:
35241
+ id the type to add: \`blocks get table\` answers table_v2 (an add of legacy
35242
+ table is refused)
35243
+ inputSchema the field ids inputs takes; operationInputSchema, an operation's own
35244
+ inputDefinitions the block's inputs by name; one a pair of fields shares (tableId for
35245
+ tableSelector and manualTableId) is accepted in place of the pair
35246
+ outputs what it outputs on success; a failed block outputs {"error":"…"}
35247
+ instead, read on its error path as <name.error>
35248
+ Block settings such as retry are not fields: \`sim workflows operations apply --help\`.`;
35220
35249
  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';
35221
35250
  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"}]';
35222
35251
  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';
@@ -35663,6 +35692,7 @@ var CLI_CONTRACT = {
35663
35692
  command: "workflows state replace",
35664
35693
  confirm: "This replaces the entire draft graph and cannot be undone."
35665
35694
  },
35695
+ getBlock: { helpText: BLOCK_DETAIL_GUIDE },
35666
35696
  applyWorkflowOperations: {
35667
35697
  command: "workflows operations apply",
35668
35698
  describe: "Edit a workflow’s blocks, connections and settings with a batch of operations",
@@ -35883,6 +35913,9 @@ var CLI_CONTRACT = {
35883
35913
  flags: { folderPath: FOLDER_PATH_FLAG }
35884
35914
  },
35885
35915
  createWorkflow: {
35916
+ helpText: `
35917
+ The new workflow's draft holds one Start block (start_trigger, named Start): connect the
35918
+ blocks you add from it.`,
35886
35919
  flags: {
35887
35920
  folderPath: {
35888
35921
  ...FOLDER_PATH_FLAG,
@@ -37005,6 +37038,10 @@ var CLI_CONTRACT = {
37005
37038
  },
37006
37039
  exportWorkflow: {
37007
37040
  describe: "Print a workflow as a portable JSON document",
37041
+ helpText: `
37042
+ Workspace bindings (a table, a child workflow, a knowledge base) print as null unless
37043
+ --include-workspace-bindings, and credentials always do: to read what a block is set to, use
37044
+ \`sim workflows state get\`.`,
37008
37045
  flags: {
37009
37046
  includeReferences: {
37010
37047
  boolean: true,
@@ -38011,7 +38048,7 @@ async function coerce(raw, field, flag, flagName) {
38011
38048
  return encodeFolderPath(raw);
38012
38049
  return raw;
38013
38050
  }
38014
- var NO_WORKSPACE_FALLBACK = "No workspace set. Pass --workspace, or run: sim configure --set-workspace <id>";
38051
+ var NO_WORKSPACE_FALLBACK = "No workspace set. Pass -w <workspaceId>, set SIM_WORKSPACE, or run: sim configure --set-workspace <id>";
38015
38052
  function asQueryValue(value) {
38016
38053
  if (value === null || value === undefined)
38017
38054
  return;
@@ -38506,6 +38543,14 @@ function foldOtherSpellings(operation, commandSpec, flags) {
38506
38543
  }
38507
38544
  }
38508
38545
  }
38546
+ function withSearchedWorkspace(error, profile) {
38547
+ if (!(error instanceof SimApiError) || error.status !== 404 || !profile.workspaceId)
38548
+ return error;
38549
+ const source = profile.sources.workspaceId;
38550
+ 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` : "";
38551
+ const searched = `searched workspace ${safeOneLine(profile.workspaceId)}${from}`;
38552
+ return new SimApiError(`${error.message} (${searched})`, error.status, error.code, error.details, error.exitCode, error.requestId);
38553
+ }
38509
38554
  async function executeOperation(operation, commandSpec, operationSpec, invocation) {
38510
38555
  const host = invocation[invocation.length - 1];
38511
38556
  const inheritedFlags = host.optsWithGlobals();
@@ -38589,6 +38634,8 @@ async function executeOperation(operation, commandSpec, operationSpec, invocatio
38589
38634
  if (cursor && rows.length < limit)
38590
38635
  progress.advance(rows.length);
38591
38636
  } while (cursor && rows.length < limit);
38637
+ } catch (error) {
38638
+ throw needsWorkspace ? withSearchedWorkspace(error, profile) : error;
38592
38639
  } finally {
38593
38640
  progress.finish();
38594
38641
  }
@@ -38614,7 +38661,7 @@ async function executeOperation(operation, commandSpec, operationSpec, invocatio
38614
38661
  reconciliation: "Find the operation using this requestId, or retry identical inputs with the same requestId."
38615
38662
  }, failure.exitCode, failure.requestId);
38616
38663
  }
38617
- throw error;
38664
+ throw needsWorkspace ? withSearchedWorkspace(error, profile) : error;
38618
38665
  }
38619
38666
  let payload = result?.data ?? result;
38620
38667
  if (commandSpec.workspaceOperation && (Boolean(request.body?.requestId) || requestFlags.wait === true || payload && typeof payload === "object" && ("operationId" in payload))) {
@@ -40751,15 +40798,20 @@ export default workflow('Cookbook', { description: 'One example of each common b
40751
40798
  code: js\`return { id: \${start.orderId}, cents: Math.round(\${start.amount} * 100) }\`,
40752
40799
  })
40753
40800
 
40754
- // Tables: query rows (each row is { id, data: { column } }) and insert a row.
40801
+ // Tables: query rows (each row is { id, data: { column } }) and write one.
40755
40802
  const recent = table.queryRows('Recent Orders', {
40756
40803
  tableId: table('orders'),
40757
40804
  filterInput: { all: [{ field: 'status', op: 'eq', value: 'open' }] },
40758
40805
  limit: 50,
40759
40806
  })
40760
- const save = table.insertRow('Save Order', {
40807
+ // Upsert: updates the row whose conflictColumn (a unique column, by name) matches data, else
40808
+ // inserts one, so a second run for the same order updates it. table.insertRow takes the same
40809
+ // data without conflictColumn and adds a row every run. data is keyed by column name: a column
40810
+ // declared as \`phone: column.string({ name: 'mobile' })\` is written as { mobile: ... }.
40811
+ const save = table.upsertRow('Save Order', {
40761
40812
  tableId: table('orders'),
40762
- data: { orderId: start.orderId, status: 'open', risk: check.risk },
40813
+ data: { orderId: start.orderId, status: 'open' },
40814
+ conflictColumn: 'orderId',
40763
40815
  })
40764
40816
 
40765
40817
  // Knowledge base search: results is the list of matching chunks.
@@ -40814,8 +40866,12 @@ export default workflow('Cookbook', { description: 'One example of each common b
40814
40866
  })
40815
40867
 
40816
40868
  // Response: the API reply body. Wrap an untyped value (fn.result.x) in t\`\` when it is text.
40869
+ // body is the short form of the editor's JSON mode: { dataMode: 'json', data } as below.
40817
40870
  const reply = response('Respond', { body: { risk: check.risk, id: t\`\${shape.result.id}\` } })
40818
- const rejected = response('Respond Rejected', { body: { status: 'rejected' } })
40871
+ const rejected = response('Respond Rejected', {
40872
+ dataMode: 'json',
40873
+ data: { status: 'rejected' },
40874
+ })
40819
40875
 
40820
40876
  // Wiring: a.to(b) chains; a block can fan out to several targets.
40821
40877
  start.to(check)
@@ -40926,7 +40982,7 @@ export default workflow(
40926
40982
  )
40927
40983
  ` };
40928
40984
  // ../workflow-sdk/src/codegen/core-text.generated.ts
40929
- 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";
40985
+ 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";
40930
40986
  // ../workflow-code/src/anchors.ts
40931
40987
  function portKey(port) {
40932
40988
  switch (port.kind) {
@@ -41933,6 +41989,16 @@ function findWorkflowReferenceTokens(source) {
41933
41989
  }
41934
41990
  return tokens.sort((left, right) => left.start - right.start);
41935
41991
  }
41992
+ function collectStringLeaves(value, out) {
41993
+ if (typeof value === "string")
41994
+ out.push(value);
41995
+ else if (Array.isArray(value))
41996
+ for (const item of value)
41997
+ collectStringLeaves(item, out);
41998
+ else if (typeof value === "object" && value !== null)
41999
+ for (const item of Object.values(value))
42000
+ collectStringLeaves(item, out);
42001
+ }
41936
42002
 
41937
42003
  // ../workflow-code/src/limits.ts
41938
42004
  var SOURCE_LIMITS = {
@@ -42415,6 +42481,7 @@ function parseWorkflowSourceHandle(handle, sourceType, branchKind) {
42415
42481
  var SIDE_ANCHORED_SOURCE_HANDLE_IDS = new Set(WORKFLOW_CARD_SIDES.map((side) => `source-${side}`));
42416
42482
  var SIDE_ANCHORED_TARGET_HANDLE_IDS = new Set(WORKFLOW_CARD_SIDES.map((side) => `target-${side}`));
42417
42483
  var WORKFLOW_CONTAINER_BLOCK_TYPES = new Set(["loop", "parallel"]);
42484
+ var WORKFLOW_ANNOTATION_ONLY_BLOCK_TYPE = "note";
42418
42485
  function getWorkflowEdgeScopeDropReason(edge, blocks) {
42419
42486
  const sourceBlock = blocks[edge.source];
42420
42487
  const targetBlock = blocks[edge.target];
@@ -42434,6 +42501,72 @@ function getWorkflowEdgeScopeDropReason(edge, blocks) {
42434
42501
  }
42435
42502
  return `blocks are in different scopes (${sourceParent ?? "root"} -> ${targetParent ?? "root"})`;
42436
42503
  }
42504
+ function isWorkflowAnnotationOnlyBlockType(blockType) {
42505
+ return blockType === WORKFLOW_ANNOTATION_ONLY_BLOCK_TYPE;
42506
+ }
42507
+ var RESPONSE_BLOCK_TYPE = "response";
42508
+ function isElseConditionTitle(title) {
42509
+ return typeof title === "string" && title.trim().toLowerCase() === "else";
42510
+ }
42511
+ function hasCycle(successors, pending) {
42512
+ const ready = [...successors.keys()].filter((id) => !pending.has(id));
42513
+ let visited = 0;
42514
+ for (let id = ready.pop();id !== undefined; id = ready.pop()) {
42515
+ visited += 1;
42516
+ for (const next of successors.get(id) ?? []) {
42517
+ const left = (pending.get(next) ?? 0) - 1;
42518
+ pending.set(next, left);
42519
+ if (left === 0)
42520
+ ready.push(next);
42521
+ }
42522
+ }
42523
+ const nodes = new Set([...successors.keys(), ...pending.keys()]);
42524
+ return visited < nodes.size;
42525
+ }
42526
+ function alwaysEndsAtResponse(blocks, edges) {
42527
+ const runs = (id) => {
42528
+ const block = Object.hasOwn(blocks, id) ? blocks[id] : undefined;
42529
+ return block?.enabled === true && !isWorkflowAnnotationOnlyBlockType(block.type);
42530
+ };
42531
+ const isRoot = (id) => blocks[id]?.parentId === null;
42532
+ const portsBySource = new Map;
42533
+ const successors = new Map;
42534
+ const pending = new Map;
42535
+ for (const edge of edges) {
42536
+ if (!runs(edge.source) || !runs(edge.target))
42537
+ continue;
42538
+ const ports = portsBySource.get(edge.source) ?? new Set;
42539
+ ports.add(edge.port);
42540
+ portsBySource.set(edge.source, ports);
42541
+ if (!isRoot(edge.source) || !isRoot(edge.target))
42542
+ continue;
42543
+ const next = successors.get(edge.source) ?? [];
42544
+ next.push(edge.target);
42545
+ successors.set(edge.source, next);
42546
+ pending.set(edge.target, (pending.get(edge.target) ?? 0) + 1);
42547
+ }
42548
+ if (hasCycle(successors, pending))
42549
+ return false;
42550
+ let responds = false;
42551
+ for (const [id, block] of Object.entries(blocks)) {
42552
+ if (!runs(id) || block.parentId !== null)
42553
+ continue;
42554
+ if (block.type === RESPONSE_BLOCK_TYPE) {
42555
+ responds = true;
42556
+ continue;
42557
+ }
42558
+ const ports = portsBySource.get(id);
42559
+ if (block.branches !== undefined) {
42560
+ const { branches } = block;
42561
+ if (branches.length === 0 || !branches.every((branch) => ports?.has(`branch:${branch}`))) {
42562
+ return false;
42563
+ }
42564
+ } else if (!ports?.has(isSubflowType(block.type) ? "subflowEnd" : "out")) {
42565
+ return false;
42566
+ }
42567
+ }
42568
+ return responds;
42569
+ }
42437
42570
  var RESERVED_WORKFLOW_BLOCK_NAMES = ["loop", "parallel", "variable"];
42438
42571
  function isReservedWorkflowBlockName(name) {
42439
42572
  return RESERVED_WORKFLOW_BLOCK_NAMES.includes(name);
@@ -42838,8 +42971,8 @@ function valueTree(value) {
42838
42971
  var SDK_MODULE = "@sim/workflow-sdk";
42839
42972
  var GENERIC_BUILDER = "block";
42840
42973
  var CUSTOM_TOOL_TYPE = "custom-tool";
42841
- var RESPONSE_BLOCK_TYPE = "response";
42842
42974
  var RESPONSE_BODY_KEYS = ["body", "status", "headers"];
42975
+ var RESPONSE_OUTPUTS = ["data", "status", "headers"];
42843
42976
  var TEMPLATE_TAGS = [
42844
42977
  "t",
42845
42978
  "js",
@@ -43719,6 +43852,9 @@ function renamedReferenceRewriter(renames) {
43719
43852
  }) : text;
43720
43853
  }
43721
43854
 
43855
+ // ../workflow-code/src/compile/blocks.ts
43856
+ var import_parser3 = __toESM(require_lib(), 1);
43857
+
43722
43858
  // ../workflow-code/src/canonicalize/values.ts
43723
43859
  var REFERENCE_CANDIDATE = /<([^<>]+)>/g;
43724
43860
  var VARIABLE_PREFIX = "variable";
@@ -43813,6 +43949,20 @@ var MODELED_ROW_KEYS = new Set(["id", "title", "value", "key"]);
43813
43949
  function isBranchExtraField(field) {
43814
43950
  return !MODELED_ROW_KEYS.has(field) && !UI_ROW_KEYS.has(field);
43815
43951
  }
43952
+ function storedTitle(kind, row, index, count) {
43953
+ if (row.titleOverride !== undefined)
43954
+ return row.titleOverride;
43955
+ return row.titleMissing ? undefined : positionalTitle(kind, index, count);
43956
+ }
43957
+ function positionalTitle(kind, index, count) {
43958
+ if (kind === "router")
43959
+ return `Route ${index + 1}`;
43960
+ if (index === 0)
43961
+ return "if";
43962
+ if (index === count - 1)
43963
+ return "else";
43964
+ return "else if";
43965
+ }
43816
43966
 
43817
43967
  // ../workflow-code/src/canonicalize/subflows.ts
43818
43968
  var PARALLEL_BATCH_MIN = 1;
@@ -47759,6 +47909,48 @@ function textField(value) {
47759
47909
  function jsonField(value) {
47760
47910
  return isJson(value) ? value : undefined;
47761
47911
  }
47912
+ function checkLoopCondition(ctx, decl, text, property) {
47913
+ if (text.trim() === "")
47914
+ return;
47915
+ const at = rangeOf(ctx, property.value);
47916
+ const selfReads = new Set;
47917
+ const ownName = normalizeWorkflowBlockName(decl.name);
47918
+ const runnable = text.replace(REFERENCE_CANDIDATE, (match, inner) => {
47919
+ if (!isLikelyWorkflowReferenceSegment(match))
47920
+ return match;
47921
+ const segments = parseStoredPath(inner);
47922
+ const [head, field] = segments ?? [];
47923
+ if (head?.kind === "name" && normalizeWorkflowBlockName(head.name) === ownName && field?.kind === "name" && LOOP_PROPERTIES.includes(field.name)) {
47924
+ selfReads.add(field.name);
47925
+ }
47926
+ return "(0)";
47927
+ });
47928
+ for (const field of selfReads) {
47929
+ 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, {
47930
+ hint: `Write <loop.${field}>: the bare loop prefix reads the iteration the condition is evaluated for.`,
47931
+ blockKey: decl.key
47932
+ });
47933
+ }
47934
+ let failure = null;
47935
+ try {
47936
+ const file = import_parser3.parse(`return Boolean(${runnable})`, {
47937
+ sourceType: "script",
47938
+ allowReturnOutsideFunction: true,
47939
+ errorRecovery: true
47940
+ });
47941
+ failure = file.errors?.[0] ?? null;
47942
+ } catch (error) {
47943
+ failure = error;
47944
+ }
47945
+ if (failure === null)
47946
+ return;
47947
+ const { message: raw } = babelErrorShape(failure);
47948
+ const message = typeof raw === "string" ? raw : "Invalid JavaScript";
47949
+ 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, {
47950
+ hint: "Write one JavaScript expression the loop repeats while it is true, e.g. condition: '<loop.index> < 3'.",
47951
+ blockKey: decl.key
47952
+ });
47953
+ }
47762
47954
  function compileContainer(ctx, decl) {
47763
47955
  const builder = decl.builder;
47764
47956
  if (builder.kind !== "container")
@@ -47790,6 +47982,12 @@ function compileContainer(ctx, decl) {
47790
47982
  ...doWhileCondition !== undefined && { doWhileCondition }
47791
47983
  };
47792
47984
  reportUnreadConfig(ctx, decl, form, written, loop);
47985
+ for (const field of ["whileCondition", "doWhileCondition"]) {
47986
+ const text = loop[field];
47987
+ const property = written.get(field);
47988
+ if (text !== undefined && property)
47989
+ checkLoopCondition(ctx, decl, text, property);
47990
+ }
47793
47991
  subflow = loop;
47794
47992
  } else {
47795
47993
  const { fields } = compileConfig(ctx, site, "parallel", parallelForm(builder.method), config);
@@ -48439,7 +48637,7 @@ function stronglyConnected(keys, successors) {
48439
48637
  }
48440
48638
 
48441
48639
  // ../workflow-code/src/compile/function-returns.ts
48442
- var import_parser3 = __toESM(require_lib(), 1);
48640
+ var import_parser4 = __toESM(require_lib(), 1);
48443
48641
  var FUNCTION_TYPE = "function";
48444
48642
  var NUMBER_FUNCTIONS = new Set(["Number", "parseInt", "parseFloat"]);
48445
48643
  var BOOLEAN_FUNCTIONS = new Set(["Boolean", "isNaN", "isFinite"]);
@@ -48775,7 +48973,7 @@ function returnedFields(object, inference) {
48775
48973
  function readReturns(code) {
48776
48974
  let program;
48777
48975
  try {
48778
- const file = import_parser3.parse(toCodeFile(code, "javascript"), {
48976
+ const file = import_parser4.parse(toCodeFile(code, "javascript"), {
48779
48977
  sourceType: "unambiguous",
48780
48978
  allowReturnOutsideFunction: true,
48781
48979
  allowAwaitOutsideFunction: true,
@@ -48875,6 +49073,7 @@ var COMPILE_SCOPE_CODES = [
48875
49073
  "W_ENV_UNKNOWN",
48876
49074
  "W_CHILD_INPUT_UNKNOWN",
48877
49075
  "W_CHILD_NO_START",
49076
+ "W_CHILD_RESULT_PATH",
48878
49077
  "E_UNKNOWN_SUBFLOW_PROPERTY",
48879
49078
  "W_FORWARD_REF",
48880
49079
  "W_REF_NOT_NORMALIZED",
@@ -48920,7 +49119,8 @@ var COMPILE_CATALOG_CODES = [
48920
49119
  "W_SUBFLOW_COUNT",
48921
49120
  "W_UNKNOWN_OUTPUT_PATH",
48922
49121
  "W_OUTPUT_PATH_UNDECLARED",
48923
- "W_JSON_REF_UNTYPED"
49122
+ "W_JSON_REF_UNTYPED",
49123
+ "W_LOOP_CONDITION_SYNTAX"
48924
49124
  ];
48925
49125
  var CODE_FILE_CODES = [
48926
49126
  "E_CODE_FILE_MISSING",
@@ -49024,6 +49224,7 @@ var APPLY_DIAGNOSTIC_CODES = [
49024
49224
  "E_APPLY_UNRESOLVED_REF",
49025
49225
  "E_APPLY_REF_OUT_OF_SCOPE",
49026
49226
  "E_APPLY_CODE_FILE_REF_SYNTAX",
49227
+ "E_APPLY_LOOP_CONDITION_SYNTAX",
49027
49228
  "W_APPLY_LINT",
49028
49229
  "W_TABLE_UNKNOWN_COLUMN",
49029
49230
  "E_APPLY_INVALID_SCHEDULE",
@@ -49065,7 +49266,8 @@ function refusalClassifier(extra = {}) {
49065
49266
  }
49066
49267
  var refusalClass = refusalClassifier();
49067
49268
  var CHANGED_BLOCK_REFUSALS = new Map([
49068
- ["W_REF_OUT_OF_SCOPE", "E_APPLY_REF_OUT_OF_SCOPE"]
49269
+ ["W_REF_OUT_OF_SCOPE", "E_APPLY_REF_OUT_OF_SCOPE"],
49270
+ ["W_LOOP_CONDITION_SYNTAX", "E_APPLY_LOOP_CONDITION_SYNTAX"]
49069
49271
  ]);
49070
49272
  var PARAM_REFUSALS = new Map([
49071
49273
  ["W_UNKNOWN_OPTION", "E_APPLY_INVALID_SUBBLOCK_FIELD"]
@@ -49084,6 +49286,7 @@ var CODE_FILE_REFUSALS = new Map([
49084
49286
  var REFUSABLE_WARNING_CODES = new Set([
49085
49287
  "W_UNKNOWN_OPTION",
49086
49288
  "W_REF_OUT_OF_SCOPE",
49289
+ "W_LOOP_CONDITION_SYNTAX",
49087
49290
  "W_UNKNOWN_OUTPUT_PATH",
49088
49291
  "W_UNRESOLVED_REF",
49089
49292
  "W_CODE_FILE_REF_SYNTAX",
@@ -50617,6 +50820,37 @@ function stableStringify(value) {
50617
50820
  function sha256Hex(text) {
50618
50821
  return bytesToHex(sha256(utf8ToBytes(text)));
50619
50822
  }
50823
+ // ../workflow-code/src/responds.ts
50824
+ function alwaysTakenBranches(block) {
50825
+ const branches = block.branches;
50826
+ if (!branches)
50827
+ return;
50828
+ const rows = branches.rows ?? [];
50829
+ if (branches.kind === "router")
50830
+ return rows.map((row) => row.key);
50831
+ const elseAt = rows.findIndex((row, index) => isElseConditionTitle(storedTitle(branches.kind, row, index, rows.length)));
50832
+ return elseAt === -1 ? [] : rows.slice(0, elseAt + 1).map((row) => row.key);
50833
+ }
50834
+ function portName(port) {
50835
+ return port.kind === "branch" ? `branch:${port.key}` : port.kind;
50836
+ }
50837
+ function respondsOnEveryRun(workflow) {
50838
+ const blocks = {};
50839
+ for (const [key, block] of Object.entries(workflow.blocks)) {
50840
+ const branches = alwaysTakenBranches(block);
50841
+ setOwn(blocks, key, {
50842
+ type: block.type,
50843
+ enabled: block.enabled,
50844
+ parentId: block.parent,
50845
+ ...branches !== undefined && { branches }
50846
+ });
50847
+ }
50848
+ return alwaysEndsAtResponse(blocks, workflow.edges.map((edge) => ({
50849
+ source: edge.from,
50850
+ target: edge.to,
50851
+ port: portName(edge.port)
50852
+ })));
50853
+ }
50620
50854
  // ../workflow-sdk/src/codegen/emit.ts
50621
50855
  function literal(value) {
50622
50856
  return typeof value === "string" ? quoteString(value) : String(value);
@@ -51287,12 +51521,14 @@ function dynamicOutputPlan(spec, outputs, operation) {
51287
51521
  var RUNTIME_SEMANTICS = [
51288
51522
  "## How it runs",
51289
51523
  "",
51290
- "- **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.",
51524
+ "- **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.",
51291
51525
  "- **`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.",
51292
- "- **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.",
51526
+ "- **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.",
51527
+ "- **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.",
51293
51528
  "- **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.",
51294
51529
  "- **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).",
51295
51530
  "- **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.",
51531
+ "- **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.",
51296
51532
  "- **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`.",
51297
51533
  ""
51298
51534
  ];
@@ -51882,6 +52118,7 @@ function describeBuilder(catalog, key) {
51882
52118
  summary: types.summary,
51883
52119
  ...entry.builder.operation ? { operation: entry.builder.operation } : {},
51884
52120
  legacy: isLegacyBuilder(key),
52121
+ ...entry.special ? docOf(key) : {},
51885
52122
  signature,
51886
52123
  tool,
51887
52124
  paramsName: types.paramsName,
@@ -51905,28 +52142,47 @@ function lookupBuilder(catalog, query) {
51905
52142
  if (SDK_CORE_EXPORTS.includes(root)) {
51906
52143
  return { kind: "core", name: key, declaration: coreDeclaration(root) };
51907
52144
  }
52145
+ const ofBlockType = paths.filter((path) => catalogBuilder(catalog, path)?.type === key);
52146
+ const only = ofBlockType.length === 1 ? describeBuilder(catalog, ofBlockType[0]) : null;
52147
+ if (only)
52148
+ return { kind: "builder", reference: only };
52149
+ if (ofBlockType.length > 1) {
52150
+ return {
52151
+ kind: "namespace",
52152
+ namespace: key,
52153
+ builders: ofBlockType.map((path) => ({ key: path, summary: summaryOf(catalog, path) }))
52154
+ };
52155
+ }
51908
52156
  const hint = suggestBuilder(key, paths.filter((path) => !isLegacyBuilder(path)));
51909
52157
  return hint ? { kind: "missing", hint } : { kind: "missing" };
51910
52158
  }
51911
52159
  var MAX_CORE_LINES = 80;
51912
- function coreDeclarationRanges(name) {
51913
- const lines = CORE_DTS.split(`
52160
+ var CORE_LINES = CORE_DTS.split(`
51914
52161
  `);
52162
+ function docCommentStart(start) {
52163
+ if (!CORE_LINES[start - 1]?.trim().endsWith("*/"))
52164
+ return start;
52165
+ let first = start - 1;
52166
+ while (first > 0 && !CORE_LINES[first].trim().startsWith("/**"))
52167
+ first--;
52168
+ return first;
52169
+ }
52170
+ function coreDeclarationRanges(name) {
51915
52171
  const start = new RegExp(`^export (?:declare )?(?:const|function|namespace|interface|type) ${escapeRegExp(name)}\\b`);
51916
52172
  const declarations = [];
51917
- for (let index = 0;index < lines.length; index++) {
51918
- if (!start.test(lines[index]))
52173
+ for (let index = 0;index < CORE_LINES.length; index++) {
52174
+ if (!start.test(CORE_LINES[index]))
51919
52175
  continue;
51920
52176
  let depth = 0;
51921
52177
  let end = index;
51922
- for (;end < lines.length; end++) {
51923
- for (const char of lines[end]) {
52178
+ for (;end < CORE_LINES.length; end++) {
52179
+ for (const char of CORE_LINES[end]) {
51924
52180
  if ("({[".includes(char))
51925
52181
  depth++;
51926
52182
  else if (")}]".includes(char))
51927
52183
  depth--;
51928
52184
  }
51929
- const continues = /[=:,|&]\s*$/.test(lines[end]) || /^\s+[?:|&]/.test(lines[end + 1] ?? "");
52185
+ const continues = /[=:,|&]\s*$/.test(CORE_LINES[end]) || /^\s+[?:|&]/.test(CORE_LINES[end + 1] ?? "");
51930
52186
  if (depth <= 0 && !continues)
51931
52187
  break;
51932
52188
  }
@@ -51936,28 +52192,26 @@ function coreDeclarationRanges(name) {
51936
52192
  return declarations;
51937
52193
  }
51938
52194
  function coreSignatures(name) {
51939
- const lines = CORE_DTS.split(`
51940
- `);
51941
- 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(`
52195
+ 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(`
51942
52196
  `);
51943
52197
  }
51944
52198
  function coreDeclaration(name) {
51945
- const lines = CORE_DTS.split(`
51946
- `);
51947
52199
  const out = [];
51948
52200
  for (const { start, end } of coreDeclarationRanges(name)) {
51949
- let first = start;
51950
- if (lines[start - 1]?.trim().endsWith("*/")) {
51951
- while (first > 0 && !lines[first].trim().startsWith("/**"))
51952
- first--;
51953
- }
51954
52201
  if (out.length > 0)
51955
52202
  out.push("");
51956
- out.push(...lines.slice(first, end));
52203
+ out.push(...CORE_LINES.slice(docCommentStart(start), end));
51957
52204
  }
51958
52205
  return out.slice(0, MAX_CORE_LINES).join(`
51959
52206
  `);
51960
52207
  }
52208
+ function docOf(name) {
52209
+ const range = coreDeclarationRanges(name)[0];
52210
+ if (!range)
52211
+ return {};
52212
+ const doc = CORE_LINES.slice(docCommentStart(range.start), range.start).map((line) => line.trim().replace(/^\/\*\*\s?|\s?\*\/$|^\*\s?/g, "")).join(" ").replace(/\s+/g, " ").trim();
52213
+ return doc ? { doc } : {};
52214
+ }
51961
52215
  var MAX_SNIPPET_TYPE = 60;
51962
52216
  var MAX_SNIPPET_OPTIONAL = 12;
51963
52217
  function shortType(type) {
@@ -52048,6 +52302,8 @@ function renderBuilderReference(reference) {
52048
52302
  if (reference.legacy) {
52049
52303
  lines.push("Legacy: an older block version. Write the current builder instead.");
52050
52304
  }
52305
+ if (reference.doc)
52306
+ lines.push("", reference.doc);
52051
52307
  lines.push("", reference.signature);
52052
52308
  if (reference.tool)
52053
52309
  lines.push(`${reference.tool} (as an agent tool)`);
@@ -52295,12 +52551,13 @@ Write like a person, not a policy. Lead with the answer, then the one detail tha
52295
52551
  import { column, defineTable } from '@sim/workflow-sdk/workspace'
52296
52552
 
52297
52553
  // tables/<key>.ts: the key (\`orders\`) is how a workflow names it: table('orders'). Its rows stay
52298
- // out of source (see plans.ts to opt in). To rename a column keep its key and set \`name\`.
52554
+ // out of source (see plans.ts to opt in). To rename a column keep its key and set \`name\`: a
52555
+ // workflow's row data (\`data\`, \`conflictColumn\`, filters) names a column by that name, not its key.
52299
52556
  export default defineTable({
52300
52557
  name: 'orders',
52301
52558
  description: 'Order questions the support workflow answered',
52302
52559
  columns: {
52303
- orderId: column.string({ required: true }),
52560
+ orderId: column.string({ required: true, unique: true }),
52304
52561
  status: column.select({ options: ['open', 'answered'] }),
52305
52562
  total: column.number(),
52306
52563
  },
@@ -52379,9 +52636,10 @@ export default workflow('Support', { description: 'Answers an order question.' }
52379
52636
  tools: [customTool('lookup-order')],
52380
52637
  skills: [skill('tone')],
52381
52638
  })
52382
- const log = table.insertRow('Log Question', {
52639
+ const log = table.upsertRow('Log Question', {
52383
52640
  tableId: table('orders'),
52384
52641
  data: { orderId: start.orderId, status: 'answered' },
52642
+ conflictColumn: 'orderId',
52385
52643
  })
52386
52644
 
52387
52645
  start.to(policy)
@@ -53894,7 +54152,7 @@ async function withSourceCommandLock(dir, run, options = {}) {
53894
54152
  return withSourceDirLock(folder ? folder.root : dir, run, options);
53895
54153
  }
53896
54154
  // ../workflow-code/src/code-files/references.ts
53897
- var import_parser4 = __toESM(require_lib(), 1);
54155
+ var import_parser5 = __toESM(require_lib(), 1);
53898
54156
  var CODE_FILE_EXPORT = "codeFile";
53899
54157
  function codeFileReferences(text) {
53900
54158
  if (utf8Bytes(text, SOURCE_LIMITS.maxTotalBytes) > SOURCE_LIMITS.maxTotalBytes)
@@ -53903,7 +54161,7 @@ function codeFileReferences(text) {
53903
54161
  return [];
53904
54162
  let program;
53905
54163
  try {
53906
- program = import_parser4.parse(text, PARSER_OPTIONS).program;
54164
+ program = import_parser5.parse(text, PARSER_OPTIONS).program;
53907
54165
  } catch {
53908
54166
  return [];
53909
54167
  }
@@ -54119,6 +54377,10 @@ function loopRows(rows) {
54119
54377
  return rows.map(([command, what]) => ` ${command.padEnd(width)}${what}`.trimEnd()).join(`
54120
54378
  `);
54121
54379
  }
54380
+ var WORKSPACE_LINE = `Workspace: a directory records it (.sim/base.json, or a starter's .sim/starter.json); any other
54381
+ command takes -w <id>, SIM_WORKSPACE or the profile's (export SIM_WORKSPACE once, or keep only the
54382
+ ID in a variable: one holding "--workspace <id>" is one argument, an unknown option alone and the
54383
+ whole ID after -w).`;
54122
54384
  function statusLine(group, dir) {
54123
54385
  return `\`${group} status --dir ${dir}\` shows what applying would do and
54124
54386
  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).
@@ -54137,6 +54399,7 @@ ${loopRows([
54137
54399
  A new workflow: \`sim workflows source create --dir ./new --workspace <workspaceId>\` writes a
54138
54400
  starter that records its workspace; edit and check it, then \`create --dir ./new --yes\` creates the
54139
54401
  workflow there, and the loop above goes on from there.
54402
+ ${WORKSPACE_LINE}
54140
54403
 
54141
54404
  Flags the loop needs: --allow-delete (apply: an edit that removes a block or variable is refused
54142
54405
  without it), --deploy (apply, create: also deploy the saved draft), --force (get: replace another
@@ -54154,6 +54417,7 @@ ${loopRows([
54154
54417
  ])}
54155
54418
  Promote dev to prod: \`sim workspaces source apply --dir ./ws --to <workspaceId> --dry-run\`, then
54156
54419
  --yes.
54420
+ ${WORKSPACE_LINE}
54157
54421
 
54158
54422
  Flags the loop needs: --allow-delete (apply: removing a resource, a column, rows or a document,
54159
54423
  or a workflow's block or variable, is refused without it), --force (get: replace edits no apply
@@ -54447,6 +54711,112 @@ async function printRunFailureSite(dir, workflowId, error) {
54447
54711
  ]);
54448
54712
  }
54449
54713
 
54714
+ // src/commands/protocol/workflow-run-get.ts
54715
+ var BLOCK_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
54716
+ var SELECT_OUTPUT_FLAG = "select-output";
54717
+ function normalizeBlockName(name) {
54718
+ return name.toLowerCase().replace(/\s+/g, "").replace(/\./g, "");
54719
+ }
54720
+ async function loadWorkflowBlocks(client, workflowId) {
54721
+ const raw = await client.request("getWorkflowState", { params: { workflowId } });
54722
+ const state = isRecordLike(raw) && isRecordLike(raw.data) ? raw.data : raw;
54723
+ const blocks = isRecordLike(state) && isRecordLike(state.blocks) ? Object.entries(state.blocks) : [];
54724
+ return blocks.map(([key, block]) => ({
54725
+ id: isRecordLike(block) && typeof block.id === "string" ? block.id : key,
54726
+ name: isRecordLike(block) && typeof block.name === "string" ? block.name : ""
54727
+ }));
54728
+ }
54729
+ function splitSelector(selector) {
54730
+ const dot = selector.indexOf(".");
54731
+ return dot === -1 ? { head: selector, path: "" } : { head: selector.slice(0, dot), path: selector.slice(dot) };
54732
+ }
54733
+ function isIdHeaded(selector) {
54734
+ return BLOCK_ID.test(splitSelector(selector).head);
54735
+ }
54736
+ function resolveSelection(typed, blocks, workflowId) {
54737
+ const resolved = [];
54738
+ const typedBy = new Map;
54739
+ const unresolved = [];
54740
+ for (const selector of typed) {
54741
+ const { head, path } = splitSelector(selector);
54742
+ let blockId = head;
54743
+ if (!BLOCK_ID.test(head)) {
54744
+ const wanted = normalizeBlockName(head);
54745
+ const matches = blocks.filter((block) => block.id === head || normalizeBlockName(block.name) === wanted);
54746
+ if (matches.length === 0) {
54747
+ unresolved.push(selector);
54748
+ continue;
54749
+ }
54750
+ if (matches.length > 1) {
54751
+ throw new SimApiError(`--${SELECT_OUTPUT_FLAG} ${selector} names ${matches.length} blocks (${matches.map((block) => block.id).join(", ")}); pass the block id instead`, 0);
54752
+ }
54753
+ blockId = matches[0].id;
54754
+ }
54755
+ const rewritten = `${blockId}${path}`;
54756
+ resolved.push(rewritten);
54757
+ if (!typedBy.has(rewritten))
54758
+ typedBy.set(rewritten, selector);
54759
+ }
54760
+ if (unresolved.length > 0) {
54761
+ const names = blocks.map((block) => block.name).filter((name) => name !== "");
54762
+ 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);
54763
+ }
54764
+ return { resolved, typedBy };
54765
+ }
54766
+ function keyByTyped(payload, typedBy) {
54767
+ if (!isRecordLike(payload) || !isRecordLike(payload.blockOutputs))
54768
+ return payload;
54769
+ const blockOutputs = {};
54770
+ for (const [key, value] of Object.entries(payload.blockOutputs)) {
54771
+ blockOutputs[typedBy.get(key) ?? key] = value;
54772
+ }
54773
+ return { ...payload, blockOutputs };
54774
+ }
54775
+ async function readRunByName(runId, typed, command, { client, profile }) {
54776
+ const flags = command.optsWithGlobals();
54777
+ const operation = V2_OPERATIONS.getWorkflowRun;
54778
+ const spec = CLI_CONTRACT.getWorkflowRun ?? {};
54779
+ await buildRequest("getWorkflowRun", [runId], flags, profile.workspaceId);
54780
+ const workflowId = String(flags.workflow);
54781
+ const selection = resolveSelection(typed, await loadWorkflowBlocks(client, workflowId), workflowId);
54782
+ const request = await buildRequest("getWorkflowRun", [runId], { ...flags, selectOutput: selection.resolved }, profile.workspaceId);
54783
+ let result;
54784
+ try {
54785
+ result = await client.request("getWorkflowRun", {
54786
+ params: request.params,
54787
+ headers: request.headers,
54788
+ query: request.query,
54789
+ body: request.body
54790
+ });
54791
+ } catch (error) {
54792
+ throw retypeApiError(error, "getWorkflowRun", spec, operation);
54793
+ }
54794
+ renderResult("getWorkflowRun", profile.output, keyByTyped(result?.data ?? result, selection.typedBy), spec, {}, result);
54795
+ }
54796
+ function attachWorkflowRunGet(runs) {
54797
+ const get = runs.commands.find((command) => command.name() === "get");
54798
+ const held = get?._actionHandler;
54799
+ if (!get || typeof held !== "function") {
54800
+ throw new Error("workflows runs get must be registered before block names can be attached to it");
54801
+ }
54802
+ const previous = held;
54803
+ const connectGet = callsOperations(get, ["getWorkflowRun", "getWorkflowState"]);
54804
+ get.action(async (runId, _options, command) => {
54805
+ const raw = command.optsWithGlobals().selectOutput;
54806
+ if (raw === undefined) {
54807
+ await previous(command.processedArgs);
54808
+ return;
54809
+ }
54810
+ const typed = await readListValues(raw, SELECT_OUTPUT_FLAG);
54811
+ command.setOptionValue("selectOutput", typed);
54812
+ if (typed.every(isIdHeaded)) {
54813
+ await previous(command.processedArgs);
54814
+ return;
54815
+ }
54816
+ await readRunByName(runId, typed, command, connectGet());
54817
+ });
54818
+ }
54819
+
54450
54820
  // src/commands/protocol/workflow-run-wait.ts
54451
54821
  var TERMINAL_STATUSES = new Set(["completed", "failed", "cancelled"]);
54452
54822
  var WAIT_EXIT_CODES = {
@@ -54880,6 +55250,14 @@ async function followRun(workflowId, command) {
54880
55250
  throw new SimApiError(safeOneLine(typeof final.error === "string" ? final.error : "The workflow run failed."), 0);
54881
55251
  }
54882
55252
  }
55253
+ function stopBlockSelection(selection, flags) {
55254
+ const stopAfter = selection?.stopAfterBlockId;
55255
+ if (stopAfter === undefined)
55256
+ return null;
55257
+ if (Array.isArray(flags.selectOutput) && flags.selectOutput.length > 0)
55258
+ return null;
55259
+ return [BLOCK_ID.test(stopAfter) ? stopAfter : normalizeBlockName(stopAfter)];
55260
+ }
54883
55261
  function followOrDelegate(previous) {
54884
55262
  return async (workflowId, _options, command) => {
54885
55263
  const initialFlags = command.optsWithGlobals();
@@ -54897,6 +55275,9 @@ function followOrDelegate(previous) {
54897
55275
  if (selection)
54898
55276
  command.setOptionValue("run", selection);
54899
55277
  const flags = command.optsWithGlobals();
55278
+ const stopBlock = stopBlockSelection(selection, flags);
55279
+ if (stopBlock)
55280
+ command.setOptionValue("selectOutput", stopBlock);
54900
55281
  if (flags.follow !== true) {
54901
55282
  if (Array.isArray(flags.selectOutput) && flags.selectOutput.length > 0 && flags.async === true) {
54902
55283
  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);
@@ -54918,6 +55299,18 @@ function followOrDelegate(previous) {
54918
55299
  await followRun(workflowId, command);
54919
55300
  };
54920
55301
  }
55302
+ var RUN_HELP = `
55303
+ Without --manual (or a flag that implies it) this runs the active deployment; a workflow never
55304
+ deployed has none. --manual runs the saved draft, as the source loop leaves it.
55305
+
55306
+ The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the
55307
+ workflow's final output) and blockOutputs (what --select-output named). It has no success field:
55308
+ branch on status, or on the exit code. With --follow it is the stream's final frame
55309
+ instead: success and output.
55310
+
55311
+ Exit codes: 0 completed or paused (--async: queued); 1 failed or cancelled (the result is printed
55312
+ first, then the error on stderr), or the command failed; ${STILL_RUNNING_EXIT_CODE} still running when --wait-timeout
55313
+ elapsed.`;
54921
55314
  function attachWorkflowRunFollow(workflows) {
54922
55315
  const run = workflows.commands.find((command) => command.name() === "run");
54923
55316
  if (!run) {
@@ -54926,113 +55319,7 @@ function attachWorkflowRunFollow(workflows) {
54926
55319
  const held = run._actionHandler;
54927
55320
  const previous = typeof held === "function" ? held : null;
54928
55321
  callsOperations(run, ["executeWorkflow", "getWorkflowRun"], { runs: "executeWorkflow" });
54929
- 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));
54930
- }
54931
-
54932
- // src/commands/protocol/workflow-run-get.ts
54933
- var BLOCK_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
54934
- var SELECT_OUTPUT_FLAG = "select-output";
54935
- function normalizeBlockName(name) {
54936
- return name.toLowerCase().replace(/\s+/g, "").replace(/\./g, "");
54937
- }
54938
- async function loadWorkflowBlocks(client, workflowId) {
54939
- const raw = await client.request("getWorkflowState", { params: { workflowId } });
54940
- const state = isRecordLike(raw) && isRecordLike(raw.data) ? raw.data : raw;
54941
- const blocks = isRecordLike(state) && isRecordLike(state.blocks) ? Object.entries(state.blocks) : [];
54942
- return blocks.map(([key, block]) => ({
54943
- id: isRecordLike(block) && typeof block.id === "string" ? block.id : key,
54944
- name: isRecordLike(block) && typeof block.name === "string" ? block.name : ""
54945
- }));
54946
- }
54947
- function splitSelector(selector) {
54948
- const dot = selector.indexOf(".");
54949
- return dot === -1 ? { head: selector, path: "" } : { head: selector.slice(0, dot), path: selector.slice(dot) };
54950
- }
54951
- function isIdHeaded(selector) {
54952
- return BLOCK_ID.test(splitSelector(selector).head);
54953
- }
54954
- function resolveSelection(typed, blocks, workflowId) {
54955
- const resolved = [];
54956
- const typedBy = new Map;
54957
- const unresolved = [];
54958
- for (const selector of typed) {
54959
- const { head, path } = splitSelector(selector);
54960
- let blockId = head;
54961
- if (!BLOCK_ID.test(head)) {
54962
- const wanted = normalizeBlockName(head);
54963
- const matches = blocks.filter((block) => block.id === head || normalizeBlockName(block.name) === wanted);
54964
- if (matches.length === 0) {
54965
- unresolved.push(selector);
54966
- continue;
54967
- }
54968
- if (matches.length > 1) {
54969
- throw new SimApiError(`--${SELECT_OUTPUT_FLAG} ${selector} names ${matches.length} blocks (${matches.map((block) => block.id).join(", ")}); pass the block id instead`, 0);
54970
- }
54971
- blockId = matches[0].id;
54972
- }
54973
- const rewritten = `${blockId}${path}`;
54974
- resolved.push(rewritten);
54975
- if (!typedBy.has(rewritten))
54976
- typedBy.set(rewritten, selector);
54977
- }
54978
- if (unresolved.length > 0) {
54979
- const names = blocks.map((block) => block.name).filter((name) => name !== "");
54980
- 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);
54981
- }
54982
- return { resolved, typedBy };
54983
- }
54984
- function keyByTyped(payload, typedBy) {
54985
- if (!isRecordLike(payload) || !isRecordLike(payload.blockOutputs))
54986
- return payload;
54987
- const blockOutputs = {};
54988
- for (const [key, value] of Object.entries(payload.blockOutputs)) {
54989
- blockOutputs[typedBy.get(key) ?? key] = value;
54990
- }
54991
- return { ...payload, blockOutputs };
54992
- }
54993
- async function readRunByName(runId, typed, command, { client, profile }) {
54994
- const flags = command.optsWithGlobals();
54995
- const operation = V2_OPERATIONS.getWorkflowRun;
54996
- const spec = CLI_CONTRACT.getWorkflowRun ?? {};
54997
- await buildRequest("getWorkflowRun", [runId], flags, profile.workspaceId);
54998
- const workflowId = String(flags.workflow);
54999
- const selection = resolveSelection(typed, await loadWorkflowBlocks(client, workflowId), workflowId);
55000
- const request = await buildRequest("getWorkflowRun", [runId], { ...flags, selectOutput: selection.resolved }, profile.workspaceId);
55001
- let result;
55002
- try {
55003
- result = await client.request("getWorkflowRun", {
55004
- params: request.params,
55005
- headers: request.headers,
55006
- query: request.query,
55007
- body: request.body
55008
- });
55009
- } catch (error) {
55010
- throw retypeApiError(error, "getWorkflowRun", spec, operation);
55011
- }
55012
- renderResult("getWorkflowRun", profile.output, keyByTyped(result?.data ?? result, selection.typedBy), spec, {}, result);
55013
- }
55014
- function attachWorkflowRunGet(runs) {
55015
- const get = runs.commands.find((command) => command.name() === "get");
55016
- const held = get?._actionHandler;
55017
- if (!get || typeof held !== "function") {
55018
- throw new Error("workflows runs get must be registered before block names can be attached to it");
55019
- }
55020
- const previous = held;
55021
- const connectGet = callsOperations(get, ["getWorkflowRun", "getWorkflowState"]);
55022
- get.action(async (runId, _options, command) => {
55023
- const raw = command.optsWithGlobals().selectOutput;
55024
- if (raw === undefined) {
55025
- await previous(command.processedArgs);
55026
- return;
55027
- }
55028
- const typed = await readListValues(raw, SELECT_OUTPUT_FLAG);
55029
- command.setOptionValue("selectOutput", typed);
55030
- if (typed.every(isIdHeaded)) {
55031
- await previous(command.processedArgs);
55032
- return;
55033
- }
55034
- await readRunByName(runId, typed, command, connectGet());
55035
- });
55322
+ 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));
55036
55323
  }
55037
55324
 
55038
55325
  // ../../node_modules/minisearch/dist/es/index.js
@@ -56248,7 +56535,7 @@ function sourceExitCodeRows(prefix) {
56248
56535
  "workflows source apply": "the source has errors (each printed as file:line:column with its frame and hint) or the command failed",
56249
56536
  "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)",
56250
56537
  "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)",
56251
- "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",
56538
+ "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",
56252
56539
  "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)"
56253
56540
  }
56254
56541
  },
@@ -56348,10 +56635,10 @@ function sourceExitCodeRows(prefix) {
56348
56635
  },
56349
56636
  {
56350
56637
  code: SOURCE_HELD_EXIT_CODE,
56351
- 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",
56638
+ 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",
56352
56639
  next: "Set the secret (`sim secrets set`) or connect the credential, then apply again",
56353
56640
  help: {
56354
- "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)"
56641
+ "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"
56355
56642
  }
56356
56643
  },
56357
56644
  {
@@ -56430,14 +56717,14 @@ var WORKFLOW_PRIMER = `# Sim workflow source: primer
56430
56717
  - **Deploy**: apply saves a draft; \`apply --deploy\` also deploys it, or \`sim workflows deploy <workflowId>\` publishes the saved draft later.
56431
56718
  ${sharedRules("sim workflows source")}
56432
56719
  `;
56433
- 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`.";
56720
+ 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`.";
56434
56721
  var WORKSPACE_PRIMER = `# Sim workspace source: primer
56435
56722
 
56436
- 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.
56723
+ 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.
56437
56724
 
56438
56725
  **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.
56439
56726
 
56440
- - **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.
56727
+ - **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.
56441
56728
  - **Deploy**: \`deployments/<workflow key>.ts\` (\`defineDeployment({ live: 'draft' })\`) deploys that workflow on apply, which prints its webhook URLs; without one, apply never deploys.
56442
56729
  - **Promote** (dev → prod): \`sim workspaces source apply --dir . --to <workspaceId> --dry-run\`, then \`--yes\`.
56443
56730
  - **Exit ${SOURCE_HELD_EXIT_CODE}**: written in part; changes using an unset secret or unbound credential were held back: set it, apply again.
@@ -57116,7 +57403,7 @@ async function runSourceWrite(flow) {
57116
57403
  preview = await flow.preview();
57117
57404
  flow.show(preview);
57118
57405
  if (preview.diagnostics.some((finding) => finding.severity === "error")) {
57119
- setSoftExitCode(refusedExitCode(preview.diagnostics));
57406
+ setSoftExitCode(flow.previewExitCode?.(preview) ?? refusedExitCode(preview.diagnostics));
57120
57407
  }
57121
57408
  if (flow.mode === "dry-run" || flow.refuses(preview)) {
57122
57409
  flow.report(preview);
@@ -57316,12 +57603,18 @@ async function readBase(directory, workflowId) {
57316
57603
  }
57317
57604
  return base;
57318
57605
  }
57606
+ var WORKFLOW_GET = `\`sim workflows source get <workflowId> --dir <new dir>\`, with the id from ${SOURCE_BASE_FILE}`;
57607
+ function lockRecoveryHint(get = WORKFLOW_GET) {
57608
+ return `Restore ${SOURCE_LOCK_FILE} from version control, or write the source into a fresh directory (${get}) and carry your edits across.`;
57609
+ }
57610
+ function lockProblem(finding) {
57611
+ return `${finding.path ? `${finding.path}: ` : ""}${finding.message}`;
57612
+ }
57319
57613
  async function readLock(directory) {
57320
57614
  const parsed = parseWorkflowLock(await readJson(directory, SOURCE_LOCK_FILE, GET_HINT));
57321
57615
  if (parsed.lock)
57322
57616
  return parsed.lock;
57323
- const problems = parsed.diagnostics.map((finding) => `${finding.path === "" ? "" : `${finding.path}: `}${finding.message}`);
57324
- throw new SourceDirError(`${SOURCE_LOCK_FILE} in ${directory} is not a valid lock: ${problems.join("; ")}`);
57617
+ throw new SourceDirError(`${SOURCE_LOCK_FILE} in ${directory} is not a valid lock: ${parsed.diagnostics.map(lockProblem).join("; ")}. ${lockRecoveryHint()}`);
57325
57618
  }
57326
57619
  function requireEntry(directory) {
57327
57620
  return requireText(directory, SOURCE_ENTRY_FILE, GET_HINT);
@@ -57360,7 +57653,7 @@ The primer above is enough to edit; read a section here when a step needs it.
57360
57653
 
57361
57654
  ## Edit loop in detail
57362
57655
 
57363
- 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}\`.
57656
+ 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}\`.
57364
57657
  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\`.
57365
57658
  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.
57366
57659
  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.
@@ -57832,7 +58125,7 @@ function summarize(data, creating, machine) {
57832
58125
  import { join as join9 } from "node:path";
57833
58126
 
57834
58127
  // ../workspace-code/src/declaration/read.ts
57835
- var import_parser5 = __toESM(require_lib(), 1);
58128
+ var import_parser6 = __toESM(require_lib(), 1);
57836
58129
 
57837
58130
  // ../workspace-code/src/limits.ts
57838
58131
  var WORKSPACE_SOURCE_LIMITS = {
@@ -57956,7 +58249,7 @@ function readDeclaration(file, raw, options) {
57956
58249
  }
57957
58250
  let program;
57958
58251
  try {
57959
- program = import_parser5.parse(text, PARSER_OPTIONS2).program;
58252
+ program = import_parser6.parse(text, PARSER_OPTIONS2).program;
57960
58253
  } catch (error) {
57961
58254
  if (error instanceof RangeError) {
57962
58255
  diagnostics.push(diagnostic2("E_LIMIT_EXCEEDED", "The file is nested too deeply to parse.", { ...at(0, 0) }));
@@ -62316,7 +62609,7 @@ var ZodRealError = $constructor("ZodError", initializer2, {
62316
62609
  });
62317
62610
 
62318
62611
  // ../../node_modules/zod/v4/classic/parse.js
62319
- var parse8 = /* @__PURE__ */ _parse(ZodRealError);
62612
+ var parse9 = /* @__PURE__ */ _parse(ZodRealError);
62320
62613
  var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError);
62321
62614
  var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError);
62322
62615
  var safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError);
@@ -62359,7 +62652,7 @@ var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
62359
62652
  reg.add(inst, meta);
62360
62653
  return inst;
62361
62654
  };
62362
- inst.parse = (data, params) => parse8(inst, data, params, { callee: inst.parse });
62655
+ inst.parse = (data, params) => parse9(inst, data, params, { callee: inst.parse });
62363
62656
  inst.safeParse = (data, params) => safeParse2(inst, data, params);
62364
62657
  inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync });
62365
62658
  inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params);
@@ -64176,6 +64469,7 @@ function declaredColumns(decl) {
64176
64469
  return new Map(Object.entries(decl.columns).map(([columnKey, column]) => [
64177
64470
  columnName(columnKey, column),
64178
64471
  {
64472
+ key: columnKey,
64179
64473
  ...column.options ? { options: column.options } : {},
64180
64474
  ...column.multiple ? { multiple: true } : {}
64181
64475
  }
@@ -64378,9 +64672,11 @@ var STRICT_CODES = new Set([
64378
64672
  "W_LITERAL_SECRET",
64379
64673
  "W_TABLE_UNKNOWN_COLUMN",
64380
64674
  "W_CHILD_INPUT_UNKNOWN",
64675
+ "W_CHILD_RESULT_PATH",
64381
64676
  "W_BRANCH_UNWIRED",
64382
64677
  "W_UNRESOLVED_REF",
64383
- "W_REF_OUT_OF_SCOPE"
64678
+ "W_REF_OUT_OF_SCOPE",
64679
+ "W_LOOP_CONDITION_SYNTAX"
64384
64680
  ]);
64385
64681
  var STORED_EXEMPT_CODES = new Set(["W_BRANCH_UNWIRED"]);
64386
64682
  var EDIT_SCOPED_CODES = new Set(["W_JSON_REF_UNTYPED"]);
@@ -64469,25 +64765,29 @@ function inputMappingOf(canonical) {
64469
64765
  const value = rowJson(mapping.value);
64470
64766
  return toRecord(value);
64471
64767
  }
64472
- function childInputFindings(block, canonical, declarations) {
64768
+ function calledWorkflowKey(canonical) {
64473
64769
  const ref = canonical.params.workflowId;
64474
64770
  const child = ref?.kind === "value" ? resourceNode(ref.value) : null;
64475
- if (child?.kind !== "workflow")
64771
+ return child?.kind === "workflow" ? child.key : null;
64772
+ }
64773
+ function childInputFindings(block, canonical, declarations) {
64774
+ const childKey = calledWorkflowKey(canonical);
64775
+ if (childKey === null)
64476
64776
  return [];
64477
- const inputs = declarations.workflowInputs?.get(child.key);
64777
+ const inputs = declarations.workflowInputs?.get(childKey);
64478
64778
  if (inputs === undefined)
64479
64779
  return [];
64480
- const entry = `${KIND_DIRS.workflow}/${child.key}/${SOURCE_ENTRY_FILE}`;
64780
+ const entry = `${KIND_DIRS.workflow}/${childKey}/${SOURCE_ENTRY_FILE}`;
64481
64781
  if (inputs === null) {
64482
64782
  return [
64483
64783
  {
64484
64784
  code: "W_CHILD_NO_START",
64485
64785
  severity: "warning",
64486
- message: `Workflow "${child.key}" has no Start trigger, so it takes no inputs and a call cannot run it.`,
64786
+ message: `Workflow "${childKey}" has no Start trigger, so it takes no inputs and a call cannot run it.`,
64487
64787
  hint: `Add trigger.start('Start', { inputFormat: { … } }) to ${entry}, or call a workflow that has one.`,
64488
64788
  block,
64489
64789
  param: "workflowId",
64490
- names: child.key
64790
+ names: childKey
64491
64791
  }
64492
64792
  ];
64493
64793
  }
@@ -64495,12 +64795,81 @@ function childInputFindings(block, canonical, declarations) {
64495
64795
  return Object.keys(inputMappingOf(canonical)).filter((field) => !names.includes(field)).map((field) => ({
64496
64796
  code: "W_CHILD_INPUT_UNKNOWN",
64497
64797
  severity: "warning",
64498
- message: `inputMapping sets ${field}, which is not an input of workflow "${child.key}"; the child never receives it.`,
64798
+ message: `inputMapping sets ${field}, which is not an input of workflow "${childKey}"; the child never receives it.`,
64499
64799
  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.`,
64500
64800
  block,
64501
64801
  param: "inputMapping"
64502
64802
  }));
64503
64803
  }
64804
+ function childResultFindings(workflow, declarations) {
64805
+ const responding = declarations.respondingWorkflows;
64806
+ if (!responding || responding.size === 0)
64807
+ return [];
64808
+ const calls = new Map;
64809
+ for (const [key, block] of Object.entries(workflow.blocks)) {
64810
+ const child = calledWorkflowKey(block);
64811
+ if (child !== null && responding.has(child))
64812
+ calls.set(key, child);
64813
+ }
64814
+ if (calls.size === 0)
64815
+ return [];
64816
+ const findings = [];
64817
+ for (const [block, canonical] of Object.entries(workflow.blocks)) {
64818
+ for (const [param, value] of Object.entries(canonical.params)) {
64819
+ if (value.kind !== "value")
64820
+ continue;
64821
+ const reported = new Set;
64822
+ const leaves = [];
64823
+ collectStringLeaves(value.value, leaves);
64824
+ for (const text of leaves) {
64825
+ for (const token of findWorkflowReferenceTokens(text)) {
64826
+ if (token.kind !== "workflow" || reported.has(token.value))
64827
+ continue;
64828
+ const segments = parseStoredPath(token.value.slice(1, -1));
64829
+ const [head, output, field, ...rest] = segments ?? [];
64830
+ const child = head?.kind === "name" ? calls.get(head.name) : undefined;
64831
+ if (child === undefined || output?.kind !== "name" || output.name !== "result")
64832
+ continue;
64833
+ if (field?.kind !== "name" || RESPONSE_OUTPUTS.includes(field.name))
64834
+ continue;
64835
+ reported.add(token.value);
64836
+ const meant = formatStoredPath([
64837
+ head,
64838
+ output,
64839
+ { kind: "name", name: "data" },
64840
+ field,
64841
+ ...rest
64842
+ ]);
64843
+ findings.push({
64844
+ code: "W_CHILD_RESULT_PATH",
64845
+ severity: "warning",
64846
+ 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.`,
64847
+ hint: `Did you mean <${meant}>? A field of the child's Response data is result.data.${field.name}.`,
64848
+ block,
64849
+ param
64850
+ });
64851
+ }
64852
+ }
64853
+ }
64854
+ }
64855
+ return findings;
64856
+ }
64857
+ function unknownColumnFinding(table, columns, field, block, param) {
64858
+ const finding = { code: "W_TABLE_UNKNOWN_COLUMN", severity: "warning", block, param };
64859
+ const renamed = [...columns].find(([, column]) => column.key === field)?.[0];
64860
+ if (renamed) {
64861
+ return {
64862
+ ...finding,
64863
+ message: `${param} writes ${field}, the key of column "${renamed}" of table "${table}": row data is keyed by column name, so the run drops it.`,
64864
+ hint: `Did you mean ${renamed}?`
64865
+ };
64866
+ }
64867
+ return {
64868
+ ...finding,
64869
+ message: `${param} writes ${field}, which is not a column of table "${table}"; the run drops it.`,
64870
+ hint: `${didYouMean(field, columns.keys()) ?? ""} Columns: ${listed2(columns.keys())}.`.trimStart()
64871
+ };
64872
+ }
64504
64873
  function declarationFindings(workflow, declarations) {
64505
64874
  const findings = [];
64506
64875
  for (const [block, canonical] of Object.entries(workflow.blocks)) {
@@ -64542,14 +64911,7 @@ function declarationFindings(workflow, declarations) {
64542
64911
  for (const [field, cell] of Object.entries(row)) {
64543
64912
  const column = columns.get(field);
64544
64913
  if (!column) {
64545
- findings.push({
64546
- code: "W_TABLE_UNKNOWN_COLUMN",
64547
- severity: "warning",
64548
- message: `${param} writes ${field}, which is not a column of table "${table}"; the run drops it.`,
64549
- hint: `${didYouMean(field, columns.keys()) ?? ""} Columns: ${listed2(columns.keys())}.`.trimStart(),
64550
- block,
64551
- param
64552
- });
64914
+ findings.push(unknownColumnFinding(table, columns, field, block, param));
64553
64915
  continue;
64554
64916
  }
64555
64917
  const { options } = column;
@@ -64569,10 +64931,13 @@ function declarationFindings(workflow, declarations) {
64569
64931
  }
64570
64932
  }
64571
64933
  }
64934
+ findings.push(...childResultFindings(workflow, declarations));
64572
64935
  return findings;
64573
64936
  }
64574
64937
  async function compileWorkflowDir(dir, workspaceCatalog, declarations) {
64575
- const { lock } = parseWorkflowLock(await readSourceJson(dir, SOURCE_LOCK_FILE));
64938
+ const lockText = await readSourceText(dir, SOURCE_LOCK_FILE);
64939
+ const parsedLock = lockText === null ? null : parseWorkflowLock(lockText);
64940
+ const lock = parsedLock?.lock;
64576
64941
  const [files, storedEdges, storedBlocks, printedWith] = await Promise.all([
64577
64942
  readSourceFiles(dir, lock ?? null),
64578
64943
  readStoredEdges(dir),
@@ -64591,16 +64956,35 @@ async function compileWorkflowDir(dir, workspaceCatalog, declarations) {
64591
64956
  ...storedEdges ? { storedUnreadEdges: storedEdges } : {},
64592
64957
  ...envNames ? { envNames, envDeclaredIn: KIND_DIRS.secret } : {}
64593
64958
  });
64594
- return { lock, files, compiled, storedBlocks, printedWith, catalog };
64959
+ return {
64960
+ lock,
64961
+ lockProblems: parsedLock?.diagnostics ?? [],
64962
+ files,
64963
+ compiled,
64964
+ storedBlocks,
64965
+ printedWith,
64966
+ catalog
64967
+ };
64968
+ }
64969
+ async function readCheckDeclarations(root, catalog) {
64970
+ const [declared, workflows] = await Promise.all([
64971
+ readWorkspaceDeclarations(root),
64972
+ compileWorkspaceWorkflows(root, catalog)
64973
+ ]);
64974
+ return { ...declared, ...workflows };
64595
64975
  }
64596
- async function workspaceWorkflowInputs(root, catalog) {
64597
- const inputs = new Map;
64976
+ async function compileWorkspaceWorkflows(root, catalog) {
64977
+ const workflowInputs = new Map;
64978
+ const respondingWorkflows = new Set;
64598
64979
  for (const key of await workspaceWorkflowKeys(root)) {
64599
64980
  const { compiled } = await compileWorkflowDir(join9(root, KIND_DIRS.workflow, key), catalog);
64600
- if (compiled.workflow)
64601
- inputs.set(key, startInputs(compiled.workflow));
64981
+ if (!compiled.workflow)
64982
+ continue;
64983
+ workflowInputs.set(key, startInputs(compiled.workflow));
64984
+ if (respondsOnEveryRun(compiled.workflow))
64985
+ respondingWorkflows.add(key);
64602
64986
  }
64603
- return inputs;
64987
+ return { workflowInputs, respondingWorkflows };
64604
64988
  }
64605
64989
  function withWorkflowInputs(local, inputs) {
64606
64990
  const workflows = { ...local.workflows };
@@ -64613,7 +64997,7 @@ function withWorkflowInputs(local, inputs) {
64613
64997
  }
64614
64998
  async function checkWorkflowDir(dir, catalog, options) {
64615
64999
  const compiledDir = await compileWorkflowDir(dir, catalog, options.declarations);
64616
- const { lock, files, compiled, storedBlocks, printedWith } = compiledDir;
65000
+ const { lock, lockProblems, files, compiled, storedBlocks, printedWith } = compiledDir;
64617
65001
  const entryText = files[SOURCE_ENTRY_FILE];
64618
65002
  const locate = (block, param, names) => {
64619
65003
  const prefix = encodeAnchor({ kind: "param", block, param: "" });
@@ -64693,6 +65077,14 @@ async function checkWorkflowDir(dir, catalog, options) {
64693
65077
  }, { changed, codeEdited }),
64694
65078
  ...compiled.diagnostics.filter(exempt)
64695
65079
  ];
65080
+ const lockFindings = lockProblems.map((problem) => ({
65081
+ code: problem.code,
65082
+ severity: "error",
65083
+ message: `${problem.message} Every apply and status refuses this lock.`,
65084
+ hint: lockRecoveryHint(options.declarations ? "`sim workspaces source get --dir <new dir>`, from the workspace directory" : undefined),
65085
+ file: `${prefix}${SOURCE_LOCK_FILE}`,
65086
+ ...problem.path ? { path: problem.path } : {}
65087
+ }));
64696
65088
  const findings = [
64697
65089
  ...refused.filter((diagnostic) => reported(diagnostic.code, diagnostic.blockKey)),
64698
65090
  ...declared
@@ -64740,7 +65132,7 @@ async function checkWorkflowDir(dir, catalog, options) {
64740
65132
  else
64741
65133
  unlisted.warnings += count;
64742
65134
  }
64743
- return { findings, entry: entryText, unlisted };
65135
+ return { findings: [...lockFindings, ...findings], entry: entryText, unlisted };
64744
65136
  }
64745
65137
  function reportCheck(output, findings, result, options = {}) {
64746
65138
  const shown = findingsOutput(output, options.verbose, options.dir);
@@ -64793,10 +65185,7 @@ function attachWorkflowSourceCheck(source) {
64793
65185
  throw new CliUsageError(`${options.dir} has no ${SOURCE_BASE_FILE} and no workspace is selected: pass --workspace <workspaceId>.`);
64794
65186
  }
64795
65187
  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\`)`);
64796
- const declarations = workspace ? {
64797
- ...await readWorkspaceDeclarations(workspace.root),
64798
- workflowInputs: await workspaceWorkflowInputs(workspace.root, catalog)
64799
- } : undefined;
65188
+ const declarations = workspace ? await readCheckDeclarations(workspace.root, catalog) : undefined;
64800
65189
  const { findings, entry, unlisted } = await checkWorkflowDir(options.dir, catalog, {
64801
65190
  strict: strictMode(options),
64802
65191
  ...declarations ? { declarations } : {}
@@ -64897,8 +65286,9 @@ Prints a builder's params (required first, with enums and defaults), the gate fi
64897
65286
  which others apply, and its outputs, from the block catalog the last get, create or check cached.
64898
65287
  No request is made. <builder> is the dotted builder path as source writes it: table.upsertRow,
64899
65288
  agent, trigger.schedule, slack.sendMessage (slack.tool.sendMessage names the same builder). A
64900
- namespace (gmail, trigger.gmail) lists its builders; a construct core.d.ts declares (loop,
64901
- parallel, t, env) prints its declaration. Run it from a workflow or workspace source directory,
65289
+ namespace (gmail, trigger.gmail) lists its builders; a block type prints the builder written for
65290
+ it (function is fn) or lists them (table_v2); a construct core.d.ts declares (loop, parallel, t,
65291
+ env) prints its declaration. Run it from a workflow or workspace source directory,
64902
65292
  or pass --dir.
64903
65293
 
64904
65294
  Exit codes: 0 printed; 1 no builder or namespace of that name (the closest one is named), or no
@@ -65565,10 +65955,14 @@ function splitLines2(text) {
65565
65955
  return result;
65566
65956
  }
65567
65957
  // src/commands/protocol/source-status.ts
65568
- function planFindings(diagnostics, listed) {
65569
- return diagnostics.filter((finding) => (finding.severity === "error" || finding.severity === "warning" || finding.code === "I_FINDINGS_TRUNCATED") && !listed(finding.code));
65958
+ function planFindings(diagnostics) {
65959
+ return diagnostics.filter((finding) => finding.severity === "error" || finding.severity === "warning" || finding.code === "I_FINDINGS_TRUNCATED");
65570
65960
  }
65571
65961
  var STATUS_EXIT_CODES_HELP = `
65962
+ With --json, \`plan\` is what applying would do as \`apply --dry-run --allow-delete\` reports it
65963
+ (its errors and warnings counted the same, a conflict as an error), and \`next\` the command to
65964
+ run (with --allow-delete only when the plan deletes something).
65965
+
65572
65966
  Exit codes: 0 clean (nothing to apply, and the server changed nothing since the directory was
65573
65967
  read); ${SOURCE_LOCAL_CHANGES_EXIT_CODE} local changes only (applying writes them); ${SOURCE_DRIFT_EXIT_CODE} the server changed since the
65574
65968
  directory was read: drift (a resource edited, added or deleted there that the directory leaves
@@ -65841,7 +66235,7 @@ async function readLocalWorkflow(dir) {
65841
66235
  };
65842
66236
  }
65843
66237
  function workflowPlanFindings(data) {
65844
- return planFindings(data.diagnostics, (code) => code === "E_APPLY_STALE");
66238
+ return planFindings(data.diagnostics).filter((finding) => finding.code !== "E_APPLY_STALE");
65845
66239
  }
65846
66240
  function planSummary(data) {
65847
66241
  const planned = workflowPlanFindings(data);
@@ -65852,12 +66246,14 @@ function planSummary(data) {
65852
66246
  blocksModified: data.diff.blocks.modified.length,
65853
66247
  edgesAdded: data.diff.edges.added,
65854
66248
  edgesRemoved: data.diff.edges.removed,
66249
+ variablesRemoved: data.diff.variables.removed.length,
65855
66250
  errors: findings("error"),
65856
66251
  warnings: findings("warning")
65857
66252
  };
65858
66253
  }
65859
66254
  function planLine(plan) {
65860
- return `Applying would: blocks +${plan.blocksAdded} -${plan.blocksRemoved} ~${plan.blocksModified}, connections +${plan.edgesAdded} -${plan.edgesRemoved}; ${plan.errors} error(s), ${plan.warnings} warning(s).`;
66255
+ const variables = plan.variablesRemoved > 0 ? `, variables -${plan.variablesRemoved}` : "";
66256
+ return `Applying would: blocks +${plan.blocksAdded} -${plan.blocksRemoved} ~${plan.blocksModified}, connections +${plan.edgesAdded} -${plan.edgesRemoved}${variables}; ${plan.errors} error(s), ${plan.warnings} warning(s).`;
65861
66257
  }
65862
66258
  function attachWorkflowSourceStatus(source) {
65863
66259
  const [command, connect] = apiCommand(source, "status", [
@@ -65935,7 +66331,7 @@ function attachWorkflowSourceStatus(source) {
65935
66331
  getArgs: `${workflowId} `,
65936
66332
  server,
65937
66333
  errors: plan?.errors ?? 0,
65938
- deletes: (plan?.blocksRemoved ?? 0) > 0,
66334
+ deletes: (plan?.blocksRemoved ?? 0) + (plan?.variablesRemoved ?? 0) > 0,
65939
66335
  scope: "",
65940
66336
  login
65941
66337
  })
@@ -66213,11 +66609,19 @@ function failedExitCode(failed) {
66213
66609
  return failed.code === "E_APPLY_FAILED" ? SOURCE_PARTIAL_EXIT_CODE : refusedExitCode([{ code: failed.code, severity: "error" }]);
66214
66610
  }
66215
66611
  function isHeldFinding(plan, finding) {
66216
- return plan.some((change) => change.held && change.kind === finding.kind && change.key === finding.key);
66612
+ return finding.code !== "E_PLAN_REF_DELETED" && plan.some((change) => change.held && change.kind === finding.kind && change.key === finding.key);
66217
66613
  }
66218
66614
  function refusesApply(data) {
66615
+ if (data.refuses !== undefined)
66616
+ return data.refuses;
66219
66617
  return data.diagnostics.some((finding) => finding.severity === "error" && !isHeldFinding(data.plan, finding));
66220
66618
  }
66619
+ function previewExitCode(data) {
66620
+ if (refusesApply(data))
66621
+ return refusedExitCode(data.diagnostics);
66622
+ const writesSome = data.plan.some((change) => change.action !== "noop" && !change.held);
66623
+ return writesSome ? SOURCE_HELD_EXIT_CODE : 1;
66624
+ }
66221
66625
  var sameChange = (a, b) => a.kind === b.kind && a.key === b.key;
66222
66626
  function wasWritten(change, outcome) {
66223
66627
  return outcome.applied.some((written) => sameChange(written, change));
@@ -66651,6 +67055,7 @@ function attachWorkspaceSourceApply(source) {
66651
67055
  findings.print(preview.diagnostics);
66652
67056
  },
66653
67057
  refuses: refusesApply,
67058
+ previewExitCode,
66654
67059
  beforeCommit: (preview) => stage(submission, preview ? new Set(preview.needBlobs) : blobsToStage(submission)),
66655
67060
  commit: async () => {
66656
67061
  const answer = reported(await send(submission, false));
@@ -66863,11 +67268,7 @@ ${SOURCE_DIR_BUSY_HELP}`).action(async (options, command) => {
66863
67268
  }
66864
67269
  await withSourceDirLock(options.dir, async () => {
66865
67270
  const catalog = cachedCatalog(workspaceId) ?? await fetchedCatalog(connect, workspaceId, options.dir);
66866
- const workflowInputs = await workspaceWorkflowInputs(options.dir, catalog);
66867
- const declarations = {
66868
- ...await readWorkspaceDeclarations(options.dir),
66869
- workflowInputs
66870
- };
67271
+ const declarations = await readCheckDeclarations(options.dir, catalog);
66871
67272
  const keys = await workspaceWorkflowKeys(options.dir);
66872
67273
  const findings = [];
66873
67274
  const unlisted = { errors: 0, warnings: 0 };
@@ -66900,7 +67301,7 @@ ${SOURCE_DIR_BUSY_HELP}`).action(async (options, command) => {
66900
67301
  column
66901
67302
  });
66902
67303
  }
66903
- await refreshWorkspaceTypes(options.dir, withWorkflowInputs(declarations.local, workflowInputs));
67304
+ await refreshWorkspaceTypes(options.dir, withWorkflowInputs(declarations.local, declarations.workflowInputs));
66904
67305
  await refreshWorkspaceTsconfigs(options.dir, workspaceId);
66905
67306
  reportCheck(profile.output, findings, { workflows: keys.length, catalogHash: catalog.hash }, {
66906
67307
  verbose: options.verbose === true,
@@ -67172,8 +67573,8 @@ function aboutWorkflowSentByBase(item, byBase) {
67172
67573
  function planAsApplied(plan, byBase) {
67173
67574
  return plan.map((change) => aboutWorkflowSentByBase(change, byBase) && change.action !== "noop" ? { kind: change.kind, key: change.key, action: "noop" } : change);
67174
67575
  }
67175
- function workspacePlanFindings(data, byBase) {
67176
- return planFindings(data.diagnostics, isServerChangeFinding).filter((finding) => !(aboutWorkflowSentByBase(finding, byBase) && isFolderEvaluationFinding(finding)));
67576
+ function dryRunFindings(data, byBase) {
67577
+ return planFindings(data.diagnostics).filter((finding) => !(aboutWorkflowSentByBase(finding, byBase) && (isFolderEvaluationFinding(finding) || finding.code === "E_APPLY_STALE")));
67177
67578
  }
67178
67579
  function planSummary2(findings, plan, conflicts) {
67179
67580
  const count = (...actions) => plan.filter((change) => actions.includes(change.action)).length;
@@ -67191,7 +67592,7 @@ function planSummary2(findings, plan, conflicts) {
67191
67592
  }
67192
67593
  function planLine2(plan) {
67193
67594
  const counts = `${plan.create} create, ${plan.update} update, ${plan.delete} delete (${plan.unchanged} unchanged); ${plan.errors} error(s), ${plan.warnings} warning(s)`;
67194
- 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}.`;
67595
+ 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}.`;
67195
67596
  }
67196
67597
  function fitsWhole(files) {
67197
67598
  const paths = Object.keys(files).filter((path) => kindOfPath(path) === "workflow");
@@ -67278,8 +67679,9 @@ ${SOURCE_DIR_BUSY_HELP}`).action(async (options, invoked) => {
67278
67679
  }
67279
67680
  const skipped = data ? await skippedResources(options.dir) : new Set;
67280
67681
  const status = sourceStatus(locals, data ? serverResourceChanges(data.diagnostics).filter((change) => !(change.server === "added" && skipped.has(`${change.kind}:${change.key}`))) : []);
67281
- const planned = data ? workspacePlanFindings(data, byBase) : [];
67282
- const plan = data ? planSummary2(planned, applyPlan, status.conflicts.length) : null;
67682
+ const dryRun = data ? dryRunFindings(data, byBase) : [];
67683
+ const planned = dryRun.filter((finding) => !isServerChangeFinding(finding.code));
67684
+ const plan = data ? planSummary2(dryRun, applyPlan, status.conflicts.length) : null;
67283
67685
  const report = {
67284
67686
  workspaceId,
67285
67687
  dir: options.dir,
@@ -69126,7 +69528,7 @@ class Parser extends Transform2 {
69126
69528
  callback(err);
69127
69529
  }
69128
69530
  }
69129
- var parse10 = function() {
69531
+ var parse11 = function() {
69130
69532
  let data, options, callback;
69131
69533
  for (const i in arguments) {
69132
69534
  const argument = arguments[i];
@@ -69291,7 +69693,7 @@ async function stagePermissionCsvs(provider, paths, signal) {
69291
69693
  parts.push({ field, path: partPath });
69292
69694
  totalBytes += partBytes;
69293
69695
  };
69294
- const parser = parse10({
69696
+ const parser = parse11({
69295
69697
  bom: true,
69296
69698
  trim: true,
69297
69699
  skip_empty_lines: true,
@@ -69655,6 +70057,15 @@ Profiles work like the AWS CLI: settings live in ~/.sim/config, keys in
69655
70057
  ~/.sim/credentials (0600), or under SIM_CONFIG_DIR when it is set. Select one
69656
70058
  with -P, --profile, or SIM_PROFILE.
69657
70059
 
70060
+ A command targets the profile's workspace unless -w <id> (--workspace <id>) or
70061
+ SIM_WORKSPACE names another. A source directory records its own: a workflow
70062
+ directory acts on the workflow its .sim/base.json names, a workspace directory
70063
+ on the workspace its base names (refusing a -w naming another), and a starter
70064
+ on the one .sim/starter.json names unless -w names another. In a script, export
70065
+ SIM_WORKSPACE=<id> once, or keep only the ID in a variable and write -w "$WS".
70066
+ A variable holding "--workspace <id>" is one argument: alone it is an unknown
70067
+ option, and after -w all of it is taken as the ID.
70068
+
69658
70069
  Workflow, knowledge-base and workspace IDs are bare UUIDs. Table IDs carry a
69659
70070
  tbl_ prefix and file IDs a wf_ one, so wf_ never names a workflow. An audit-log
69660
70071
  or custom-tool ID can open with a dash, which reads as a flag; put -- in front