sim 2.1.7 → 2.1.8-dev.94.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.
Files changed (55) hide show
  1. package/README.md +1 -18
  2. package/dist/auth/device-flow.d.ts +38 -0
  3. package/dist/commands/auth.d.ts +5 -0
  4. package/dist/commands/configure.d.ts +2 -0
  5. package/dist/commands/credentials.d.ts +3 -0
  6. package/dist/commands/protocol/chat.d.ts +11 -0
  7. package/dist/commands/protocol/files-get.d.ts +25 -0
  8. package/dist/commands/protocol/files-upload.d.ts +2 -0
  9. package/dist/commands/protocol/index.d.ts +3 -0
  10. package/dist/commands/protocol/knowledge-document-upload.d.ts +2 -0
  11. package/dist/commands/protocol/logs-follow.d.ts +39 -0
  12. package/dist/commands/protocol/resource-directory.d.ts +24 -0
  13. package/dist/commands/protocol/result.d.ts +2 -0
  14. package/dist/commands/protocol/tables-import.d.ts +2 -0
  15. package/dist/commands/protocol/workflow-run-follow.d.ts +56 -0
  16. package/dist/commands/protocol/workflow-run-get.d.ts +15 -0
  17. package/dist/commands/protocol/workflow-run-wait.d.ts +3 -0
  18. package/dist/commands/secrets.d.ts +3 -0
  19. package/dist/config/index.d.ts +2 -0
  20. package/dist/config/ini.d.ts +111 -0
  21. package/dist/config/paths.d.ts +10 -0
  22. package/dist/config/profile.d.ts +158 -0
  23. package/dist/context.d.ts +21 -0
  24. package/dist/contract/commands.d.ts +14 -0
  25. package/dist/contract/types.d.ts +292 -0
  26. package/dist/embed-context.d.ts +83 -0
  27. package/dist/embed-output.d.ts +15 -0
  28. package/dist/generated/v2-api.d.ts +12969 -0
  29. package/dist/helpers.d.ts +9 -0
  30. package/dist/http/client.d.ts +166 -0
  31. package/dist/http/environment.d.ts +32 -0
  32. package/dist/index.js +895 -1115
  33. package/dist/output/presentation.d.ts +4 -0
  34. package/dist/output/render.d.ts +60 -0
  35. package/dist/output/terminal-text.d.ts +17 -0
  36. package/dist/output/trace.d.ts +3 -0
  37. package/dist/program.d.ts +21 -0
  38. package/dist/runtime/build.d.ts +38 -0
  39. package/dist/runtime/derive.d.ts +20 -0
  40. package/dist/runtime/execute.d.ts +30 -0
  41. package/dist/runtime/naming.d.ts +25 -0
  42. package/dist/runtime/options.d.ts +7 -0
  43. package/dist/runtime/renamed.d.ts +20 -0
  44. package/dist/runtime/request.d.ts +109 -0
  45. package/dist/runtime/result.d.ts +50 -0
  46. package/dist/runtime/types.d.ts +23 -0
  47. package/dist/runtime.d.ts +4 -0
  48. package/dist/runtime.js +16832 -0
  49. package/dist/terminal/secret-input.d.ts +15 -0
  50. package/dist/terminal.d.ts +6 -0
  51. package/dist/transfer/local-file.d.ts +16 -0
  52. package/dist/transfer/streaming-upload.d.ts +16 -0
  53. package/dist/transfer/upload-session.d.ts +18 -0
  54. package/dist/version.d.ts +10 -0
  55. package/package.json +15 -2
package/dist/index.js CHANGED
@@ -19,15 +19,13 @@ var __toESM = (mod, isNodeMode, target) => {
19
19
  return cached;
20
20
  }
21
21
  target = mod != null ? __create(__getProtoOf(mod)) : {};
22
- const to = isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
23
- if (mod && typeof mod === "object" || typeof mod === "function") {
24
- for (let key of __getOwnPropNames(mod))
25
- if (!__hasOwnProp.call(to, key))
26
- __defProp(to, key, {
27
- get: __accessProp.bind(mod, key),
28
- enumerable: true
29
- });
30
- }
22
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
23
+ for (let key of __getOwnPropNames(mod))
24
+ if (!__hasOwnProp.call(to, key))
25
+ __defProp(to, key, {
26
+ get: __accessProp.bind(mod, key),
27
+ enumerable: true
28
+ });
31
29
  if (canCache)
32
30
  cache.set(mod, to);
33
31
  return to;
@@ -36,7 +34,7 @@ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports,
36
34
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
37
35
 
38
36
  // ../../node_modules/commander/lib/error.js
39
- var require_error = __commonJS(function(exports) {
37
+ var require_error = __commonJS((exports) => {
40
38
  class CommanderError extends Error {
41
39
  constructor(exitCode, code, message) {
42
40
  super(message);
@@ -60,7 +58,7 @@ var require_error = __commonJS(function(exports) {
60
58
  });
61
59
 
62
60
  // ../../node_modules/commander/lib/argument.js
63
- var require_argument = __commonJS(function(exports) {
61
+ var require_argument = __commonJS((exports) => {
64
62
  var { InvalidArgumentError } = require_error();
65
63
 
66
64
  class Argument {
@@ -139,7 +137,7 @@ var require_argument = __commonJS(function(exports) {
139
137
  });
140
138
 
141
139
  // ../../node_modules/commander/lib/help.js
142
- var require_help = __commonJS(function(exports) {
140
+ var require_help = __commonJS((exports) => {
143
141
  var { humanReadableArgName } = require_argument();
144
142
 
145
143
  class Help {
@@ -150,7 +148,7 @@ var require_help = __commonJS(function(exports) {
150
148
  this.showGlobalOptions = false;
151
149
  }
152
150
  visibleCommands(cmd) {
153
- const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
151
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
154
152
  if (cmd._hasImplicitHelpCommand()) {
155
153
  const [, helpName, helpArgs] = cmd._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/);
156
154
  const helpCommand = cmd.createCommand(helpName).helpOption(false);
@@ -343,8 +341,8 @@ var require_help = __commonJS(function(exports) {
343
341
  output = output.concat(["Global Options:", formatList(globalOptionList), ""]);
344
342
  }
345
343
  }
346
- const commandList = helper.visibleCommands(cmd).map((cmd) => {
347
- return formatItem(helper.subcommandTerm(cmd), helper.subcommandDescription(cmd));
344
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
345
+ return formatItem(helper.subcommandTerm(cmd2), helper.subcommandDescription(cmd2));
348
346
  });
349
347
  if (commandList.length > 0) {
350
348
  output = output.concat(["Commands:", formatList(commandList), ""]);
@@ -355,16 +353,16 @@ var require_help = __commonJS(function(exports) {
355
353
  padWidth(cmd, helper) {
356
354
  return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
357
355
  }
358
- wrap(str, width, indent, minColumnWidth = 40) {
356
+ wrap(str2, width, indent, minColumnWidth = 40) {
359
357
  const indents = " \\f\\t\\v   -    \uFEFF";
360
358
  const manualIndent = new RegExp(`[\\n][${indents}]+`);
361
- if (str.match(manualIndent))
362
- return str;
359
+ if (str2.match(manualIndent))
360
+ return str2;
363
361
  const columnWidth = width - indent;
364
362
  if (columnWidth < minColumnWidth)
365
- return str;
366
- const leadingStr = str.slice(0, indent);
367
- const columnText = str.slice(indent).replace(`\r
363
+ return str2;
364
+ const leadingStr = str2.slice(0, indent);
365
+ const columnText = str2.slice(indent).replace(`\r
368
366
  `, `
369
367
  `);
370
368
  const indentString = " ".repeat(indent);
@@ -386,7 +384,7 @@ var require_help = __commonJS(function(exports) {
386
384
  });
387
385
 
388
386
  // ../../node_modules/commander/lib/option.js
389
- var require_option = __commonJS(function(exports) {
387
+ var require_option = __commonJS((exports) => {
390
388
  var { InvalidArgumentError } = require_error();
391
389
 
392
390
  class Option {
@@ -514,9 +512,9 @@ var require_option = __commonJS(function(exports) {
514
512
  return option.negate === (negativeValue === value);
515
513
  }
516
514
  }
517
- function camelcase(str) {
518
- return str.split("-").reduce((str, word) => {
519
- return str + word[0].toUpperCase() + word.slice(1);
515
+ function camelcase(str2) {
516
+ return str2.split("-").reduce((str3, word) => {
517
+ return str3 + word[0].toUpperCase() + word.slice(1);
520
518
  });
521
519
  }
522
520
  function splitOptionFlags(flags) {
@@ -538,9 +536,9 @@ var require_option = __commonJS(function(exports) {
538
536
  });
539
537
 
540
538
  // ../../node_modules/commander/lib/suggestSimilar.js
541
- var require_suggestSimilar = __commonJS(function(exports) {
539
+ var require_suggestSimilar = __commonJS((exports) => {
542
540
  var maxDistance = 3;
543
- function editDistance(a, b) {
541
+ function editDistance2(a, b) {
544
542
  if (Math.abs(a.length - b.length) > maxDistance)
545
543
  return Math.max(a.length, b.length);
546
544
  const d = [];
@@ -581,7 +579,7 @@ var require_suggestSimilar = __commonJS(function(exports) {
581
579
  candidates.forEach((candidate) => {
582
580
  if (candidate.length <= 1)
583
581
  return;
584
- const distance = editDistance(word, candidate);
582
+ const distance = editDistance2(word, candidate);
585
583
  const length = Math.max(word.length, candidate.length);
586
584
  const similarity = (length - distance) / length;
587
585
  if (similarity > minSimilarity) {
@@ -611,12 +609,12 @@ var require_suggestSimilar = __commonJS(function(exports) {
611
609
  });
612
610
 
613
611
  // ../../node_modules/commander/lib/command.js
614
- var require_command = __commonJS(function(exports) {
612
+ var require_command = __commonJS((exports) => {
615
613
  var EventEmitter = __require("events").EventEmitter;
616
614
  var childProcess = __require("child_process");
617
615
  var path = __require("path");
618
616
  var fs = __require("fs");
619
- var process2 = __require("process");
617
+ var process3 = __require("process");
620
618
  var { Argument, humanReadableArgName } = require_argument();
621
619
  var { CommanderError } = require_error();
622
620
  var { Help } = require_help();
@@ -658,11 +656,11 @@ var require_command = __commonJS(function(exports) {
658
656
  this._showHelpAfterError = false;
659
657
  this._showSuggestionAfterError = true;
660
658
  this._outputConfiguration = {
661
- writeOut: (str) => process2.stdout.write(str),
662
- writeErr: (str) => process2.stderr.write(str),
663
- getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
664
- getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
665
- outputError: (str, write) => write(str)
659
+ writeOut: (str2) => process3.stdout.write(str2),
660
+ writeErr: (str2) => process3.stderr.write(str2),
661
+ getOutHelpWidth: () => process3.stdout.isTTY ? process3.stdout.columns : undefined,
662
+ getErrHelpWidth: () => process3.stderr.isTTY ? process3.stderr.columns : undefined,
663
+ outputError: (str2, write) => write(str2)
666
664
  };
667
665
  this._hidden = false;
668
666
  this._hasHelpOption = true;
@@ -850,7 +848,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
850
848
  if (this._exitCallback) {
851
849
  this._exitCallback(new CommanderError(exitCode, code, message));
852
850
  }
853
- process2.exit(exitCode);
851
+ process3.exit(exitCode);
854
852
  }
855
853
  action(fn) {
856
854
  const listener = (args) => {
@@ -1012,35 +1010,35 @@ Expecting one of '${allowedValues.join("', '")}'`);
1012
1010
  });
1013
1011
  return source;
1014
1012
  }
1015
- _prepareUserArgs(argv2, parseOptions) {
1016
- if (argv2 !== undefined && !Array.isArray(argv2)) {
1013
+ _prepareUserArgs(argv, parseOptions) {
1014
+ if (argv !== undefined && !Array.isArray(argv)) {
1017
1015
  throw new Error("first parameter to parse must be array or undefined");
1018
1016
  }
1019
1017
  parseOptions = parseOptions || {};
1020
- if (argv2 === undefined) {
1021
- argv2 = process2.argv;
1022
- if (process2.versions && process2.versions.electron) {
1018
+ if (argv === undefined) {
1019
+ argv = process3.argv;
1020
+ if (process3.versions && process3.versions.electron) {
1023
1021
  parseOptions.from = "electron";
1024
1022
  }
1025
1023
  }
1026
- this.rawArgs = argv2.slice();
1024
+ this.rawArgs = argv.slice();
1027
1025
  let userArgs;
1028
1026
  switch (parseOptions.from) {
1029
1027
  case undefined:
1030
1028
  case "node":
1031
- this._scriptPath = argv2[1];
1032
- userArgs = argv2.slice(2);
1029
+ this._scriptPath = argv[1];
1030
+ userArgs = argv.slice(2);
1033
1031
  break;
1034
1032
  case "electron":
1035
- if (process2.defaultApp) {
1036
- this._scriptPath = argv2[1];
1037
- userArgs = argv2.slice(2);
1033
+ if (process3.defaultApp) {
1034
+ this._scriptPath = argv[1];
1035
+ userArgs = argv.slice(2);
1038
1036
  } else {
1039
- userArgs = argv2.slice(1);
1037
+ userArgs = argv.slice(1);
1040
1038
  }
1041
1039
  break;
1042
1040
  case "user":
1043
- userArgs = argv2.slice(0);
1041
+ userArgs = argv.slice(0);
1044
1042
  break;
1045
1043
  default:
1046
1044
  throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
@@ -1100,23 +1098,23 @@ Expecting one of '${allowedValues.join("', '")}'`);
1100
1098
  }
1101
1099
  launchWithNode = sourceExt.includes(path.extname(executableFile));
1102
1100
  let proc;
1103
- if (process2.platform !== "win32") {
1101
+ if (process3.platform !== "win32") {
1104
1102
  if (launchWithNode) {
1105
1103
  args.unshift(executableFile);
1106
- args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1107
- proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1104
+ args = incrementNodeInspectorPort(process3.execArgv).concat(args);
1105
+ proc = childProcess.spawn(process3.argv[0], args, { stdio: "inherit" });
1108
1106
  } else {
1109
1107
  proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1110
1108
  }
1111
1109
  } else {
1112
1110
  args.unshift(executableFile);
1113
- args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1114
- proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1111
+ args = incrementNodeInspectorPort(process3.execArgv).concat(args);
1112
+ proc = childProcess.spawn(process3.execPath, args, { stdio: "inherit" });
1115
1113
  }
1116
1114
  if (!proc.killed) {
1117
1115
  const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1118
1116
  signals.forEach((signal) => {
1119
- process2.on(signal, () => {
1117
+ process3.on(signal, () => {
1120
1118
  if (proc.killed === false && proc.exitCode === null) {
1121
1119
  proc.kill(signal);
1122
1120
  }
@@ -1125,10 +1123,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
1125
1123
  }
1126
1124
  const exitCallback = this._exitCallback;
1127
1125
  if (!exitCallback) {
1128
- proc.on("close", process2.exit.bind(process2));
1126
+ proc.on("close", process3.exit.bind(process3));
1129
1127
  } else {
1130
1128
  proc.on("close", () => {
1131
- exitCallback(new CommanderError(process2.exitCode || 0, "commander.executeSubCommandAsync", "(close)"));
1129
+ exitCallback(new CommanderError(process3.exitCode || 0, "commander.executeSubCommandAsync", "(close)"));
1132
1130
  });
1133
1131
  }
1134
1132
  proc.on("error", (err) => {
@@ -1143,7 +1141,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
1143
1141
  throw new Error(`'${executableFile}' not executable`);
1144
1142
  }
1145
1143
  if (!exitCallback) {
1146
- process2.exit(1);
1144
+ process3.exit(1);
1147
1145
  } else {
1148
1146
  const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1149
1147
  wrappedError.nestedError = err;
@@ -1493,11 +1491,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
1493
1491
  }
1494
1492
  _parseOptionsEnv() {
1495
1493
  this.options.forEach((option) => {
1496
- if (option.envVar && option.envVar in process2.env) {
1494
+ if (option.envVar && option.envVar in process3.env) {
1497
1495
  const optionKey = option.attributeName();
1498
1496
  if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
1499
1497
  if (option.required || option.optional) {
1500
- this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
1498
+ this.emit(`optionEnv:${option.name()}`, process3.env[option.envVar]);
1501
1499
  } else {
1502
1500
  this.emit(`optionEnv:${option.name()}`);
1503
1501
  }
@@ -1529,18 +1527,18 @@ Expecting one of '${allowedValues.join("', '")}'`);
1529
1527
  this.error(message, { code: "commander.missingMandatoryOptionValue" });
1530
1528
  }
1531
1529
  _conflictingOption(option, conflictingOption) {
1532
- const findBestOptionFromValue = (option) => {
1533
- const optionKey = option.attributeName();
1530
+ const findBestOptionFromValue = (option2) => {
1531
+ const optionKey = option2.attributeName();
1534
1532
  const optionValue = this.getOptionValue(optionKey);
1535
1533
  const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
1536
1534
  const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
1537
1535
  if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
1538
1536
  return negativeOption;
1539
1537
  }
1540
- return positiveOption || option;
1538
+ return positiveOption || option2;
1541
1539
  };
1542
- const getErrorMessage = (option) => {
1543
- const bestOption = findBestOptionFromValue(option);
1540
+ const getErrorMessage = (option2) => {
1541
+ const bestOption = findBestOptionFromValue(option2);
1544
1542
  const optionKey = bestOption.attributeName();
1545
1543
  const source = this.getOptionValueSource(optionKey);
1546
1544
  if (source === "env") {
@@ -1592,35 +1590,35 @@ Expecting one of '${allowedValues.join("', '")}'`);
1592
1590
  const message = `error: unknown command '${unknownName}'${suggestion}`;
1593
1591
  this.error(message, { code: "commander.unknownCommand" });
1594
1592
  }
1595
- version(str, flags, description) {
1596
- if (str === undefined)
1593
+ version(str2, flags, description) {
1594
+ if (str2 === undefined)
1597
1595
  return this._version;
1598
- this._version = str;
1596
+ this._version = str2;
1599
1597
  flags = flags || "-V, --version";
1600
1598
  description = description || "output the version number";
1601
1599
  const versionOption = this.createOption(flags, description);
1602
1600
  this._versionOptionName = versionOption.attributeName();
1603
1601
  this.options.push(versionOption);
1604
1602
  this.on("option:" + versionOption.name(), () => {
1605
- this._outputConfiguration.writeOut(`${str}
1603
+ this._outputConfiguration.writeOut(`${str2}
1606
1604
  `);
1607
- this._exit(0, "commander.version", str);
1605
+ this._exit(0, "commander.version", str2);
1608
1606
  });
1609
1607
  return this;
1610
1608
  }
1611
- description(str, argsDescription) {
1612
- if (str === undefined && argsDescription === undefined)
1609
+ description(str2, argsDescription) {
1610
+ if (str2 === undefined && argsDescription === undefined)
1613
1611
  return this._description;
1614
- this._description = str;
1612
+ this._description = str2;
1615
1613
  if (argsDescription) {
1616
1614
  this._argsDescription = argsDescription;
1617
1615
  }
1618
1616
  return this;
1619
1617
  }
1620
- summary(str) {
1621
- if (str === undefined)
1618
+ summary(str2) {
1619
+ if (str2 === undefined)
1622
1620
  return this._summary;
1623
- this._summary = str;
1621
+ this._summary = str2;
1624
1622
  return this;
1625
1623
  }
1626
1624
  alias(alias) {
@@ -1641,8 +1639,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
1641
1639
  aliases.forEach((alias) => this.alias(alias));
1642
1640
  return this;
1643
1641
  }
1644
- usage(str) {
1645
- if (str === undefined) {
1642
+ usage(str2) {
1643
+ if (str2 === undefined) {
1646
1644
  if (this._usage)
1647
1645
  return this._usage;
1648
1646
  const args = this.registeredArguments.map((arg) => {
@@ -1650,23 +1648,23 @@ Expecting one of '${allowedValues.join("', '")}'`);
1650
1648
  });
1651
1649
  return [].concat(this.options.length || this._hasHelpOption ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
1652
1650
  }
1653
- this._usage = str;
1651
+ this._usage = str2;
1654
1652
  return this;
1655
1653
  }
1656
- name(str) {
1657
- if (str === undefined)
1654
+ name(str2) {
1655
+ if (str2 === undefined)
1658
1656
  return this._name;
1659
- this._name = str;
1657
+ this._name = str2;
1660
1658
  return this;
1661
1659
  }
1662
1660
  nameFromFilename(filename) {
1663
1661
  this._name = path.basename(filename, path.extname(filename));
1664
1662
  return this;
1665
1663
  }
1666
- executableDir(path) {
1667
- if (path === undefined)
1664
+ executableDir(path2) {
1665
+ if (path2 === undefined)
1668
1666
  return this._executableDir;
1669
- this._executableDir = path;
1667
+ this._executableDir = path2;
1670
1668
  return this;
1671
1669
  }
1672
1670
  helpInformation(contextOptions) {
@@ -1726,13 +1724,13 @@ Expecting one of '${allowedValues.join("', '")}'`);
1726
1724
  }
1727
1725
  help(contextOptions) {
1728
1726
  this.outputHelp(contextOptions);
1729
- let exitCode2 = process2.exitCode || 0;
1730
- if (exitCode2 === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
1731
- exitCode2 = 1;
1727
+ let exitCode = process3.exitCode || 0;
1728
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
1729
+ exitCode = 1;
1732
1730
  }
1733
- this._exit(exitCode2, "commander.help", "(outputHelp)");
1731
+ this._exit(exitCode, "commander.help", "(outputHelp)");
1734
1732
  }
1735
- addHelpText(position, text) {
1733
+ addHelpText(position, text2) {
1736
1734
  const allowedValues = ["beforeAll", "before", "after", "afterAll"];
1737
1735
  if (!allowedValues.includes(position)) {
1738
1736
  throw new Error(`Unexpected value for position to addHelpText.
@@ -1741,10 +1739,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
1741
1739
  const helpEvent = `${position}Help`;
1742
1740
  this.on(helpEvent, (context) => {
1743
1741
  let helpStr;
1744
- if (typeof text === "function") {
1745
- helpStr = text({ error: context.error, command: context.command });
1742
+ if (typeof text2 === "function") {
1743
+ helpStr = text2({ error: context.error, command: context.command });
1746
1744
  } else {
1747
- helpStr = text;
1745
+ helpStr = text2;
1748
1746
  }
1749
1747
  if (helpStr) {
1750
1748
  context.write(`${helpStr}
@@ -1794,7 +1792,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
1794
1792
  });
1795
1793
 
1796
1794
  // ../../node_modules/commander/index.js
1797
- var require_commander = __commonJS(function(exports, module) {
1795
+ var require_commander = __commonJS((exports, module) => {
1798
1796
  var { Argument } = require_argument();
1799
1797
  var { Command } = require_command();
1800
1798
  var { CommanderError, InvalidArgumentError } = require_error();
@@ -2172,6 +2170,12 @@ var applyOptions = (object, options = {}) => {
2172
2170
  const colorLevel = stdoutColor ? stdoutColor.level : 0;
2173
2171
  object.level = options.level === undefined ? colorLevel : options.level;
2174
2172
  };
2173
+
2174
+ class Chalk {
2175
+ constructor(options) {
2176
+ return chalkFactory(options);
2177
+ }
2178
+ }
2175
2179
  var chalkFactory = (options) => {
2176
2180
  const chalk = (...strings) => strings.join(" ");
2177
2181
  applyOptions(chalk, options);
@@ -2300,6 +2304,41 @@ var chalk = createChalk();
2300
2304
  var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
2301
2305
  var source_default = chalk;
2302
2306
 
2307
+ // src/embed-context.ts
2308
+ import { AsyncLocalStorage } from "node:async_hooks";
2309
+ function setSoftExitCode(code) {
2310
+ const ctx = embedStore.getStore();
2311
+ if (ctx)
2312
+ ctx.softExitCode = code;
2313
+ else
2314
+ process.exitCode = code;
2315
+ }
2316
+ var embedStore = new AsyncLocalStorage;
2317
+ function embeddedProfile() {
2318
+ const ctx = embedStore.getStore();
2319
+ if (!ctx)
2320
+ return null;
2321
+ return {
2322
+ name: "embedded",
2323
+ endpoint: ctx.identity.endpoint,
2324
+ apiKey: ctx.identity.apiKey,
2325
+ workspaceId: ctx.identity.workspaceId ?? null,
2326
+ output: "json",
2327
+ ...ctx.identity.transport ? { transport: ctx.identity.transport } : {},
2328
+ ...ctx.identity.signal ? { signal: ctx.identity.signal } : {},
2329
+ sources: { endpoint: "flag", apiKey: "flag", workspaceId: "flag", output: "flag" }
2330
+ };
2331
+ }
2332
+
2333
+ // src/output/presentation.ts
2334
+ var plain = new Chalk({ level: 0 });
2335
+ function styles3() {
2336
+ return embedStore.getStore() ? plain : source_default;
2337
+ }
2338
+ function hasProgressTerminal() {
2339
+ return !embedStore.getStore() && Boolean(process.stderr.isTTY);
2340
+ }
2341
+
2303
2342
  // src/config/paths.ts
2304
2343
  import { homedir } from "node:os";
2305
2344
  import { join } from "node:path";
@@ -2312,9 +2351,6 @@ function configPath() {
2312
2351
  function credentialsPath() {
2313
2352
  return process.env.SIM_CREDENTIALS_FILE || join(configDir(), "credentials");
2314
2353
  }
2315
- function updateCachePath() {
2316
- return join(configDir(), "update-check.json");
2317
- }
2318
2354
  // src/config/profile.ts
2319
2355
  import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2320
2356
  import { dirname } from "node:path";
@@ -2634,6 +2670,9 @@ function refuseBlankOverrides(overrides) {
2634
2670
  }
2635
2671
  }
2636
2672
  function resolveProfile(overrides = {}) {
2673
+ const embedded = embeddedProfile();
2674
+ if (embedded)
2675
+ return embedded;
2637
2676
  refuseBlankOverrides(overrides);
2638
2677
  const named = overrides.profile || process.env.SIM_PROFILE;
2639
2678
  const name = named || DEFAULT_PROFILE;
@@ -2686,14 +2725,22 @@ function resolveProfile(overrides = {}) {
2686
2725
  // src/version.ts
2687
2726
  import { readFileSync as readFileSync2 } from "node:fs";
2688
2727
  function readPackageVersion() {
2689
- const metadata = JSON.parse(readFileSync2(new URL("../package.json", import.meta.url), "utf8"));
2690
- if (typeof metadata !== "object" || metadata === null || !("version" in metadata) || typeof metadata.version !== "string") {
2691
- throw new Error("CLI package metadata is missing a valid version");
2692
- }
2693
- return metadata.version;
2728
+ try {
2729
+ const metadata = JSON.parse(readFileSync2(new URL("../package.json", import.meta.url), "utf8"));
2730
+ if (typeof metadata === "object" && metadata !== null && "version" in metadata && typeof metadata.version === "string") {
2731
+ return metadata.version;
2732
+ }
2733
+ } catch {}
2734
+ return "0.0.0-embedded";
2735
+ }
2736
+ var cachedVersion = null;
2737
+ function cliVersion() {
2738
+ cachedVersion ??= readPackageVersion();
2739
+ return cachedVersion;
2740
+ }
2741
+ function userAgent() {
2742
+ return `sim-cli/${cliVersion()} node/${process.versions.node} (${process.platform}; ${process.arch})`;
2694
2743
  }
2695
- var CLI_VERSION = readPackageVersion();
2696
- var USER_AGENT = `sim-cli/${CLI_VERSION} node/${process.versions.node} (${process.platform}; ${process.arch})`;
2697
2744
 
2698
2745
  // src/http/environment.ts
2699
2746
  var reported = new Set;
@@ -2716,11 +2763,11 @@ function runtimeCanProxy(version) {
2716
2763
  return minor >= firstSupportedMinor;
2717
2764
  return major > FIRST_SUPPORTED_MAJOR;
2718
2765
  }
2719
- function warnIfProxyIgnored(env = process.env, version = process.version) {
2720
- const variable = PROXY_VARIABLES.find((name) => env[name]);
2766
+ function warnIfProxyIgnored(env2 = process.env, version = process.version) {
2767
+ const variable = PROXY_VARIABLES.find((name) => env2[name]);
2721
2768
  if (!variable)
2722
2769
  return;
2723
- if (env.NODE_USE_ENV_PROXY && runtimeCanProxy(version))
2770
+ if (env2.NODE_USE_ENV_PROXY && runtimeCanProxy(version))
2724
2771
  return;
2725
2772
  once("proxy", runtimeCanProxy(version) ? `${variable} is set but Node only uses it when NODE_USE_ENV_PROXY=1. Re-run with NODE_USE_ENV_PROXY=1 to route through the proxy.` : `${variable} is set but Node ${version} cannot use it. Upgrade to Node 22.21 or 24.5 and set NODE_USE_ENV_PROXY=1 to route through the proxy.`);
2726
2773
  }
@@ -2832,8 +2879,8 @@ var RAISE_TIMEOUT_HINT = "Raise SIM_TIMEOUT_SECONDS, or set it to 0 to wait inde
2832
2879
  function isRequestTimeout(error) {
2833
2880
  return error instanceof DOMException && error.name === "TimeoutError";
2834
2881
  }
2835
- function resolveTimeoutMs(env = process.env) {
2836
- const raw = env.SIM_TIMEOUT_SECONDS;
2882
+ function resolveTimeoutMs(env2 = process.env) {
2883
+ const raw = env2.SIM_TIMEOUT_SECONDS;
2837
2884
  if (raw === undefined || raw.trim() === "")
2838
2885
  return DEFAULT_TIMEOUT_SECONDS * 1000;
2839
2886
  const seconds = Number(raw);
@@ -2863,12 +2910,12 @@ function combineSignals(caller, timeout) {
2863
2910
  }
2864
2911
  return controller.signal;
2865
2912
  }
2866
- function debugEnabled(env = process.env) {
2867
- const raw = env.SIM_DEBUG;
2913
+ function debugEnabled(env2 = process.env) {
2914
+ const raw = env2.SIM_DEBUG;
2868
2915
  return raw !== undefined && raw !== "" && raw !== "0" && raw.toLowerCase() !== "false";
2869
2916
  }
2870
2917
  function traceRequest(method, url, status, startedAt) {
2871
- process.stderr.write(`${source_default.dim(`[sim] ${method} ${url} → ${status} ${Math.round(performance.now() - startedAt)}ms`)}
2918
+ process.stderr.write(`${styles3().dim(`[sim] ${method} ${url} → ${status} ${Math.round(performance.now() - startedAt)}ms`)}
2872
2919
  `);
2873
2920
  }
2874
2921
  function withoutLeadingLabel(message, label) {
@@ -2966,17 +3013,20 @@ class SimClient {
2966
3013
  warnIfKeyOverCleartext(this.profile.endpoint, Boolean(apiKey));
2967
3014
  const timeoutMs = resolveTimeoutMs();
2968
3015
  const timeout = timeoutMs > 0 ? AbortSignal.timeout(timeoutMs) : undefined;
2969
- const signal = combineSignals(options.signal, timeout);
3016
+ const caller = combineSignals(options.signal, this.profile.signal);
3017
+ if (caller?.aborted)
3018
+ throw new SimApiError("Request cancelled.", 0);
3019
+ const signal = combineSignals(caller, timeout);
2970
3020
  const trace = debugEnabled();
2971
3021
  const startedAt = performance.now();
2972
3022
  let response;
2973
3023
  try {
2974
- response = await fetch(url, {
3024
+ response = await (this.profile.transport ?? fetch)(url, {
2975
3025
  method,
2976
3026
  headers: {
2977
3027
  ...apiKey ? { "x-api-key": apiKey } : {},
2978
3028
  accept: "application/json",
2979
- "user-agent": USER_AGENT,
3029
+ "user-agent": userAgent(),
2980
3030
  ...hasBody ? { "content-type": "application/json" } : {},
2981
3031
  ...options.headers
2982
3032
  },
@@ -2987,7 +3037,7 @@ class SimClient {
2987
3037
  } catch (cause) {
2988
3038
  if (trace)
2989
3039
  traceRequest(method, url, "failed", startedAt);
2990
- if (options.signal?.aborted) {
3040
+ if (caller?.aborted) {
2991
3041
  throw new SimApiError("Request cancelled.", 0);
2992
3042
  }
2993
3043
  if (timeout?.aborted) {
@@ -3038,16 +3088,16 @@ function redirectEndpoint(endpoint, requestPath, target) {
3038
3088
  return suggested === endpoint.replace(/\/+$/, "") ? null : suggested;
3039
3089
  }
3040
3090
  function pageProgress() {
3041
- let reported = false;
3091
+ let reported2 = false;
3042
3092
  return {
3043
3093
  advance: (fetched) => {
3044
- if (!process.stderr.isTTY)
3094
+ if (!hasProgressTerminal())
3045
3095
  return;
3046
- reported = true;
3047
- process.stderr.write(`\r${source_default.dim(`fetched ${fetched}…`)}\x1B[K`);
3096
+ reported2 = true;
3097
+ process.stderr.write(`\r${styles3().dim(`fetched ${fetched}…`)}\x1B[K`);
3048
3098
  },
3049
3099
  finish: () => {
3050
- if (reported)
3100
+ if (reported2)
3051
3101
  process.stderr.write("\r\x1B[K");
3052
3102
  }
3053
3103
  };
@@ -5721,14 +5771,14 @@ function requireDumper() {
5721
5771
  let hasFoldableLine = false;
5722
5772
  const shouldTrackWidth = lineWidth !== -1;
5723
5773
  let previousLineBreak = -1;
5724
- let plain = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1));
5774
+ let plain2 = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1));
5725
5775
  if (singleLineOnly || forceQuotes) {
5726
5776
  for (i = 0;i < string.length; char >= 65536 ? i += 2 : i++) {
5727
5777
  char = codePointAt(string, i);
5728
5778
  if (!isPrintable(char)) {
5729
5779
  return STYLE_DOUBLE;
5730
5780
  }
5731
- plain = plain && isPlainSafe(char, prevChar, inblock);
5781
+ plain2 = plain2 && isPlainSafe(char, prevChar, inblock);
5732
5782
  prevChar = char;
5733
5783
  }
5734
5784
  } else {
@@ -5743,13 +5793,13 @@ function requireDumper() {
5743
5793
  } else if (!isPrintable(char)) {
5744
5794
  return STYLE_DOUBLE;
5745
5795
  }
5746
- plain = plain && isPlainSafe(char, prevChar, inblock);
5796
+ plain2 = plain2 && isPlainSafe(char, prevChar, inblock);
5747
5797
  prevChar = char;
5748
5798
  }
5749
5799
  hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ");
5750
5800
  }
5751
5801
  if (!hasLineBreak && !hasFoldableLine) {
5752
- if (plain && !forceQuotes && !testAmbiguousType(string)) {
5802
+ if (plain2 && !forceQuotes && !testAmbiguousType(string)) {
5753
5803
  return STYLE_PLAIN;
5754
5804
  }
5755
5805
  return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
@@ -6251,7 +6301,6 @@ function isWideCodePoint(codePoint) {
6251
6301
 
6252
6302
  // src/output/render.ts
6253
6303
  var EMPTY_GLYPH = "—";
6254
- var EMPTY = source_default.dim(EMPTY_GLYPH);
6255
6304
  var ESC = String.fromCharCode(27);
6256
6305
  var CONTROL_PATTERN = new RegExp([
6257
6306
  `${ESC}\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\)?`,
@@ -6270,12 +6319,12 @@ function safeOneLine(value) {
6270
6319
  }
6271
6320
  function text(value) {
6272
6321
  if (value === null || value === undefined || value === "")
6273
- return EMPTY;
6322
+ return styles3().dim(EMPTY_GLYPH);
6274
6323
  return sanitize(String(value));
6275
6324
  }
6276
6325
  function timestamp2(value) {
6277
6326
  if (!value)
6278
- return EMPTY;
6327
+ return styles3().dim(EMPTY_GLYPH);
6279
6328
  const date = new Date(value);
6280
6329
  if (Number.isNaN(date.getTime()))
6281
6330
  return sanitize(String(value));
@@ -6283,12 +6332,12 @@ function timestamp2(value) {
6283
6332
  }
6284
6333
  function bool2(value) {
6285
6334
  if (value === null || value === undefined)
6286
- return EMPTY;
6287
- return value ? source_default.green("yes") : source_default.dim("no");
6335
+ return styles3().dim(EMPTY_GLYPH);
6336
+ return value ? styles3().green("yes") : styles3().dim("no");
6288
6337
  }
6289
6338
  function bytes(value) {
6290
6339
  if (value === null || value === undefined)
6291
- return EMPTY;
6340
+ return styles3().dim(EMPTY_GLYPH);
6292
6341
  const units = ["B", "KB", "MB", "GB", "TB"];
6293
6342
  let size = value;
6294
6343
  let unit = 0;
@@ -6300,7 +6349,7 @@ function bytes(value) {
6300
6349
  }
6301
6350
  function duration(ms) {
6302
6351
  if (ms === null || ms === undefined)
6303
- return EMPTY;
6352
+ return styles3().dim(EMPTY_GLYPH);
6304
6353
  if (ms < 1000)
6305
6354
  return `${Math.round(ms)}ms`;
6306
6355
  if (ms < 60000)
@@ -6312,8 +6361,8 @@ function visibleWidth(value) {
6312
6361
  return displayWidth(value);
6313
6362
  }
6314
6363
  function stripAnsi(value) {
6315
- const plain = value.replace(ANSI_PATTERN, "");
6316
- return plain === EMPTY_GLYPH ? "" : plain;
6364
+ const plain2 = value.replace(ANSI_PATTERN, "");
6365
+ return plain2 === EMPTY_GLYPH ? "" : plain2;
6317
6366
  }
6318
6367
  function pad(value, width) {
6319
6368
  return value + " ".repeat(Math.max(0, width - visibleWidth(value)));
@@ -6331,11 +6380,11 @@ function clamp(value, width) {
6331
6380
  }
6332
6381
  function renderTable(rows, columns) {
6333
6382
  if (rows.length === 0)
6334
- return source_default.dim("No results.");
6383
+ return styles3().dim("No results.");
6335
6384
  const headers = columns.map((column) => sanitize(column.header));
6336
6385
  const cells = rows.map((row) => columns.map((column) => clamp(oneLine(column.value(row)), MAX_CELL_WIDTH)));
6337
6386
  const widths = columns.map((_column, index) => Math.max(visibleWidth(headers[index]), ...cells.map((line) => visibleWidth(line[index]))));
6338
- const header = headers.map((label, index) => source_default.dim(pad(label.toUpperCase(), widths[index]))).join(" ").trimEnd();
6387
+ const header = headers.map((label, index) => styles3().dim(pad(label.toUpperCase(), widths[index]))).join(" ").trimEnd();
6339
6388
  const body = cells.map((line) => line.map((cell, index) => pad(cell, widths[index])).join(" ").trimEnd());
6340
6389
  return [header, ...body].join(`
6341
6390
  `);
@@ -6379,7 +6428,7 @@ function printRecord(format, fields, raw) {
6379
6428
  }
6380
6429
  const width = Math.max(...safeFields.map(([label]) => visibleWidth(label)));
6381
6430
  for (const [label, value] of safeFields) {
6382
- console.log(`${source_default.dim(pad(`${label}:`, width + 1))} ${clamp(oneLine(value), MAX_RECORD_WIDTH)}`);
6431
+ console.log(`${styles3().dim(pad(`${label}:`, width + 1))} ${clamp(oneLine(value), MAX_RECORD_WIDTH)}`);
6383
6432
  }
6384
6433
  }
6385
6434
 
@@ -6408,7 +6457,7 @@ import { createHash, randomBytes, randomInt } from "node:crypto";
6408
6457
 
6409
6458
  // src/helpers.ts
6410
6459
  function sleep(ms) {
6411
- return new Promise((resolve) => setTimeout(resolve, ms));
6460
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
6412
6461
  }
6413
6462
 
6414
6463
  // src/auth/device-flow.ts
@@ -6475,7 +6524,7 @@ async function pollForKey(endpoint, auth, signal) {
6475
6524
  headers: {
6476
6525
  "content-type": "application/json",
6477
6526
  accept: "application/json",
6478
- "user-agent": USER_AGENT
6527
+ "user-agent": userAgent()
6479
6528
  },
6480
6529
  body: JSON.stringify({ request: auth.request, verifier: auth.pollSecret }),
6481
6530
  signal,
@@ -6636,8 +6685,8 @@ var V2_OPERATIONS = {
6636
6685
  },
6637
6686
  outputColumns: {
6638
6687
  kind: "array",
6639
- required: true,
6640
- describe: "Columns created for producer outputs."
6688
+ default: [],
6689
+ describe: "Columns to create for producer outputs. An entry naming a column the table already has attaches that column to the group instead of creating it (its `type` must match), and an output whose column already exists may omit its entry entirely — so `[]` attaches existing columns only."
6641
6690
  },
6642
6691
  autoRun: {
6643
6692
  kind: "boolean",
@@ -6723,7 +6772,7 @@ var V2_OPERATIONS = {
6723
6772
  summary: "Delete Files",
6724
6773
  body: {
6725
6774
  workspaceId: { kind: "string", required: true, describe: "Workspace containing the files." },
6726
- fileIds: { kind: "array", required: true, describe: "File identifiers to update." }
6775
+ fileIds: { kind: "array", required: true, describe: "File identifiers to delete." }
6727
6776
  }
6728
6777
  },
6729
6778
  bulkDeleteTables: {
@@ -6941,7 +6990,7 @@ var V2_OPERATIONS = {
6941
6990
  rowId: { kind: "string", describe: "Row whose runs should be canceled for row scope." },
6942
6991
  filter: {
6943
6992
  kind: "unknown",
6944
- describe: 'Recursive predicate tree. Each group node is exactly one non-empty `all` or `any` array whose members are further groups or `{ field, op, value }` conditions; the root must be a group, not a bare condition. At most 100 members per group, 10 levels of nesting, and 500 nodes in total. The negating operators include nulls: `ne`, `nin`, `ncontains`, `nlike`, and `nilike` match rows whose column is null or absent, so "not X" is not the complement of "X" over a nullable column. That holds for every column type, multi-select included. To exclude nulls, `all`-combine the negation with `isNotEmpty` (multi-select) or `isNotNull`. Comparison: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. Membership: `in`, `nin` (array operand). Emptiness: `isEmpty`, `isNotEmpty`, `isNull`, `isNotNull` (no operand). Substring, always case-insensitive, operand matched literally: `contains`, `ncontains`, `startsWith`, `endsWith`. Pattern: `like`/`nlike` (case-sensitive), `ilike`/`nilike` (case-insensitive). **`*` is the only wildcard** and stands for any run of characters; `%`, `_`, and backslash match themselves. Use `like: "Hi*"`, not `like: "Hi%"`. A `select` column compares by option id and restricts its operators: single-select accepts `eq`, `ne`, `in`, `nin`; multi-select accepts `contains`, `ncontains`. Option names are accepted as operands and resolved to ids.'
6993
+ describe: 'A single `{ field, op, value }` condition or a recursive `all`/`any` group; either form is normalized to a grouped predicate after validation. At most 100 members per group, 10 levels of nesting, and 500 nodes in total. The negating operators include nulls: `ne`, `nin`, `ncontains`, `nlike`, and `nilike` match rows whose column is null or absent, so "not X" is not the complement of "X" over a nullable column. That holds for every column type, multi-select included. To exclude nulls, `all`-combine the negation with `isNotEmpty` (multi-select) or `isNotNull`. Comparison: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. Membership: `in`, `nin` (array operand). Emptiness: `isEmpty`, `isNotEmpty`, `isNull`, `isNotNull` (no operand). Substring, always case-insensitive, operand matched literally: `contains`, `ncontains`, `startsWith`, `endsWith`. Pattern: `like`/`nlike` (case-sensitive), `ilike`/`nilike` (case-insensitive). **`*` is the only wildcard** and stands for any run of characters; `%`, `_`, and backslash match themselves. Use `like: "Hi*"`, not `like: "Hi%"`. A `select` column compares by option id and restricts its operators: single-select accepts `eq`, `ne`, `in`, `nin`; multi-select accepts `contains`, `ncontains`. Option names are accepted as operands and resolved to ids.'
6945
6994
  },
6946
6995
  excludeRowIds: { kind: "array", describe: "Rows excluded from an all-scope cancellation." }
6947
6996
  }
@@ -6972,6 +7021,11 @@ var V2_OPERATIONS = {
6972
7021
  conversationId: {
6973
7022
  kind: "string",
6974
7023
  describe: "Conversation to continue; a new one starts when omitted."
7024
+ },
7025
+ effort: {
7026
+ kind: "enum",
7027
+ values: ["low", "medium", "high", "xhigh", "max"],
7028
+ describe: "Model effort for this turn; defaults to the deployment default (high)."
6975
7029
  }
6976
7030
  }
6977
7031
  },
@@ -7051,6 +7105,13 @@ var V2_OPERATIONS = {
7051
7105
  responseMode: "json",
7052
7106
  summary: "Create Credential Connection",
7053
7107
  personalKeyOnly: true,
7108
+ body: {
7109
+ workspaceId: {
7110
+ kind: "string",
7111
+ required: true,
7112
+ describe: "Workspace that will own the credential."
7113
+ }
7114
+ },
7054
7115
  opaqueBody: true
7055
7116
  },
7056
7117
  createCustomTool: {
@@ -7463,47 +7524,6 @@ var V2_OPERATIONS = {
7463
7524
  }
7464
7525
  }
7465
7526
  },
7466
- createSandbox: {
7467
- method: "POST",
7468
- path: "/api/v2/sandboxes",
7469
- pathParams: [],
7470
- responseMode: "json",
7471
- summary: "Create Sandbox",
7472
- personalKeyOnly: true,
7473
- body: {
7474
- workspaceId: {
7475
- kind: "string",
7476
- required: true,
7477
- describe: "Workspace in which to create the sandbox."
7478
- },
7479
- name: {
7480
- kind: "string",
7481
- required: true,
7482
- describe: "Display name, unique within the workspace; 1 to 64 characters."
7483
- },
7484
- language: {
7485
- kind: "enum",
7486
- required: true,
7487
- values: ["javascript", "python"],
7488
- describe: "Dependency ecosystem: `javascript` installs from npm, `python` from PyPI."
7489
- },
7490
- dependencies: {
7491
- kind: "array",
7492
- default: [],
7493
- describe: "Package specifiers installed into the sandbox, one per entry."
7494
- },
7495
- cliTools: {
7496
- kind: "array",
7497
- default: [],
7498
- describe: "Pinned managed CLI ids installed into the sandbox, at most 10, no duplicates."
7499
- },
7500
- systemPackages: {
7501
- kind: "array",
7502
- default: [],
7503
- describe: "Debian packages installed into the sandbox, one per entry."
7504
- }
7505
- }
7506
- },
7507
7527
  createServiceAccountCredential: {
7508
7528
  method: "POST",
7509
7529
  path: "/api/v2/credentials",
@@ -7534,7 +7554,7 @@ var V2_OPERATIONS = {
7534
7554
  description: { kind: "string", describe: "Optional credential description." },
7535
7555
  id: {
7536
7556
  kind: "string",
7537
- describe: "Required only when provider discovery requests a client-generated ID."
7557
+ describe: "Optional client-generated credential ID. The server mints one when it is omitted, so no provider requires it. A `slack-custom-bot` credential may supply one so its Slack Request URL, which embeds the ID, can be configured before the credential exists; every other provider ignores it."
7538
7558
  },
7539
7559
  credentials: {
7540
7560
  kind: "string",
@@ -7610,7 +7630,7 @@ var V2_OPERATIONS = {
7610
7630
  rowIds: { kind: "array", describe: "Explicit row subset to run." },
7611
7631
  filter: {
7612
7632
  kind: "unknown",
7613
- describe: 'Recursive predicate tree. Each group node is exactly one non-empty `all` or `any` array whose members are further groups or `{ field, op, value }` conditions; the root must be a group, not a bare condition. At most 100 members per group, 10 levels of nesting, and 500 nodes in total. The negating operators include nulls: `ne`, `nin`, `ncontains`, `nlike`, and `nilike` match rows whose column is null or absent, so "not X" is not the complement of "X" over a nullable column. That holds for every column type, multi-select included. To exclude nulls, `all`-combine the negation with `isNotEmpty` (multi-select) or `isNotNull`. Comparison: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. Membership: `in`, `nin` (array operand). Emptiness: `isEmpty`, `isNotEmpty`, `isNull`, `isNotNull` (no operand). Substring, always case-insensitive, operand matched literally: `contains`, `ncontains`, `startsWith`, `endsWith`. Pattern: `like`/`nlike` (case-sensitive), `ilike`/`nilike` (case-insensitive). **`*` is the only wildcard** and stands for any run of characters; `%`, `_`, and backslash match themselves. Use `like: "Hi*"`, not `like: "Hi%"`. A `select` column compares by option id and restricts its operators: single-select accepts `eq`, `ne`, `in`, `nin`; multi-select accepts `contains`, `ncontains`. Option names are accepted as operands and resolved to ids.'
7633
+ describe: 'A single `{ field, op, value }` condition or a recursive `all`/`any` group; either form is normalized to a grouped predicate after validation. At most 100 members per group, 10 levels of nesting, and 500 nodes in total. The negating operators include nulls: `ne`, `nin`, `ncontains`, `nlike`, and `nilike` match rows whose column is null or absent, so "not X" is not the complement of "X" over a nullable column. That holds for every column type, multi-select included. To exclude nulls, `all`-combine the negation with `isNotEmpty` (multi-select) or `isNotNull`. Comparison: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. Membership: `in`, `nin` (array operand). Emptiness: `isEmpty`, `isNotEmpty`, `isNull`, `isNotNull` (no operand). Substring, always case-insensitive, operand matched literally: `contains`, `ncontains`, `startsWith`, `endsWith`. Pattern: `like`/`nlike` (case-sensitive), `ilike`/`nilike` (case-insensitive). **`*` is the only wildcard** and stands for any run of characters; `%`, `_`, and backslash match themselves. Use `like: "Hi*"`, not `like: "Hi%"`. A `select` column compares by option id and restricts its operators: single-select accepts `eq`, `ne`, `in`, `nin`; multi-select accepts `contains`, `ncontains`. Option names are accepted as operands and resolved to ids.'
7614
7634
  },
7615
7635
  excludeRowIds: { kind: "array", describe: "Rows excluded from a select-all run scope." },
7616
7636
  limit: { kind: "object", describe: "Optional cap on eligible rows to run." }
@@ -8021,18 +8041,6 @@ var V2_OPERATIONS = {
8021
8041
  }
8022
8042
  }
8023
8043
  },
8024
- deleteSandbox: {
8025
- method: "DELETE",
8026
- path: "/api/v2/sandboxes/[sandboxId]",
8027
- pathParams: ["sandboxId"],
8028
- pathParamDocs: { sandboxId: "Unique sandbox identifier." },
8029
- responseMode: "json",
8030
- summary: "Delete Sandbox",
8031
- personalKeyOnly: true,
8032
- query: {
8033
- workspaceId: { kind: "string", required: true, describe: "Workspace that owns the sandbox." }
8034
- }
8035
- },
8036
8044
  deleteSecret: {
8037
8045
  method: "DELETE",
8038
8046
  path: "/api/v2/secrets/[name]",
@@ -8144,7 +8152,7 @@ var V2_OPERATIONS = {
8144
8152
  workspaceId: { kind: "string", required: true, describe: "Unique workspace identifier." },
8145
8153
  filter: {
8146
8154
  kind: "unknown",
8147
- describe: 'Recursive predicate tree. Each group node is exactly one non-empty `all` or `any` array whose members are further groups or `{ field, op, value }` conditions; the root must be a group, not a bare condition. At most 100 members per group, 10 levels of nesting, and 500 nodes in total. The negating operators include nulls: `ne`, `nin`, `ncontains`, `nlike`, and `nilike` match rows whose column is null or absent, so "not X" is not the complement of "X" over a nullable column. That holds for every column type, multi-select included. To exclude nulls, `all`-combine the negation with `isNotEmpty` (multi-select) or `isNotNull`. Comparison: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. Membership: `in`, `nin` (array operand). Emptiness: `isEmpty`, `isNotEmpty`, `isNull`, `isNotNull` (no operand). Substring, always case-insensitive, operand matched literally: `contains`, `ncontains`, `startsWith`, `endsWith`. Pattern: `like`/`nlike` (case-sensitive), `ilike`/`nilike` (case-insensitive). **`*` is the only wildcard** and stands for any run of characters; `%`, `_`, and backslash match themselves. Use `like: "Hi*"`, not `like: "Hi%"`. A `select` column compares by option id and restricts its operators: single-select accepts `eq`, `ne`, `in`, `nin`; multi-select accepts `contains`, `ncontains`. Option names are accepted as operands and resolved to ids.'
8155
+ describe: 'A single `{ field, op, value }` condition or a recursive `all`/`any` group; either form is normalized to a grouped predicate after validation. At most 100 members per group, 10 levels of nesting, and 500 nodes in total. The negating operators include nulls: `ne`, `nin`, `ncontains`, `nlike`, and `nilike` match rows whose column is null or absent, so "not X" is not the complement of "X" over a nullable column. That holds for every column type, multi-select included. To exclude nulls, `all`-combine the negation with `isNotEmpty` (multi-select) or `isNotNull`. Comparison: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. Membership: `in`, `nin` (array operand). Emptiness: `isEmpty`, `isNotEmpty`, `isNull`, `isNotNull` (no operand). Substring, always case-insensitive, operand matched literally: `contains`, `ncontains`, `startsWith`, `endsWith`. Pattern: `like`/`nlike` (case-sensitive), `ilike`/`nilike` (case-insensitive). **`*` is the only wildcard** and stands for any run of characters; `%`, `_`, and backslash match themselves. Use `like: "Hi*"`, not `like: "Hi%"`. A `select` column compares by option id and restricts its operators: single-select accepts `eq`, `ne`, `in`, `nin`; multi-select accepts `contains`, `ncontains`. Option names are accepted as operands and resolved to ids.'
8148
8156
  },
8149
8157
  limit: { kind: "integer", describe: "Maximum matching rows to delete." },
8150
8158
  rowIds: { kind: "array", describe: "Explicit row identifiers to delete." }
@@ -8314,53 +8322,6 @@ var V2_OPERATIONS = {
8314
8322
  }
8315
8323
  }
8316
8324
  },
8317
- editFileContent: {
8318
- method: "PATCH",
8319
- path: "/api/v2/files/[fileId]/content",
8320
- pathParams: ["fileId"],
8321
- pathParamDocs: { fileId: "File identifier." },
8322
- responseMode: "json",
8323
- summary: "Edit File Content",
8324
- body: {
8325
- workspaceId: { kind: "string", required: true, describe: "Workspace that owns the file." },
8326
- edit: {
8327
- kind: "unknown",
8328
- required: true,
8329
- describe: "One exact or anchor-based edit: search_replace, replace_between, insert_after, or delete_between."
8330
- }
8331
- }
8332
- },
8333
- executeTool: {
8334
- method: "POST",
8335
- path: "/api/v2/tools/[toolId]/execute",
8336
- pathParams: ["toolId"],
8337
- pathParamDocs: {
8338
- toolId: "Tool identifier. An unversioned name resolves to the newest version, and the response echoes the resolved id."
8339
- },
8340
- responseMode: "json",
8341
- summary: "Run Tool",
8342
- personalKeyOnly: true,
8343
- body: {
8344
- workspaceId: {
8345
- kind: "string",
8346
- required: true,
8347
- describe: "Workspace whose integration allowlist, credentials, and environment variables govern this call."
8348
- },
8349
- input: {
8350
- kind: "object",
8351
- default: {},
8352
- describe: "Arguments for the tool, keyed by the parameter ids the tool catalog publishes for it. A parameter whose visibility is `user-only` also accepts an environment-variable reference written as the whole value, `{{VAR_NAME}}`, resolved server-side against the workspace environment; any other value is sent verbatim."
8353
- },
8354
- credentialId: {
8355
- kind: "string",
8356
- describe: "Credential to authenticate with. Required when the tool declares an OAuth requirement; the workspace credentials list names the candidates."
8357
- },
8358
- timeoutSeconds: {
8359
- kind: "integer",
8360
- describe: "How long to wait for the tool before abandoning the call."
8361
- }
8362
- }
8363
- },
8364
8325
  executeWorkflow: {
8365
8326
  method: "POST",
8366
8327
  path: "/api/v2/workflows/[workflowId]/execute",
@@ -8393,7 +8354,7 @@ var V2_OPERATIONS = {
8393
8354
  },
8394
8355
  selectedOutputs: {
8395
8356
  kind: "array",
8396
- describe: "Block output references to include in a streamed response. Use `<blockName>.<outputPath>` for the executed workflow or `<childWorkflowId>.<blockName>.<outputPath>` for a child workflow; block names are normalized workflow reference names. Selecting a child workflow applies to every invocation of it. Requires `stream: true` it shapes the streamed envelope only, so it is rejected on a sync request and when `async` is true. To narrow a finished run, pass `selectedOutputs` to the run resource instead."
8357
+ describe: "Block output references to include in the response. Use `<blockName>.<outputPath>` for the executed workflow or `<childWorkflowId>.<blockName>.<outputPath>` for a child workflow; block names are normalized workflow reference names, and selecting a child workflow applies to every invocation of it. On a sync request the named outputs come back in `blockOutputs`, keyed by these selector strings exactly as sent; on a stream they shape the streamed envelope. A selector whose block name or id matches no block in the workflow is rejected with `400` naming the available blocks, before the run starts. A selector whose block did not run or whose path is absent is omitted. Rejected when `async` is true a queued run has produced nothing to select; narrow the finished run via the run resource instead."
8397
8358
  },
8398
8359
  includeThinking: {
8399
8360
  kind: "boolean",
@@ -8431,7 +8392,13 @@ var V2_OPERATIONS = {
8431
8392
  pathParams: ["workflowId"],
8432
8393
  pathParamDocs: { workflowId: "Unique workflow identifier." },
8433
8394
  responseMode: "json",
8434
- summary: "Export Workflow"
8395
+ summary: "Export Workflow",
8396
+ query: {
8397
+ includeWorkspaceBindings: {
8398
+ kind: "boolean",
8399
+ describe: "Whether to keep workspace-scoped bindings — table, knowledge base, document, folder, channel, and other resource selectors — in the exported state. Defaults to false, the sharing-safe export in which those ids are cleared because they resolve nowhere else. Send true for a same-workspace round trip so the re-imported workflow can run without re-selecting them. Credentials, passwords, and table sub-block values are cleared either way."
8400
+ }
8401
+ }
8435
8402
  },
8436
8403
  getAuditLog: {
8437
8404
  method: "GET",
@@ -8652,6 +8619,10 @@ var V2_OPERATIONS = {
8652
8619
  values: ["info", "error"],
8653
8620
  describe: "Severity level to include."
8654
8621
  },
8622
+ includeHandledErrors: {
8623
+ kind: "boolean",
8624
+ describe: "Whether runs with a handled block error are counted as `handledErrorRuns`, and whether `level=error` also selects them. Off by default: counting them scans each run’s stored trace."
8625
+ },
8655
8626
  startDate: {
8656
8627
  kind: "string",
8657
8628
  describe: "Only include runs started at or after this UTC ISO 8601 timestamp, e.g. `2026-08-06T00:00:00Z`. A date without a time, or a timestamp carrying a UTC offset instead of `Z`, is rejected, as is year `0000`, which names no storable instant."
@@ -8663,7 +8634,26 @@ var V2_OPERATIONS = {
8663
8634
  segmentCount: {
8664
8635
  kind: "integer",
8665
8636
  default: 72,
8666
- describe: "Number of equal time buckets to divide the window into, from 1 to 500. Exactly this many buckets are always returned. Buckets are never narrower than one minute, so on a short window the series extends past the end of the window rather than being compressed, and the trailing buckets are empty."
8637
+ describe: "Number of equal time buckets to divide the window into, from 1 to 500. It is the ceiling on how many buckets a series carries: with `includeEmpty=true` exactly this many are returned, otherwise only the buckets holding at least one run. Buckets are never narrower than one minute, so on a short window the series extends past the end of the window rather than being compressed, and the trailing buckets are empty."
8638
+ },
8639
+ includeEmpty: {
8640
+ kind: "enum",
8641
+ values: [
8642
+ "true",
8643
+ "1",
8644
+ "yes",
8645
+ "on",
8646
+ "y",
8647
+ "enabled",
8648
+ "false",
8649
+ "0",
8650
+ "no",
8651
+ "off",
8652
+ "n",
8653
+ "disabled"
8654
+ ],
8655
+ default: false,
8656
+ describe: "Whether buckets with no runs are included in every series. Off by default, so each series carries only the buckets that hold at least one run; set it to publish exactly `segmentCount` buckets per series, empty ones included. The listed spellings are the whole accepted vocabulary and are case-sensitive; any other value is rejected."
8667
8657
  }
8668
8658
  }
8669
8659
  },
@@ -8721,22 +8711,11 @@ var V2_OPERATIONS = {
8721
8711
  groupId: "Workflow or enrichment group to run."
8722
8712
  },
8723
8713
  responseMode: "json",
8724
- summary: "Get Enrichment Run Detail",
8714
+ summary: "Get Row Group Run",
8725
8715
  query: {
8726
8716
  workspaceId: { kind: "string", required: true, describe: "Workspace that owns the table." }
8727
8717
  }
8728
8718
  },
8729
- getSandbox: {
8730
- method: "GET",
8731
- path: "/api/v2/sandboxes/[sandboxId]",
8732
- pathParams: ["sandboxId"],
8733
- pathParamDocs: { sandboxId: "Unique sandbox identifier." },
8734
- responseMode: "json",
8735
- summary: "Get Sandbox",
8736
- query: {
8737
- workspaceId: { kind: "string", required: true, describe: "Workspace that owns the sandbox." }
8738
- }
8739
- },
8740
8719
  getSkill: {
8741
8720
  method: "GET",
8742
8721
  path: "/api/v2/skills/[skillId]",
@@ -9056,8 +9035,7 @@ var V2_OPERATIONS = {
9056
9035
  "knowledge-base",
9057
9036
  "voice-input",
9058
9037
  "enrichment",
9059
- "voice-output",
9060
- "api-tool"
9038
+ "voice-output"
9061
9039
  ],
9062
9040
  describe: "Restrict results to one usage source."
9063
9041
  },
@@ -9121,6 +9099,10 @@ var V2_OPERATIONS = {
9121
9099
  values: ["builtin", "custom"],
9122
9100
  describe: "Restrict to shipped blocks or to this workspace’s deployed custom blocks."
9123
9101
  },
9102
+ includeSunset: {
9103
+ kind: "boolean",
9104
+ describe: "Include `legacy` and `deprecated` blocks. Off by default: a sunset block keeps executing where it is already placed, but it is not offered for new authoring. Each returned entry carries `sunset.replacedBy`, the block to build with instead."
9105
+ },
9124
9106
  sortBy: {
9125
9107
  kind: "enum",
9126
9108
  values: ["id", "name", "category"],
@@ -9196,6 +9178,21 @@ var V2_OPERATIONS = {
9196
9178
  search: {
9197
9179
  kind: "string",
9198
9180
  describe: "Case-insensitive substring match against the connector name."
9181
+ },
9182
+ detail: {
9183
+ kind: "enum",
9184
+ values: ["summary", "full"],
9185
+ default: "summary",
9186
+ describe: "Projection of each item. `summary` (the default) carries the identifier, name, description, and auth mode; `full` adds the version, the complete auth settings, the `sourceConfig` field schema, incremental-sync support, and tag definitions."
9187
+ },
9188
+ limit: {
9189
+ kind: "integer",
9190
+ default: 25,
9191
+ describe: "Maximum connector types to return per page. Must be a whole number from 1 to 100. Defaults to 25."
9192
+ },
9193
+ cursor: {
9194
+ kind: "string",
9195
+ describe: "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor."
9199
9196
  }
9200
9197
  }
9201
9198
  },
@@ -9341,28 +9338,6 @@ var V2_OPERATIONS = {
9341
9338
  values: ["active", "archived"],
9342
9339
  default: "active",
9343
9340
  describe: "Which lifecycle set to list: `active` (default) returns live folders only; `archived` returns folders a recursive delete soft-deleted, which is how a caller finds a path to hand to the folder restore. Authorization is identical for both."
9344
- },
9345
- recursive: {
9346
- kind: "enum",
9347
- values: [
9348
- "true",
9349
- "1",
9350
- "yes",
9351
- "on",
9352
- "y",
9353
- "enabled",
9354
- "false",
9355
- "0",
9356
- "no",
9357
- "off",
9358
- "n",
9359
- "disabled"
9360
- ],
9361
- describe: "Whether parentPath includes every descendant instead of direct children only."
9362
- },
9363
- depth: {
9364
- kind: "integer",
9365
- describe: "Deepest level below parentPath to include when recursive is true."
9366
9341
  }
9367
9342
  }
9368
9343
  },
@@ -9797,6 +9772,10 @@ var V2_OPERATIONS = {
9797
9772
  kind: "string",
9798
9773
  describe: "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor."
9799
9774
  },
9775
+ includeHandledErrors: {
9776
+ kind: "boolean",
9777
+ describe: "Whether `level=error` also selects runs that finished at `info` after a block error was recovered by an error path. Off by default: such a run succeeded, so it is an error only to a caller auditing error handling. Every row reports `hasHandledErrors` whether or not this is set. Job runs carry no block trace, so the flag never widens that branch."
9778
+ },
9800
9779
  status: {
9801
9780
  kind: "string",
9802
9781
  describe: "Comma-separated execution statuses to include, from `pending` | `running` | `paused` | `redacting` | `completed` | `failed` | `cancelled`. An empty entry is rejected. ANDed with `level`, which reports severity rather than lifecycle."
@@ -9887,41 +9866,6 @@ var V2_OPERATIONS = {
9887
9866
  }
9888
9867
  }
9889
9868
  },
9890
- listSandboxes: {
9891
- method: "GET",
9892
- path: "/api/v2/sandboxes",
9893
- pathParams: [],
9894
- responseMode: "json",
9895
- summary: "List Sandboxes",
9896
- query: {
9897
- workspaceId: { kind: "string", required: true, describe: "Workspace that owns the sandbox." },
9898
- search: {
9899
- kind: "string",
9900
- describe: "Case-insensitive substring match against the sandbox name."
9901
- },
9902
- sortBy: {
9903
- kind: "enum",
9904
- values: ["name", "createdAt", "updatedAt"],
9905
- default: "name",
9906
- describe: "Field used to sort the result. Sorting by `name` is case-sensitive and follows the storage collation, so do not rely on a case-insensitive order."
9907
- },
9908
- sortOrder: {
9909
- kind: "enum",
9910
- values: ["asc", "desc"],
9911
- default: "asc",
9912
- describe: "Sort direction."
9913
- },
9914
- limit: {
9915
- kind: "integer",
9916
- default: 50,
9917
- describe: "Maximum sandboxes to return per page. Must be a whole number from 1 to 100. Defaults to 50."
9918
- },
9919
- cursor: {
9920
- kind: "string",
9921
- describe: "Opaque cursor from the previous page. Send it back with the same sort and filters; only `limit` may change. Change anything else and pagination must restart without a cursor."
9922
- }
9923
- }
9924
- },
9925
9869
  listSecrets: {
9926
9870
  method: "GET",
9927
9871
  path: "/api/v2/secrets",
@@ -10042,7 +9986,7 @@ var V2_OPERATIONS = {
10042
9986
  pathParams: ["tableId"],
10043
9987
  pathParamDocs: { tableId: "Unique table identifier." },
10044
9988
  responseMode: "json",
10045
- summary: "List Active Run Dispatches",
9989
+ summary: "List Run Dispatches",
10046
9990
  query: {
10047
9991
  workspaceId: { kind: "string", required: true, describe: "Workspace that owns the table." }
10048
9992
  }
@@ -10454,8 +10398,8 @@ var V2_OPERATIONS = {
10454
10398
  },
10455
10399
  limit: {
10456
10400
  kind: "integer",
10457
- default: 50,
10458
- describe: "Maximum workspaces to return per page. Must be a whole number from 1 to 100. Defaults to 50."
10401
+ default: 25,
10402
+ describe: "Maximum workspaces to return per page. Must be a whole number from 1 to 100. Defaults to 25."
10459
10403
  },
10460
10404
  cursor: {
10461
10405
  kind: "string",
@@ -10567,7 +10511,9 @@ var V2_OPERATIONS = {
10567
10511
  method: "GET",
10568
10512
  path: "/api/v2/files/[fileId]/text",
10569
10513
  pathParams: ["fileId"],
10570
- pathParamDocs: { fileId: "File identifier." },
10514
+ pathParamDocs: {
10515
+ fileId: "File identifier, or the file’s VFS path: `files/<folder>/<name>`, or `uploads/<name>` for a Chat upload."
10516
+ },
10571
10517
  responseMode: "json",
10572
10518
  summary: "Read File Text",
10573
10519
  query: {
@@ -10575,14 +10521,6 @@ var V2_OPERATIONS = {
10575
10521
  maxBytes: {
10576
10522
  kind: "integer",
10577
10523
  describe: "Optional ceiling on the source bytes fed to the parser, lowering but never raising the server limit."
10578
- },
10579
- offset: {
10580
- kind: "integer",
10581
- describe: "First line to return, 1-based. Absent starts at the first line."
10582
- },
10583
- limit: {
10584
- kind: "integer",
10585
- describe: "How many lines to return from `offset`. Absent reads to the end."
10586
10524
  }
10587
10525
  }
10588
10526
  },
@@ -10598,7 +10536,7 @@ var V2_OPERATIONS = {
10598
10536
  destinationPath: {
10599
10537
  kind: "string",
10600
10538
  required: true,
10601
- describe: "New full path for the folder and its descendants."
10539
+ describe: "Where the folder lands, with `mv` semantics. A path naming an existing folder receives the source as a child under its current name; `/` moves it to the workspace root under its current name; any other path becomes the folder’s new full path (a rename, a relocation, or both)."
10602
10540
  }
10603
10541
  }
10604
10542
  },
@@ -10614,7 +10552,7 @@ var V2_OPERATIONS = {
10614
10552
  destinationPath: {
10615
10553
  kind: "string",
10616
10554
  required: true,
10617
- describe: "New full path for the folder and its descendants."
10555
+ describe: "Where the folder lands, with `mv` semantics. A path naming an existing folder receives the source as a child under its current name; `/` moves it to the workspace root under its current name; any other path becomes the folder’s new full path (a rename, a relocation, or both)."
10618
10556
  }
10619
10557
  }
10620
10558
  },
@@ -10630,7 +10568,7 @@ var V2_OPERATIONS = {
10630
10568
  destinationPath: {
10631
10569
  kind: "string",
10632
10570
  required: true,
10633
- describe: "New full path for the folder and its descendants."
10571
+ describe: "Where the folder lands, with `mv` semantics. A path naming an existing folder receives the source as a child under its current name; `/` moves it to the workspace root under its current name; any other path becomes the folder’s new full path (a rename, a relocation, or both)."
10634
10572
  }
10635
10573
  }
10636
10574
  },
@@ -10646,7 +10584,7 @@ var V2_OPERATIONS = {
10646
10584
  destinationPath: {
10647
10585
  kind: "string",
10648
10586
  required: true,
10649
- describe: "New full path for the folder and its descendants."
10587
+ describe: "Where the folder lands, with `mv` semantics. A path naming an existing folder receives the source as a child under its current name; `/` moves it to the workspace root under its current name; any other path becomes the folder’s new full path (a rename, a relocation, or both)."
10650
10588
  }
10651
10589
  }
10652
10590
  },
@@ -10913,50 +10851,6 @@ var V2_OPERATIONS = {
10913
10851
  workspaceId: { kind: "string", required: true, describe: "Unique workspace identifier." }
10914
10852
  }
10915
10853
  },
10916
- searchFileContent: {
10917
- method: "GET",
10918
- path: "/api/v2/files/search",
10919
- pathParams: [],
10920
- responseMode: "json",
10921
- summary: "Search File Content",
10922
- query: {
10923
- workspaceId: { kind: "string", required: true, describe: "Workspace to search." },
10924
- query: {
10925
- kind: "string",
10926
- required: true,
10927
- describe: "Regular expression, or exact text when `mode` is `exact`."
10928
- },
10929
- mode: {
10930
- kind: "enum",
10931
- values: ["exact", "regex"],
10932
- default: "regex",
10933
- describe: "How `query` is read."
10934
- },
10935
- maxResults: { kind: "integer", default: 50, describe: "Maximum matching lines to return." },
10936
- folderPaths: {
10937
- kind: "string",
10938
- describe: "Folders the search is confined to, comma-separated. Absent searches the whole workspace. The scope also narrows `indexStatus`, so `complete` describes the folders searched rather than the workspace."
10939
- },
10940
- includeSubfolders: {
10941
- kind: "enum",
10942
- values: [
10943
- "true",
10944
- "1",
10945
- "yes",
10946
- "on",
10947
- "y",
10948
- "enabled",
10949
- "false",
10950
- "0",
10951
- "no",
10952
- "off",
10953
- "n",
10954
- "disabled"
10955
- ],
10956
- describe: "Whether the scope descends into nested folders. Absent means yes. The listed spellings are the whole accepted vocabulary and are case-sensitive; any other value is rejected."
10957
- }
10958
- }
10959
- },
10960
10854
  searchKnowledge: {
10961
10855
  method: "POST",
10962
10856
  path: "/api/v2/knowledge/search",
@@ -10989,6 +10883,7 @@ var V2_OPERATIONS = {
10989
10883
  },
10990
10884
  searchMode: {
10991
10885
  kind: "enum",
10886
+ default: "vector",
10992
10887
  describe: "Retrieval strategy: vector is semantic-only, while hybrid also runs full-text search."
10993
10888
  },
10994
10889
  rerankerEnabled: {
@@ -11019,7 +10914,7 @@ var V2_OPERATIONS = {
11019
10914
  q: { kind: "string", required: true, describe: "Case-insensitive cell substring to find." },
11020
10915
  predicate: {
11021
10916
  kind: "unknown",
11022
- describe: 'Recursive predicate tree. Each group node is exactly one non-empty `all` or `any` array whose members are further groups or `{ field, op, value }` conditions; the root must be a group, not a bare condition. At most 100 members per group, 10 levels of nesting, and 500 nodes in total. The negating operators include nulls: `ne`, `nin`, `ncontains`, `nlike`, and `nilike` match rows whose column is null or absent, so "not X" is not the complement of "X" over a nullable column. That holds for every column type, multi-select included. To exclude nulls, `all`-combine the negation with `isNotEmpty` (multi-select) or `isNotNull`. Comparison: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. Membership: `in`, `nin` (array operand). Emptiness: `isEmpty`, `isNotEmpty`, `isNull`, `isNotNull` (no operand). Substring, always case-insensitive, operand matched literally: `contains`, `ncontains`, `startsWith`, `endsWith`. Pattern: `like`/`nlike` (case-sensitive), `ilike`/`nilike` (case-insensitive). **`*` is the only wildcard** and stands for any run of characters; `%`, `_`, and backslash match themselves. Use `like: "Hi*"`, not `like: "Hi%"`. A `select` column compares by option id and restricts its operators: single-select accepts `eq`, `ne`, `in`, `nin`; multi-select accepts `contains`, `ncontains`. Option names are accepted as operands and resolved to ids.'
10917
+ describe: 'A single `{ field, op, value }` condition or a recursive `all`/`any` group; either form is normalized to a grouped predicate after validation. At most 100 members per group, 10 levels of nesting, and 500 nodes in total. The negating operators include nulls: `ne`, `nin`, `ncontains`, `nlike`, and `nilike` match rows whose column is null or absent, so "not X" is not the complement of "X" over a nullable column. That holds for every column type, multi-select included. To exclude nulls, `all`-combine the negation with `isNotEmpty` (multi-select) or `isNotNull`. Comparison: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. Membership: `in`, `nin` (array operand). Emptiness: `isEmpty`, `isNotEmpty`, `isNull`, `isNotNull` (no operand). Substring, always case-insensitive, operand matched literally: `contains`, `ncontains`, `startsWith`, `endsWith`. Pattern: `like`/`nlike` (case-sensitive), `ilike`/`nilike` (case-insensitive). **`*` is the only wildcard** and stands for any run of characters; `%`, `_`, and backslash match themselves. Use `like: "Hi*"`, not `like: "Hi%"`. A `select` column compares by option id and restricts its operators: single-select accepts `eq`, `ne`, `in`, `nin`; multi-select accepts `contains`, `ncontains`. Option names are accepted as operands and resolved to ids.'
11023
10918
  },
11024
10919
  sort: { kind: "array", describe: "Ordered table-row sort specification." }
11025
10920
  }
@@ -11461,7 +11356,7 @@ var V2_OPERATIONS = {
11461
11356
  filter: {
11462
11357
  kind: "unknown",
11463
11358
  required: true,
11464
- describe: 'Recursive predicate tree. Each group node is exactly one non-empty `all` or `any` array whose members are further groups or `{ field, op, value }` conditions; the root must be a group, not a bare condition. At most 100 members per group, 10 levels of nesting, and 500 nodes in total. The negating operators include nulls: `ne`, `nin`, `ncontains`, `nlike`, and `nilike` match rows whose column is null or absent, so "not X" is not the complement of "X" over a nullable column. That holds for every column type, multi-select included. To exclude nulls, `all`-combine the negation with `isNotEmpty` (multi-select) or `isNotNull`. Comparison: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. Membership: `in`, `nin` (array operand). Emptiness: `isEmpty`, `isNotEmpty`, `isNull`, `isNotNull` (no operand). Substring, always case-insensitive, operand matched literally: `contains`, `ncontains`, `startsWith`, `endsWith`. Pattern: `like`/`nlike` (case-sensitive), `ilike`/`nilike` (case-insensitive). **`*` is the only wildcard** and stands for any run of characters; `%`, `_`, and backslash match themselves. Use `like: "Hi*"`, not `like: "Hi%"`. A `select` column compares by option id and restricts its operators: single-select accepts `eq`, `ne`, `in`, `nin`; multi-select accepts `contains`, `ncontains`. Option names are accepted as operands and resolved to ids.'
11359
+ describe: 'A single `{ field, op, value }` condition or a recursive `all`/`any` group; either form is normalized to a grouped predicate after validation. At most 100 members per group, 10 levels of nesting, and 500 nodes in total. The negating operators include nulls: `ne`, `nin`, `ncontains`, `nlike`, and `nilike` match rows whose column is null or absent, so "not X" is not the complement of "X" over a nullable column. That holds for every column type, multi-select included. To exclude nulls, `all`-combine the negation with `isNotEmpty` (multi-select) or `isNotNull`. Comparison: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. Membership: `in`, `nin` (array operand). Emptiness: `isEmpty`, `isNotEmpty`, `isNull`, `isNotNull` (no operand). Substring, always case-insensitive, operand matched literally: `contains`, `ncontains`, `startsWith`, `endsWith`. Pattern: `like`/`nlike` (case-sensitive), `ilike`/`nilike` (case-insensitive). **`*` is the only wildcard** and stands for any run of characters; `%`, `_`, and backslash match themselves. Use `like: "Hi*"`, not `like: "Hi%"`. A `select` column compares by option id and restricts its operators: single-select accepts `eq`, `ne`, `in`, `nin`; multi-select accepts `contains`, `ncontains`. Option names are accepted as operands and resolved to ids.'
11465
11360
  },
11466
11361
  data: {
11467
11362
  kind: "object",
@@ -11471,39 +11366,6 @@ var V2_OPERATIONS = {
11471
11366
  limit: { kind: "integer", describe: "Maximum matching rows to update." }
11472
11367
  }
11473
11368
  },
11474
- updateSandbox: {
11475
- method: "PATCH",
11476
- path: "/api/v2/sandboxes/[sandboxId]",
11477
- pathParams: ["sandboxId"],
11478
- pathParamDocs: { sandboxId: "Unique sandbox identifier." },
11479
- responseMode: "json",
11480
- summary: "Update Sandbox",
11481
- personalKeyOnly: true,
11482
- body: {
11483
- workspaceId: { kind: "string", required: true, describe: "Workspace that owns the sandbox." },
11484
- name: {
11485
- kind: "string",
11486
- describe: "New display name, unique within the workspace; 1 to 64 characters."
11487
- },
11488
- language: {
11489
- kind: "enum",
11490
- values: ["javascript", "python"],
11491
- describe: "Replacement dependency ecosystem. The whole spec is revalidated against it, so a Python dependency list does not survive a switch to JavaScript."
11492
- },
11493
- dependencies: {
11494
- kind: "array",
11495
- describe: "Replacement package list; replaces the whole list."
11496
- },
11497
- cliTools: {
11498
- kind: "array",
11499
- describe: "Replacement managed CLI list; replaces the whole list."
11500
- },
11501
- systemPackages: {
11502
- kind: "array",
11503
- describe: "Replacement Debian package list; replaces the whole list."
11504
- }
11505
- }
11506
- },
11507
11369
  updateSkill: {
11508
11370
  method: "PATCH",
11509
11371
  path: "/api/v2/skills/[skillId]",
@@ -11871,10 +11733,10 @@ function addProfileCommand() {
11871
11733
  auth_profile: authProfile,
11872
11734
  workspace: normalizeWorkspaceId(workspace.id, "the workspace response")
11873
11735
  });
11874
- console.log(source_default.green(`✓ Added profile "${safeOneLine(profileName)}" in ${configPath()}`));
11736
+ console.log(styles3().green(`✓ Added profile "${safeOneLine(profileName)}" in ${configPath()}`));
11875
11737
  console.log(` Workspace: ${safeOneLine(workspace.name)} (${workspace.id})`);
11876
11738
  console.log(` Authentication: ${safeOneLine(authProfile)}`);
11877
- console.log(source_default.dim(` Try: sim --profile ${safeOneLine(profileName)} whoami`));
11739
+ console.log(styles3().dim(` Try: sim --profile ${safeOneLine(profileName)} whoami`));
11878
11740
  });
11879
11741
  }
11880
11742
  function loginCommand() {
@@ -11891,21 +11753,21 @@ function loginCommand() {
11891
11753
  if (readCredentialsProfile(profile.name).api_key && !options.yes) {
11892
11754
  const confirmed = await confirmProfileOverwrite(profile.name);
11893
11755
  if (!confirmed) {
11894
- console.log(source_default.dim("Login cancelled; the existing profile was not changed."));
11756
+ console.log(styles3().dim("Login cancelled; the existing profile was not changed."));
11895
11757
  return;
11896
11758
  }
11897
11759
  }
11898
11760
  const auth = createAuthRequest();
11899
11761
  const url = buildApprovalUrl(profile.endpoint, auth, scope, profile.workspaceId ?? undefined);
11900
- console.log(`Signing in to ${source_default.bold(profile.endpoint)} as profile ${source_default.bold(safeOneLine(profile.name))}`);
11762
+ console.log(`Signing in to ${styles3().bold(profile.endpoint)} as profile ${styles3().bold(safeOneLine(profile.name))}`);
11901
11763
  console.log(`
11902
- Pairing code: ${source_default.bold(auth.pairing)}`);
11903
- console.log(source_default.dim(`Confirm this code matches what the browser shows before approving.
11764
+ Pairing code: ${styles3().bold(auth.pairing)}`);
11765
+ console.log(styles3().dim(`Confirm this code matches what the browser shows before approving.
11904
11766
  `));
11905
11767
  console.log(url);
11906
11768
  if (options.browser)
11907
11769
  openBrowser(url);
11908
- console.log(source_default.dim(`
11770
+ console.log(styles3().dim(`
11909
11771
  Waiting for approval…`));
11910
11772
  const key = await pollForKey(profile.endpoint, auth);
11911
11773
  if (key.scope !== scope) {
@@ -11918,14 +11780,14 @@ Waiting for approval…`));
11918
11780
  requireStorableKey(key.apiKey);
11919
11781
  writeConfigProfile(profile.name, settings);
11920
11782
  writeCredentialsProfile(profile.name, key.apiKey);
11921
- console.log(source_default.green(`
11783
+ console.log(styles3().green(`
11922
11784
  ✓ Logged in. Key stored in ${credentialsPath()}`));
11923
11785
  if (key.workspaceBound && key.workspaceId) {
11924
- console.log(source_default.dim(` Workspace-scoped key — it can only reach ${key.workspaceId}.`));
11786
+ console.log(styles3().dim(` Workspace-scoped key — it can only reach ${key.workspaceId}.`));
11925
11787
  } else if (key.workspaceId) {
11926
- console.log(source_default.dim(` Personal key, defaulting to ${key.workspaceId}. Override per command with --workspace.`));
11788
+ console.log(styles3().dim(` Personal key, defaulting to ${key.workspaceId}. Override per command with --workspace.`));
11927
11789
  } else {
11928
- console.log(source_default.dim(" Personal key with no default workspace. Set one with: sim configure --set-workspace <id>"));
11790
+ console.log(styles3().dim(" Personal key with no default workspace. Set one with: sim configure --set-workspace <id>"));
11929
11791
  }
11930
11792
  });
11931
11793
  }
@@ -11939,10 +11801,10 @@ function logoutCommand() {
11939
11801
  }
11940
11802
  const removed = deleteProfile(profileName);
11941
11803
  if (!removed.config && !removed.credentials) {
11942
- console.log(source_default.dim(`Nothing stored for profile "${safeOneLine(profileName)}".`));
11804
+ console.log(styles3().dim(`Nothing stored for profile "${safeOneLine(profileName)}".`));
11943
11805
  return;
11944
11806
  }
11945
- console.log(source_default.green(`✓ Removed profile "${safeOneLine(profileName)}".`));
11807
+ console.log(styles3().green(`✓ Removed profile "${safeOneLine(profileName)}".`));
11946
11808
  return;
11947
11809
  }
11948
11810
  const profile = profileFrom(command);
@@ -11951,12 +11813,12 @@ function logoutCommand() {
11951
11813
  throw new SimApiError(`Profile "${redact(profile.name)}" shares authentication with "${redact(authProfile)}". Log out of the authentication profile instead: sim logout --profile ${redact(authProfile)}`, 0);
11952
11814
  }
11953
11815
  if (!readCredentialsProfile(profile.name).api_key) {
11954
- console.log(source_default.dim(`No stored key for profile "${safeOneLine(profile.name)}".`));
11816
+ console.log(styles3().dim(`No stored key for profile "${safeOneLine(profile.name)}".`));
11955
11817
  return;
11956
11818
  }
11957
11819
  writeCredentialsProfile(profile.name, null);
11958
- console.log(source_default.green(`✓ Removed the stored key for profile "${safeOneLine(profile.name)}".`));
11959
- console.log(source_default.dim(" The key itself is still active — revoke it in Settings → API keys."));
11820
+ console.log(styles3().green(`✓ Removed the stored key for profile "${safeOneLine(profile.name)}".`));
11821
+ console.log(styles3().dim(" The key itself is still active — revoke it in Settings → Sim API keys."));
11960
11822
  });
11961
11823
  }
11962
11824
  async function readKeyType(client) {
@@ -12017,18 +11879,18 @@ function presentVerification(verification) {
12017
11879
  if (verification.status === "verified") {
12018
11880
  const { name, memberCount } = verification.workspace;
12019
11881
  const members = `${memberCount} ${memberCount === 1 ? "member" : "members"}`;
12020
- return `${source_default.green("✓")} ${safeOneLine(name)} · ${members}`;
11882
+ return `${styles3().green("✓")} ${safeOneLine(name)} · ${members}`;
12021
11883
  }
12022
11884
  const detail = safeOneLine(verification.detail);
12023
11885
  switch (verification.status) {
12024
11886
  case "rejected":
12025
- return `${source_default.red("✗")} ${detail}`;
11887
+ return `${styles3().red("✗")} ${detail}`;
12026
11888
  case "unauthenticated":
12027
- return source_default.yellow(`not logged in — ${detail}`);
11889
+ return styles3().yellow(`not logged in — ${detail}`);
12028
11890
  case "disabled":
12029
- return source_default.dim(detail);
11891
+ return styles3().dim(detail);
12030
11892
  default:
12031
- return source_default.yellow(`could not check — ${detail}`);
11893
+ return styles3().yellow(`could not check — ${detail}`);
12032
11894
  }
12033
11895
  }
12034
11896
  function whoamiCommand() {
@@ -12042,17 +11904,17 @@ function whoamiCommand() {
12042
11904
  keyType: null,
12043
11905
  detail: "not checked (--no-verify)"
12044
11906
  };
12045
- const annotate = (value, source) => source === "unset" ? source_default.dim("not set") : `${value} ${source_default.dim(`(${source})`)}`;
11907
+ const annotate = (value, source) => source === "unset" ? styles3().dim("not set") : `${value} ${styles3().dim(`(${source})`)}`;
12046
11908
  printRecord(profile.output, [
12047
11909
  ["Profile", profile.name],
12048
11910
  ["Endpoint", annotate(profile.endpoint, sources.endpoint)],
12049
11911
  [
12050
11912
  "API key",
12051
- authentication.authenticated ? annotate("configured", authentication.source) : source_default.yellow("not logged in")
11913
+ authentication.authenticated ? annotate("configured", authentication.source) : styles3().yellow("not logged in")
12052
11914
  ],
12053
11915
  [
12054
11916
  "Key type",
12055
- verification.keyType ?? source_default.dim(options.verify ? "unknown" : "not checked (--no-verify)")
11917
+ verification.keyType ?? styles3().dim(options.verify ? "unknown" : "not checked (--no-verify)")
12056
11918
  ],
12057
11919
  ["Workspace", annotate(profile.workspaceId ?? "", sources.workspaceId)],
12058
11920
  ["Output", annotate(profile.output, sources.output)],
@@ -12078,15 +11940,18 @@ function whoamiCommand() {
12078
11940
  });
12079
11941
  const exitCode = WHOAMI_EXIT_CODES[verification.status];
12080
11942
  if (exitCode !== 0)
12081
- process.exitCode = exitCode;
11943
+ setSoftExitCode(exitCode);
12082
11944
  });
12083
11945
  }
12084
11946
  var PROFILE_COLUMNS = [
12085
- { header: "", value: (row) => row.active ? source_default.green("*") : " " },
11947
+ { header: "", value: (row) => row.active ? styles3().green("*") : " " },
12086
11948
  { header: "profile", value: (row) => safeOneLine(row.name) },
12087
11949
  { header: "key", value: (row) => row.error ? text(null) : row.hasKey ? "yes" : "no" },
12088
11950
  { header: "auth", value: (row) => row.authProfile ? safeOneLine(row.authProfile) : text(null) },
12089
- { header: "error", value: (row) => row.error ? source_default.red(safeOneLine(row.error)) : text(null) }
11951
+ {
11952
+ header: "error",
11953
+ value: (row) => row.error ? styles3().red(safeOneLine(row.error)) : text(null)
11954
+ }
12090
11955
  ];
12091
11956
  function buildProfileRow(name, active) {
12092
11957
  try {
@@ -12133,7 +11998,7 @@ function profilesCommand() {
12133
11998
  const rows = listProfiles().map((name) => buildProfileRow(name, name === activeName));
12134
11999
  if (rows.length === 0) {
12135
12000
  if (output === "table")
12136
- console.log(source_default.dim("No profiles yet. Run: sim login"));
12001
+ console.log(styles3().dim("No profiles yet. Run: sim login"));
12137
12002
  else
12138
12003
  printList(output, rows, PROFILE_COLUMNS);
12139
12004
  return;
@@ -12213,21 +12078,21 @@ function configureCommand() {
12213
12078
  if (Object.keys(updates).length === 0) {
12214
12079
  const current = readConfigProfile(profile.name);
12215
12080
  if (Object.keys(current).length === 0) {
12216
- console.log(source_default.dim(`No settings stored for profile "${profile.name}".`));
12081
+ console.log(styles3().dim(`No settings stored for profile "${profile.name}".`));
12217
12082
  return;
12218
12083
  }
12219
12084
  for (const [key, value] of Object.entries(current)) {
12220
- console.log(`${source_default.dim(`${key}:`)} ${value}`);
12085
+ console.log(`${styles3().dim(`${key}:`)} ${value}`);
12221
12086
  }
12222
12087
  return;
12223
12088
  }
12224
12089
  const removalOnly = Object.values(updates).every((value) => value === null);
12225
12090
  if (removalOnly && Object.keys(readConfigProfile(profile.name)).length === 0) {
12226
- console.log(source_default.dim(`No settings stored for profile "${profile.name}".`));
12091
+ console.log(styles3().dim(`No settings stored for profile "${profile.name}".`));
12227
12092
  return;
12228
12093
  }
12229
12094
  writeConfigProfile(profile.name, updates);
12230
- console.log(source_default.green(`✓ Updated profile "${profile.name}" in ${configPath()}`));
12095
+ console.log(styles3().green(`✓ Updated profile "${profile.name}" in ${configPath()}`));
12231
12096
  });
12232
12097
  }
12233
12098
 
@@ -12239,7 +12104,6 @@ var TABLE_SORT_HELP = 'Ordered sort keys: [{"field":"createdAt","direction":"des
12239
12104
  var KNOWLEDGE_TAG_DEFINITIONS_HELP = 'Tag definitions: [{"tagSlot":"tag1","displayName":"category","fieldType":"text"}]';
12240
12105
  var CUSTOM_TOOL_SCHEMA_HELP = 'OpenAI function schema: {"type":"function","function":{"name":"...","parameters":{"type":"object","properties":{}}}}';
12241
12106
  var DISPATCH_ROW_LIMIT_HELP = "Stop after this many eligible rows have run (1-1,000,000). Omit for an unbounded run";
12242
- var FILE_EDIT_HELP = 'One edit object: {"mode":"search_replace","search":"old","content":"new","replaceAll":false}, {"mode":"replace_between","beforeAnchor":"start line","afterAnchor":"end line","content":"new"}, {"mode":"insert_after","anchor":"line","content":"new"}, or {"mode":"delete_between","startAnchor":"first line deleted","endAnchor":"ending line kept"}. Anchored modes also accept occurrence starting at 1';
12243
12107
  var WORKFLOW_OPERATIONS_HELP = 'Edits to apply, in a single batch, keyed by operation_type: [{"operation_type":"add","block_id":"my-fn","params":{"type":"function","name":"My Fn","inputs":{"code":"return {ok:true}"}}},{"operation_type":"edit","block_id":"<uuid>","params":{"name":"Renamed","connections":{"success":"my-fn"}}},{"operation_type":"delete","block_id":"<uuid>"}]. Also extract_from_subflow, whose params carry {"subflowId":"<loop-id>"}, and insert_into_subflow, which creates a block and so takes an add’s params plus that subflowId';
12244
12108
  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';
12245
12109
  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"}]';
@@ -12437,9 +12301,6 @@ var CLI_CONTRACT = {
12437
12301
  confirm: "This revokes the explicit skill editor grant for the selected email."
12438
12302
  },
12439
12303
  deleteCustomTool: { confirm: "This deletes the custom tool." },
12440
- deleteSandbox: {
12441
- confirm: "This deletes the sandbox; Function blocks that select it fail until re-pointed."
12442
- },
12443
12304
  deleteMcpServer: {
12444
12305
  confirm: "This removes the MCP server and the tools it provides."
12445
12306
  },
@@ -12451,7 +12312,7 @@ var CLI_CONTRACT = {
12451
12312
  },
12452
12313
  deleteTableView: { confirm: "This deletes the saved view and its filters." },
12453
12314
  deleteWorkflowGroup: {
12454
- confirm: "This deletes the group, every column it fed, and the values in them.",
12315
+ confirm: "This deletes the group AND its output columns with all of their row data; the workflow it pointed at is untouched.",
12455
12316
  fields: [
12456
12317
  { header: "id" },
12457
12318
  { header: "deleted", format: "bool" },
@@ -12571,7 +12432,7 @@ var CLI_CONTRACT = {
12571
12432
  },
12572
12433
  applyWorkflowOperations: {
12573
12434
  command: "workflows operations apply",
12574
- confirm: "This edits the draft graph, and a delete operation removes blocks and their edges.",
12435
+ confirm: "This edits the draft graph: the batch adds, edits, or deletes blocks and their edges as written.",
12575
12436
  flags: {
12576
12437
  operations: { json: true, describe: WORKFLOW_OPERATIONS_HELP },
12577
12438
  setBlockEnabled: { json: true, describe: WORKFLOW_SET_BLOCK_ENABLED_HELP }
@@ -12623,26 +12484,7 @@ var CLI_CONTRACT = {
12623
12484
  flags: { folderPaths: FOLDER_PATHS_FLAG },
12624
12485
  confirm: "This deletes every listed table and all of their rows."
12625
12486
  },
12626
- searchFileContent: {
12627
- flags: {
12628
- folderPaths: {
12629
- ...FOLDER_PATHS_FLAG,
12630
- describe: "Folders to search, by path as shown in the app; omit to search the whole workspace"
12631
- },
12632
- includeSubfolders: {
12633
- boolean: true,
12634
- negatable: true,
12635
- describe: "Whether each folder scope includes nested folders; on by default"
12636
- }
12637
- },
12638
- itemsPath: "results",
12639
- columns: [
12640
- { header: "file", path: "fileId" },
12641
- { header: "line", path: "lineNumber" },
12642
- { header: "text" }
12643
- ]
12644
- },
12645
- searchKnowledge: {
12487
+ searchKnowledge: {
12646
12488
  flags: {
12647
12489
  knowledgeBaseIds: { name: "kb", list: true, describe: "Knowledge base ID (repeatable)" },
12648
12490
  query: { describe: "Text to search for" },
@@ -12726,20 +12568,6 @@ var CLI_CONTRACT = {
12726
12568
  importWorkflow: { flags: { folderPath: FOLDER_PATH_FLAG } },
12727
12569
  createCustomTool: { flags: { schema: { json: true, describe: CUSTOM_TOOL_SCHEMA_HELP } } },
12728
12570
  updateCustomTool: { flags: { schema: { json: true, describe: CUSTOM_TOOL_SCHEMA_HELP } } },
12729
- createSandbox: {
12730
- flags: {
12731
- dependencies: { list: true, manifest: true },
12732
- cliTools: { list: true },
12733
- systemPackages: { list: true, manifest: true }
12734
- }
12735
- },
12736
- updateSandbox: {
12737
- flags: {
12738
- dependencies: { list: true, manifest: true },
12739
- cliTools: { list: true },
12740
- systemPackages: { list: true, manifest: true }
12741
- }
12742
- },
12743
12571
  listTables: {
12744
12572
  flags: { folderPath: FOLDER_PATH_FLAG },
12745
12573
  columns: [
@@ -12881,15 +12709,6 @@ var CLI_CONTRACT = {
12881
12709
  { header: "updated", path: "updatedAt", format: "timestamp" }
12882
12710
  ]
12883
12711
  },
12884
- listSandboxes: {
12885
- columns: [
12886
- { header: "id" },
12887
- { header: "name" },
12888
- { header: "language" },
12889
- { header: "status", path: "buildStatus" },
12890
- { header: "updated", path: "updatedAt", format: "timestamp" }
12891
- ]
12892
- },
12893
12712
  listCredentials: {
12894
12713
  columns: [
12895
12714
  { header: "id" },
@@ -13084,13 +12903,6 @@ var CLI_CONTRACT = {
13084
12903
  folderPaths: FOLDER_PATHS_FLAG
13085
12904
  }
13086
12905
  },
13087
- editFileContent: {
13088
- command: "files edit",
13089
- describe: "Apply one exact or anchor-based edit to a text file",
13090
- flags: {
13091
- edit: { describe: FILE_EDIT_HELP }
13092
- }
13093
- },
13094
12906
  updateFileContent: {
13095
12907
  command: "files set-content",
13096
12908
  describe: "Replace a file’s contents",
@@ -13329,24 +13141,6 @@ var CLI_CONTRACT = {
13329
13141
  describe: "Print a workflow as a portable JSON document",
13330
13142
  document: true
13331
13143
  },
13332
- executeTool: {
13333
- command: "tools execute",
13334
- describe: "Run one built-in tool and print what it produced",
13335
- flags: {
13336
- input: {
13337
- json: true,
13338
- describe: "Tool arguments as JSON, keyed by the parameter ids `sim tools get <toolId>` lists"
13339
- },
13340
- credentialId: { describe: "Credential to authenticate with, required for OAuth tools" },
13341
- timeoutSeconds: { name: "timeout", describe: "Seconds to wait before abandoning the call" }
13342
- },
13343
- fields: [
13344
- { path: "toolId", header: "Tool" },
13345
- { path: "status", header: "Status" },
13346
- { path: "output", header: "Output" },
13347
- { path: "error.message", header: "Error" }
13348
- ]
13349
- },
13350
13144
  executeWorkflow: {
13351
13145
  command: "workflows run",
13352
13146
  describe: "Run a deployed workflow or execute saved state manually",
@@ -13360,7 +13154,7 @@ var CLI_CONTRACT = {
13360
13154
  selectedOutputs: {
13361
13155
  name: "select-output",
13362
13156
  list: true,
13363
- describe: "Return streamed outputs as blockName.path or childWorkflowId.blockName.path; selecting a child workflow applies to every invocation, requires --follow"
13157
+ describe: "Return blockName.path values (e.g. agent_1.content), or childWorkflowId.blockName.path for a child workflow (applies to every invocation) — in blockOutputs on a sync run, or from the streamed result with --follow; missing paths are omitted. Not available with --async"
13364
13158
  },
13365
13159
  stream: { omit: true },
13366
13160
  includeThinking: { omit: true },
@@ -13384,7 +13178,7 @@ var CLI_CONTRACT = {
13384
13178
  selectedOutputs: {
13385
13179
  name: "select-output",
13386
13180
  list: true,
13387
- describe: "Include blockId or blockId.path values in JSON or YAML output; block names are not resolved on a finished run"
13181
+ describe: "Include blockName.path or blockId.path values (e.g. agent_1.content) in JSON or YAML output; names resolve against the workflow’s current blocks, and missing paths are omitted"
13388
13182
  }
13389
13183
  },
13390
13184
  fields: [
@@ -13492,6 +13286,87 @@ function camel(flag) {
13492
13286
 
13493
13287
  // src/runtime/request.ts
13494
13288
  import { existsSync as existsSync2, readFileSync as readFileSync3, readSync } from "node:fs";
13289
+
13290
+ // src/transfer/local-file.ts
13291
+ import { constants } from "node:fs";
13292
+ import { access, stat } from "node:fs/promises";
13293
+ import { basename } from "node:path";
13294
+ function embeddedFileKey(path) {
13295
+ return path.startsWith("@") ? path.slice(1) : path;
13296
+ }
13297
+ async function embeddedFileContent(embedded, path) {
13298
+ const key = embeddedFileKey(path);
13299
+ embedded.identity.signal?.throwIfAborted();
13300
+ if (!embedded.readFile)
13301
+ throw new SimApiError("This invocation has no machine to read from", 0);
13302
+ const content = await embedded.readFile(key);
13303
+ embedded.identity.signal?.throwIfAborted();
13304
+ return typeof content === "string" ? content : new Uint8Array(content);
13305
+ }
13306
+ var CONTENT_TYPES = {
13307
+ css: "text/css",
13308
+ csv: "text/csv",
13309
+ doc: "application/msword",
13310
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
13311
+ gif: "image/gif",
13312
+ html: "text/html",
13313
+ htm: "text/html",
13314
+ jpeg: "image/jpeg",
13315
+ jpg: "image/jpeg",
13316
+ js: "text/javascript",
13317
+ json: "application/json",
13318
+ jsonl: "application/jsonl",
13319
+ md: "text/markdown",
13320
+ pdf: "application/pdf",
13321
+ ppt: "application/vnd.ms-powerpoint",
13322
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
13323
+ png: "image/png",
13324
+ svg: "image/svg+xml",
13325
+ txt: "text/plain",
13326
+ webp: "image/webp",
13327
+ yaml: "application/yaml",
13328
+ yml: "application/yaml",
13329
+ xls: "application/vnd.ms-excel",
13330
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
13331
+ zip: "application/zip"
13332
+ };
13333
+ function contentTypeFor(name) {
13334
+ const dot = name.lastIndexOf(".");
13335
+ const extension = dot === -1 ? "" : name.slice(dot + 1).toLowerCase();
13336
+ return CONTENT_TYPES[extension] ?? "application/octet-stream";
13337
+ }
13338
+ async function localFile(path, override) {
13339
+ const embedded = embedStore.getStore();
13340
+ if (embedded) {
13341
+ embedded.identity.signal?.throwIfAborted();
13342
+ if (!embedded.openFile)
13343
+ throw new SimApiError("This invocation has no machine to read from", 0);
13344
+ const { size: size2 } = await embedded.openFile(embeddedFileKey(path));
13345
+ embedded.identity.signal?.throwIfAborted();
13346
+ if (!Number.isSafeInteger(size2) || size2 < 0)
13347
+ throw new SimApiError("Invalid file size", 0);
13348
+ if (size2 === 0)
13349
+ throw new SimApiError(`${path} is empty`, 0);
13350
+ return { name: override ?? basename(embeddedFileKey(path)), size: size2 };
13351
+ }
13352
+ let size;
13353
+ try {
13354
+ const stats = await stat(path);
13355
+ if (!stats.isFile())
13356
+ throw new SimApiError(`${path} is not a regular file`, 0);
13357
+ await access(path, constants.R_OK);
13358
+ size = stats.size;
13359
+ } catch (error) {
13360
+ if (error instanceof SimApiError)
13361
+ throw error;
13362
+ throw new SimApiError(`Cannot read ${path}: ${error.message}`, 0);
13363
+ }
13364
+ if (size === 0)
13365
+ throw new SimApiError(`${path} is empty`, 0);
13366
+ return { name: override ?? basename(path), size };
13367
+ }
13368
+
13369
+ // src/runtime/request.ts
13495
13370
  var PROFILE_INJECTED_FIELD = "workspaceId";
13496
13371
  function isProfileWorkspacePath(commandSpec, param) {
13497
13372
  return commandSpec.profileWorkspacePath === true && param === PROFILE_INJECTED_FIELD;
@@ -13573,11 +13448,21 @@ function readStdin() {
13573
13448
  function literalAtHint(error, path) {
13574
13449
  return error?.code === "ENOENT" ? `. To pass the literal value @${path}, write @@${path}` : "";
13575
13450
  }
13576
- function readArgumentSource(raw, flagName) {
13451
+ async function readArgumentSource(raw, flagName) {
13577
13452
  if (raw.startsWith("@@"))
13578
13453
  return { text: raw.slice(1), from: "" };
13579
13454
  if (!raw.startsWith("@"))
13580
13455
  return { text: raw, from: "" };
13456
+ const embedded = embedStore.getStore();
13457
+ if (embedded) {
13458
+ if (raw === "@-")
13459
+ throw new SimApiError(`--${flagName}: this invocation has no stdin; use @path or an inline value`, 0);
13460
+ const content = await embeddedFileContent(embedded, raw);
13461
+ return {
13462
+ text: typeof content === "string" ? content : new TextDecoder("utf-8", { fatal: true }).decode(content),
13463
+ from: " (read from your machine)"
13464
+ };
13465
+ }
13581
13466
  const path = raw.slice(1);
13582
13467
  if (path === "-") {
13583
13468
  if (process.stdin.isTTY) {
@@ -13595,34 +13480,32 @@ function readArgumentSource(raw, flagName) {
13595
13480
  throw new SimApiError(`--${flagName} cannot read ${path}: ${error.message}${literalAtHint(error, path)}`, 0);
13596
13481
  }
13597
13482
  }
13598
- function isManifestNoise(line) {
13599
- const trimmed = line.trim();
13600
- return trimmed === "" || trimmed.startsWith("#");
13601
- }
13602
- function readListValues(raw, flagName, manifest = false) {
13483
+ async function readListValues(raw, flagName) {
13603
13484
  const arguments_ = Array.isArray(raw) ? raw : [raw];
13604
- const values = arguments_.flatMap((argument) => {
13485
+ const values = [];
13486
+ for (const argument of arguments_) {
13605
13487
  if (typeof argument !== "string") {
13606
13488
  throw new SimApiError(`--${flagName} values must be strings`, 0);
13607
13489
  }
13608
- if (!argument.startsWith("@"))
13609
- return [argument];
13610
- const source = readArgumentSource(argument, flagName);
13490
+ if (!argument.startsWith("@")) {
13491
+ values.push(argument);
13492
+ continue;
13493
+ }
13494
+ const source = await readArgumentSource(argument, flagName);
13611
13495
  const lines = source.text.split(/\r?\n/);
13612
13496
  if (lines.at(-1) === "")
13613
13497
  lines.pop();
13614
- const kept = manifest ? lines.filter((line) => !isManifestNoise(line)) : lines;
13615
- if (kept.length === 0) {
13498
+ if (lines.length === 0) {
13616
13499
  throw new SimApiError(`--${flagName}${source.from} contains no values`, 0);
13617
13500
  }
13618
- return kept.map((line, index) => {
13501
+ values.push(...lines.map((line, index) => {
13619
13502
  const value = line.trim();
13620
13503
  if (!value) {
13621
13504
  throw new SimApiError(`--${flagName}${source.from} has an empty value on line ${index + 1}`, 0);
13622
13505
  }
13623
13506
  return value;
13624
- });
13625
- });
13507
+ }));
13508
+ }
13626
13509
  return values.map((value) => {
13627
13510
  const trimmed = value.trim();
13628
13511
  if (!trimmed)
@@ -13654,13 +13537,13 @@ var FRACTIONAL_DIGITS = /\.\d*[1-9]/;
13654
13537
  function pathHint(raw) {
13655
13538
  if (raw.startsWith("@") || /^\s*[[{"\-\d]|^\s*(true|false|null)/.test(raw))
13656
13539
  return "";
13657
- return existsSync2(raw) ? `. ${raw} is a file — pass it as @${raw}` : ". To read a file, pass @path (or @- for stdin)";
13540
+ return !embedStore.getStore() && existsSync2(raw) ? `. ${raw} is a file — pass it as @${raw}` : ". To read a file, pass @path (or @- for stdin)";
13658
13541
  }
13659
- function coerce(raw, field, flag, flagName) {
13542
+ async function coerce(raw, field, flag, flagName) {
13660
13543
  if (raw === undefined)
13661
13544
  return;
13662
13545
  if (flag.list) {
13663
- const values = readListValues(raw, flagName, flag.manifest === true).map((value) => flag.folderPath ? encodeFolderPath(value) : value);
13546
+ const values = (await readListValues(raw, flagName)).map((value) => flag.folderPath ? encodeFolderPath(value) : value);
13664
13547
  return field.kind === "string" ? values.join(",") : values;
13665
13548
  }
13666
13549
  if (flag.rowCap)
@@ -13668,7 +13551,7 @@ function coerce(raw, field, flag, flagName) {
13668
13551
  if (takesJson(field, flag)) {
13669
13552
  if (typeof raw !== "string")
13670
13553
  return raw;
13671
- const source = readArgumentSource(raw, flagName);
13554
+ const source = await readArgumentSource(raw, flagName);
13672
13555
  try {
13673
13556
  return JSON.parse(source.text);
13674
13557
  } catch (error) {
@@ -13705,7 +13588,7 @@ function asQueryValue(value) {
13705
13588
  return JSON.stringify(value);
13706
13589
  return value;
13707
13590
  }
13708
- function buildRequest(operation, positional, flags, workspaceId) {
13591
+ async function buildRequest(operation, positional, flags, workspaceId) {
13709
13592
  const commandSpec = CLI_CONTRACT[operation] ?? {};
13710
13593
  const spec = V2_OPERATIONS[operation];
13711
13594
  let path = spec.path;
@@ -13743,7 +13626,7 @@ function buildRequest(operation, positional, flags, workspaceId) {
13743
13626
  if ((slot === "query" || NUMERIC_KINDS.has(descriptor.kind)) && typeof raw === "string" && raw.trim() === "" && !(field === "limit" && paginatedLimit)) {
13744
13627
  throw new SimApiError(`--${flagName} cannot be empty`, 0);
13745
13628
  }
13746
- const value = coerce(raw ?? undefined, descriptor, flag, flagName);
13629
+ const value = await coerce(raw ?? undefined, descriptor, flag, flagName);
13747
13630
  if (field === "limit" && !paginatedLimit && NUMERIC_KINDS.has(descriptor.kind) && typeof value === "number" && value < 1) {
13748
13631
  throw new SimApiError(`--${flagName} must be 1 or more`, 0);
13749
13632
  }
@@ -13764,25 +13647,25 @@ function buildRequest(operation, positional, flags, workspaceId) {
13764
13647
  const headerSlot = Object.keys(headers).length > 0 ? { headers } : {};
13765
13648
  if (spec.opaqueBody) {
13766
13649
  if (commandSpec.bodyVariants) {
13767
- const provided = commandSpec.bodyVariants.filter((variant) => flags[camel(variant.name)] !== undefined);
13768
- const names = commandSpec.bodyVariants.map((variant) => `--${variant.name}`).join(" or ");
13650
+ const provided = commandSpec.bodyVariants.filter((variant2) => flags[camel(variant2.name)] !== undefined);
13651
+ const names = commandSpec.bodyVariants.map((variant2) => `--${variant2.name}`).join(" or ");
13769
13652
  if (provided.length !== 1) {
13770
13653
  throw new SimApiError(`Pass exactly one of ${names}`, 0);
13771
13654
  }
13772
13655
  const variant = provided[0];
13773
- const raw = flags[camel(variant.name)];
13774
- if (typeof raw !== "string")
13656
+ const raw2 = flags[camel(variant.name)];
13657
+ if (typeof raw2 !== "string")
13775
13658
  throw new SimApiError(`--${variant.name} is required`, 0);
13776
- const parsed = coerce(raw, { kind: variant.kind }, { json: true }, variant.name);
13777
- if (variant.kind === "object" && (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) || variant.kind === "array" && !Array.isArray(parsed)) {
13659
+ const parsed2 = await coerce(raw2, { kind: variant.kind }, { json: true }, variant.name);
13660
+ if (variant.kind === "object" && (!parsed2 || typeof parsed2 !== "object" || Array.isArray(parsed2)) || variant.kind === "array" && !Array.isArray(parsed2)) {
13778
13661
  throw new SimApiError(`--${variant.name} must be a JSON ${variant.kind}`, 0);
13779
13662
  }
13780
- return { path, query, body: { ...body, [variant.property]: parsed }, ...headerSlot };
13663
+ return { path, query, body: { ...body, [variant.property]: parsed2 }, ...headerSlot };
13781
13664
  }
13782
13665
  const raw = flags.body;
13783
13666
  if (typeof raw !== "string")
13784
13667
  throw new SimApiError("--body is required", 0);
13785
- const parsed = coerce(raw, { kind: "object" }, { json: true }, "body");
13668
+ const parsed = await coerce(raw, { kind: "object" }, { json: true }, "body");
13786
13669
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
13787
13670
  throw new SimApiError("--body must be a JSON object", 0);
13788
13671
  }
@@ -13809,7 +13692,7 @@ function withoutWireVocabulary(documented) {
13809
13692
  return documented.replace(WIRE_VOCABULARY_SENTENCE, " ").trim();
13810
13693
  }
13811
13694
  var NON_PAGINATED_LIMIT_HINT = " (caps a --filter match only; omit it to act on every match, and note 0 is not accepted)";
13812
- function addFieldOption(command, operation, field, descriptor, slot, paginates, capsAFilter) {
13695
+ function addFieldOption(command, operation, field, descriptor, slot, paginates) {
13813
13696
  if (field === PROFILE_INJECTED_FIELD || field === "cursor")
13814
13697
  return;
13815
13698
  const flag = flagSpecFor(operation, field);
@@ -13821,7 +13704,7 @@ function addFieldOption(command, operation, field, descriptor, slot, paginates,
13821
13704
  command.option("--limit <n>", "Maximum items to return (0 for everything)", String(DEFAULT_LIMIT));
13822
13705
  return;
13823
13706
  }
13824
- const documented = `${describeField(flag, descriptor, name, field)}${capsAFilter && field === "limit" && (descriptor.kind === "number" || descriptor.kind === "integer") ? NON_PAGINATED_LIMIT_HINT : ""}`;
13707
+ const documented = `${describeField(flag, descriptor, name, field)}${field === "limit" && (descriptor.kind === "number" || descriptor.kind === "integer") ? NON_PAGINATED_LIMIT_HINT : ""}`;
13825
13708
  if (descriptor.kind === "boolean" || flag.boolean) {
13826
13709
  const booleanDoc = withoutWireVocabulary(documented);
13827
13710
  if (descriptor.required) {
@@ -13839,7 +13722,7 @@ function addFieldOption(command, operation, field, descriptor, slot, paginates,
13839
13722
  const placeholder = takesList ? "<value...>" : flag.rowCap ? "<n>" : wantsJson ? "<json|@file>" : "<value>";
13840
13723
  const choices = flag.choices ?? descriptor.values;
13841
13724
  const literalNull = slot === "body" && !takesList && !wantsJson;
13842
- const describe = `${documented}${takesList ? flag.manifest ? " (space-separated, or @path / @- with one value per line; in a file, blank lines and # comments are ignored, while inline values are sent as typed and may not be empty; @@value for a literal leading @)" : " (space-separated, or @path / @- with one value per line; @@value for a literal leading @)" : wantsJson ? " (JSON, or @path / @- to read a file or stdin)" : ""}${descriptor.required ? " (required)" : ""}${literalNull ? literalNullHint(documented, name) : ""}`;
13725
+ const describe = `${documented}${takesList ? " (space-separated, or @path / @- with one value per line; @@value for a literal leading @)" : wantsJson ? " (JSON, or @path / @- to read a file or stdin)" : ""}${descriptor.required ? " (required)" : ""}${literalNull ? literalNullHint(documented, name) : ""}`;
13843
13726
  const renamedFrom = flag.renamedFrom ?? [];
13844
13727
  const option = new Option(`${short}--${name} ${placeholder}`, describe);
13845
13728
  if (flag.hidden)
@@ -13869,14 +13752,13 @@ function addOperationOptions(command, operation, commandSpec, operationSpec) {
13869
13752
  command.addOption(new Option(`${short}--${name} <${flag.placeholder ?? "value"}>`, `${flag.describe ?? operationSpec.pathParamDocs?.[param] ?? `Set ${name.replaceAll("-", " ")}`} (required)`).makeOptionMandatory());
13870
13753
  }
13871
13754
  const paginates = cursorSlot(operationSpec) !== null;
13872
- const capsAFilter = ["query", "body", "headers"].some((slot) => operationSpec[slot] !== undefined && ("filter" in operationSpec[slot]));
13873
13755
  for (const slot of ["query", "body", "headers"]) {
13874
13756
  for (const [field, descriptor] of Object.entries(operationSpec[slot] ?? {})) {
13875
13757
  if (commandSpec.requestFields && !commandSpec.requestFields.includes(field))
13876
13758
  continue;
13877
13759
  if (commandSpec.positionals?.includes(field))
13878
13760
  continue;
13879
- addFieldOption(command, operation, field, descriptor, slot, paginates, capsAFilter);
13761
+ addFieldOption(command, operation, field, descriptor, slot, paginates);
13880
13762
  }
13881
13763
  }
13882
13764
  if (commandSpec.allWorkspaces) {
@@ -13975,13 +13857,13 @@ function renderSpan(value, depth) {
13975
13857
  const indent = " ".repeat(depth);
13976
13858
  const detailIndent = `${indent} `;
13977
13859
  const name = requiredText(span, "name");
13978
- const type = requiredText(span, "type");
13860
+ const type2 = requiredText(span, "type");
13979
13861
  const status = optionalText(span, "status");
13980
13862
  const elapsed = optionalNumber(span, "durationMs") ?? optionalNumber(span, "duration");
13981
13863
  const totalCost = costTotal(span);
13982
13864
  const summary = [
13983
13865
  `${indent}- ${name}`,
13984
- `[${type}]`,
13866
+ `[${type2}]`,
13985
13867
  status,
13986
13868
  elapsed === undefined ? undefined : duration(Math.round(elapsed)),
13987
13869
  totalCost === undefined ? undefined : `$${totalCost.toFixed(4)}`
@@ -14020,9 +13902,9 @@ function printTraceSpans(format, traceSpans) {
14020
13902
  if (format === "json" || format === "yaml")
14021
13903
  return;
14022
13904
  console.log("");
14023
- console.log(format === "table" ? source_default.dim("trace:") : "trace:");
13905
+ console.log(format === "table" ? styles3().dim("trace:") : "trace:");
14024
13906
  if (traceSpans.length === 0) {
14025
- console.log(source_default.dim(" No trace spans."));
13907
+ console.log(styles3().dim(" No trace spans."));
14026
13908
  return;
14027
13909
  }
14028
13910
  console.log(traceSpans.flatMap((span) => renderSpan(span, 0)).join(`
@@ -14190,7 +14072,7 @@ function writePageNote(spec, envelope) {
14190
14072
  const value = at(envelope, spec.pageNote.path);
14191
14073
  if (value === undefined || value === null)
14192
14074
  return;
14193
- process.stderr.write(source_default.dim(`${spec.pageNote.label}: ${String(value)}
14075
+ process.stderr.write(styles3().dim(`${spec.pageNote.label}: ${String(value)}
14194
14076
  `));
14195
14077
  }
14196
14078
  var TRUNCATION_FLAG = /^truncated$|^[A-Za-z0-9]+Truncated$/;
@@ -14223,14 +14105,14 @@ function clippedSubject(flag) {
14223
14105
  }
14224
14106
  function writeEnvelopeTruncation(envelope) {
14225
14107
  for (const flag of responseTruncationFlags(envelope)) {
14226
- process.stderr.write(source_default.dim(`${spellOut(flag)}: the server clipped ${clippedSubject(flag)}, so the answer is incomplete
14108
+ process.stderr.write(styles3().dim(`${spellOut(flag)}: the server clipped ${clippedSubject(flag)}, so the answer is incomplete
14227
14109
  `));
14228
14110
  }
14229
14111
  }
14230
14112
  function writeCursorTruncation(count, truncated) {
14231
14113
  if (!truncated)
14232
14114
  return;
14233
- process.stderr.write(source_default.dim(`showing the first ${count}; more results exist — re-run with --limit 0 for all
14115
+ process.stderr.write(styles3().dim(`showing the first ${count}; more results exist — re-run with --limit 0 for all
14234
14116
  `));
14235
14117
  }
14236
14118
  function renderResult(operation, format, raw, spec, options = {}, envelope) {
@@ -14239,7 +14121,7 @@ function renderResult(operation, format, raw, spec, options = {}, envelope) {
14239
14121
  printDocument(format, raw);
14240
14122
  return;
14241
14123
  }
14242
- const data = unwrapResource(raw);
14124
+ const data = format === "json" || format === "yaml" ? raw : unwrapResource(raw);
14243
14125
  if (spec.itemsPath) {
14244
14126
  const items = at(data, spec.itemsPath);
14245
14127
  if (!Array.isArray(items)) {
@@ -14267,29 +14149,24 @@ function renderResult(operation, format, raw, spec, options = {}, envelope) {
14267
14149
  }
14268
14150
 
14269
14151
  // src/runtime/execute.ts
14270
- var RUN_OUTCOME_OPERATIONS = {
14271
- executeWorkflow: {
14272
- failed: "The workflow run failed.",
14273
- cancelled: "The workflow run was cancelled."
14274
- },
14275
- executeTool: {
14276
- failed: "The tool call failed."
14277
- }
14152
+ var RUN_OUTCOME_OPERATIONS = new Set(["executeWorkflow"]);
14153
+ var FAILED_RUN_STATUS_MESSAGES = {
14154
+ failed: "The workflow run failed.",
14155
+ cancelled: "The workflow run was cancelled."
14278
14156
  };
14279
14157
  function runFailureMessage(operation, payload) {
14280
- const failureMessages = RUN_OUTCOME_OPERATIONS[operation];
14281
- if (!failureMessages)
14158
+ if (!RUN_OUTCOME_OPERATIONS.has(operation))
14282
14159
  return null;
14283
14160
  if (!payload || typeof payload !== "object" || Array.isArray(payload))
14284
14161
  return null;
14285
14162
  const { status, error } = payload;
14286
14163
  if (typeof status !== "string")
14287
14164
  return null;
14288
- const fallback = failureMessages[status];
14165
+ const fallback = FAILED_RUN_STATUS_MESSAGES[status];
14289
14166
  if (!fallback)
14290
14167
  return null;
14291
- const reported = error?.message;
14292
- return safeOneLine(typeof reported === "string" && reported ? reported : fallback);
14168
+ const reported2 = error?.message;
14169
+ return safeOneLine(typeof reported2 === "string" && reported2 ? reported2 : fallback);
14293
14170
  }
14294
14171
  var BULK_OUTCOME_CHECKS = {
14295
14172
  bulkDeleteFiles: (payload, body) => {
@@ -14324,8 +14201,8 @@ var BULK_OUTCOME_CHECKS = {
14324
14201
  const requested = lengthOf(body?.chunkIds);
14325
14202
  if (requested === 0)
14326
14203
  return null;
14327
- const reported = payload.errors?.[0];
14328
- return typeof reported === "string" && reported ? safeOneLine(reported) : `Updated nothing: none of the ${requested} requested ${requested === 1 ? "chunk" : "chunks"} matched.`;
14204
+ const reported2 = payload.errors?.[0];
14205
+ return typeof reported2 === "string" && reported2 ? safeOneLine(reported2) : `Updated nothing: none of the ${requested} requested ${requested === 1 ? "chunk" : "chunks"} matched.`;
14329
14206
  },
14330
14207
  deleteTableRows: (payload) => {
14331
14208
  if (countOf(payload.deletedCount) > 0)
@@ -14358,6 +14235,22 @@ function countOf(value) {
14358
14235
  function lengthOf(value) {
14359
14236
  return Array.isArray(value) ? value.length : 0;
14360
14237
  }
14238
+ var RESULT_NOTES = {
14239
+ replaceWorkflowChatDeployment: (payload, body) => {
14240
+ const authType = payload.authType ?? body?.authType ?? "public";
14241
+ return authType === "public" ? "note: auth type is public — anyone with the link can chat; pass --auth-type password|email to restrict it." : null;
14242
+ }
14243
+ };
14244
+ function writeResultNote(operation, payload, body) {
14245
+ const note = RESULT_NOTES[operation];
14246
+ if (!note)
14247
+ return;
14248
+ const record = payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
14249
+ const message = note(record, body);
14250
+ if (message)
14251
+ process.stderr.write(styles3().dim(`${message}
14252
+ `));
14253
+ }
14361
14254
  function bulkFailureMessage(operation, payload, body) {
14362
14255
  const check = BULK_OUTCOME_CHECKS[operation];
14363
14256
  if (!check)
@@ -14370,8 +14263,8 @@ var EXCLUSIVE_CAP_FIELDS = {
14370
14263
  deleteTableRows: { cap: "limit", ids: "rowIds" }
14371
14264
  };
14372
14265
  function readPagedLimit(raw) {
14373
- const text = String(raw ?? DEFAULT_LIMIT).trim();
14374
- const value = text === "" ? Number.NaN : Number(text);
14266
+ const text2 = String(raw ?? DEFAULT_LIMIT).trim();
14267
+ const value = text2 === "" ? Number.NaN : Number(text2);
14375
14268
  if (!Number.isInteger(value) || value < 0) {
14376
14269
  throw new SimApiError("--limit must be a whole number of 0 or more (0 for everything)", 0);
14377
14270
  }
@@ -14446,7 +14339,7 @@ async function executeOperation(operation, commandSpec, operationSpec, invocatio
14446
14339
  const needsWorkspace = (hasWorkspaceField || commandSpec.profileWorkspacePath === true) && !omitsWorkspace;
14447
14340
  const paging = cursorSlot(operationSpec);
14448
14341
  const pagedLimit = paging ? readPagedLimit(requestFlags.limit) : 0;
14449
- const request = buildRequest(operation, positional, requestFlags, needsWorkspace ? client.requireWorkspace() : profile.workspaceId);
14342
+ const request = await buildRequest(operation, positional, requestFlags, needsWorkspace ? client.requireWorkspace() : profile.workspaceId);
14450
14343
  if (paging) {
14451
14344
  const limit = pagedLimit === 0 ? Number.POSITIVE_INFINITY : pagedLimit;
14452
14345
  const pageSize = Math.min(Number.isFinite(limit) ? limit : DEFAULT_LIMIT, DEFAULT_LIMIT);
@@ -14483,6 +14376,7 @@ async function executeOperation(operation, commandSpec, operationSpec, invocatio
14483
14376
  });
14484
14377
  const payload = result?.data ?? result;
14485
14378
  renderResult(operation, profile.output, payload, commandSpec, { expandedTrace: requestFlags.trace === true }, result);
14379
+ writeResultNote(operation, payload, request.body);
14486
14380
  const failure = runFailureMessage(operation, payload) ?? bulkFailureMessage(operation, payload, request.body);
14487
14381
  if (failure)
14488
14382
  throw new SimApiError(failure, 0);
@@ -14545,7 +14439,7 @@ function retypeMessage(message, spellings) {
14545
14439
  }
14546
14440
  function retypeDetails(details, spellings) {
14547
14441
  if (Array.isArray(details))
14548
- return details.map((issue) => retypeDetails(issue, spellings));
14442
+ return details.map((issue2) => retypeDetails(issue2, spellings));
14549
14443
  if (!details || typeof details !== "object")
14550
14444
  return details;
14551
14445
  const issue = details;
@@ -14582,7 +14476,6 @@ var GROUP_ALIASES = {
14582
14476
  knowledge: "kb",
14583
14477
  logs: "log",
14584
14478
  "mcp-servers": "mcp-server",
14585
- sandboxes: "sandbox",
14586
14479
  secrets: "secret",
14587
14480
  skills: "skill",
14588
14481
  tables: "table",
@@ -14608,8 +14501,8 @@ function commandPath(command) {
14608
14501
  return names.join(" ");
14609
14502
  }
14610
14503
  var UNKNOWN_OPTION_TOKEN = /^error: unknown option '(.+?)'/;
14611
- function looksLikeAnId(token) {
14612
- return token.length > 2 && !token.startsWith("--") && /^-[A-Za-z0-9_-]*[A-Z0-9][A-Za-z0-9_-]*$/.test(token);
14504
+ function looksLikeAnId(token2) {
14505
+ return token2.length > 2 && !token2.startsWith("--") && /^-[A-Za-z0-9_-]*[A-Z0-9][A-Za-z0-9_-]*$/.test(token2);
14613
14506
  }
14614
14507
  function addArgumentExamples(command) {
14615
14508
  const outputError = command.configureOutput().outputError;
@@ -14627,10 +14520,10 @@ function addArgumentExamples(command) {
14627
14520
  }
14628
14521
  if (command.registeredArguments.length === 0)
14629
14522
  return;
14630
- const token = UNKNOWN_OPTION_TOKEN.exec(message)?.[1];
14631
- if (!token || !looksLikeAnId(token))
14523
+ const token2 = UNKNOWN_OPTION_TOKEN.exec(message)?.[1];
14524
+ if (!token2 || !looksLikeAnId(token2))
14632
14525
  return;
14633
- write(`Example: ${commandPath(command)} -- ${token}
14526
+ write(`Example: ${commandPath(command)} -- ${token2}
14634
14527
  `);
14635
14528
  }
14636
14529
  });
@@ -14646,7 +14539,7 @@ function assertNoReservedFlags(command, operation) {
14646
14539
  }
14647
14540
  }
14648
14541
  var RESERVED_FLAG_EXEMPTIONS = new Set(["profiles add"]);
14649
- function assertNoReservedProgramFlags(program) {
14542
+ function assertNoReservedProgramFlags(program2) {
14650
14543
  const walk = (command, prefix) => {
14651
14544
  const path = [...prefix, command.name()];
14652
14545
  const name = path.join(" ");
@@ -14662,10 +14555,10 @@ function assertNoReservedProgramFlags(program) {
14662
14555
  for (const child of command.commands)
14663
14556
  walk(child, path);
14664
14557
  };
14665
- for (const child of program.commands)
14558
+ for (const child of program2.commands)
14666
14559
  walk(child, []);
14667
14560
  }
14668
- function refuseHelpAfterUnknownCommand(program) {
14561
+ function refuseHelpAfterUnknownCommand(program2) {
14669
14562
  const walk = (command) => {
14670
14563
  const internals = command;
14671
14564
  const dispatchesOnly = command.commands.length > 0 && !internals._actionHandler && command.registeredArguments.length === 0;
@@ -14686,7 +14579,7 @@ function refuseHelpAfterUnknownCommand(program) {
14686
14579
  for (const child of command.commands)
14687
14580
  walk(child);
14688
14581
  };
14689
- walk(program);
14582
+ walk(program2);
14690
14583
  }
14691
14584
  function configureOperation(command, operation, spec) {
14692
14585
  const operationSpec = V2_OPERATIONS[operation];
@@ -14890,8 +14783,8 @@ function serviceAccountProvider(providers, providerId) {
14890
14783
  }
14891
14784
  return provider;
14892
14785
  }
14893
- function credentialValues(provider, raw) {
14894
- const parsed = coerce(raw, { kind: "object" }, { json: true }, "credentials");
14786
+ async function credentialValues(provider, raw) {
14787
+ const parsed = await coerce(raw, { kind: "object" }, { json: true }, "credentials");
14895
14788
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
14896
14789
  throw new SimApiError("--credentials must be a JSON object", 0);
14897
14790
  }
@@ -14928,7 +14821,7 @@ async function createServiceAccount(command, providerId, options) {
14928
14821
  if (provider.requiresClientGeneratedCredentialId && !options.id) {
14929
14822
  throw new SimApiError(`--id is required for ${providerId}.`, 0);
14930
14823
  }
14931
- const credentialFields = credentialValues(provider, options.credentials);
14824
+ const credentialFields = await credentialValues(provider, options.credentials);
14932
14825
  const operation = V2_OPERATIONS.createServiceAccountCredential;
14933
14826
  const response = await client.request(operation.path, {
14934
14827
  method: operation.method,
@@ -14970,8 +14863,8 @@ function acceptNameOnUpdate(credentials) {
14970
14863
  options.displayName = options.name;
14971
14864
  });
14972
14865
  }
14973
- function attachCredentialCommands(program) {
14974
- const credentials = program.commands.find((command) => command.name() === "credentials");
14866
+ function attachCredentialCommands(program2) {
14867
+ const credentials = program2.commands.find((command) => command.name() === "credentials");
14975
14868
  if (!credentials)
14976
14869
  throw new Error("The generated credentials command group is missing");
14977
14870
  acceptNameOnUpdate(credentials);
@@ -15065,8 +14958,8 @@ function ignoreBrokenPipe(stream) {
15065
14958
  stream.off("error", onError);
15066
14959
  };
15067
14960
  }
15068
- function attachChat(program) {
15069
- program.command("chat").description("Ask Sim and print the reply").argument("<message>", "What to ask Sim").allowExcessArguments(false).option("-c, --conversation <id>", "Continue the conversation with this ID").addHelpText("after", `
14961
+ function attachChat(program2) {
14962
+ program2.command("chat").description("Ask Sim and print the reply").argument("<message>", "What to ask Sim").allowExcessArguments(false).option("-c, --conversation <id>", "Continue the conversation with this ID").addHelpText("after", `
15070
14963
  Each turn prints the reply on stdout and the conversation ID on stderr; pass
15071
14964
  that ID back with -c to continue the same conversation. With --output json or
15072
14965
  yaml the reply is not streamed — the finished result is printed as one
@@ -15107,11 +15000,11 @@ Examples:
15107
15000
  };
15108
15001
  const restorePipeHandling = streaming ? ignoreBrokenPipe(process.stdout) : undefined;
15109
15002
  try {
15110
- const result = await readChatStream(response, (content) => {
15003
+ const result = await readChatStream(response, (content2) => {
15111
15004
  if (!streaming)
15112
15005
  return;
15113
- streamed += content;
15114
- process.stdout.write(content);
15006
+ streamed += content2;
15007
+ process.stdout.write(content2);
15115
15008
  });
15116
15009
  if (!streaming) {
15117
15010
  printProtocolResult(profile.output, result);
@@ -15123,7 +15016,7 @@ Examples:
15123
15016
  streamed = content;
15124
15017
  }
15125
15018
  endStreamedLine();
15126
- process.stderr.write(`${source_default.dim(`conversation: ${result.conversationId}`)}
15019
+ process.stderr.write(`${styles3().dim(`conversation: ${result.conversationId}`)}
15127
15020
  `);
15128
15021
  } catch (error) {
15129
15022
  endStreamedLine();
@@ -15254,6 +15147,20 @@ async function saveStagedFile(body, target, force) {
15254
15147
  }
15255
15148
  }
15256
15149
  async function saveToFile(body, target, force) {
15150
+ const embedded = embedStore.getStore();
15151
+ if (embedded) {
15152
+ try {
15153
+ embedded.identity.signal?.throwIfAborted();
15154
+ if (!embedded.writeFile) {
15155
+ throw new SimApiError(`--output-file cannot save ${target} here: this surface has no machine to write to. Read the file instead, or use a client with filesystem access to download it.`, 0);
15156
+ }
15157
+ await embedded.writeFile(target, body, { overwrite: force });
15158
+ embedded.identity.signal?.throwIfAborted();
15159
+ } finally {
15160
+ await body.cancel().catch(() => {});
15161
+ }
15162
+ return;
15163
+ }
15257
15164
  return saveStagedFile(body, target, force);
15258
15165
  }
15259
15166
  async function streamToStdout(body, output = process.stdout) {
@@ -15267,6 +15174,7 @@ async function streamToStdout(body, output = process.stdout) {
15267
15174
  await once2(output, "drain");
15268
15175
  }
15269
15176
  } finally {
15177
+ await reader.cancel().catch(() => {});
15270
15178
  reader.releaseLock();
15271
15179
  }
15272
15180
  }
@@ -15304,9 +15212,10 @@ function attachFileGet(files) {
15304
15212
  }
15305
15213
  if (options.outputFile === undefined || options.outputFile === "-") {
15306
15214
  const contentType = response.headers.get("content-type");
15307
- if (process.stdout.isTTY && !isTerminalSafeContentType(contentType)) {
15215
+ const embedded = embedStore.getStore();
15216
+ if ((embedded || process.stdout.isTTY) && !isTerminalSafeContentType(contentType)) {
15308
15217
  await response.body.cancel();
15309
- throw new SimApiError(`Refusing to write ${contentType ?? "unknown content"} to an interactive terminal. Use --output-file <path> or pipe stdout.`, 0);
15218
+ throw new SimApiError(embedded ? `Refusing to put ${contentType ?? "unknown content"} in a text result. Use --output-file <path>.` : `Refusing to write ${contentType ?? "unknown content"} to an interactive terminal. Use --output-file <path> or pipe stdout.`, 0);
15310
15219
  }
15311
15220
  await streamToStdout(response.body);
15312
15221
  return;
@@ -15321,74 +15230,120 @@ function attachFileGet(files) {
15321
15230
  });
15322
15231
  }
15323
15232
 
15324
- // src/transfer/local-file.ts
15325
- import { constants } from "node:fs";
15326
- import { access, stat } from "node:fs/promises";
15327
- import { basename } from "node:path";
15328
- var CONTENT_TYPES = {
15329
- css: "text/css",
15330
- csv: "text/csv",
15331
- doc: "application/msword",
15332
- docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
15333
- gif: "image/gif",
15334
- html: "text/html",
15335
- htm: "text/html",
15336
- jpeg: "image/jpeg",
15337
- jpg: "image/jpeg",
15338
- js: "text/javascript",
15339
- json: "application/json",
15340
- jsonl: "application/jsonl",
15341
- md: "text/markdown",
15342
- pdf: "application/pdf",
15343
- ppt: "application/vnd.ms-powerpoint",
15344
- pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
15345
- png: "image/png",
15346
- svg: "image/svg+xml",
15347
- txt: "text/plain",
15348
- webp: "image/webp",
15349
- yaml: "application/yaml",
15350
- yml: "application/yaml",
15351
- xls: "application/vnd.ms-excel",
15352
- xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
15353
- zip: "application/zip"
15354
- };
15355
- function contentTypeFor(name) {
15356
- const dot = name.lastIndexOf(".");
15357
- const extension = dot === -1 ? "" : name.slice(dot + 1).toLowerCase();
15358
- return CONTENT_TYPES[extension] ?? "application/octet-stream";
15359
- }
15360
- async function localFile(path, override) {
15361
- let size;
15362
- try {
15363
- const stats = await stat(path);
15364
- if (!stats.isFile())
15365
- throw new SimApiError(`${path} is not a regular file`, 0);
15366
- await access(path, constants.R_OK);
15367
- size = stats.size;
15368
- } catch (error) {
15369
- if (error instanceof SimApiError)
15370
- throw error;
15371
- throw new SimApiError(`Cannot read ${path}: ${error.message}`, 0);
15233
+ // src/transfer/upload-session.ts
15234
+ import { openAsBlob } from "node:fs";
15235
+
15236
+ // src/transfer/streaming-upload.ts
15237
+ class StreamingUpload {
15238
+ size;
15239
+ position = 0;
15240
+ pending = new Uint8Array(0);
15241
+ closed = false;
15242
+ reader;
15243
+ onAbort;
15244
+ stopped = new AbortController;
15245
+ signal;
15246
+ constructor(stream, size, signal) {
15247
+ this.size = size;
15248
+ this.signal = signal ? AbortSignal.any([signal, this.stopped.signal]) : this.stopped.signal;
15249
+ this.reader = stream.getReader();
15250
+ this.onAbort = () => {
15251
+ this.reader.cancel(this.signal.reason).catch(() => {});
15252
+ };
15253
+ this.signal.addEventListener("abort", this.onAbort, { once: true });
15254
+ if (this.signal.aborted)
15255
+ this.onAbort();
15256
+ }
15257
+ slice(start, end) {
15258
+ this.signal.throwIfAborted();
15259
+ if (this.closed || start !== this.position || end <= start || end > this.size) {
15260
+ throw new SimApiError("Upload parts must consume the snapshot in order", 0);
15261
+ }
15262
+ return new ReadableStream({
15263
+ pull: async (controller) => {
15264
+ try {
15265
+ this.signal.throwIfAborted();
15266
+ while (this.pending.byteLength === 0) {
15267
+ const next = await this.reader.read();
15268
+ this.signal.throwIfAborted();
15269
+ if (next.done)
15270
+ throw new SimApiError("Upload file ended before its declared size", 0);
15271
+ this.pending = next.value;
15272
+ }
15273
+ const length = Math.min(this.pending.byteLength, end - this.position);
15274
+ controller.enqueue(this.pending.subarray(0, length));
15275
+ this.pending = this.pending.subarray(length);
15276
+ this.position += length;
15277
+ if (this.position === end)
15278
+ controller.close();
15279
+ } catch (error) {
15280
+ controller.error(error);
15281
+ }
15282
+ },
15283
+ cancel: (reason) => this.reader.cancel(reason)
15284
+ }, { highWaterMark: 0 });
15285
+ }
15286
+ assertConsumed(end) {
15287
+ this.signal.throwIfAborted();
15288
+ if (this.position !== end) {
15289
+ throw new SimApiError("Upload was acknowledged before its complete body was consumed", 0);
15290
+ }
15291
+ }
15292
+ async verifyComplete() {
15293
+ this.assertConsumed(this.size);
15294
+ if (this.pending.byteLength > 0) {
15295
+ throw new SimApiError("Upload file exceeds its declared size", 0);
15296
+ }
15297
+ while (true) {
15298
+ const next = await this.reader.read();
15299
+ this.signal.throwIfAborted();
15300
+ if (next.done)
15301
+ return;
15302
+ if (next.value.byteLength > 0)
15303
+ throw new SimApiError("Upload file exceeds its declared size", 0);
15304
+ }
15305
+ }
15306
+ async close() {
15307
+ if (this.closed)
15308
+ return;
15309
+ this.closed = true;
15310
+ this.stopped.abort();
15311
+ this.signal.removeEventListener("abort", this.onAbort);
15312
+ try {
15313
+ await this.reader.cancel().catch(() => {});
15314
+ } finally {
15315
+ this.reader.releaseLock();
15316
+ }
15372
15317
  }
15373
- if (size === 0)
15374
- throw new SimApiError(`${path} is empty`, 0);
15375
- return { name: override ?? basename(path), size };
15376
15318
  }
15377
15319
 
15378
15320
  // src/transfer/upload-session.ts
15379
- import { openAsBlob } from "node:fs";
15380
15321
  var PART_URL_BATCH = 100;
15381
- async function uploadPut(transfer, blob) {
15382
- const response = await fetch(transfer.url, {
15322
+ async function uploadBytes(url, headers, file, start, end, label) {
15323
+ const body = file.slice(start, end);
15324
+ const options = {
15383
15325
  method: "PUT",
15384
- headers: transfer.headers,
15385
- body: blob
15386
- });
15326
+ headers,
15327
+ body,
15328
+ signal: file instanceof StreamingUpload ? file.signal : embedStore.getStore()?.identity.signal
15329
+ };
15330
+ if (file instanceof StreamingUpload) {
15331
+ const streamedHeaders = new Headers(headers);
15332
+ streamedHeaders.set("content-length", String(end - start));
15333
+ options.headers = streamedHeaders;
15334
+ options.duplex = "half";
15335
+ }
15336
+ const response = await fetch(url, options);
15387
15337
  if (!response.ok) {
15388
- throw new SimApiError(`Upload failed with status ${response.status}`, response.status);
15338
+ throw new SimApiError(`${label} failed with status ${response.status}`, response.status);
15389
15339
  }
15340
+ if (file instanceof StreamingUpload)
15341
+ file.assertConsumed(end);
15390
15342
  }
15391
- async function uploadParts(client, workspaceId, session, transfer, blob) {
15343
+ async function uploadParts(client, workspaceId, session, transfer, file) {
15344
+ if (file instanceof StreamingUpload && (!Number.isSafeInteger(transfer.partSize) || transfer.partSize <= 0)) {
15345
+ throw new SimApiError("Invalid upload part size", 0);
15346
+ }
15392
15347
  const expectedPartCount = Math.ceil(session.size / transfer.partSize);
15393
15348
  if (expectedPartCount !== transfer.partCount) {
15394
15349
  throw new Error(`Upload session expected ${transfer.partCount} parts, but file requires ${expectedPartCount}`);
@@ -15404,28 +15359,49 @@ async function uploadParts(client, workspaceId, session, transfer, blob) {
15404
15359
  headers: { "upload-token": session.uploadToken },
15405
15360
  body: { partNumbers }
15406
15361
  });
15407
- for (const part of signed.data.parts) {
15408
- const start = (part.partNumber - 1) * transfer.partSize;
15409
- const chunk = blob.slice(start, Math.min(start + transfer.partSize, session.size));
15410
- const response = await fetch(part.url, {
15411
- method: "PUT",
15412
- headers: part.headers,
15413
- body: chunk
15414
- });
15415
- if (!response.ok) {
15416
- throw new SimApiError(`Part ${part.partNumber} failed with status ${response.status}`, response.status);
15362
+ let parts = signed.data.parts;
15363
+ if (file instanceof StreamingUpload) {
15364
+ const numbers = new Set(parts.map((part) => part.partNumber));
15365
+ if (parts.length !== partNumbers.length || partNumbers.some((n) => !numbers.has(n))) {
15366
+ throw new SimApiError("Upload part URLs do not match the requested parts", 0);
15417
15367
  }
15368
+ parts = [...parts].sort((a, b) => a.partNumber - b.partNumber);
15369
+ }
15370
+ for (const part of parts) {
15371
+ const start = (part.partNumber - 1) * transfer.partSize;
15372
+ await uploadBytes(part.url, part.headers, file, start, Math.min(start + transfer.partSize, session.size), `Part ${part.partNumber}`);
15418
15373
  }
15419
15374
  }
15420
15375
  }
15421
15376
  async function finishUploadSession(client, workspaceId, session, path) {
15377
+ let snapshot;
15378
+ let streamed;
15422
15379
  try {
15423
- const blob = await openAsBlob(path);
15380
+ const embedded = embedStore.getStore();
15381
+ let file;
15382
+ if (embedded) {
15383
+ embedded.identity.signal?.throwIfAborted();
15384
+ if (!embedded.openFile)
15385
+ throw new SimApiError("This invocation has no machine to read from", 0);
15386
+ snapshot = await embedded.openFile(embeddedFileKey(path));
15387
+ if (snapshot.size !== session.size)
15388
+ throw new SimApiError("Upload snapshot size changed", 0);
15389
+ streamed = new StreamingUpload(await snapshot.stream(), snapshot.size, AbortSignal.any([
15390
+ ...embedded.identity.signal ? [embedded.identity.signal] : [],
15391
+ ...snapshot.signal ? [snapshot.signal] : []
15392
+ ]));
15393
+ file = streamed;
15394
+ } else {
15395
+ file = await openAsBlob(path);
15396
+ }
15424
15397
  if (session.transfer.method === "put") {
15425
- await uploadPut(session.transfer, blob);
15398
+ await uploadBytes(session.transfer.url, session.transfer.headers, file, 0, file instanceof Blob ? file.size : session.size, "Upload");
15426
15399
  } else {
15427
- await uploadParts(client, workspaceId, session, session.transfer, blob);
15400
+ await uploadParts(client, workspaceId, session, session.transfer, file);
15428
15401
  }
15402
+ await streamed?.verifyComplete();
15403
+ await streamed?.close();
15404
+ await snapshot?.dispose().catch(() => {});
15429
15405
  const completed = await client.request(`${session.basePath}/complete`, {
15430
15406
  method: "POST",
15431
15407
  query: { workspaceId },
@@ -15433,7 +15409,10 @@ async function finishUploadSession(client, workspaceId, session, path) {
15433
15409
  });
15434
15410
  return completed.data;
15435
15411
  } catch (error) {
15436
- await client.request(session.basePath, {
15412
+ await streamed?.close();
15413
+ const profile = embeddedProfile();
15414
+ const cleanupClient = profile ? new SimClient({ ...profile, signal: AbortSignal.timeout(5000) }) : client;
15415
+ await cleanupClient.request(session.basePath, {
15437
15416
  method: "DELETE",
15438
15417
  query: { workspaceId },
15439
15418
  headers: { "upload-token": session.uploadToken }
@@ -15441,6 +15420,9 @@ async function finishUploadSession(client, workspaceId, session, path) {
15441
15420
  return;
15442
15421
  });
15443
15422
  throw error;
15423
+ } finally {
15424
+ await streamed?.close();
15425
+ await snapshot?.dispose().catch(() => {});
15444
15426
  }
15445
15427
  }
15446
15428
 
@@ -15526,9 +15508,11 @@ function attachKnowledgeDocumentUpload(documents) {
15526
15508
  printProtocolResult(profile.output, {
15527
15509
  id: completed.document.id,
15528
15510
  knowledgeBaseId: completed.document.knowledgeBaseId,
15529
- name: completed.document.filename,
15530
- size: completed.document.fileSize,
15531
- status: completed.document.processingStatus
15511
+ filename: completed.document.filename,
15512
+ fileSize: completed.document.fileSize,
15513
+ mimeType: completed.document.mimeType,
15514
+ processingStatus: completed.document.processingStatus,
15515
+ chunkCount: completed.document.chunkCount
15532
15516
  });
15533
15517
  });
15534
15518
  }
@@ -15590,7 +15574,7 @@ function createTableWriter() {
15590
15574
  if (!widths) {
15591
15575
  widths = COLUMNS.map((column, index) => Math.min(MAX_CELL_WIDTH2, Math.max(column.floor, visibleWidth(column.header), ...lines.map((line) => visibleWidth(line[index])))));
15592
15576
  const header = widths;
15593
- console.log(source_default.dim(COLUMNS.map((column, index) => pad2(column.header.toUpperCase(), header[index])).join(" ").trimEnd()));
15577
+ console.log(styles3().dim(COLUMNS.map((column, index) => pad2(column.header.toUpperCase(), header[index])).join(" ").trimEnd()));
15594
15578
  }
15595
15579
  const locked = widths;
15596
15580
  for (const line of lines) {
@@ -15622,26 +15606,26 @@ ${dump(row, { lineWidth: 0, noRefs: true }).trimEnd()}`);
15622
15606
  return createTableWriter();
15623
15607
  }
15624
15608
  function followStatus() {
15625
- let reported = false;
15609
+ let reported2 = false;
15626
15610
  return {
15627
15611
  note: (message) => {
15628
- if (!process.stderr.isTTY)
15612
+ if (!hasProgressTerminal())
15629
15613
  return;
15630
- reported = true;
15631
- process.stderr.write(`\r${source_default.dim(message)}${ERASE_LINE}`);
15614
+ reported2 = true;
15615
+ process.stderr.write(`\r${styles3().dim(message)}${ERASE_LINE}`);
15632
15616
  },
15633
15617
  warn: (message) => {
15634
- if (reported) {
15635
- reported = false;
15618
+ if (reported2) {
15619
+ reported2 = false;
15636
15620
  process.stderr.write(`\r${ERASE_LINE}`);
15637
15621
  }
15638
15622
  process.stderr.write(`warning: ${message}
15639
15623
  `);
15640
15624
  },
15641
15625
  clear: () => {
15642
- if (!reported)
15626
+ if (!reported2)
15643
15627
  return;
15644
- reported = false;
15628
+ reported2 = false;
15645
15629
  process.stderr.write(`\r${ERASE_LINE}`);
15646
15630
  }
15647
15631
  };
@@ -15929,18 +15913,18 @@ function progressLine(job) {
15929
15913
  }
15930
15914
  async function watchImport(client, workspaceId, job) {
15931
15915
  let current = job;
15932
- let reported = null;
15916
+ let reported2 = null;
15933
15917
  while (!IMPORT_SETTLED.has(current.status)) {
15934
15918
  await sleep2(IMPORT_POLL_MS);
15935
15919
  const next = await client.request(`/api/v2/tables/imports/${encodeURIComponent(current.id)}`, { query: { workspaceId } });
15936
15920
  current = next.data;
15937
15921
  const line = progressLine(current);
15938
- if (process.stderr.isTTY && line !== reported) {
15939
- reported = line;
15940
- process.stderr.write(`\r${source_default.dim(line)}\x1B[K`);
15922
+ if (hasProgressTerminal() && line !== reported2) {
15923
+ reported2 = line;
15924
+ process.stderr.write(`\r${styles3().dim(line)}\x1B[K`);
15941
15925
  }
15942
15926
  }
15943
- if (process.stderr.isTTY && reported !== null)
15927
+ if (hasProgressTerminal() && reported2 !== null)
15944
15928
  process.stderr.write("\r\x1B[K");
15945
15929
  return current;
15946
15930
  }
@@ -15999,8 +15983,8 @@ function attachTableImport(tables) {
15999
15983
  workspaceId,
16000
15984
  source,
16001
15985
  target,
16002
- ...options.mapping ? { mapping: jsonFlag(options.mapping, "mapping", "object") } : {},
16003
- ...options.createColumns ? { createColumns: jsonFlag(options.createColumns, "create-columns", "array") } : {},
15986
+ ...options.mapping ? { mapping: await jsonFlag(options.mapping, "mapping", "object") } : {},
15987
+ ...options.createColumns ? { createColumns: await jsonFlag(options.createColumns, "create-columns", "array") } : {},
16004
15988
  ...options.timezone ? { timezone: options.timezone } : {}
16005
15989
  }
16006
15990
  });
@@ -16045,14 +16029,11 @@ var AGENT_STREAM_PROTOCOL_HEADER = "x-sim-stream-protocol";
16045
16029
  var AGENT_STREAM_PROTOCOL_V1 = "agent-events-v1";
16046
16030
  var DONE_SENTINEL = "[DONE]";
16047
16031
  function resolveWorkflowRunSelection(flags) {
16048
- const manual = flags.manual === true;
16049
16032
  const trigger = typeof flags.trigger === "string" ? flags.trigger : undefined;
16050
16033
  const useMockPayload = flags.mockPayload === true;
16034
+ const manual = flags.manual === true || trigger !== undefined || useMockPayload;
16051
16035
  const fromBlock = typeof flags.fromBlock === "string" ? flags.fromBlock : undefined;
16052
16036
  const sourceRun = typeof flags.sourceRun === "string" ? flags.sourceRun : undefined;
16053
- if ((trigger || useMockPayload) && !manual) {
16054
- throw new SimApiError("--trigger and --mock-payload require --manual", 0);
16055
- }
16056
16037
  if (fromBlock && (trigger || useMockPayload)) {
16057
16038
  throw new SimApiError("--from-block cannot be combined with --trigger or --mock-payload", 0);
16058
16039
  }
@@ -16127,16 +16108,16 @@ class Commentary {
16127
16108
  constructor(sink) {
16128
16109
  this.sink = sink;
16129
16110
  }
16130
- inline(text) {
16131
- if (text.length === 0)
16111
+ inline(text2) {
16112
+ if (text2.length === 0)
16132
16113
  return;
16133
- this.sink.write(text);
16134
- this.atLineStart = text.endsWith(`
16114
+ this.sink.write(text2);
16115
+ this.atLineStart = text2.endsWith(`
16135
16116
  `);
16136
16117
  }
16137
- line(text) {
16118
+ line(text2) {
16138
16119
  this.sink.write(`${this.atLineStart ? "" : `
16139
- `}${text}
16120
+ `}${text2}
16140
16121
  `);
16141
16122
  this.atLineStart = true;
16142
16123
  }
@@ -16151,11 +16132,11 @@ class Commentary {
16151
16132
  function toolNotice(frame) {
16152
16133
  const name = safeOneLine(stringField(frame, "name") ?? "tool");
16153
16134
  if (frame.phase === "start")
16154
- return source_default.dim(`→ ${name}`);
16135
+ return styles3().dim(`→ ${name}`);
16155
16136
  const status = stringField(frame, "status");
16156
16137
  if (status && status !== "success")
16157
- return source_default.yellow(`✗ ${name} (${safeOneLine(status)})`);
16158
- return source_default.dim(`✓ ${name}`);
16138
+ return styles3().yellow(`✗ ${name} (${safeOneLine(status)})`);
16139
+ return styles3().dim(`✓ ${name}`);
16159
16140
  }
16160
16141
  async function renderRunStream(body, options) {
16161
16142
  const commentary = new Commentary(options.stderr);
@@ -16177,11 +16158,11 @@ async function renderRunStream(body, options) {
16177
16158
  }
16178
16159
  switch (frame.event) {
16179
16160
  case "chunk_reset":
16180
- commentary.line(source_default.dim("… retracted; that turn resolved to tool calls"));
16161
+ commentary.line(styles3().dim("… retracted; that turn resolved to tool calls"));
16181
16162
  break;
16182
16163
  case "thinking":
16183
16164
  if (options.includeThinking && typeof frame.data === "string") {
16184
- commentary.inline(source_default.dim(sanitize(frame.data)));
16165
+ commentary.inline(styles3().dim(sanitize(frame.data)));
16185
16166
  }
16186
16167
  break;
16187
16168
  case "tool":
@@ -16189,7 +16170,7 @@ async function renderRunStream(body, options) {
16189
16170
  commentary.line(toolNotice(frame));
16190
16171
  break;
16191
16172
  case "stream_error":
16192
- commentary.line(source_default.yellow(`warning: ${safeOneLine(stringField(frame, "error") ?? "stream read failed")}`));
16173
+ commentary.line(styles3().yellow(`warning: ${safeOneLine(stringField(frame, "error") ?? "stream read failed")}`));
16193
16174
  break;
16194
16175
  case "error":
16195
16176
  commentary.endLine();
@@ -16218,7 +16199,7 @@ async function followRun(workflowId, command) {
16218
16199
  const negotiates = includeThinking || includeToolCalls;
16219
16200
  const { client, profile } = clientFrom(command);
16220
16201
  const operation = V2_OPERATIONS.executeWorkflow;
16221
- const request = buildRequest("executeWorkflow", [workflowId], flags, profile.workspaceId);
16202
+ const request = await buildRequest("executeWorkflow", [workflowId], flags, profile.workspaceId);
16222
16203
  const response = await client.requestRaw(request.path, {
16223
16204
  method: "POST",
16224
16205
  query: request.query,
@@ -16259,8 +16240,8 @@ function followOrDelegate(previous) {
16259
16240
  command.setOptionValue("run", selection);
16260
16241
  const flags = command.optsWithGlobals();
16261
16242
  if (flags.follow !== true) {
16262
- if (Array.isArray(flags.selectOutput) && flags.selectOutput.length > 0) {
16263
- throw new SimApiError(flags.async === true ? "--select-output shapes a streamed result, and --async returns as soon as the run is queued, so there is no stream to shape. Drop one of them, or read the finished run with: sim workflows runs get <runId> --workflow <workflowId> --select-output <blockId>[.path] — that resource matches block ids, not the block names --select-output takes here." : "--select-output shapes a streamed result; add --follow. To narrow a run that has already finished: sim workflows runs get <runId> --workflow <workflowId> --select-output <blockId>[.path] — that resource matches block ids, not the block names --select-output takes here.", 0);
16243
+ if (Array.isArray(flags.selectOutput) && flags.selectOutput.length > 0 && flags.async === true) {
16244
+ 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);
16264
16245
  }
16265
16246
  if (flags.includeThinking === true || flags.includeToolCalls === true) {
16266
16247
  throw new SimApiError("--include-thinking and --include-tool-calls describe a stream; add --follow", 0);
@@ -16282,7 +16263,119 @@ function attachWorkflowRunFollow(workflows) {
16282
16263
  }
16283
16264
  const held = run._actionHandler;
16284
16265
  const previous = typeof held === "function" ? held : null;
16285
- run.option("--manual", "Run the current saved workflow state instead of the active deployment").option("--trigger <blockId>", "Enter a manual run through this runnable trigger (requires --manual)").option("--mock-payload", "Use the selected trigger's server-derived mock payload (requires --manual)").option("--from-block <blockId>", "Run manually from this saved workflow block").option("--source-run <runId>", "Prior run whose persisted state supplies upstream outputs (requires --from-block)").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));
16266
+ run.option("--manual", "Run the current saved workflow state instead of the active deployment").option("--trigger <blockId>", "Enter the run through this runnable trigger; 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 <blockId>", "Run manually from this saved workflow block").option("--source-run <runId>", "Prior run whose persisted state supplies upstream outputs (requires --from-block)").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));
16267
+ }
16268
+
16269
+ // src/commands/protocol/workflow-run-get.ts
16270
+ var BLOCK_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
16271
+ var SELECT_OUTPUT_FLAG = "select-output";
16272
+ function normalizeBlockName(name) {
16273
+ return name.toLowerCase().replace(/\s+/g, "").replace(/\./g, "");
16274
+ }
16275
+ function isRecord2(value) {
16276
+ return typeof value === "object" && value !== null && !Array.isArray(value);
16277
+ }
16278
+ async function loadWorkflowBlocks(client, workflowId) {
16279
+ const operation = V2_OPERATIONS.getWorkflowState;
16280
+ const raw = await client.request(resolvePath(operation.path, { workflowId }), {
16281
+ method: operation.method
16282
+ });
16283
+ const state = isRecord2(raw) && isRecord2(raw.data) ? raw.data : raw;
16284
+ const blocks = isRecord2(state) && isRecord2(state.blocks) ? Object.entries(state.blocks) : [];
16285
+ return blocks.map(([key, block]) => ({
16286
+ id: isRecord2(block) && typeof block.id === "string" ? block.id : key,
16287
+ name: isRecord2(block) && typeof block.name === "string" ? block.name : ""
16288
+ }));
16289
+ }
16290
+ function splitSelector(selector) {
16291
+ const dot = selector.indexOf(".");
16292
+ return dot === -1 ? { head: selector, path: "" } : { head: selector.slice(0, dot), path: selector.slice(dot) };
16293
+ }
16294
+ function isIdHeaded(selector) {
16295
+ return BLOCK_ID.test(splitSelector(selector).head);
16296
+ }
16297
+ function resolveSelection(typed, blocks, workflowId) {
16298
+ const resolved = [];
16299
+ const typedBy = new Map;
16300
+ const unresolved = [];
16301
+ for (const selector of typed) {
16302
+ const { head, path } = splitSelector(selector);
16303
+ let blockId = head;
16304
+ if (!BLOCK_ID.test(head)) {
16305
+ const wanted = normalizeBlockName(head);
16306
+ const matches = blocks.filter((block) => block.id === head || normalizeBlockName(block.name) === wanted);
16307
+ if (matches.length === 0) {
16308
+ unresolved.push(selector);
16309
+ continue;
16310
+ }
16311
+ if (matches.length > 1) {
16312
+ throw new SimApiError(`--${SELECT_OUTPUT_FLAG} ${selector} names ${matches.length} blocks (${matches.map((block) => block.id).join(", ")}); pass the block id instead`, 0);
16313
+ }
16314
+ blockId = matches[0].id;
16315
+ }
16316
+ const rewritten = `${blockId}${path}`;
16317
+ resolved.push(rewritten);
16318
+ if (!typedBy.has(rewritten))
16319
+ typedBy.set(rewritten, selector);
16320
+ }
16321
+ if (unresolved.length > 0) {
16322
+ const names = blocks.map((block) => block.name).filter((name) => name !== "");
16323
+ 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);
16324
+ }
16325
+ return { resolved, typedBy };
16326
+ }
16327
+ function keyByTyped(payload, typedBy) {
16328
+ if (!isRecord2(payload) || !isRecord2(payload.blockOutputs))
16329
+ return payload;
16330
+ const blockOutputs = {};
16331
+ for (const [key, value] of Object.entries(payload.blockOutputs)) {
16332
+ blockOutputs[typedBy.get(key) ?? key] = value;
16333
+ }
16334
+ return { ...payload, blockOutputs };
16335
+ }
16336
+ async function readRunByName(runId, typed, command) {
16337
+ const flags = command.optsWithGlobals();
16338
+ const { client, profile } = clientFrom(command);
16339
+ const operation = V2_OPERATIONS.getWorkflowRun;
16340
+ const spec = CLI_CONTRACT.getWorkflowRun ?? {};
16341
+ await buildRequest("getWorkflowRun", [runId], flags, profile.workspaceId);
16342
+ const workflowId = String(flags.workflow);
16343
+ const selection = resolveSelection(typed, await loadWorkflowBlocks(client, workflowId), workflowId);
16344
+ const request = await buildRequest("getWorkflowRun", [runId], { ...flags, selectOutput: selection.resolved }, profile.workspaceId);
16345
+ let result;
16346
+ try {
16347
+ result = await client.request(request.path, {
16348
+ method: operation.method,
16349
+ headers: request.headers,
16350
+ query: request.query,
16351
+ body: request.body
16352
+ });
16353
+ } catch (error) {
16354
+ throw retypeApiError(error, "getWorkflowRun", spec, operation);
16355
+ }
16356
+ renderResult("getWorkflowRun", profile.output, keyByTyped(result?.data ?? result, selection.typedBy), spec, {}, result);
16357
+ }
16358
+ function attachWorkflowRunGet(runs) {
16359
+ const get = runs.commands.find((command) => command.name() === "get");
16360
+ const held = get?._actionHandler;
16361
+ if (!get || typeof held !== "function") {
16362
+ throw new Error("workflows runs get must be registered before block names can be attached to it");
16363
+ }
16364
+ const previous = held;
16365
+ get.action(async (runId, _options, command) => {
16366
+ const raw = command.optsWithGlobals().selectOutput;
16367
+ if (raw === undefined) {
16368
+ await previous(command.processedArgs);
16369
+ return;
16370
+ }
16371
+ const typed = await readListValues(raw, SELECT_OUTPUT_FLAG);
16372
+ command.setOptionValue("selectOutput", typed);
16373
+ if (typed.every(isIdHeaded)) {
16374
+ await previous(command.processedArgs);
16375
+ return;
16376
+ }
16377
+ await readRunByName(runId, typed, command);
16378
+ });
16286
16379
  }
16287
16380
 
16288
16381
  // src/commands/protocol/workflow-run-wait.ts
@@ -16299,18 +16392,21 @@ var MAX_POLL_DELAY_MS = 15000;
16299
16392
  var POLL_BACKOFF_FACTOR = 2;
16300
16393
  var DEFAULT_WAIT_TIMEOUT_SECONDS = 3600;
16301
16394
  var WAIT_TIMEOUT_FLAG = "--wait-timeout <seconds>";
16302
- function isRecord2(value) {
16395
+ function isRecord3(value) {
16303
16396
  return typeof value === "object" && value !== null && !Array.isArray(value);
16304
16397
  }
16305
16398
  function optionalString(value) {
16306
16399
  return typeof value === "string" && value !== "" ? value : null;
16307
16400
  }
16401
+ function runData(raw) {
16402
+ return isRecord3(raw) && isRecord3(raw.data) ? raw.data : raw;
16403
+ }
16308
16404
  function readRun(raw) {
16309
- const run = isRecord2(raw) && isRecord2(raw.data) ? raw.data : raw;
16310
- if (!isRecord2(run) || typeof run.status !== "string") {
16405
+ const run = isRecord3(raw) && isRecord3(raw.data) ? raw.data : raw;
16406
+ if (!isRecord3(run) || typeof run.status !== "string") {
16311
16407
  throw new SimApiError("Run status response carried no status.", 0);
16312
16408
  }
16313
- const paused = isRecord2(run.paused) ? run.paused : null;
16409
+ const paused = isRecord3(run.paused) ? run.paused : null;
16314
16410
  return {
16315
16411
  status: run.status,
16316
16412
  pauseKind: paused ? optionalString(paused.pauseKind) : null,
@@ -16326,18 +16422,18 @@ function classify(snapshot) {
16326
16422
  return snapshot.status === "completed" ? "completed" : snapshot.status === "cancelled" ? "cancelled" : "failed";
16327
16423
  }
16328
16424
  function waitProgress() {
16329
- let reported = false;
16425
+ let reported2 = false;
16330
16426
  return {
16331
16427
  advance: (status, elapsedMs) => {
16332
- if (!process.stderr.isTTY)
16428
+ if (!hasProgressTerminal())
16333
16429
  return;
16334
- reported = true;
16335
- process.stderr.write(`\r${source_default.dim(`${status} — waiting ${Math.round(elapsedMs / 1000)}s…`)}\x1B[K`);
16430
+ reported2 = true;
16431
+ process.stderr.write(`\r${styles3().dim(`${status} — waiting ${Math.round(elapsedMs / 1000)}s…`)}\x1B[K`);
16336
16432
  },
16337
16433
  finish: () => {
16338
- if (!reported)
16434
+ if (!reported2)
16339
16435
  return;
16340
- reported = false;
16436
+ reported2 = false;
16341
16437
  process.stderr.write("\r\x1B[K");
16342
16438
  }
16343
16439
  };
@@ -16379,19 +16475,19 @@ function attachWorkflowRunWait(runs) {
16379
16475
  const outcome = classify(snapshot);
16380
16476
  if (outcome) {
16381
16477
  progress.finish();
16382
- renderResult("getWorkflowRun", profile.output, raw, runSpec());
16478
+ renderResult("getWorkflowRun", profile.output, runData(raw), runSpec());
16383
16479
  const message = explain(outcome, runId, options.workflow, snapshot);
16384
16480
  if (message)
16385
- console.error(source_default.red(message));
16386
- process.exitCode = WAIT_EXIT_CODES[outcome];
16481
+ console.error(styles3().red(message));
16482
+ setSoftExitCode(WAIT_EXIT_CODES[outcome]);
16387
16483
  return;
16388
16484
  }
16389
16485
  const remainingMs = deadline - Date.now();
16390
16486
  if (remainingMs <= 0) {
16391
16487
  progress.finish();
16392
- renderResult("getWorkflowRun", profile.output, raw, runSpec());
16393
- console.error(source_default.red(`Timed out after ${timeoutSeconds}s waiting for run ${runId} (status: ${snapshot.status}${snapshot.resumeAt ? `, resuming at ${snapshot.resumeAt}` : ""}). Raise ${WAIT_TIMEOUT_FLAG}, or set it to 0 to wait indefinitely.`));
16394
- process.exitCode = WAIT_EXIT_CODES.timeout;
16488
+ renderResult("getWorkflowRun", profile.output, runData(raw), runSpec());
16489
+ console.error(styles3().red(`Timed out after ${timeoutSeconds}s waiting for run ${runId} (status: ${snapshot.status}${snapshot.resumeAt ? `, resuming at ${snapshot.resumeAt}` : ""}). Raise ${WAIT_TIMEOUT_FLAG}, or set it to 0 to wait indefinitely.`));
16490
+ setSoftExitCode(WAIT_EXIT_CODES.timeout);
16395
16491
  return;
16396
16492
  }
16397
16493
  progress.advance(snapshot.status, Date.now() - startedAt);
@@ -16405,16 +16501,16 @@ function attachWorkflowRunWait(runs) {
16405
16501
  }
16406
16502
 
16407
16503
  // src/commands/protocol/index.ts
16408
- function group(program, name) {
16409
- const existing = program.commands.find((command) => command.name() === name);
16504
+ function group(program2, name) {
16505
+ const existing = program2.commands.find((command) => command.name() === name);
16410
16506
  if (existing)
16411
16507
  return existing;
16412
16508
  const created = new Command(name);
16413
- program.addCommand(created);
16509
+ program2.addCommand(created);
16414
16510
  return created;
16415
16511
  }
16416
- function attachProtocolCommands(program) {
16417
- const files = group(program, "files");
16512
+ function attachProtocolCommands(program2) {
16513
+ const files = group(program2, "files");
16418
16514
  attachFileUpload(files);
16419
16515
  attachFileGet(files);
16420
16516
  attachResourceDirectoryCommands(files, {
@@ -16423,7 +16519,7 @@ function attachProtocolCommands(program) {
16423
16519
  folders: "listFileFolders",
16424
16520
  createFolder: "createFileFolder"
16425
16521
  });
16426
- const knowledge = group(program, "knowledge");
16522
+ const knowledge = group(program2, "knowledge");
16427
16523
  attachKnowledgeDocumentUpload(group(knowledge, "documents"));
16428
16524
  attachResourceDirectoryCommands(knowledge, {
16429
16525
  kind: "knowledge",
@@ -16431,7 +16527,7 @@ function attachProtocolCommands(program) {
16431
16527
  folders: "listKnowledgeFolders",
16432
16528
  createFolder: "createKnowledgeFolder"
16433
16529
  });
16434
- const tables = group(program, "tables");
16530
+ const tables = group(program2, "tables");
16435
16531
  attachTableImport(tables);
16436
16532
  attachResourceDirectoryCommands(tables, {
16437
16533
  kind: "table",
@@ -16439,7 +16535,7 @@ function attachProtocolCommands(program) {
16439
16535
  folders: "listTableFolders",
16440
16536
  createFolder: "createTableFolder"
16441
16537
  });
16442
- const workflows = group(program, "workflows");
16538
+ const workflows = group(program2, "workflows");
16443
16539
  attachResourceDirectoryCommands(workflows, {
16444
16540
  kind: "workflow",
16445
16541
  resources: "listWorkflows",
@@ -16447,9 +16543,11 @@ function attachProtocolCommands(program) {
16447
16543
  createFolder: "createWorkflowFolder"
16448
16544
  });
16449
16545
  attachWorkflowRunFollow(workflows);
16450
- attachWorkflowRunWait(group(workflows, "runs"));
16451
- attachLogsFollow(group(program, "logs"));
16452
- attachChat(program);
16546
+ const runs = group(workflows, "runs");
16547
+ attachWorkflowRunGet(runs);
16548
+ attachWorkflowRunWait(runs);
16549
+ attachLogsFollow(group(program2, "logs"));
16550
+ attachChat(program2);
16453
16551
  }
16454
16552
 
16455
16553
  // src/terminal/secret-input.ts
@@ -16481,7 +16579,7 @@ function promptSecret(input = process.stdin, output = process.stderr) {
16481
16579
  emitKeypressEvents(input);
16482
16580
  input.setRawMode(true);
16483
16581
  input.resume();
16484
- return new Promise((resolve, reject) => {
16582
+ return new Promise((resolve3, reject) => {
16485
16583
  const cleanup = () => {
16486
16584
  input.removeListener("keypress", onKeypress);
16487
16585
  input.setRawMode(wasRaw);
@@ -16502,7 +16600,7 @@ function promptSecret(input = process.stdin, output = process.stderr) {
16502
16600
  };
16503
16601
  const fail = (message) => finish(() => reject(new SimApiError(message, 0)));
16504
16602
  const cancel = () => finish(() => reject(new SecretInputCancelledError));
16505
- function onKeypress(text, key) {
16603
+ function onKeypress(text2, key) {
16506
16604
  if (key.ctrl && (key.name === "c" || key.name === "d")) {
16507
16605
  cancel();
16508
16606
  return;
@@ -16511,7 +16609,7 @@ function promptSecret(input = process.stdin, output = process.stderr) {
16511
16609
  if (value.length === 0)
16512
16610
  fail("Secret value cannot be empty.");
16513
16611
  else
16514
- finish(() => resolve(value));
16612
+ finish(() => resolve3(value));
16515
16613
  return;
16516
16614
  }
16517
16615
  if (key.name === "backspace") {
@@ -16523,7 +16621,7 @@ function promptSecret(input = process.stdin, output = process.stderr) {
16523
16621
  }
16524
16622
  return;
16525
16623
  }
16526
- const entered = text || metaCharacter(key);
16624
+ const entered = text2 || metaCharacter(key);
16527
16625
  if (!entered || key.ctrl || key.name === "escape")
16528
16626
  return;
16529
16627
  if (value.length + entered.length > MAX_SECRET_LENGTH) {
@@ -16550,12 +16648,12 @@ var SECRET_RESULT = {
16550
16648
  { header: "description" }
16551
16649
  ]
16552
16650
  };
16553
- function readValueArgument(raw) {
16651
+ async function readValueArgument(raw) {
16554
16652
  if (raw.startsWith("@@"))
16555
16653
  return raw.slice(1);
16556
16654
  if (!raw.startsWith("@"))
16557
16655
  return raw;
16558
- return readArgumentSource(raw, "value").text;
16656
+ return (await readArgumentSource(raw, "value")).text;
16559
16657
  }
16560
16658
  function validateSecretValue(value) {
16561
16659
  if (value.length === 0)
@@ -16575,7 +16673,7 @@ function validateWorkspaceOnlyFlag(flag, value, scope) {
16575
16673
  }
16576
16674
  async function readSecretValue(options) {
16577
16675
  if (options.value !== undefined)
16578
- return validateSecretValue(readValueArgument(options.value));
16676
+ return validateSecretValue(await readValueArgument(options.value));
16579
16677
  if (options.description !== undefined || options.unredacted !== undefined)
16580
16678
  return;
16581
16679
  try {
@@ -16583,7 +16681,7 @@ async function readSecretValue(options) {
16583
16681
  } catch (error) {
16584
16682
  if (!(error instanceof SecretInputCancelledError))
16585
16683
  throw error;
16586
- console.error(source_default.red(`Error: ${error.message}`));
16684
+ console.error(styles3().red(`Error: ${error.message}`));
16587
16685
  return process.exit(CANCELLED_EXIT_CODE);
16588
16686
  }
16589
16687
  }
@@ -16608,336 +16706,14 @@ async function setSecret(name, options, command, redactionSpellings) {
16608
16706
  });
16609
16707
  renderResult("setSecret", profile.output, response.data, SECRET_RESULT);
16610
16708
  }
16611
- function attachSecretCommands(program) {
16612
- const secrets = program.commands.find((command) => command.name() === "secrets");
16709
+ function attachSecretCommands(program2) {
16710
+ const secrets = program2.commands.find((command) => command.name() === "secrets");
16613
16711
  if (!secrets)
16614
16712
  throw new Error("The generated secrets command group is missing");
16615
16713
  const redactionSpellings = new Set;
16616
16714
  secrets.command("set").argument("<name>", "Secret name, as referenced in workflows").description(describeOperation(V2_OPERATIONS.setSecret, "Create or replace a named secret")).addOption(new Option("--scope <scope>", "Secret ownership scope (required)").choices([...SECRET_SCOPES]).makeOptionMandatory()).option("--value <value|@file>", "Secret value. Passing it inline exposes it to shell history and process listings; @path reads it from a file and @- from stdin, verbatim — a trailing newline is part of the value, so write the file with printf rather than echo. Prefix a literal leading @ with a second one").option("--description <description>", "What the secret is for, shown to teammates; workspace scope only. Omit to leave an existing description unchanged").option("--unredacted", `${V2_OPERATIONS.setSecret.body.unredacted.describe} Pass --no-unredacted to restore redaction`).option("--no-unredacted", "Send --unredacted as false").on("option:unredacted", () => redactionSpellings.add("--unredacted")).on("option:no-unredacted", () => redactionSpellings.add("--no-unredacted")).action((name, options, command) => setSecret(name, options, command, redactionSpellings));
16617
16715
  }
16618
16716
 
16619
- // src/update/check.ts
16620
- import { spawn as spawn2 } from "node:child_process";
16621
- import {
16622
- closeSync,
16623
- constants as constants2,
16624
- fstatSync,
16625
- lstatSync,
16626
- mkdirSync as mkdirSync2,
16627
- openSync,
16628
- readSync as readSync2,
16629
- renameSync,
16630
- unlinkSync,
16631
- writeFileSync as writeFileSync2
16632
- } from "node:fs";
16633
- import { dirname as dirname3 } from "node:path";
16634
- import { fileURLToPath } from "node:url";
16635
- var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
16636
- var REGISTRY_TIMEOUT_MS = 1000;
16637
- var DEFAULT_REGISTRY = "https://registry.npmjs.org";
16638
- var PACKAGE_NAME = "sim";
16639
- var DIST_TAGS_PATH = `-/package/${PACKAGE_NAME}/dist-tags`;
16640
- var MAX_RESPONSE_BYTES = 64 * 1024;
16641
- var MAX_CACHE_BYTES = 4 * 1024;
16642
- var STABLE_VERSION_PATTERN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
16643
- function parseStableVersion(version) {
16644
- const match = STABLE_VERSION_PATTERN.exec(version);
16645
- if (!match)
16646
- return null;
16647
- const parsed = [Number(match[1]), Number(match[2]), Number(match[3])];
16648
- return parsed.every(Number.isSafeInteger) ? parsed : null;
16649
- }
16650
- function isNewerVersion(candidate, current) {
16651
- if (candidate[0] !== current[0])
16652
- return candidate[0] > current[0];
16653
- if (candidate[1] !== current[1])
16654
- return candidate[1] > current[1];
16655
- return candidate[2] > current[2];
16656
- }
16657
- var CI_VARIABLES = [
16658
- "CI",
16659
- "GITHUB_ACTIONS",
16660
- "JENKINS_URL",
16661
- "TEAMCITY_VERSION",
16662
- "BUILDKITE"
16663
- ];
16664
- var CACHE_VERSION = 1;
16665
- var cacheWriteSequence = 0;
16666
- function isEnabled(value) {
16667
- if (value === undefined)
16668
- return false;
16669
- const normalized = value.trim().toLowerCase();
16670
- return normalized !== "" && normalized !== "0" && normalized !== "false";
16671
- }
16672
- function isProjectLocalInstall(modulePath, cwd) {
16673
- const normalizedModulePath = normalizeModulePath(modulePath);
16674
- const nodeModulesIndex = normalizedModulePath.indexOf("/node_modules/");
16675
- if (nodeModulesIndex < 0)
16676
- return false;
16677
- const installRoot = normalizedModulePath.slice(0, nodeModulesIndex);
16678
- const workingDirectory = normalizeModulePath(cwd).replace(/\/+$/, "");
16679
- return workingDirectory === installRoot || workingDirectory.startsWith(`${installRoot}/`);
16680
- }
16681
- function isUnadvisableInstall(modulePath, env, cwd) {
16682
- const normalized = normalizeModulePath(modulePath);
16683
- return env.npm_command === "exec" || normalized.includes("/_npx/") || normalized.includes("/packages/sim-cli/") || isProjectLocalInstall(modulePath, cwd);
16684
- }
16685
- function normalizeModulePath(modulePath) {
16686
- return modulePath.replace(/\\/g, "/").toLowerCase();
16687
- }
16688
- function registryUrl(env) {
16689
- const fallback = new URL(DIST_TAGS_PATH, DEFAULT_REGISTRY);
16690
- const configured = env.npm_config_registry?.trim();
16691
- if (!configured)
16692
- return fallback;
16693
- try {
16694
- const base = new URL(configured);
16695
- if (base.protocol !== "http:" && base.protocol !== "https:")
16696
- return null;
16697
- if (base.username || base.password)
16698
- return null;
16699
- base.pathname = `${base.pathname.replace(/\/$/, "")}/${DIST_TAGS_PATH}`;
16700
- return base;
16701
- } catch {
16702
- return null;
16703
- }
16704
- }
16705
- var REGISTRY_REQUEST_SCRIPT = `
16706
- let input = ''
16707
- process.stdin.setEncoding('utf8')
16708
- for await (const chunk of process.stdin) input += chunk
16709
-
16710
- try {
16711
- const { url, headers, maxResponseBytes, timeoutMs } = JSON.parse(input)
16712
- const deadline = setTimeout(() => process.exit(1), timeoutMs)
16713
- const response = await fetch(url, { headers, redirect: 'error' })
16714
- const declared = Number(response.headers.get('content-length'))
16715
-
16716
- if (!response.ok || !response.body || (Number.isFinite(declared) && declared > maxResponseBytes)) {
16717
- process.exit(1)
16718
- }
16719
-
16720
- const reader = response.body.getReader()
16721
- const chunks = []
16722
- let seen = 0
16723
-
16724
- while (true) {
16725
- const { done, value } = await reader.read()
16726
- if (done) break
16727
- seen += value.byteLength
16728
- if (seen > maxResponseBytes) {
16729
- process.exit(1)
16730
- }
16731
- chunks.push(Buffer.from(value))
16732
- }
16733
-
16734
- clearTimeout(deadline)
16735
- process.stdout.write(Buffer.concat(chunks), () => process.exit(0))
16736
- } catch {
16737
- process.exit(1)
16738
- }
16739
- `;
16740
- function registryProcessEnv() {
16741
- const env = { ...process.env };
16742
- for (const key of Object.keys(env)) {
16743
- const normalized = key.toLowerCase();
16744
- if (normalized === "npm_config_registry" || normalized === "sim_api_key")
16745
- delete env[key];
16746
- }
16747
- return env;
16748
- }
16749
- function requestRegistry(url, { headers, maxResponseBytes, timeoutMs }) {
16750
- return new Promise((resolve, reject) => {
16751
- const proxyArguments = process.execArgv.filter((argument) => argument === "--use-env-proxy" || argument === "--no-use-env-proxy");
16752
- const child = spawn2(process.execPath, [...proxyArguments, "--input-type=module", "--eval", REGISTRY_REQUEST_SCRIPT], {
16753
- env: registryProcessEnv(),
16754
- killSignal: "SIGKILL",
16755
- stdio: ["pipe", "pipe", "ignore"],
16756
- timeout: timeoutMs,
16757
- windowsHide: true
16758
- });
16759
- const chunks = [];
16760
- let failed = false;
16761
- let seen = 0;
16762
- child.stdout.on("data", (chunk) => {
16763
- seen += chunk.byteLength;
16764
- if (seen > maxResponseBytes) {
16765
- failed = true;
16766
- child.kill("SIGKILL");
16767
- return;
16768
- }
16769
- chunks.push(chunk);
16770
- });
16771
- child.stdout.on("error", () => {
16772
- failed = true;
16773
- child.kill("SIGKILL");
16774
- });
16775
- child.stdin.on("error", () => {});
16776
- child.once("error", reject);
16777
- child.once("close", (code) => {
16778
- resolve(code === 0 && !failed ? Buffer.concat(chunks).toString("utf8") : null);
16779
- });
16780
- child.stdin.end(JSON.stringify({ headers, maxResponseBytes, timeoutMs, url: url.href }));
16781
- });
16782
- }
16783
- async function fetchDistTags(env, request) {
16784
- try {
16785
- const url = registryUrl(env);
16786
- if (!url)
16787
- return null;
16788
- const text = await request(url, {
16789
- headers: { accept: "application/json", "user-agent": `${PACKAGE_NAME}-cli/${CLI_VERSION}` },
16790
- maxResponseBytes: MAX_RESPONSE_BYTES,
16791
- timeoutMs: REGISTRY_TIMEOUT_MS
16792
- });
16793
- if (text === null || Buffer.byteLength(text) > MAX_RESPONSE_BYTES)
16794
- return null;
16795
- const body = JSON.parse(text);
16796
- if (typeof body !== "object" || body === null || Array.isArray(body))
16797
- return null;
16798
- const tags = {};
16799
- for (const [tag, version] of Object.entries(body)) {
16800
- if (typeof version === "string")
16801
- tags[tag] = version;
16802
- }
16803
- return tags;
16804
- } catch {
16805
- return null;
16806
- }
16807
- }
16808
- function readCache(path) {
16809
- let descriptor = null;
16810
- try {
16811
- if (!lstatSync(path).isFile())
16812
- return null;
16813
- descriptor = openSync(path, constants2.O_RDONLY | constants2.O_NONBLOCK | constants2.O_NOFOLLOW);
16814
- const descriptorStats = fstatSync(descriptor);
16815
- if (!descriptorStats.isFile() || descriptorStats.size > MAX_CACHE_BYTES) {
16816
- return null;
16817
- }
16818
- const buffer = Buffer.allocUnsafe(MAX_CACHE_BYTES + 1);
16819
- let bytesRead = 0;
16820
- while (bytesRead < buffer.byteLength) {
16821
- const count = readSync2(descriptor, buffer, bytesRead, buffer.byteLength - bytesRead, bytesRead);
16822
- if (count === 0)
16823
- break;
16824
- bytesRead += count;
16825
- }
16826
- if (bytesRead > MAX_CACHE_BYTES)
16827
- return null;
16828
- const parsed = JSON.parse(buffer.subarray(0, bytesRead).toString("utf8"));
16829
- if (typeof parsed !== "object" || parsed === null)
16830
- return null;
16831
- const entry = parsed;
16832
- if (entry.version !== CACHE_VERSION)
16833
- return null;
16834
- if (typeof entry.checkedAt !== "string" || Number.isNaN(Date.parse(entry.checkedAt)))
16835
- return null;
16836
- return {
16837
- version: CACHE_VERSION,
16838
- checkedAt: entry.checkedAt
16839
- };
16840
- } catch {
16841
- return null;
16842
- } finally {
16843
- if (descriptor !== null) {
16844
- try {
16845
- closeSync(descriptor);
16846
- } catch {}
16847
- }
16848
- }
16849
- }
16850
- function writeCache(path, entry) {
16851
- let descriptor = null;
16852
- let temporaryCreated = false;
16853
- const temporaryPath = `${path}.${process.pid}.${Date.now()}.${cacheWriteSequence++}.tmp`;
16854
- try {
16855
- mkdirSync2(dirname3(path), { recursive: true, mode: 448 });
16856
- descriptor = openSync(temporaryPath, "wx", 420);
16857
- temporaryCreated = true;
16858
- writeFileSync2(descriptor, `${JSON.stringify(entry, null, 2)}
16859
- `);
16860
- closeSync(descriptor);
16861
- descriptor = null;
16862
- renameSync(temporaryPath, path);
16863
- temporaryCreated = false;
16864
- } catch {} finally {
16865
- if (descriptor !== null) {
16866
- try {
16867
- closeSync(descriptor);
16868
- } catch {}
16869
- }
16870
- if (temporaryCreated) {
16871
- try {
16872
- unlinkSync(temporaryPath);
16873
- } catch {}
16874
- }
16875
- }
16876
- }
16877
- function isFresh(entry, now) {
16878
- const age = now.getTime() - Date.parse(entry.checkedAt);
16879
- return age >= 0 && age < CHECK_INTERVAL_MS;
16880
- }
16881
- function upgradeCommand(modulePath = fileURLToPath(import.meta.url), env = process.env) {
16882
- const target = `${PACKAGE_NAME}@latest`;
16883
- const normalized = normalizeModulePath(modulePath);
16884
- if (normalized.includes(".bun/install/global"))
16885
- return `bun add -g ${target}`;
16886
- if (normalized.includes("/pnpm/") || normalized.includes("/.pnpm/")) {
16887
- return `pnpm add -g ${target}`;
16888
- }
16889
- if (normalized.includes("/.yarn/") || normalized.includes("/yarn/")) {
16890
- return `yarn global add ${target}`;
16891
- }
16892
- const agent = env.npm_config_user_agent ?? "";
16893
- if (agent.startsWith("pnpm/"))
16894
- return `pnpm add -g ${target}`;
16895
- if (agent.startsWith("yarn/"))
16896
- return `yarn global add ${target}`;
16897
- if (agent.startsWith("bun/"))
16898
- return `bun add -g ${target}`;
16899
- return `npm install -g ${target}`;
16900
- }
16901
- async function announceUpdateIfAvailable(options = {}) {
16902
- try {
16903
- const env = options.env ?? process.env;
16904
- const isTty = options.isTty ?? process.stderr.isTTY === true;
16905
- const modulePath = options.modulePath ?? fileURLToPath(import.meta.url);
16906
- const cwd = options.cwd ?? process.cwd();
16907
- const now = options.now ?? new Date;
16908
- if (isEnabled(env.SIM_NO_UPDATE_CHECK))
16909
- return;
16910
- if (!isTty)
16911
- return;
16912
- if (CI_VARIABLES.some((variable) => isEnabled(env[variable])))
16913
- return;
16914
- if (isUnadvisableInstall(modulePath, env, cwd))
16915
- return;
16916
- const currentVersion = options.currentVersion ?? CLI_VERSION;
16917
- const current = parseStableVersion(currentVersion);
16918
- if (!current)
16919
- return;
16920
- const cachePath = updateCachePath();
16921
- const cached = readCache(cachePath);
16922
- if (cached && isFresh(cached, now))
16923
- return;
16924
- const tags = await fetchDistTags(env, options.registryRequest ?? requestRegistry);
16925
- const latest = tags?.latest ?? null;
16926
- const available = latest ? parseStableVersion(latest) : null;
16927
- writeCache(cachePath, {
16928
- version: CACHE_VERSION,
16929
- checkedAt: now.toISOString()
16930
- });
16931
- if (!latest || !available)
16932
- return;
16933
- if (!isNewerVersion(available, current))
16934
- return;
16935
- const write = options.write ?? ((message) => void process.stderr.write(message));
16936
- write(`Update available: sim ${currentVersion} → ${latest}. Run: ${upgradeCommand(modulePath, env)}
16937
- `);
16938
- } catch {}
16939
- }
16940
-
16941
16717
  // src/program.ts
16942
16718
  var PROGRAM_DESCRIPTION = "Talk to the Sim API from your terminal";
16943
16719
  var HELP_EPILOGUE = `
@@ -16974,75 +16750,77 @@ var ROOT_VALUE_FLAGS = new Set([
16974
16750
  function namesASubcommandFirst(rawArgs) {
16975
16751
  const tokens = rawArgs.slice(2);
16976
16752
  for (let index = 0;index < tokens.length; index += 1) {
16977
- const token = tokens[index];
16978
- if (token === "--version" || token === "-V")
16753
+ const token2 = tokens[index];
16754
+ if (token2 === "--version" || token2 === "-V")
16979
16755
  return false;
16980
- if (ROOT_VALUE_FLAGS.has(token)) {
16756
+ if (ROOT_VALUE_FLAGS.has(token2)) {
16981
16757
  index += 1;
16982
16758
  continue;
16983
16759
  }
16984
- if (token.startsWith("-"))
16760
+ if (token2.startsWith("-"))
16985
16761
  continue;
16986
16762
  return true;
16987
16763
  }
16988
16764
  return false;
16989
16765
  }
16990
- function addVersionOption(program) {
16991
- program.on("option:version", (value) => {
16766
+ function addVersionOption(program2) {
16767
+ program2.on("option:version", (value) => {
16992
16768
  if (value === null || value === undefined) {
16993
- const { rawArgs } = program;
16769
+ const { rawArgs } = program2;
16994
16770
  if (!namesASubcommandFirst(rawArgs ?? []))
16995
16771
  return;
16996
- program.error("error: --version reports the Sim CLI version and is not a command flag. A command that acts on a deployment version reads it from --to-version.");
16772
+ program2.error("error: --version reports the Sim CLI version and is not a command flag. A command that acts on a deployment version reads it from --to-version.");
16997
16773
  }
16998
- program.error("error: --version reports the Sim CLI version and takes no value. A command that acts on a deployment version reads it from --to-version.");
16774
+ program2.error("error: --version reports the Sim CLI version and takes no value. A command that acts on a deployment version reads it from --to-version.");
16999
16775
  });
17000
- program.version(CLI_VERSION, "-V, --version [none]", "output the version number (takes no value)");
16776
+ program2.version(cliVersion(), "-V, --version [none]", "output the version number (takes no value)");
17001
16777
  }
17002
16778
  function buildProgram(options = {}) {
17003
- const program = new Command;
17004
- program.name("sim").description(PROGRAM_DESCRIPTION);
16779
+ const program2 = options.program ?? new Command;
16780
+ program2.name("sim").description(PROGRAM_DESCRIPTION);
17005
16781
  if (options.version !== false)
17006
- addVersionOption(program);
17007
- program.option("-P, --profile <name>", "Profile to use (env: SIM_PROFILE)").option("--endpoint <url>", "Sim deployment to talk to (env: SIM_ENDPOINT)").option("-w, --workspace <id>", "Workspace to target (env: SIM_WORKSPACE)").addOption(new Option("--output <format>", "Output format for this command").choices([...OUTPUT_FORMATS]));
17008
- program.addCommand(loginCommand());
17009
- program.addCommand(logoutCommand());
17010
- program.addCommand(whoamiCommand());
17011
- program.addCommand(profilesCommand());
17012
- program.addCommand(configureCommand());
16782
+ addVersionOption(program2);
16783
+ program2.option("-P, --profile <name>", "Profile to use (env: SIM_PROFILE)").option("--endpoint <url>", "Sim deployment to talk to (env: SIM_ENDPOINT)").option("-w, --workspace <id>", "Workspace to target (env: SIM_WORKSPACE)").addOption(new Option("--output <format>", "Output format for this command").choices([...OUTPUT_FORMATS]));
16784
+ for (const command of [
16785
+ loginCommand,
16786
+ logoutCommand,
16787
+ whoamiCommand,
16788
+ profilesCommand,
16789
+ configureCommand
16790
+ ])
16791
+ program2.addCommand(command());
17013
16792
  for (const command of buildGeneratedCommands()) {
17014
- program.addCommand(command);
16793
+ program2.addCommand(command);
17015
16794
  }
17016
- attachCredentialCommands(program);
17017
- attachProtocolCommands(program);
17018
- attachSecretCommands(program);
17019
- program.addHelpText("after", HELP_EPILOGUE);
17020
- program.hook("preAction", () => announceUpdateIfAvailable());
17021
- refuseHelpAfterUnknownCommand(program);
17022
- assertNoReservedProgramFlags(program);
17023
- return program;
16795
+ attachCredentialCommands(program2);
16796
+ attachProtocolCommands(program2);
16797
+ attachSecretCommands(program2);
16798
+ program2.addHelpText("after", options.helpText ?? HELP_EPILOGUE);
16799
+ refuseHelpAfterUnknownCommand(program2);
16800
+ assertNoReservedProgramFlags(program2);
16801
+ return program2;
17024
16802
  }
17025
16803
 
17026
- // src/index.ts
17027
- async function main() {
16804
+ // src/terminal.ts
16805
+ async function runTerminalCli(program2 = buildProgram()) {
17028
16806
  try {
17029
- await buildProgram().parseAsync(process.argv);
16807
+ await program2.parseAsync(process.argv);
17030
16808
  } catch (error) {
17031
16809
  if (error instanceof ProfileConfigError) {
17032
- console.error(source_default.red(`Error: ${sanitize(error.message)}`));
16810
+ console.error(styles3().red(`Error: ${sanitize(error.message)}`));
17033
16811
  process.exit(1);
17034
16812
  }
17035
16813
  if (isRequestTimeout(error)) {
17036
- console.error(source_default.red(`Error: the request timed out. ${RAISE_TIMEOUT_HINT}`));
16814
+ console.error(styles3().red(`Error: the request timed out. ${RAISE_TIMEOUT_HINT}`));
17037
16815
  process.exit(1);
17038
16816
  }
17039
16817
  if (error instanceof SimApiError) {
17040
- console.error(source_default.red(`Error: ${sanitize(error.message)}`));
16818
+ console.error(styles3().red(`Error: ${sanitize(error.message)}`));
17041
16819
  if (error.code)
17042
- console.error(source_default.dim(` code: ${sanitize(error.code)}`));
16820
+ console.error(styles3().dim(` code: ${sanitize(error.code)}`));
17043
16821
  if (error.details !== undefined) {
17044
16822
  for (const line of formatApiErrorDetails(error.details)) {
17045
- console.error(source_default.dim(sanitize(line)));
16823
+ console.error(styles3().dim(sanitize(line)));
17046
16824
  }
17047
16825
  }
17048
16826
  process.exit(1);
@@ -17050,4 +16828,6 @@ async function main() {
17050
16828
  throw error;
17051
16829
  }
17052
16830
  }
17053
- main();
16831
+
16832
+ // src/index.ts
16833
+ runTerminalCli();