sim 2.2.33-preview.322.1 → 2.3.0-preview.324.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -24497,6 +24497,16 @@ function toRecord(value) {
24497
24497
  function toRecordOrNull(value) {
24498
24498
  return isRecordLike(value) ? value : null;
24499
24499
  }
24500
+ function canonicalJson(value) {
24501
+ if (value instanceof Date)
24502
+ return JSON.stringify(value.toISOString());
24503
+ if (value === null || typeof value !== "object")
24504
+ return JSON.stringify(value) ?? "null";
24505
+ if (Array.isArray(value))
24506
+ return `[${Array.from(value, canonicalJson).join(",")}]`;
24507
+ const entries = Object.entries(value).filter(([, entry]) => entry !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
24508
+ return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}`;
24509
+ }
24500
24510
 
24501
24511
  // src/terminal/line-input.ts
24502
24512
  import { createInterface } from "node:readline/promises";
@@ -35478,7 +35488,8 @@ var CLI_CONTRACT = {
35478
35488
  getWorkflowState: { command: "workflows state get" },
35479
35489
  getWorkflowOutline: {
35480
35490
  command: "workflows outline",
35481
- describe: "Show a workflow’s draft as a compact read-only outline"
35491
+ describe: "Show a workflow’s draft as a compact read-only outline",
35492
+ dataKeys: true
35482
35493
  },
35483
35494
  getWorkflowSource: {
35484
35495
  command: "workflows source get",
@@ -37244,6 +37255,12 @@ function inferHeader(key, format) {
37244
37255
  const trimmed = format === "duration" || format === "bytes" ? key.replace(/(?:Ms|Bytes)$/, "") : format === "bool" ? key.replace(/^is(?=[A-Z])/, "") : key;
37245
37256
  return humanizeKey(trimmed || key);
37246
37257
  }
37258
+ function inferredFields(record, dataKeys) {
37259
+ return Object.entries(record).map(([key, value]) => [
37260
+ dataKeys ? key : inferHeader(key, inferFormat(key, value)),
37261
+ inferredCell(key, value)
37262
+ ]);
37263
+ }
37247
37264
  function columnsFrom(specs) {
37248
37265
  return specs.map((spec) => ({
37249
37266
  header: spec.header,
@@ -37366,10 +37383,7 @@ function renderResult(operation, format, raw, spec, options = {}, envelope) {
37366
37383
  printList(format, data, spec.columns ? columnsFrom(spec.columns) : inferColumns(data, spec.expand));
37367
37384
  return;
37368
37385
  }
37369
- const fields = spec.fields ? fieldsFrom(data, spec.fields, options) : data && typeof data === "object" ? Object.entries(data).map(([key, value]) => [
37370
- inferHeader(key, inferFormat(key, value)),
37371
- inferredCell(key, value)
37372
- ]) : [];
37386
+ const fields = spec.fields ? fieldsFrom(data, spec.fields, options) : data && typeof data === "object" ? inferredFields(data, spec.dataKeys === true) : [];
37373
37387
  printRecord(format, fields, data);
37374
37388
  if (spec.expandedTrace && options.expandedTrace) {
37375
37389
  const traceSpans = at(data, "traceSpans");
@@ -41154,6 +41168,7 @@ function attachWorkflowRunGet(runs) {
41154
41168
  var SOURCE_LIMITS = {
41155
41169
  maxBlocks: 2000,
41156
41170
  maxEdges: 1e4,
41171
+ maxVariables: 2000,
41157
41172
  maxFiles: 2001,
41158
41173
  maxTotalBytes: 4000000,
41159
41174
  maxDepth: 200
@@ -44694,25 +44709,23 @@ class LockReader {
44694
44709
  }
44695
44710
  }
44696
44711
  }
44712
+ const cyclic = blocksOnParentCycles(blocks);
44697
44713
  for (const [key, block] of Object.entries(blocks)) {
44698
44714
  if (block.parent === null)
44699
44715
  continue;
44700
44716
  if (!Object.hasOwn(blocks, block.parent)) {
44701
44717
  this.report("E_LOCK_PARENT", ["blocks", key, "parent"], `Parent "${block.parent}" is not a block in this lock.`);
44702
- continue;
44703
- }
44704
- const visited = new Set;
44705
- let current = block.parent;
44706
- while (current !== null && Object.hasOwn(blocks, current) && !visited.has(current)) {
44707
- if (current === key) {
44708
- this.report("E_LOCK_PARENT", ["blocks", key, "parent"], `"${key}" contains itself.`);
44709
- break;
44710
- }
44711
- visited.add(current);
44712
- current = blocks[current].parent;
44718
+ } else if (cyclic.has(key)) {
44719
+ this.report("E_LOCK_PARENT", ["blocks", key, "parent"], `"${key}" contains itself.`);
44713
44720
  }
44714
44721
  }
44715
44722
  }
44723
+ overCap(raw, max, at) {
44724
+ if (!isRecordLike(raw) || Object.keys(raw).length <= max)
44725
+ return false;
44726
+ this.report("E_LOCK_SHAPE", at, `Expected at most ${max} entries.`);
44727
+ return true;
44728
+ }
44716
44729
  variables(raw) {
44717
44730
  const variables = this.idRecord(raw, ["variables"]);
44718
44731
  for (const key of Object.keys(variables)) {
@@ -44723,6 +44736,29 @@ class LockReader {
44723
44736
  return variables;
44724
44737
  }
44725
44738
  }
44739
+ function blocksOnParentCycles(blocks) {
44740
+ const cyclic = new Set;
44741
+ const finished = new Set;
44742
+ for (const start of Object.keys(blocks)) {
44743
+ const path = [];
44744
+ const onPath = new Map;
44745
+ let current = start;
44746
+ while (current !== null && Object.hasOwn(blocks, current) && !finished.has(current)) {
44747
+ const index = onPath.get(current);
44748
+ if (index !== undefined) {
44749
+ for (const key of path.slice(index))
44750
+ cyclic.add(key);
44751
+ break;
44752
+ }
44753
+ onPath.set(current, path.length);
44754
+ path.push(current);
44755
+ current = blocks[current].parent;
44756
+ }
44757
+ for (const key of path)
44758
+ finished.add(key);
44759
+ }
44760
+ return cyclic;
44761
+ }
44726
44762
  function upgradeWorkflowLock(json) {
44727
44763
  return json.version === 1 ? { ...json, version: 1 } : null;
44728
44764
  }
@@ -44774,16 +44810,20 @@ function parseWorkflowLock(input) {
44774
44810
  reader.report("E_LOCK_VERSION", ["version"], "Unsupported lock version; expected 1.");
44775
44811
  return { diagnostics: reader.diagnostics };
44776
44812
  }
44813
+ const blocksOverCap = reader.overCap(json.blocks, SOURCE_LIMITS.maxBlocks, ["blocks"]);
44814
+ const variablesOverCap = reader.overCap(json.variables, SOURCE_LIMITS.maxVariables, ["variables"]);
44815
+ if (blocksOverCap || variablesOverCap)
44816
+ return { diagnostics: reader.diagnostics };
44777
44817
  const extensions = reader.extensions(json, LOCK_FIELDS, []);
44778
44818
  const blockEntries = [];
44779
- if (isRecordLike(json.blocks)) {
44819
+ if (!isRecordLike(json.blocks)) {
44820
+ reader.report("E_LOCK_SHAPE", ["blocks"], '"blocks" must be an object.');
44821
+ } else {
44780
44822
  for (const [key, raw] of Object.entries(json.blocks)) {
44781
44823
  const block = reader.block(key, raw);
44782
44824
  if (block)
44783
44825
  blockEntries.push([key, block]);
44784
44826
  }
44785
- } else {
44786
- reader.report("E_LOCK_SHAPE", ["blocks"], '"blocks" must be an object.');
44787
44827
  }
44788
44828
  const blocks = Object.fromEntries(blockEntries);
44789
44829
  reader.crossCheckBlocks(blocks);
@@ -45505,10 +45545,35 @@ function checkLiteralRefs(ctx, node, text, site) {
45505
45545
  checkIterationTag(ctx, rangeOf(ctx, node), site.decl.key, segments);
45506
45546
  continue;
45507
45547
  }
45508
- const target = ctx.declsByKey.get(normalized);
45509
- ctx.reporter.report("W_REF_NOT_NORMALIZED", normalized === head.name ? `${token.value} names no block; the text is kept as written.` : `${token.value} is not written with the block key ${normalized}; the text is kept as written.`, rangeOf(ctx, node), {
45510
- hint: target?.ident ? `Write \${${formatMemberPath(target.ident, segments.slice(1))}} in a template, so a rename follows the block.` : "Reference a declared block through its ident, so a rename follows the block.",
45548
+ const tag = {
45549
+ token: token.value,
45550
+ segments,
45551
+ normalized,
45552
+ at: rangeOf(ctx, node),
45511
45553
  blockKey: site.decl.key
45554
+ };
45555
+ if (!ctx.declsByKey.has(normalized) && segments.length > 1)
45556
+ ctx.unresolvedTags.push(tag);
45557
+ else
45558
+ reportNotNormalized(ctx, tag);
45559
+ }
45560
+ }
45561
+ function reportNotNormalized(ctx, tag) {
45562
+ const target = ctx.declsByKey.get(tag.normalized);
45563
+ ctx.reporter.report("W_REF_NOT_NORMALIZED", target ? `${tag.token} is not written with the block key ${tag.normalized}; the text is kept as written.` : `${tag.token} names no block; the text is kept as written.`, tag.at, {
45564
+ hint: () => target?.ident ? `Write \${${formatMemberPath(target.ident, tag.segments.slice(1))}} in a template, so a rename follows the block.` : "Reference a declared block through its ident, so a rename follows the block.",
45565
+ blockKey: tag.blockKey
45566
+ });
45567
+ }
45568
+ function checkUnresolvedTags(ctx, renamed) {
45569
+ for (const tag of ctx.unresolvedTags) {
45570
+ if (renamed.has(tag.normalized)) {
45571
+ reportNotNormalized(ctx, tag);
45572
+ continue;
45573
+ }
45574
+ ctx.reporter.report("W_UNRESOLVED_REF", `${tag.token} names no block, so it does not resolve at run time.`, tag.at, {
45575
+ hint: "Reference a declared block through its ident, so a rename follows the block.",
45576
+ blockKey: tag.blockKey
45512
45577
  });
45513
45578
  }
45514
45579
  }
@@ -45741,7 +45806,7 @@ function compileRef(ctx, node, site) {
45741
45806
  const key = normalizeWorkflowBlockName(name);
45742
45807
  if (!ctx.variables.has(key)) {
45743
45808
  ctx.reporter.report("E_UNKNOWN_VARIABLE", `No workflow variable is keyed ${name}.`, rangeOf(ctx, first), {
45744
- hint: didYouMean(key, ctx.variables.keys(), (known) => `vars.${known}`),
45809
+ hint: () => didYouMean(key, ctx.variables.keys(), (known) => `vars.${known}`),
45745
45810
  blockKey: site.decl.key
45746
45811
  });
45747
45812
  return null;
@@ -45808,11 +45873,14 @@ function segmentsOf(ctx, members, site) {
45808
45873
  }
45809
45874
  function checkEnvName(ctx, name, at, blockKey) {
45810
45875
  ctx.envReferences.add(name);
45811
- if (!ctx.envNames || ctx.envNames.has(name))
45876
+ const envNames = ctx.envNames;
45877
+ if (!envNames || envNames.has(name))
45812
45878
  return;
45813
- const near = didYouMean(name, ctx.envNames);
45814
45879
  ctx.reporter.report("W_ENV_UNKNOWN", `The workspace has no env variable ${name}, so it resolves to nothing at run time.`, at, {
45815
- hint: ctx.envDeclaredIn ? `${near ? `${near} Otherwise d` : "D"}eclare ${name} in ${ctx.envDeclaredIn} and set its value with \`sim secrets set ${name} --scope workspace\`.` : near ?? `Add ${name} under the workspace's or your environment variables, or use a name .sim/sdk/workspace.d.ts lists.`,
45880
+ hint: () => {
45881
+ const near = didYouMean(name, envNames);
45882
+ return ctx.envDeclaredIn ? `${near ? `${near} Otherwise d` : "D"}eclare ${name} in ${ctx.envDeclaredIn} and set its value with \`sim secrets set ${name} --scope workspace\`.` : near ?? `Add ${name} under the workspace's or your environment variables, or use a name .sim/sdk/workspace.d.ts lists.`;
45883
+ },
45816
45884
  blockKey
45817
45885
  });
45818
45886
  }
@@ -45955,7 +46023,7 @@ function checkCodeFileRefs(ctx, renamed) {
45955
46023
  const suggested = byIdent ?? byName;
45956
46024
  const rewritten = (key) => spell([{ kind: "name", name: key }, ...rest]);
45957
46025
  ctx.reporter.report("W_UNRESOLVED_REF", `${written} names no block, so it does not resolve at run time.`, at, {
45958
- hint: suggested ? `${ref.tag ? "A tag" : REF_ROOT} names a block by its key: write ${rewritten(suggested.key)}.` : ctx.knownKeys.has(head.name) ? formerBlockHint(ctx, head.name, renamed, rewritten, spell) : () => didYouMean(head.name, ctx.declsByKey.keys(), (key) => spell([{ kind: "name", name: key }])),
46026
+ hint: suggested ? `${ref.tag ? "A tag" : REF_ROOT} names a block by its key: write ${rewritten(suggested.key)}.` : ctx.knownKeys.has(head.name) ? () => formerBlockHint(ctx, head.name, renamed, rewritten, spell) : () => didYouMean(head.name, ctx.declsByKey.keys(), (key) => spell([{ kind: "name", name: key }])),
45959
46027
  blockKey
45960
46028
  });
45961
46029
  }
@@ -47290,6 +47358,7 @@ var import_parser2 = __toESM(require_lib(), 1);
47290
47358
  var DEFAULT_LIMITS = {
47291
47359
  maxBlocks: SOURCE_LIMITS.maxBlocks,
47292
47360
  maxEdges: SOURCE_LIMITS.maxEdges,
47361
+ maxVariables: SOURCE_LIMITS.maxVariables,
47293
47362
  maxTotalBytes: SOURCE_LIMITS.maxTotalBytes,
47294
47363
  maxDepth: SOURCE_LIMITS.maxDepth,
47295
47364
  maxCodeFileRefs: SOURCE_LIMITS.maxBlocks
@@ -49204,22 +49273,42 @@ function compileContainer(ctx, decl) {
49204
49273
  function compileBlock(ctx, decl) {
49205
49274
  if (decl.duplicate || decl.builder.kind === "unknown")
49206
49275
  return null;
49207
- if (decl.builder.kind !== "container")
49276
+ if (decl.builder.kind !== "container") {
49208
49277
  checkLegacyType(ctx, decl);
49278
+ checkUnplaceableType(ctx, decl);
49279
+ }
49209
49280
  return decl.builder.kind === "container" ? compileContainer(ctx, decl) : compileRegularBlock(ctx, decl);
49210
49281
  }
49282
+ function lockBinds(ctx, decl) {
49283
+ const lock = ctx.storedUnread;
49284
+ return lock !== undefined && (Object.hasOwn(lock.blocks, decl.key) || decl.ident !== null && ctx.storedUnreadIdents.has(decl.ident));
49285
+ }
49286
+ function checkUnplaceableType(ctx, decl) {
49287
+ const { builder } = decl;
49288
+ if (builder.kind !== "generic" && builder.kind !== "catalog")
49289
+ return;
49290
+ const notAddable = builder.block?.addable === false;
49291
+ const uncatalogued = builder.kind === "generic" && !builder.block;
49292
+ if (!(notAddable || uncatalogued) || ctx.storedTypes.has(builder.type) || lockBinds(ctx, decl)) {
49293
+ return;
49294
+ }
49295
+ if (notAddable) {
49296
+ ctx.reporter.report("W_TYPE_NOT_ADDABLE", `${builder.type} can stay where a workflow already uses it, but an apply cannot add a new block of it.`, rangeOf(ctx, decl.call), { hint: "Use a block type this workspace offers.", blockKey: decl.key });
49297
+ return;
49298
+ }
49299
+ ctx.reporter.report("W_UNKNOWN_BLOCK_TYPE", `${builder.type} is not a block type this workspace offers, so an apply cannot add the block.`, rangeOf(ctx, decl.call), {
49300
+ hint: () => didYouMean(builder.type, Object.keys(ctx.catalog.blocks)) ?? "Use a block type from the catalog, or a builder such as api() or fn().",
49301
+ blockKey: decl.key
49302
+ });
49303
+ }
49211
49304
  function checkLegacyType(ctx, decl) {
49212
49305
  const block = catalogBlockOf(decl);
49213
49306
  const sunset = block?.lifecycle?.sunset;
49214
49307
  if (!block || !sunset)
49215
49308
  return;
49216
49309
  const stored = ctx.stored ? getOwn(ctx.stored.blocks, decl.key) : undefined;
49217
- if (stored?.type === block.type)
49310
+ if (stored?.type === block.type || lockBinds(ctx, decl))
49218
49311
  return;
49219
- const lock = ctx.storedUnread;
49220
- if (lock && (Object.hasOwn(lock.blocks, decl.key) || Object.values(lock.blocks).some((entry) => entry.ident === decl.ident))) {
49221
- return;
49222
- }
49223
49312
  const replacement = sunset.replacedBy;
49224
49313
  const namespaces = replacement ? [
49225
49314
  ...new Set(catalogBuildersOfType(ctx.catalog, replacement).map(([path]) => {
@@ -50265,6 +50354,8 @@ var COMPILE_CATALOG_CODES = [
50265
50354
  "E_UNKNOWN_OPERATION",
50266
50355
  "W_UNKNOWN_MODEL",
50267
50356
  "W_LEGACY_BLOCK_TYPE",
50357
+ "W_UNKNOWN_BLOCK_TYPE",
50358
+ "W_TYPE_NOT_ADDABLE",
50268
50359
  "I_SCHEDULE_UTC",
50269
50360
  "E_STORED_VALUE_MISSING",
50270
50361
  "W_VALUE_KIND",
@@ -50425,7 +50516,10 @@ var PARAM_REFUSALS = new Map([
50425
50516
  ["W_UNKNOWN_OPTION", "E_APPLY_INVALID_SUBBLOCK_FIELD"]
50426
50517
  ]);
50427
50518
  var ENTRY_REFUSALS = new Map([
50428
- ["W_UNKNOWN_OUTPUT_PATH", "E_APPLY_UNRESOLVED_REF"]
50519
+ ["W_UNKNOWN_OUTPUT_PATH", "E_APPLY_UNRESOLVED_REF"],
50520
+ ["W_UNRESOLVED_REF", "E_APPLY_UNRESOLVED_REF"],
50521
+ ["W_UNKNOWN_BLOCK_TYPE", "E_APPLY_INVALID_BLOCK_TYPE"],
50522
+ ["W_TYPE_NOT_ADDABLE", "E_APPLY_TYPE_NOT_ADDABLE"]
50429
50523
  ]);
50430
50524
  var CODE_FILE_REFUSALS = new Map([
50431
50525
  ["W_UNRESOLVED_REF", "E_APPLY_UNRESOLVED_REF"],
@@ -50437,7 +50531,9 @@ var REFUSABLE_WARNING_CODES = new Set([
50437
50531
  "W_REF_OUT_OF_SCOPE",
50438
50532
  "W_UNKNOWN_OUTPUT_PATH",
50439
50533
  "W_UNRESOLVED_REF",
50440
- "W_CODE_FILE_REF_SYNTAX"
50534
+ "W_CODE_FILE_REF_SYNTAX",
50535
+ "W_UNKNOWN_BLOCK_TYPE",
50536
+ "W_TYPE_NOT_ADDABLE"
50441
50537
  ]);
50442
50538
  var EDIT_REFUSALS = [
50443
50539
  ...[...CHANGED_BLOCK_REFUSALS].map(([warning, refusal]) => ({
@@ -51181,6 +51277,11 @@ function compileVariables(ctx, node) {
51181
51277
  unsupported(ctx, node, "variables is an object literal.", "Write variables: { name: { type: 'string', value: '' } }.");
51182
51278
  return;
51183
51279
  }
51280
+ const overLimit = node.properties[ctx.limits.maxVariables];
51281
+ if (overLimit) {
51282
+ ctx.reporter.report("E_LIMIT_EXCEEDED", `The workflow declares ${node.properties.length} variables; the limit is ${ctx.limits.maxVariables}.`, rangeOf(ctx, overLimit), { hint: "Keep related values together in one object or array variable." });
51283
+ return;
51284
+ }
51184
51285
  const entries = objectEntries(ctx, node);
51185
51286
  const addItem = ctx.comments.list(node.start ?? 0, node.end ?? 0, {
51186
51287
  owner: encodeAnchor({ kind: "header" }),
@@ -51380,6 +51481,7 @@ function compileEntry(input, file, text, reporter) {
51380
51481
  if (!ast)
51381
51482
  return emptyResult(reporter, parsed.sdkMajor);
51382
51483
  checkStorableLiterals(file, text, ast, reporter);
51484
+ const storedUnread = input.stored === undefined ? input.storedUnread : undefined;
51383
51485
  const ctx = {
51384
51486
  file,
51385
51487
  reporter,
@@ -51399,12 +51501,15 @@ function compileEntry(input, file, text, reporter) {
51399
51501
  metaSpans: {},
51400
51502
  knownKeys: input.knownKeys ?? new Set,
51401
51503
  stored: input.stored,
51402
- storedUnread: input.stored === undefined ? input.storedUnread : undefined,
51504
+ storedUnread,
51505
+ storedTypes: new Set(Object.values(input.stored?.blocks ?? {}).map((block) => block.type)),
51506
+ storedUnreadIdents: new Set(Object.values(storedUnread?.blocks ?? {}).map((entry) => entry.ident)),
51403
51507
  envNames: input.envNames,
51404
51508
  envDeclaredIn: input.envDeclaredIn,
51405
51509
  envReferences: new Set,
51406
51510
  jsonFields: [],
51407
51511
  dynamicOutputRefs: [],
51512
+ unresolvedTags: [],
51408
51513
  errorOutputRefs: [],
51409
51514
  refusedBranches: new Map,
51410
51515
  valueConsts: new Set
@@ -51480,6 +51585,7 @@ function compileEntry(input, file, text, reporter) {
51480
51585
  const unreadRenames = unread ? lockIdentRenames(hints, unread, (key) => Object.hasOwn(unread.blocks, key)) : new Map;
51481
51586
  const renamed = new Map([...unreadRenames, ...input.renamedKeys ?? []]);
51482
51587
  checkCodeFileRefs(ctx, renamed);
51588
+ checkUnresolvedTags(ctx, renamed);
51483
51589
  const stored = storedView(input.stored, renamed);
51484
51590
  const refTypes = {
51485
51591
  catalog: input.catalog,
@@ -55478,8 +55584,7 @@ export default workflow('Support', { description: 'Answers an order question.' }
55478
55584
  })
55479
55585
  ` };
55480
55586
  // ../workflow-sdk/src/codegen/workspace-text.generated.ts
55481
- var WORKSPACE_SDK_DTS = {
55482
- "credentials.d.ts": `/**
55587
+ var WORKSPACE_SDK_DTS = { "credentials.d.ts": `/**
55483
55588
  * Credential declarations: \`credentials.ts\` at the root of a workspace source directory names the
55484
55589
  * saved credentials its workflows use, each by the provider it is for. Never a token: connect one
55485
55590
  * with \`sim credentials connect <provider> --name "<display name>"\`.
@@ -55523,8 +55628,7 @@ export declare function defineCredentials<const T extends Record<string, Credent
55523
55628
  export type DeclaredCredentials<T> = {
55524
55629
  [K in keyof T]: T[K] extends { provider: infer P } ? { provider: P } : never
55525
55630
  }
55526
- `,
55527
- "deployment.d.ts": `/**
55631
+ `, "deployment.d.ts": `/**
55528
55632
  * Deployment declarations: \`deployments/<workflow key>.ts\` in a workspace source directory deploys
55529
55633
  * \`workflows/<workflow key>/\`, so its schedule, webhook, API and chat triggers run.
55530
55634
  *
@@ -55606,9 +55710,7 @@ export interface DeploymentDeclaration {
55606
55710
 
55607
55711
  /** Declares a workflow's deployment. Its default export is the whole file. */
55608
55712
  export declare function defineDeployment(deployment: DeploymentDeclaration): DeploymentDeclaration
55609
- `,
55610
- "file.d.ts": "/**\n * Workspace files need no declaration: every file under `files/` is one workspace file, at the\n * folder path and name it has there (`files/reports/q1.pdf` is `q1.pdf` in the `reports`\n * folder), synced by content hash. Each apply that changes a file's bytes records a new version\n * of it, so an earlier one can be restored in the Files tab. Files over 10 MB, or whose name no\n * directory can hold (a reserved character, or a path that differs only in letter case from\n * another file or folder), are left out of a get (listed in `.sim/skipped.json`) and never written\n * by an apply; a file the directory no longer holds is deleted only with `--allow-delete`.\n */\nexport {}\n",
55611
- "index.d.ts": `/**
55713
+ `, "file.d.ts": "/**\n * Workspace files need no declaration: every file under `files/` is one workspace file, at the\n * folder path and name it has there (`files/reports/q1.pdf` is `q1.pdf` in the `reports`\n * folder), synced by content hash. Each apply that changes a file's bytes records a new version\n * of it, so an earlier one can be restored in the Files tab. Files over 10 MB, or whose name no\n * directory can hold (a reserved character, or a path that differs only in letter case from\n * another file or folder), are left out of a get (listed in `.sim/skipped.json`) and never written\n * by an apply; a file the directory no longer holds is deleted only with `--allow-delete`.\n */\nexport {}\n", "index.d.ts": `/**
55612
55714
  * The workspace declaration SDK: \`import { … } from '@sim/workflow-sdk/workspace'\` in the
55613
55715
  * declaration files of a workspace source directory (\`tables/<key>.ts\`, …). Like the workflow
55614
55716
  * SDK, nothing here runs: the server reads each file statically.
@@ -55622,8 +55724,7 @@ export * from './secrets'
55622
55724
  export * from './skill'
55623
55725
  export * from './table'
55624
55726
  export * from './tool'
55625
- `,
55626
- "knowledge.d.ts": `/**
55727
+ `, "knowledge.d.ts": `/**
55627
55728
  * Knowledge base declarations: \`knowledge/<key>/knowledge.ts\` in a workspace source directory,
55628
55729
  * beside \`knowledge/<key>/docs/\`, which holds one file per document.
55629
55730
  *
@@ -55682,9 +55783,7 @@ export interface KnowledgeBaseDeclaration {
55682
55783
  export declare function defineKnowledgeBase(
55683
55784
  knowledgeBase: KnowledgeBaseDeclaration
55684
55785
  ): KnowledgeBaseDeclaration
55685
- `,
55686
- "mcp.d.ts": "/**\n * MCP server declarations: `mcp/<key>.ts` declares one server the workspace's agents call tools\n * on.\n *\n * ```ts\n * // @sim-sdk 1\n * import { defineMcpServer, env } from '@sim/workflow-sdk/workspace'\n *\n * export default defineMcpServer({\n * name: 'GitHub',\n * url: 'https://api.githubcopilot.com/mcp/',\n * headers: { Authorization: 'Bearer {{GITHUB_TOKEN}}', 'X-Team': env.GITHUB_TEAM },\n * })\n * ```\n *\n * A workflow names the server by its key and one of its tools by name:\n * `mcp('github').tool('create_issue')`. Secrets never sit in source: a credential header\n * (`Authorization`, `Cookie`, or a name with `key`, `token`, `secret`, `auth`, …) holds env\n * references (`env.NAME`, or `{{NAME}}` in its text after a scheme such as `Bearer`) or\n * `stored()`, which keeps the value the server holds. The server's id derives from its URL, so a\n * `url` with another host or path replaces the server; a new query string updates it in place.\n */\nimport type { EnvRef } from '@sim/workflow-sdk'\n\nexport { env, stored } from '@sim/workflow-sdk'\n\n/** A header value: text (`{{NAME}}` names an env variable), `env.NAME`, or `stored()`. */\nexport type McpHeaderValue = string | EnvRef\n\n/** How the server authenticates. */\nexport interface McpServerAuth {\n /** `headers` (the default) sends the declared headers; `oauth` signs in with an OAuth grant. */\n type: 'none' | 'headers' | 'oauth'\n /** A pre-registered OAuth client, for a server without dynamic client registration. */\n clientId?: string\n}\n\n/** An MCP server declaration. */\nexport interface McpServerDeclaration {\n /** The display name; the key when left out. */\n name?: string\n description?: string\n /** An `http://` or `https://` URL. A new host or path replaces the server; a new query does not. */\n url: string\n transport?: 'streamable-http'\n headers?: { [name: string]: McpHeaderValue }\n /** `{ type: 'headers' }` when left out. The OAuth client secret is set in the server settings. */\n auth?: McpServerAuth\n /** Milliseconds a request waits; 30000 when left out. */\n timeout?: number\n /** 3 when left out. */\n retries?: number\n /** `true` when left out. */\n enabled?: boolean\n}\n\n/** Declares an MCP server. Its default export is the whole file. */\nexport declare function defineMcpServer(server: McpServerDeclaration): McpServerDeclaration\n",
55687
- "secrets.d.ts": `/**
55786
+ `, "mcp.d.ts": "/**\n * MCP server declarations: `mcp/<key>.ts` declares one server the workspace's agents call tools\n * on.\n *\n * ```ts\n * // @sim-sdk 1\n * import { defineMcpServer, env } from '@sim/workflow-sdk/workspace'\n *\n * export default defineMcpServer({\n * name: 'GitHub',\n * url: 'https://api.githubcopilot.com/mcp/',\n * headers: { Authorization: 'Bearer {{GITHUB_TOKEN}}', 'X-Team': env.GITHUB_TEAM },\n * })\n * ```\n *\n * A workflow names the server by its key and one of its tools by name:\n * `mcp('github').tool('create_issue')`. Secrets never sit in source: a credential header\n * (`Authorization`, `Cookie`, or a name with `key`, `token`, `secret`, `auth`, …) holds env\n * references (`env.NAME`, or `{{NAME}}` in its text after a scheme such as `Bearer`) or\n * `stored()`, which keeps the value the server holds. The server's id derives from its URL, so a\n * `url` with another host or path replaces the server; a new query string updates it in place.\n */\nimport type { EnvRef } from '@sim/workflow-sdk'\n\nexport { env, stored } from '@sim/workflow-sdk'\n\n/** A header value: text (`{{NAME}}` names an env variable), `env.NAME`, or `stored()`. */\nexport type McpHeaderValue = string | EnvRef\n\n/** How the server authenticates. */\nexport interface McpServerAuth {\n /** `headers` (the default) sends the declared headers; `oauth` signs in with an OAuth grant. */\n type: 'none' | 'headers' | 'oauth'\n /** A pre-registered OAuth client, for a server without dynamic client registration. */\n clientId?: string\n}\n\n/** An MCP server declaration. */\nexport interface McpServerDeclaration {\n /** The display name; the key when left out. */\n name?: string\n description?: string\n /** An `http://` or `https://` URL. A new host or path replaces the server; a new query does not. */\n url: string\n transport?: 'streamable-http'\n headers?: { [name: string]: McpHeaderValue }\n /** `{ type: 'headers' }` when left out. The OAuth client secret is set in the server settings. */\n auth?: McpServerAuth\n /** Milliseconds a request waits; 30000 when left out. */\n timeout?: number\n /** 3 when left out. */\n retries?: number\n /** `true` when left out. */\n enabled?: boolean\n}\n\n/** Declares an MCP server. Its default export is the whole file. */\nexport declare function defineMcpServer(server: McpServerDeclaration): McpServerDeclaration\n", "secrets.d.ts": `/**
55688
55787
  * Secret declarations: \`secrets.ts\` at the root of a workspace source directory names the
55689
55788
  * workspace secrets its workflows read, by name and what each is for. Never a value: set one with
55690
55789
  * \`sim secrets set <NAME> --scope workspace\`, or in the workspace's secrets settings.
@@ -55718,9 +55817,7 @@ export declare function defineSecrets<const T extends Record<string, SecretDecla
55718
55817
 
55719
55818
  /** The env names a \`secrets.ts\` declaration adds, as \`workspace.d.ts\` merges them into \`env\`. */
55720
55819
  export type DeclaredSecretNames<T> = { [K in keyof T]: true }
55721
- `,
55722
- "skill.d.ts": '/**\n * Skills are markdown, not TypeScript: `skills/<key>.md` is a frontmatter block of `name` and\n * `description`, then the skill\'s content.\n *\n * ```md\n * ---\n * name: tone\n * description: "Answer in the support team\'s voice: short, warm, specific."\n * ---\n * Write like a person, not a policy.\n * ```\n *\n * A value is plain text on one line, or a JSON string (`"…"`) when it holds a line break,\n * surrounding spaces, quotes, `: ` or ` #`, ends in `:`, or starts with anything but a letter,\n * digit or `(`. Quote a value YAML would read as a boolean, number or date (`"yes"`, `"1e3"`) too,\n * so other markdown tools read it as text. The name is kebab-case; a workflow names the skill by\n * its key, `skill(\'tone\')`. This module declares nothing.\n */\nexport {}\n',
55723
- "table.d.ts": `/**
55820
+ `, "skill.d.ts": '/**\n * Skills are markdown, not TypeScript: `skills/<key>.md` is a frontmatter block of `name` and\n * `description`, then the skill\'s content.\n *\n * ```md\n * ---\n * name: tone\n * description: "Answer in the support team\'s voice: short, warm, specific."\n * ---\n * Write like a person, not a policy.\n * ```\n *\n * A value is plain text on one line, or a JSON string (`"…"`) when it holds a line break,\n * surrounding spaces, quotes, `: ` or ` #`, ends in `:`, or starts with anything but a letter,\n * digit or `(`. Quote a value YAML would read as a boolean, number or date (`"yes"`, `"1e3"`) too,\n * so other markdown tools read it as text. The name is kebab-case; a workflow names the skill by\n * its key, `skill(\'tone\')`. This module declares nothing.\n */\nexport {}\n', "table.d.ts": `/**
55724
55821
  * Table declarations: \`tables/<key>.ts\` in a workspace source directory.
55725
55822
  *
55726
55823
  * \`\`\`ts
@@ -55865,8 +55962,7 @@ type CellOf<C> = C extends Column<infer V, infer _N, infer R>
55865
55962
  export type RowOf<T> = T extends TableDeclaration<infer C>
55866
55963
  ? { [K in keyof C as StoredName<K, C[K]>]: CellOf<C[K]> }
55867
55964
  : never
55868
- `,
55869
- "tool.d.ts": `/**
55965
+ `, "tool.d.ts": `/**
55870
55966
  * Custom tool declarations: \`tools/<key>.ts\`, with the tool's code beside it in \`tools/<key>.js\`.
55871
55967
  *
55872
55968
  * \`\`\`ts
@@ -55933,8 +56029,7 @@ export interface ToolDeclaration {
55933
56029
 
55934
56030
  /** Declares a custom tool. Its default export is the whole file. */
55935
56031
  export declare function defineTool(tool: ToolDeclaration): ToolDeclaration
55936
- `
55937
- };
56032
+ ` };
55938
56033
  // src/commands/protocol/source-primer.ts
55939
56034
  var MAX_SNIPPETS = 12;
55940
56035
  var MAX_SNIPPET_BYTES = 4096;
@@ -62385,18 +62480,8 @@ function coerceRowCells(data, columns, policyFor) {
62385
62480
  }
62386
62481
  }
62387
62482
  }
62388
- function canonicalCellJson(value) {
62389
- if (value instanceof Date)
62390
- return JSON.stringify(value.toISOString());
62391
- if (value === null || typeof value !== "object")
62392
- return JSON.stringify(value) ?? "null";
62393
- if (Array.isArray(value))
62394
- return `[${value.map(canonicalCellJson).join(",")}]`;
62395
- const entries = Object.entries(value).filter(([, entry]) => entry !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
62396
- return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalCellJson(entry)}`).join(",")}}`;
62397
- }
62398
62483
  function uniqueValueKey(value, column) {
62399
- return canonicalCellJson(cellRuleOf(column).valueForEquality?.(value) ?? value);
62484
+ return canonicalJson(cellRuleOf(column).valueForEquality?.(value) ?? value);
62400
62485
  }
62401
62486
  function scanBatchUniqueValues(rows, uniqueColumns) {
62402
62487
  const rowErrors = [];
@@ -63729,10 +63814,31 @@ async function assertWorkspaceDir(dir) {
63729
63814
  function keepFile(kind) {
63730
63815
  return isFileKind(kind) ? null : `${KIND_DIRS[kind]}/${KEEP_FILE}`;
63731
63816
  }
63817
+ function toolOfCodeFile(path) {
63818
+ if (kindOfPath(path) !== "custom-tool")
63819
+ return null;
63820
+ const [key] = toolCodec.group([path]).groups.keys();
63821
+ if (key === undefined)
63822
+ return null;
63823
+ const declaration = toolDeclarationPath(key);
63824
+ return path === declaration ? null : { key, declaration };
63825
+ }
63826
+ function isUnnamedToolCode(files, path) {
63827
+ const tool = toolOfCodeFile(path);
63828
+ const text = tool ? files[tool.declaration] : undefined;
63829
+ if (!tool || text === undefined)
63830
+ return false;
63831
+ return toolCodec.parse(tool.key, { [tool.declaration]: text }, []).decl !== undefined;
63832
+ }
63732
63833
  function dropUnnamedCodeFiles(files) {
63733
63834
  const named = new Map;
63734
63835
  const unnamed = [];
63735
63836
  for (const path of Object.keys(files)) {
63837
+ if (isUnnamedToolCode(files, path)) {
63838
+ unnamed.push(path);
63839
+ delete files[path];
63840
+ continue;
63841
+ }
63736
63842
  if (kindOfPath(path) !== "workflow")
63737
63843
  continue;
63738
63844
  const segments = path.split("/");
@@ -65851,14 +65957,20 @@ function droppedResourceFiles(sent, reprinted) {
65851
65957
  }
65852
65958
  async function saveApplied(dir, data, submission, written, records) {
65853
65959
  assertWorkspacePaths(Object.keys(data.files));
65854
- const orphaned = [
65855
- ...await orphanedWorkflowFiles(dir, data.files, written.digests),
65856
- ...droppedResourceFiles(submission.files, data.files)
65857
- ];
65960
+ const toolCode = [];
65961
+ const orphaned = await orphanedWorkflowFiles(dir, data.files, written.digests);
65962
+ for (const path of droppedResourceFiles(submission.files, data.files)) {
65963
+ const tool = toolOfCodeFile(path);
65964
+ if (tool)
65965
+ toolCode.push({ path, declaration: tool.declaration });
65966
+ else
65967
+ orphaned.push(path);
65968
+ }
65858
65969
  const kept = { ...written.digests, ...appliedBlobDigests(submission, data.base) };
65859
65970
  const deleted = await deletedRecordedPaths(dir, written.digests, submission.kinds, data.base);
65860
- for (const path of [...orphaned, ...deleted])
65971
+ for (const path of [...orphaned, ...deleted, ...toolCode.map(({ path }) => path)]) {
65861
65972
  delete kept[path];
65973
+ }
65862
65974
  const record = writtenRecord(data.files, kept, new Map([...recordedStats(written), ...submission.hashed]));
65863
65975
  await updateSourceDir(dir, {
65864
65976
  write: [
@@ -65870,6 +65982,9 @@ async function saveApplied(dir, data, submission, written, records) {
65870
65982
  ],
65871
65983
  remove: [...orphaned, ...removedWorkflowRecords(deleted)]
65872
65984
  });
65985
+ for (const { path, declaration } of toolCode) {
65986
+ printError(`warning: ${path} is no longer named by ${declaration} (its code is now kept as stored() or printed inline), so it was left on disk as written and no apply sends it: delete it, or name it again with codeFile(). Never commit one that holds a credential.`);
65987
+ }
65873
65988
  }
65874
65989
  function baseWorkflowOf(base) {
65875
65990
  return isRecordLike(base) && typeof base.workflowId === "string" ? base.workflowId : null;