@aiaiai-pt/martha-cli 0.61.2 → 0.63.0

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 (3) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/index.js +757 -666
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,36 +1,44 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module";
3
- var __create = Object.create;
4
- var __getProtoOf = Object.getPrototypeOf;
5
3
  var __defProp = Object.defineProperty;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __toESM = (mod, isNodeMode, target) => {
9
- target = mod != null ? __create(__getProtoOf(mod)) : {};
10
- const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
11
- for (let key of __getOwnPropNames(mod))
12
- if (!__hasOwnProp.call(to, key))
13
- __defProp(to, key, {
14
- get: () => mod[key],
15
- enumerable: true
16
- });
17
- return to;
18
- };
19
4
  var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
5
+ var __returnValue = (v) => v;
6
+ function __exportSetter(name, newValue) {
7
+ this[name] = __returnValue.bind(null, newValue);
8
+ }
20
9
  var __export = (target, all) => {
21
10
  for (var name in all)
22
11
  __defProp(target, name, {
23
12
  get: all[name],
24
13
  enumerable: true,
25
14
  configurable: true,
26
- set: (newValue) => all[name] = () => newValue
15
+ set: __exportSetter.bind(all, name)
16
+ });
17
+ };
18
+ var __esm = (fn, res, err) => () => {
19
+ if (fn)
20
+ try {
21
+ res = fn(fn = 0);
22
+ } catch (e) {
23
+ err = [e];
24
+ }
25
+ if (err)
26
+ throw err[0];
27
+ return res;
28
+ };
29
+ var __exportCjs = (target, getters, setters) => {
30
+ for (var name in getters)
31
+ __defProp(target, name, {
32
+ get: getters[name],
33
+ set: setters[name],
34
+ enumerable: true,
35
+ configurable: true
27
36
  });
28
37
  };
29
- var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
30
38
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
31
39
 
32
40
  // node_modules/commander/lib/error.js
33
- var require_error = __commonJS((exports) => {
41
+ var require_error = __commonJS(function(exports) {
34
42
  class CommanderError extends Error {
35
43
  constructor(exitCode, code, message) {
36
44
  super(message);
@@ -54,7 +62,7 @@ var require_error = __commonJS((exports) => {
54
62
  });
55
63
 
56
64
  // node_modules/commander/lib/argument.js
57
- var require_argument = __commonJS((exports) => {
65
+ var require_argument = __commonJS(function(exports) {
58
66
  var { InvalidArgumentError } = require_error();
59
67
 
60
68
  class Argument {
@@ -134,7 +142,7 @@ var require_argument = __commonJS((exports) => {
134
142
  });
135
143
 
136
144
  // node_modules/commander/lib/help.js
137
- var require_help = __commonJS((exports) => {
145
+ var require_help = __commonJS(function(exports) {
138
146
  var { humanReadableArgName } = require_argument();
139
147
 
140
148
  class Help {
@@ -149,7 +157,7 @@ var require_help = __commonJS((exports) => {
149
157
  this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
150
158
  }
151
159
  visibleCommands(cmd) {
152
- const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
160
+ const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
153
161
  const helpCommand = cmd._getHelpCommand();
154
162
  if (helpCommand && !helpCommand._hidden) {
155
163
  visibleCommands.push(helpCommand);
@@ -491,7 +499,7 @@ ${itemIndentStr}`);
491
499
  });
492
500
 
493
501
  // node_modules/commander/lib/option.js
494
- var require_option = __commonJS((exports) => {
502
+ var require_option = __commonJS(function(exports) {
495
503
  var { InvalidArgumentError } = require_error();
496
504
 
497
505
  class Option {
@@ -629,8 +637,8 @@ var require_option = __commonJS((exports) => {
629
637
  }
630
638
  }
631
639
  function camelcase(str) {
632
- return str.split("-").reduce((str2, word) => {
633
- return str2 + word[0].toUpperCase() + word.slice(1);
640
+ return str.split("-").reduce((str, word) => {
641
+ return str + word[0].toUpperCase() + word.slice(1);
634
642
  });
635
643
  }
636
644
  function splitOptionFlags(flags) {
@@ -675,7 +683,7 @@ var require_option = __commonJS((exports) => {
675
683
  });
676
684
 
677
685
  // node_modules/commander/lib/suggestSimilar.js
678
- var require_suggestSimilar = __commonJS((exports) => {
686
+ var require_suggestSimilar = __commonJS(function(exports) {
679
687
  var maxDistance = 3;
680
688
  function editDistance(a, b) {
681
689
  if (Math.abs(a.length - b.length) > maxDistance)
@@ -748,7 +756,7 @@ var require_suggestSimilar = __commonJS((exports) => {
748
756
  });
749
757
 
750
758
  // node_modules/commander/lib/command.js
751
- var require_command = __commonJS((exports) => {
759
+ var require_command = __commonJS(function(exports) {
752
760
  var EventEmitter = __require("node:events").EventEmitter;
753
761
  var childProcess = __require("node:child_process");
754
762
  var path = __require("node:path");
@@ -1001,7 +1009,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
1001
1009
  this._exitCallback = (err) => {
1002
1010
  if (err.code !== "commander.executeSubCommandAsync") {
1003
1011
  throw err;
1004
- } else {}
1012
+ }
1005
1013
  };
1006
1014
  }
1007
1015
  return this;
@@ -1201,44 +1209,44 @@ Expecting one of '${allowedValues.join("', '")}'`);
1201
1209
  });
1202
1210
  return source;
1203
1211
  }
1204
- _prepareUserArgs(argv, parseOptions) {
1205
- if (argv !== undefined && !Array.isArray(argv)) {
1212
+ _prepareUserArgs(argv2, parseOptions) {
1213
+ if (argv2 !== undefined && !Array.isArray(argv2)) {
1206
1214
  throw new Error("first parameter to parse must be array or undefined");
1207
1215
  }
1208
1216
  parseOptions = parseOptions || {};
1209
- if (argv === undefined && parseOptions.from === undefined) {
1217
+ if (argv2 === undefined && parseOptions.from === undefined) {
1210
1218
  if (process2.versions?.electron) {
1211
1219
  parseOptions.from = "electron";
1212
1220
  }
1213
- const execArgv = process2.execArgv ?? [];
1214
- if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1221
+ const execArgv2 = process2.execArgv ?? [];
1222
+ if (execArgv2.includes("-e") || execArgv2.includes("--eval") || execArgv2.includes("-p") || execArgv2.includes("--print")) {
1215
1223
  parseOptions.from = "eval";
1216
1224
  }
1217
1225
  }
1218
- if (argv === undefined) {
1219
- argv = process2.argv;
1226
+ if (argv2 === undefined) {
1227
+ argv2 = process2.argv;
1220
1228
  }
1221
- this.rawArgs = argv.slice();
1229
+ this.rawArgs = argv2.slice();
1222
1230
  let userArgs;
1223
1231
  switch (parseOptions.from) {
1224
1232
  case undefined:
1225
1233
  case "node":
1226
- this._scriptPath = argv[1];
1227
- userArgs = argv.slice(2);
1234
+ this._scriptPath = argv2[1];
1235
+ userArgs = argv2.slice(2);
1228
1236
  break;
1229
1237
  case "electron":
1230
1238
  if (process2.defaultApp) {
1231
- this._scriptPath = argv[1];
1232
- userArgs = argv.slice(2);
1239
+ this._scriptPath = argv2[1];
1240
+ userArgs = argv2.slice(2);
1233
1241
  } else {
1234
- userArgs = argv.slice(1);
1242
+ userArgs = argv2.slice(1);
1235
1243
  }
1236
1244
  break;
1237
1245
  case "user":
1238
- userArgs = argv.slice(0);
1246
+ userArgs = argv2.slice(0);
1239
1247
  break;
1240
1248
  case "eval":
1241
- userArgs = argv.slice(1);
1249
+ userArgs = argv2.slice(1);
1242
1250
  break;
1243
1251
  default:
1244
1252
  throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
@@ -1761,18 +1769,18 @@ Expecting one of '${allowedValues.join("', '")}'`);
1761
1769
  this.error(message, { code: "commander.missingMandatoryOptionValue" });
1762
1770
  }
1763
1771
  _conflictingOption(option, conflictingOption) {
1764
- const findBestOptionFromValue = (option2) => {
1765
- const optionKey = option2.attributeName();
1772
+ const findBestOptionFromValue = (option) => {
1773
+ const optionKey = option.attributeName();
1766
1774
  const optionValue = this.getOptionValue(optionKey);
1767
1775
  const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
1768
1776
  const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
1769
1777
  if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
1770
1778
  return negativeOption;
1771
1779
  }
1772
- return positiveOption || option2;
1780
+ return positiveOption || option;
1773
1781
  };
1774
- const getErrorMessage = (option2) => {
1775
- const bestOption = findBestOptionFromValue(option2);
1782
+ const getErrorMessage = (option) => {
1783
+ const bestOption = findBestOptionFromValue(option);
1776
1784
  const optionKey = bestOption.attributeName();
1777
1785
  const source = this.getOptionValueSource(optionKey);
1778
1786
  if (source === "env") {
@@ -1926,10 +1934,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
1926
1934
  this._name = path.basename(filename, path.extname(filename));
1927
1935
  return this;
1928
1936
  }
1929
- executableDir(path2) {
1930
- if (path2 === undefined)
1937
+ executableDir(path) {
1938
+ if (path === undefined)
1931
1939
  return this._executableDir;
1932
- this._executableDir = path2;
1940
+ this._executableDir = path;
1933
1941
  return this;
1934
1942
  }
1935
1943
  helpInformation(contextOptions) {
@@ -2026,11 +2034,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
2026
2034
  }
2027
2035
  help(contextOptions) {
2028
2036
  this.outputHelp(contextOptions);
2029
- let exitCode = Number(process2.exitCode ?? 0);
2030
- if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2031
- exitCode = 1;
2037
+ let exitCode2 = Number(process2.exitCode ?? 0);
2038
+ if (exitCode2 === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2039
+ exitCode2 = 1;
2032
2040
  }
2033
- this._exit(exitCode, "commander.help", "(outputHelp)");
2041
+ this._exit(exitCode2, "commander.help", "(outputHelp)");
2034
2042
  }
2035
2043
  addHelpText(position, text) {
2036
2044
  const allowedValues = ["beforeAll", "before", "after", "afterAll"];
@@ -2102,26 +2110,6 @@ Expecting one of '${allowedValues.join("', '")}'`);
2102
2110
  exports.useColor = useColor;
2103
2111
  });
2104
2112
 
2105
- // node_modules/commander/index.js
2106
- var require_commander = __commonJS((exports) => {
2107
- var { Argument } = require_argument();
2108
- var { Command } = require_command();
2109
- var { CommanderError, InvalidArgumentError } = require_error();
2110
- var { Help } = require_help();
2111
- var { Option } = require_option();
2112
- exports.program = new Command;
2113
- exports.createCommand = (name) => new Command(name);
2114
- exports.createOption = (flags, description) => new Option(flags, description);
2115
- exports.createArgument = (name, description) => new Argument(name, description);
2116
- exports.Command = Command;
2117
- exports.Option = Option;
2118
- exports.Argument = Argument;
2119
- exports.Help = Help;
2120
- exports.CommanderError = CommanderError;
2121
- exports.InvalidArgumentError = InvalidArgumentError;
2122
- exports.InvalidOptionArgumentError = InvalidArgumentError;
2123
- });
2124
-
2125
2113
  // src/lib/errors.ts
2126
2114
  function extractDetail(body) {
2127
2115
  if (typeof body === "string")
@@ -2197,7 +2185,7 @@ var init_errors = __esm(() => {
2197
2185
  });
2198
2186
 
2199
2187
  // node_modules/yaml/dist/nodes/identity.js
2200
- var require_identity = __commonJS((exports) => {
2188
+ var require_identity = __commonJS(function(exports) {
2201
2189
  var ALIAS = Symbol.for("yaml.alias");
2202
2190
  var DOC = Symbol.for("yaml.document");
2203
2191
  var MAP = Symbol.for("yaml.map");
@@ -2251,7 +2239,7 @@ var require_identity = __commonJS((exports) => {
2251
2239
  });
2252
2240
 
2253
2241
  // node_modules/yaml/dist/visit.js
2254
- var require_visit = __commonJS((exports) => {
2242
+ var require_visit = __commonJS(function(exports) {
2255
2243
  var identity = require_identity();
2256
2244
  var BREAK = Symbol("break visit");
2257
2245
  var SKIP = Symbol("skip children");
@@ -2406,7 +2394,7 @@ var require_visit = __commonJS((exports) => {
2406
2394
  });
2407
2395
 
2408
2396
  // node_modules/yaml/dist/doc/directives.js
2409
- var require_directives = __commonJS((exports) => {
2397
+ var require_directives = __commonJS(function(exports) {
2410
2398
  var identity = require_identity();
2411
2399
  var visit = require_visit();
2412
2400
  var escapeChars = {
@@ -2558,7 +2546,7 @@ var require_directives = __commonJS((exports) => {
2558
2546
  });
2559
2547
 
2560
2548
  // node_modules/yaml/dist/doc/anchors.js
2561
- var require_anchors = __commonJS((exports) => {
2549
+ var require_anchors = __commonJS(function(exports) {
2562
2550
  var identity = require_identity();
2563
2551
  var visit = require_visit();
2564
2552
  function anchorIsValid(anchor) {
@@ -2620,7 +2608,7 @@ var require_anchors = __commonJS((exports) => {
2620
2608
  });
2621
2609
 
2622
2610
  // node_modules/yaml/dist/doc/applyReviver.js
2623
- var require_applyReviver = __commonJS((exports) => {
2611
+ var require_applyReviver = __commonJS(function(exports) {
2624
2612
  function applyReviver(reviver, obj, key, val) {
2625
2613
  if (val && typeof val === "object") {
2626
2614
  if (Array.isArray(val)) {
@@ -2667,7 +2655,7 @@ var require_applyReviver = __commonJS((exports) => {
2667
2655
  });
2668
2656
 
2669
2657
  // node_modules/yaml/dist/nodes/toJS.js
2670
- var require_toJS = __commonJS((exports) => {
2658
+ var require_toJS = __commonJS(function(exports) {
2671
2659
  var identity = require_identity();
2672
2660
  function toJS(value, arg, ctx) {
2673
2661
  if (Array.isArray(value))
@@ -2677,8 +2665,8 @@ var require_toJS = __commonJS((exports) => {
2677
2665
  return value.toJSON(arg, ctx);
2678
2666
  const data = { aliasCount: 0, count: 1, res: undefined };
2679
2667
  ctx.anchors.set(value, data);
2680
- ctx.onCreate = (res2) => {
2681
- data.res = res2;
2668
+ ctx.onCreate = (res) => {
2669
+ data.res = res;
2682
2670
  delete ctx.onCreate;
2683
2671
  };
2684
2672
  const res = value.toJSON(arg, ctx);
@@ -2694,7 +2682,7 @@ var require_toJS = __commonJS((exports) => {
2694
2682
  });
2695
2683
 
2696
2684
  // node_modules/yaml/dist/nodes/Node.js
2697
- var require_Node = __commonJS((exports) => {
2685
+ var require_Node = __commonJS(function(exports) {
2698
2686
  var applyReviver = require_applyReviver();
2699
2687
  var identity = require_identity();
2700
2688
  var toJS = require_toJS();
@@ -2722,8 +2710,8 @@ var require_Node = __commonJS((exports) => {
2722
2710
  };
2723
2711
  const res = toJS.toJS(this, "", ctx);
2724
2712
  if (typeof onAnchor === "function")
2725
- for (const { count, res: res2 } of ctx.anchors.values())
2726
- onAnchor(res2, count);
2713
+ for (const { count, res } of ctx.anchors.values())
2714
+ onAnchor(res, count);
2727
2715
  return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res;
2728
2716
  }
2729
2717
  }
@@ -2731,7 +2719,7 @@ var require_Node = __commonJS((exports) => {
2731
2719
  });
2732
2720
 
2733
2721
  // node_modules/yaml/dist/nodes/Alias.js
2734
- var require_Alias = __commonJS((exports) => {
2722
+ var require_Alias = __commonJS(function(exports) {
2735
2723
  var anchors = require_anchors();
2736
2724
  var visit = require_visit();
2737
2725
  var identity = require_identity();
@@ -2775,16 +2763,16 @@ var require_Alias = __commonJS((exports) => {
2775
2763
  toJSON(_arg, ctx) {
2776
2764
  if (!ctx)
2777
2765
  return { source: this.source };
2778
- const { anchors: anchors2, doc, maxAliasCount } = ctx;
2766
+ const { anchors, doc, maxAliasCount } = ctx;
2779
2767
  const source = this.resolve(doc, ctx);
2780
2768
  if (!source) {
2781
2769
  const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
2782
2770
  throw new ReferenceError(msg);
2783
2771
  }
2784
- let data = anchors2.get(source);
2772
+ let data = anchors.get(source);
2785
2773
  if (!data) {
2786
2774
  toJS.toJS(source, null, ctx);
2787
- data = anchors2.get(source);
2775
+ data = anchors.get(source);
2788
2776
  }
2789
2777
  if (data?.res === undefined) {
2790
2778
  const msg = "This should not happen: Alias anchor was not resolved?";
@@ -2793,7 +2781,7 @@ var require_Alias = __commonJS((exports) => {
2793
2781
  if (maxAliasCount >= 0) {
2794
2782
  data.count += 1;
2795
2783
  if (data.aliasCount === 0)
2796
- data.aliasCount = getAliasCount(doc, source, anchors2);
2784
+ data.aliasCount = getAliasCount(doc, source, anchors);
2797
2785
  if (data.count * data.aliasCount > maxAliasCount) {
2798
2786
  const msg = "Excessive alias count indicates a resource exhaustion attack";
2799
2787
  throw new ReferenceError(msg);
@@ -2815,22 +2803,22 @@ var require_Alias = __commonJS((exports) => {
2815
2803
  return src;
2816
2804
  }
2817
2805
  }
2818
- function getAliasCount(doc, node, anchors2) {
2806
+ function getAliasCount(doc, node, anchors) {
2819
2807
  if (identity.isAlias(node)) {
2820
2808
  const source = node.resolve(doc);
2821
- const anchor = anchors2 && source && anchors2.get(source);
2809
+ const anchor = anchors && source && anchors.get(source);
2822
2810
  return anchor ? anchor.count * anchor.aliasCount : 0;
2823
2811
  } else if (identity.isCollection(node)) {
2824
2812
  let count = 0;
2825
2813
  for (const item of node.items) {
2826
- const c = getAliasCount(doc, item, anchors2);
2814
+ const c = getAliasCount(doc, item, anchors);
2827
2815
  if (c > count)
2828
2816
  count = c;
2829
2817
  }
2830
2818
  return count;
2831
2819
  } else if (identity.isPair(node)) {
2832
- const kc = getAliasCount(doc, node.key, anchors2);
2833
- const vc = getAliasCount(doc, node.value, anchors2);
2820
+ const kc = getAliasCount(doc, node.key, anchors);
2821
+ const vc = getAliasCount(doc, node.value, anchors);
2834
2822
  return Math.max(kc, vc);
2835
2823
  }
2836
2824
  return 1;
@@ -2839,7 +2827,7 @@ var require_Alias = __commonJS((exports) => {
2839
2827
  });
2840
2828
 
2841
2829
  // node_modules/yaml/dist/nodes/Scalar.js
2842
- var require_Scalar = __commonJS((exports) => {
2830
+ var require_Scalar = __commonJS(function(exports) {
2843
2831
  var identity = require_identity();
2844
2832
  var Node = require_Node();
2845
2833
  var toJS = require_toJS();
@@ -2867,7 +2855,7 @@ var require_Scalar = __commonJS((exports) => {
2867
2855
  });
2868
2856
 
2869
2857
  // node_modules/yaml/dist/doc/createNode.js
2870
- var require_createNode = __commonJS((exports) => {
2858
+ var require_createNode = __commonJS(function(exports) {
2871
2859
  var Alias = require_Alias();
2872
2860
  var identity = require_identity();
2873
2861
  var Scalar = require_Scalar();
@@ -2915,10 +2903,10 @@ var require_createNode = __commonJS((exports) => {
2915
2903
  value = value.toJSON();
2916
2904
  }
2917
2905
  if (!value || typeof value !== "object") {
2918
- const node2 = new Scalar.Scalar(value);
2906
+ const node = new Scalar.Scalar(value);
2919
2907
  if (ref)
2920
- ref.node = node2;
2921
- return node2;
2908
+ ref.node = node;
2909
+ return node;
2922
2910
  }
2923
2911
  tagObj = value instanceof Map ? schema[identity.MAP] : (Symbol.iterator in Object(value)) ? schema[identity.SEQ] : schema[identity.MAP];
2924
2912
  }
@@ -2939,7 +2927,7 @@ var require_createNode = __commonJS((exports) => {
2939
2927
  });
2940
2928
 
2941
2929
  // node_modules/yaml/dist/nodes/Collection.js
2942
- var require_Collection = __commonJS((exports) => {
2930
+ var require_Collection = __commonJS(function(exports) {
2943
2931
  var createNode = require_createNode();
2944
2932
  var identity = require_identity();
2945
2933
  var Node = require_Node();
@@ -3054,7 +3042,7 @@ var require_Collection = __commonJS((exports) => {
3054
3042
  });
3055
3043
 
3056
3044
  // node_modules/yaml/dist/stringify/stringifyComment.js
3057
- var require_stringifyComment = __commonJS((exports) => {
3045
+ var require_stringifyComment = __commonJS(function(exports) {
3058
3046
  var stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, "#");
3059
3047
  function indentComment(comment, indent) {
3060
3048
  if (/^\n+$/.test(comment))
@@ -3071,7 +3059,7 @@ var require_stringifyComment = __commonJS((exports) => {
3071
3059
  });
3072
3060
 
3073
3061
  // node_modules/yaml/dist/stringify/foldFlowLines.js
3074
- var require_foldFlowLines = __commonJS((exports) => {
3062
+ var require_foldFlowLines = __commonJS(function(exports) {
3075
3063
  var FOLD_FLOW = "flow";
3076
3064
  var FOLD_BLOCK = "block";
3077
3065
  var FOLD_QUOTED = "quoted";
@@ -3167,17 +3155,17 @@ var require_foldFlowLines = __commonJS((exports) => {
3167
3155
  if (onFold)
3168
3156
  onFold();
3169
3157
  let res = text.slice(0, folds[0]);
3170
- for (let i2 = 0;i2 < folds.length; ++i2) {
3171
- const fold = folds[i2];
3172
- const end2 = folds[i2 + 1] || text.length;
3158
+ for (let i = 0;i < folds.length; ++i) {
3159
+ const fold = folds[i];
3160
+ const end = folds[i + 1] || text.length;
3173
3161
  if (fold === 0)
3174
3162
  res = `
3175
- ${indent}${text.slice(0, end2)}`;
3163
+ ${indent}${text.slice(0, end)}`;
3176
3164
  else {
3177
3165
  if (mode === FOLD_QUOTED && escapedFolds[fold])
3178
3166
  res += `${text[fold]}\\`;
3179
3167
  res += `
3180
- ${indent}${text.slice(fold + 1, end2)}`;
3168
+ ${indent}${text.slice(fold + 1, end)}`;
3181
3169
  }
3182
3170
  }
3183
3171
  return res;
@@ -3208,7 +3196,7 @@ ${indent}${text.slice(fold + 1, end2)}`;
3208
3196
  });
3209
3197
 
3210
3198
  // node_modules/yaml/dist/stringify/stringifyString.js
3211
- var require_stringifyString = __commonJS((exports) => {
3199
+ var require_stringifyString = __commonJS(function(exports) {
3212
3200
  var Scalar = require_Scalar();
3213
3201
  var foldFlowLines = require_foldFlowLines();
3214
3202
  var getFoldOptions = (ctx, isBlock) => ({
@@ -3506,7 +3494,7 @@ ${indent}`);
3506
3494
  });
3507
3495
 
3508
3496
  // node_modules/yaml/dist/stringify/stringify.js
3509
- var require_stringify = __commonJS((exports) => {
3497
+ var require_stringify = __commonJS(function(exports) {
3510
3498
  var anchors = require_anchors();
3511
3499
  var identity = require_identity();
3512
3500
  var stringifyComment = require_stringifyComment();
@@ -3626,7 +3614,7 @@ ${ctx.indent}${str}`;
3626
3614
  });
3627
3615
 
3628
3616
  // node_modules/yaml/dist/stringify/stringifyPair.js
3629
- var require_stringifyPair = __commonJS((exports) => {
3617
+ var require_stringifyPair = __commonJS(function(exports) {
3630
3618
  var identity = require_identity();
3631
3619
  var Scalar = require_Scalar();
3632
3620
  var stringify = require_stringify();
@@ -3762,7 +3750,7 @@ ${ctx.indent}`;
3762
3750
  });
3763
3751
 
3764
3752
  // node_modules/yaml/dist/log.js
3765
- var require_log = __commonJS((exports) => {
3753
+ var require_log = __commonJS(function(exports) {
3766
3754
  var node_process = __require("process");
3767
3755
  function debug(logLevel, ...messages) {
3768
3756
  if (logLevel === "debug")
@@ -3781,7 +3769,7 @@ var require_log = __commonJS((exports) => {
3781
3769
  });
3782
3770
 
3783
3771
  // node_modules/yaml/dist/schema/yaml-1.1/merge.js
3784
- var require_merge = __commonJS((exports) => {
3772
+ var require_merge = __commonJS(function(exports) {
3785
3773
  var identity = require_identity();
3786
3774
  var Scalar = require_Scalar();
3787
3775
  var MERGE_KEY = "<<";
@@ -3812,15 +3800,15 @@ var require_merge = __commonJS((exports) => {
3812
3800
  if (!identity.isMap(source))
3813
3801
  throw new Error("Merge sources must be maps or map aliases");
3814
3802
  const srcMap = source.toJSON(null, ctx, Map);
3815
- for (const [key, value2] of srcMap) {
3803
+ for (const [key, value] of srcMap) {
3816
3804
  if (map instanceof Map) {
3817
3805
  if (!map.has(key))
3818
- map.set(key, value2);
3806
+ map.set(key, value);
3819
3807
  } else if (map instanceof Set) {
3820
3808
  map.add(key);
3821
3809
  } else if (!Object.prototype.hasOwnProperty.call(map, key)) {
3822
3810
  Object.defineProperty(map, key, {
3823
- value: value2,
3811
+ value,
3824
3812
  writable: true,
3825
3813
  enumerable: true,
3826
3814
  configurable: true
@@ -3835,7 +3823,7 @@ var require_merge = __commonJS((exports) => {
3835
3823
  });
3836
3824
 
3837
3825
  // node_modules/yaml/dist/nodes/addPairToJSMap.js
3838
- var require_addPairToJSMap = __commonJS((exports) => {
3826
+ var require_addPairToJSMap = __commonJS(function(exports) {
3839
3827
  var log = require_log();
3840
3828
  var merge = require_merge();
3841
3829
  var stringify = require_stringify();
@@ -3896,7 +3884,7 @@ var require_addPairToJSMap = __commonJS((exports) => {
3896
3884
  });
3897
3885
 
3898
3886
  // node_modules/yaml/dist/nodes/Pair.js
3899
- var require_Pair = __commonJS((exports) => {
3887
+ var require_Pair = __commonJS(function(exports) {
3900
3888
  var createNode = require_createNode();
3901
3889
  var stringifyPair = require_stringifyPair();
3902
3890
  var addPairToJSMap = require_addPairToJSMap();
@@ -3934,14 +3922,14 @@ var require_Pair = __commonJS((exports) => {
3934
3922
  });
3935
3923
 
3936
3924
  // node_modules/yaml/dist/stringify/stringifyCollection.js
3937
- var require_stringifyCollection = __commonJS((exports) => {
3925
+ var require_stringifyCollection = __commonJS(function(exports) {
3938
3926
  var identity = require_identity();
3939
3927
  var stringify = require_stringify();
3940
3928
  var stringifyComment = require_stringifyComment();
3941
3929
  function stringifyCollection(collection, ctx, options) {
3942
3930
  const flow = ctx.inFlow ?? collection.flow;
3943
- const stringify2 = flow ? stringifyFlowCollection : stringifyBlockCollection;
3944
- return stringify2(collection, ctx, options);
3931
+ const stringify = flow ? stringifyFlowCollection : stringifyBlockCollection;
3932
+ return stringify(collection, ctx, options);
3945
3933
  }
3946
3934
  function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {
3947
3935
  const { indent, options: { commentString } } = ctx;
@@ -3950,13 +3938,13 @@ var require_stringifyCollection = __commonJS((exports) => {
3950
3938
  const lines = [];
3951
3939
  for (let i = 0;i < items.length; ++i) {
3952
3940
  const item = items[i];
3953
- let comment2 = null;
3941
+ let comment = null;
3954
3942
  if (identity.isNode(item)) {
3955
3943
  if (!chompKeep && item.spaceBefore)
3956
3944
  lines.push("");
3957
3945
  addCommentBefore(ctx, lines, item.commentBefore, chompKeep);
3958
3946
  if (item.comment)
3959
- comment2 = item.comment;
3947
+ comment = item.comment;
3960
3948
  } else if (identity.isPair(item)) {
3961
3949
  const ik = identity.isNode(item.key) ? item.key : null;
3962
3950
  if (ik) {
@@ -3966,12 +3954,12 @@ var require_stringifyCollection = __commonJS((exports) => {
3966
3954
  }
3967
3955
  }
3968
3956
  chompKeep = false;
3969
- let str2 = stringify.stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true);
3970
- if (comment2)
3971
- str2 += stringifyComment.lineComment(str2, itemIndent, commentString(comment2));
3972
- if (chompKeep && comment2)
3957
+ let str = stringify.stringify(item, itemCtx, () => comment = null, () => chompKeep = true);
3958
+ if (comment)
3959
+ str += stringifyComment.lineComment(str, itemIndent, commentString(comment));
3960
+ if (chompKeep && comment)
3973
3961
  chompKeep = false;
3974
- lines.push(blockItemPrefix + str2);
3962
+ lines.push(blockItemPrefix + str);
3975
3963
  }
3976
3964
  let str;
3977
3965
  if (lines.length === 0) {
@@ -4079,7 +4067,7 @@ ${indent}${end}`;
4079
4067
  });
4080
4068
 
4081
4069
  // node_modules/yaml/dist/nodes/YAMLMap.js
4082
- var require_YAMLMap = __commonJS((exports) => {
4070
+ var require_YAMLMap = __commonJS(function(exports) {
4083
4071
  var stringifyCollection = require_stringifyCollection();
4084
4072
  var addPairToJSMap = require_addPairToJSMap();
4085
4073
  var Collection = require_Collection();
@@ -4206,7 +4194,7 @@ var require_YAMLMap = __commonJS((exports) => {
4206
4194
  });
4207
4195
 
4208
4196
  // node_modules/yaml/dist/schema/common/map.js
4209
- var require_map = __commonJS((exports) => {
4197
+ var require_map = __commonJS(function(exports) {
4210
4198
  var identity = require_identity();
4211
4199
  var YAMLMap = require_YAMLMap();
4212
4200
  var map = {
@@ -4214,10 +4202,10 @@ var require_map = __commonJS((exports) => {
4214
4202
  default: true,
4215
4203
  nodeClass: YAMLMap.YAMLMap,
4216
4204
  tag: "tag:yaml.org,2002:map",
4217
- resolve(map2, onError) {
4218
- if (!identity.isMap(map2))
4205
+ resolve(map, onError) {
4206
+ if (!identity.isMap(map))
4219
4207
  onError("Expected a mapping for this tag");
4220
- return map2;
4208
+ return map;
4221
4209
  },
4222
4210
  createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx)
4223
4211
  };
@@ -4225,7 +4213,7 @@ var require_map = __commonJS((exports) => {
4225
4213
  });
4226
4214
 
4227
4215
  // node_modules/yaml/dist/nodes/YAMLSeq.js
4228
- var require_YAMLSeq = __commonJS((exports) => {
4216
+ var require_YAMLSeq = __commonJS(function(exports) {
4229
4217
  var createNode = require_createNode();
4230
4218
  var stringifyCollection = require_stringifyCollection();
4231
4219
  var Collection = require_Collection();
@@ -4318,7 +4306,7 @@ var require_YAMLSeq = __commonJS((exports) => {
4318
4306
  });
4319
4307
 
4320
4308
  // node_modules/yaml/dist/schema/common/seq.js
4321
- var require_seq = __commonJS((exports) => {
4309
+ var require_seq = __commonJS(function(exports) {
4322
4310
  var identity = require_identity();
4323
4311
  var YAMLSeq = require_YAMLSeq();
4324
4312
  var seq = {
@@ -4326,10 +4314,10 @@ var require_seq = __commonJS((exports) => {
4326
4314
  default: true,
4327
4315
  nodeClass: YAMLSeq.YAMLSeq,
4328
4316
  tag: "tag:yaml.org,2002:seq",
4329
- resolve(seq2, onError) {
4330
- if (!identity.isSeq(seq2))
4317
+ resolve(seq, onError) {
4318
+ if (!identity.isSeq(seq))
4331
4319
  onError("Expected a sequence for this tag");
4332
- return seq2;
4320
+ return seq;
4333
4321
  },
4334
4322
  createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx)
4335
4323
  };
@@ -4337,7 +4325,7 @@ var require_seq = __commonJS((exports) => {
4337
4325
  });
4338
4326
 
4339
4327
  // node_modules/yaml/dist/schema/common/string.js
4340
- var require_string = __commonJS((exports) => {
4328
+ var require_string = __commonJS(function(exports) {
4341
4329
  var stringifyString = require_stringifyString();
4342
4330
  var string = {
4343
4331
  identify: (value) => typeof value === "string",
@@ -4353,7 +4341,7 @@ var require_string = __commonJS((exports) => {
4353
4341
  });
4354
4342
 
4355
4343
  // node_modules/yaml/dist/schema/common/null.js
4356
- var require_null = __commonJS((exports) => {
4344
+ var require_null = __commonJS(function(exports) {
4357
4345
  var Scalar = require_Scalar();
4358
4346
  var nullTag = {
4359
4347
  identify: (value) => value == null,
@@ -4368,7 +4356,7 @@ var require_null = __commonJS((exports) => {
4368
4356
  });
4369
4357
 
4370
4358
  // node_modules/yaml/dist/schema/core/bool.js
4371
- var require_bool = __commonJS((exports) => {
4359
+ var require_bool = __commonJS(function(exports) {
4372
4360
  var Scalar = require_Scalar();
4373
4361
  var boolTag = {
4374
4362
  identify: (value) => typeof value === "boolean",
@@ -4389,7 +4377,7 @@ var require_bool = __commonJS((exports) => {
4389
4377
  });
4390
4378
 
4391
4379
  // node_modules/yaml/dist/stringify/stringifyNumber.js
4392
- var require_stringifyNumber = __commonJS((exports) => {
4380
+ var require_stringifyNumber = __commonJS(function(exports) {
4393
4381
  function stringifyNumber({ format, minFractionDigits, tag, value }) {
4394
4382
  if (typeof value === "bigint")
4395
4383
  return String(value);
@@ -4413,7 +4401,7 @@ var require_stringifyNumber = __commonJS((exports) => {
4413
4401
  });
4414
4402
 
4415
4403
  // node_modules/yaml/dist/schema/core/float.js
4416
- var require_float = __commonJS((exports) => {
4404
+ var require_float = __commonJS(function(exports) {
4417
4405
  var Scalar = require_Scalar();
4418
4406
  var stringifyNumber = require_stringifyNumber();
4419
4407
  var floatNaN = {
@@ -4456,7 +4444,7 @@ var require_float = __commonJS((exports) => {
4456
4444
  });
4457
4445
 
4458
4446
  // node_modules/yaml/dist/schema/core/int.js
4459
- var require_int = __commonJS((exports) => {
4447
+ var require_int = __commonJS(function(exports) {
4460
4448
  var stringifyNumber = require_stringifyNumber();
4461
4449
  var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value);
4462
4450
  var intResolve = (str, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix);
@@ -4498,7 +4486,7 @@ var require_int = __commonJS((exports) => {
4498
4486
  });
4499
4487
 
4500
4488
  // node_modules/yaml/dist/schema/core/schema.js
4501
- var require_schema = __commonJS((exports) => {
4489
+ var require_schema = __commonJS(function(exports) {
4502
4490
  var map = require_map();
4503
4491
  var _null = require_null();
4504
4492
  var seq = require_seq();
@@ -4523,7 +4511,7 @@ var require_schema = __commonJS((exports) => {
4523
4511
  });
4524
4512
 
4525
4513
  // node_modules/yaml/dist/schema/json/schema.js
4526
- var require_schema2 = __commonJS((exports) => {
4514
+ var require_schema2 = __commonJS(function(exports) {
4527
4515
  var Scalar = require_Scalar();
4528
4516
  var map = require_map();
4529
4517
  var seq = require_seq();
@@ -4587,7 +4575,7 @@ var require_schema2 = __commonJS((exports) => {
4587
4575
  });
4588
4576
 
4589
4577
  // node_modules/yaml/dist/schema/yaml-1.1/binary.js
4590
- var require_binary = __commonJS((exports) => {
4578
+ var require_binary = __commonJS(function(exports) {
4591
4579
  var node_buffer = __require("buffer");
4592
4580
  var Scalar = require_Scalar();
4593
4581
  var stringifyString = require_stringifyString();
@@ -4642,7 +4630,7 @@ var require_binary = __commonJS((exports) => {
4642
4630
  });
4643
4631
 
4644
4632
  // node_modules/yaml/dist/schema/yaml-1.1/pairs.js
4645
- var require_pairs = __commonJS((exports) => {
4633
+ var require_pairs = __commonJS(function(exports) {
4646
4634
  var identity = require_identity();
4647
4635
  var Pair = require_Pair();
4648
4636
  var Scalar = require_Scalar();
@@ -4675,8 +4663,8 @@ ${cn.comment}` : item.comment;
4675
4663
  }
4676
4664
  function createPairs(schema, iterable, ctx) {
4677
4665
  const { replacer } = ctx;
4678
- const pairs2 = new YAMLSeq.YAMLSeq(schema);
4679
- pairs2.tag = "tag:yaml.org,2002:pairs";
4666
+ const pairs = new YAMLSeq.YAMLSeq(schema);
4667
+ pairs.tag = "tag:yaml.org,2002:pairs";
4680
4668
  let i = 0;
4681
4669
  if (iterable && Symbol.iterator in Object(iterable))
4682
4670
  for (let it of iterable) {
@@ -4700,9 +4688,9 @@ ${cn.comment}` : item.comment;
4700
4688
  } else {
4701
4689
  key = it;
4702
4690
  }
4703
- pairs2.items.push(Pair.createPair(key, value, ctx));
4691
+ pairs.items.push(Pair.createPair(key, value, ctx));
4704
4692
  }
4705
- return pairs2;
4693
+ return pairs;
4706
4694
  }
4707
4695
  var pairs = {
4708
4696
  collection: "seq",
@@ -4717,7 +4705,7 @@ ${cn.comment}` : item.comment;
4717
4705
  });
4718
4706
 
4719
4707
  // node_modules/yaml/dist/schema/yaml-1.1/omap.js
4720
- var require_omap = __commonJS((exports) => {
4708
+ var require_omap = __commonJS(function(exports) {
4721
4709
  var identity = require_identity();
4722
4710
  var toJS = require_toJS();
4723
4711
  var YAMLMap = require_YAMLMap();
@@ -4756,9 +4744,9 @@ var require_omap = __commonJS((exports) => {
4756
4744
  }
4757
4745
  static from(schema, iterable, ctx) {
4758
4746
  const pairs$1 = pairs.createPairs(schema, iterable, ctx);
4759
- const omap2 = new this;
4760
- omap2.items = pairs$1.items;
4761
- return omap2;
4747
+ const omap = new this;
4748
+ omap.items = pairs$1.items;
4749
+ return omap;
4762
4750
  }
4763
4751
  }
4764
4752
  YAMLOMap.tag = "tag:yaml.org,2002:omap";
@@ -4789,7 +4777,7 @@ var require_omap = __commonJS((exports) => {
4789
4777
  });
4790
4778
 
4791
4779
  // node_modules/yaml/dist/schema/yaml-1.1/bool.js
4792
- var require_bool2 = __commonJS((exports) => {
4780
+ var require_bool2 = __commonJS(function(exports) {
4793
4781
  var Scalar = require_Scalar();
4794
4782
  function boolStringify({ value, source }, ctx) {
4795
4783
  const boolObj = value ? trueTag : falseTag;
@@ -4818,7 +4806,7 @@ var require_bool2 = __commonJS((exports) => {
4818
4806
  });
4819
4807
 
4820
4808
  // node_modules/yaml/dist/schema/yaml-1.1/float.js
4821
- var require_float2 = __commonJS((exports) => {
4809
+ var require_float2 = __commonJS(function(exports) {
4822
4810
  var Scalar = require_Scalar();
4823
4811
  var stringifyNumber = require_stringifyNumber();
4824
4812
  var floatNaN = {
@@ -4864,7 +4852,7 @@ var require_float2 = __commonJS((exports) => {
4864
4852
  });
4865
4853
 
4866
4854
  // node_modules/yaml/dist/schema/yaml-1.1/int.js
4867
- var require_int2 = __commonJS((exports) => {
4855
+ var require_int2 = __commonJS(function(exports) {
4868
4856
  var stringifyNumber = require_stringifyNumber();
4869
4857
  var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value);
4870
4858
  function intResolve(str, offset, radix, { intAsBigInt }) {
@@ -4884,8 +4872,8 @@ var require_int2 = __commonJS((exports) => {
4884
4872
  str = `0x${str}`;
4885
4873
  break;
4886
4874
  }
4887
- const n2 = BigInt(str);
4888
- return sign === "-" ? BigInt(-1) * n2 : n2;
4875
+ const n = BigInt(str);
4876
+ return sign === "-" ? BigInt(-1) * n : n;
4889
4877
  }
4890
4878
  const n = parseInt(str, radix);
4891
4879
  return sign === "-" ? -1 * n : n;
@@ -4940,7 +4928,7 @@ var require_int2 = __commonJS((exports) => {
4940
4928
  });
4941
4929
 
4942
4930
  // node_modules/yaml/dist/schema/yaml-1.1/set.js
4943
- var require_set = __commonJS((exports) => {
4931
+ var require_set = __commonJS(function(exports) {
4944
4932
  var identity = require_identity();
4945
4933
  var Pair = require_Pair();
4946
4934
  var YAMLMap = require_YAMLMap();
@@ -4989,14 +4977,14 @@ var require_set = __commonJS((exports) => {
4989
4977
  }
4990
4978
  static from(schema, iterable, ctx) {
4991
4979
  const { replacer } = ctx;
4992
- const set2 = new this(schema);
4980
+ const set = new this(schema);
4993
4981
  if (iterable && Symbol.iterator in Object(iterable))
4994
4982
  for (let value of iterable) {
4995
4983
  if (typeof replacer === "function")
4996
4984
  value = replacer.call(iterable, value, value);
4997
- set2.items.push(Pair.createPair(value, null, ctx));
4985
+ set.items.push(Pair.createPair(value, null, ctx));
4998
4986
  }
4999
- return set2;
4987
+ return set;
5000
4988
  }
5001
4989
  }
5002
4990
  YAMLSet.tag = "tag:yaml.org,2002:set";
@@ -5023,13 +5011,13 @@ var require_set = __commonJS((exports) => {
5023
5011
  });
5024
5012
 
5025
5013
  // node_modules/yaml/dist/schema/yaml-1.1/timestamp.js
5026
- var require_timestamp = __commonJS((exports) => {
5014
+ var require_timestamp = __commonJS(function(exports) {
5027
5015
  var stringifyNumber = require_stringifyNumber();
5028
5016
  function parseSexagesimal(str, asBigInt) {
5029
5017
  const sign = str[0];
5030
5018
  const parts = sign === "-" || sign === "+" ? str.substring(1) : str;
5031
5019
  const num = (n) => asBigInt ? BigInt(n) : Number(n);
5032
- const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num(60) + num(p), num(0));
5020
+ const res = parts.replace(/_/g, "").split(":").reduce((res, p) => res * num(60) + num(p), num(0));
5033
5021
  return sign === "-" ? num(-1) * res : res;
5034
5022
  }
5035
5023
  function stringifySexagesimal(node) {
@@ -5105,7 +5093,7 @@ var require_timestamp = __commonJS((exports) => {
5105
5093
  });
5106
5094
 
5107
5095
  // node_modules/yaml/dist/schema/yaml-1.1/schema.js
5108
- var require_schema3 = __commonJS((exports) => {
5096
+ var require_schema3 = __commonJS(function(exports) {
5109
5097
  var map = require_map();
5110
5098
  var _null = require_null();
5111
5099
  var seq = require_seq();
@@ -5146,7 +5134,7 @@ var require_schema3 = __commonJS((exports) => {
5146
5134
  });
5147
5135
 
5148
5136
  // node_modules/yaml/dist/schema/tags.js
5149
- var require_tags = __commonJS((exports) => {
5137
+ var require_tags = __commonJS(function(exports) {
5150
5138
  var map = require_map();
5151
5139
  var _null = require_null();
5152
5140
  var seq = require_seq();
@@ -5220,16 +5208,16 @@ var require_tags = __commonJS((exports) => {
5220
5208
  }
5221
5209
  if (addMergeTag)
5222
5210
  tags = tags.concat(merge.merge);
5223
- return tags.reduce((tags2, tag) => {
5211
+ return tags.reduce((tags, tag) => {
5224
5212
  const tagObj = typeof tag === "string" ? tagsByName[tag] : tag;
5225
5213
  if (!tagObj) {
5226
5214
  const tagName = JSON.stringify(tag);
5227
5215
  const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", ");
5228
5216
  throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`);
5229
5217
  }
5230
- if (!tags2.includes(tagObj))
5231
- tags2.push(tagObj);
5232
- return tags2;
5218
+ if (!tags.includes(tagObj))
5219
+ tags.push(tagObj);
5220
+ return tags;
5233
5221
  }, []);
5234
5222
  }
5235
5223
  exports.coreKnownTags = coreKnownTags;
@@ -5237,7 +5225,7 @@ var require_tags = __commonJS((exports) => {
5237
5225
  });
5238
5226
 
5239
5227
  // node_modules/yaml/dist/schema/Schema.js
5240
- var require_Schema = __commonJS((exports) => {
5228
+ var require_Schema = __commonJS(function(exports) {
5241
5229
  var identity = require_identity();
5242
5230
  var map = require_map();
5243
5231
  var seq = require_seq();
@@ -5267,7 +5255,7 @@ var require_Schema = __commonJS((exports) => {
5267
5255
  });
5268
5256
 
5269
5257
  // node_modules/yaml/dist/stringify/stringifyDocument.js
5270
- var require_stringifyDocument = __commonJS((exports) => {
5258
+ var require_stringifyDocument = __commonJS(function(exports) {
5271
5259
  var identity = require_identity();
5272
5260
  var stringify = require_stringify();
5273
5261
  var stringifyComment = require_stringifyComment();
@@ -5347,7 +5335,7 @@ var require_stringifyDocument = __commonJS((exports) => {
5347
5335
  });
5348
5336
 
5349
5337
  // node_modules/yaml/dist/doc/Document.js
5350
- var require_Document = __commonJS((exports) => {
5338
+ var require_Document = __commonJS(function(exports) {
5351
5339
  var Alias = require_Alias();
5352
5340
  var Collection = require_Collection();
5353
5341
  var identity = require_identity();
@@ -5556,8 +5544,8 @@ var require_Document = __commonJS((exports) => {
5556
5544
  };
5557
5545
  const res = toJS.toJS(this.contents, jsonArg ?? "", ctx);
5558
5546
  if (typeof onAnchor === "function")
5559
- for (const { count, res: res2 } of ctx.anchors.values())
5560
- onAnchor(res2, count);
5547
+ for (const { count, res } of ctx.anchors.values())
5548
+ onAnchor(res, count);
5561
5549
  return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res;
5562
5550
  }
5563
5551
  toJSON(jsonArg, onAnchor) {
@@ -5582,7 +5570,7 @@ var require_Document = __commonJS((exports) => {
5582
5570
  });
5583
5571
 
5584
5572
  // node_modules/yaml/dist/errors.js
5585
- var require_errors = __commonJS((exports) => {
5573
+ var require_errors = __commonJS(function(exports) {
5586
5574
  class YAMLError extends Error {
5587
5575
  constructor(name, pos, code, message) {
5588
5576
  super();
@@ -5647,7 +5635,7 @@ ${pointer}
5647
5635
  });
5648
5636
 
5649
5637
  // node_modules/yaml/dist/compose/resolve-props.js
5650
- var require_resolve_props = __commonJS((exports) => {
5638
+ var require_resolve_props = __commonJS(function(exports) {
5651
5639
  function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) {
5652
5640
  let spaceBefore = false;
5653
5641
  let atNewline = startOnNewline;
@@ -5777,7 +5765,7 @@ var require_resolve_props = __commonJS((exports) => {
5777
5765
  });
5778
5766
 
5779
5767
  // node_modules/yaml/dist/compose/util-contains-newline.js
5780
- var require_util_contains_newline = __commonJS((exports) => {
5768
+ var require_util_contains_newline = __commonJS(function(exports) {
5781
5769
  function containsNewline(key) {
5782
5770
  if (!key)
5783
5771
  return null;
@@ -5817,7 +5805,7 @@ var require_util_contains_newline = __commonJS((exports) => {
5817
5805
  });
5818
5806
 
5819
5807
  // node_modules/yaml/dist/compose/util-flow-indent-check.js
5820
- var require_util_flow_indent_check = __commonJS((exports) => {
5808
+ var require_util_flow_indent_check = __commonJS(function(exports) {
5821
5809
  var utilContainsNewline = require_util_contains_newline();
5822
5810
  function flowIndentCheck(indent, fc, onError) {
5823
5811
  if (fc?.type === "flow-collection") {
@@ -5832,7 +5820,7 @@ var require_util_flow_indent_check = __commonJS((exports) => {
5832
5820
  });
5833
5821
 
5834
5822
  // node_modules/yaml/dist/compose/util-map-includes.js
5835
- var require_util_map_includes = __commonJS((exports) => {
5823
+ var require_util_map_includes = __commonJS(function(exports) {
5836
5824
  var identity = require_identity();
5837
5825
  function mapIncludes(ctx, items, search) {
5838
5826
  const { uniqueKeys } = ctx.options;
@@ -5845,7 +5833,7 @@ var require_util_map_includes = __commonJS((exports) => {
5845
5833
  });
5846
5834
 
5847
5835
  // node_modules/yaml/dist/compose/resolve-block-map.js
5848
- var require_resolve_block_map = __commonJS((exports) => {
5836
+ var require_resolve_block_map = __commonJS(function(exports) {
5849
5837
  var Pair = require_Pair();
5850
5838
  var YAMLMap = require_YAMLMap();
5851
5839
  var resolveProps = require_resolve_props();
@@ -5952,7 +5940,7 @@ var require_resolve_block_map = __commonJS((exports) => {
5952
5940
  });
5953
5941
 
5954
5942
  // node_modules/yaml/dist/compose/resolve-block-seq.js
5955
- var require_resolve_block_seq = __commonJS((exports) => {
5943
+ var require_resolve_block_seq = __commonJS(function(exports) {
5956
5944
  var YAMLSeq = require_YAMLSeq();
5957
5945
  var resolveProps = require_resolve_props();
5958
5946
  var utilFlowIndentCheck = require_util_flow_indent_check();
@@ -6000,7 +5988,7 @@ var require_resolve_block_seq = __commonJS((exports) => {
6000
5988
  });
6001
5989
 
6002
5990
  // node_modules/yaml/dist/compose/resolve-end.js
6003
- var require_resolve_end = __commonJS((exports) => {
5991
+ var require_resolve_end = __commonJS(function(exports) {
6004
5992
  function resolveEnd(end, offset, reqSpace, onError) {
6005
5993
  let comment = "";
6006
5994
  if (end) {
@@ -6040,7 +6028,7 @@ var require_resolve_end = __commonJS((exports) => {
6040
6028
  });
6041
6029
 
6042
6030
  // node_modules/yaml/dist/compose/resolve-flow-collection.js
6043
- var require_resolve_flow_collection = __commonJS((exports) => {
6031
+ var require_resolve_flow_collection = __commonJS(function(exports) {
6044
6032
  var identity = require_identity();
6045
6033
  var Pair = require_Pair();
6046
6034
  var YAMLMap = require_YAMLMap();
@@ -6231,7 +6219,7 @@ var require_resolve_flow_collection = __commonJS((exports) => {
6231
6219
  });
6232
6220
 
6233
6221
  // node_modules/yaml/dist/compose/compose-collection.js
6234
- var require_compose_collection = __commonJS((exports) => {
6222
+ var require_compose_collection = __commonJS(function(exports) {
6235
6223
  var identity = require_identity();
6236
6224
  var Scalar = require_Scalar();
6237
6225
  var YAMLMap = require_YAMLMap();
@@ -6293,7 +6281,7 @@ var require_compose_collection = __commonJS((exports) => {
6293
6281
  });
6294
6282
 
6295
6283
  // node_modules/yaml/dist/compose/resolve-block-scalar.js
6296
- var require_resolve_block_scalar = __commonJS((exports) => {
6284
+ var require_resolve_block_scalar = __commonJS(function(exports) {
6297
6285
  var Scalar = require_Scalar();
6298
6286
  function resolveBlockScalar(ctx, scalar, onError) {
6299
6287
  const start = scalar.offset;
@@ -6311,12 +6299,12 @@ var require_resolve_block_scalar = __commonJS((exports) => {
6311
6299
  break;
6312
6300
  }
6313
6301
  if (chompStart === 0) {
6314
- const value2 = header.chomp === "+" && lines.length > 0 ? `
6302
+ const value = header.chomp === "+" && lines.length > 0 ? `
6315
6303
  `.repeat(Math.max(1, lines.length - 1)) : "";
6316
- let end2 = start + header.length;
6304
+ let end = start + header.length;
6317
6305
  if (scalar.source)
6318
- end2 += scalar.source.length;
6319
- return { value: value2, type, comment: header.comment, range: [start, end2, end2] };
6306
+ end += scalar.source.length;
6307
+ return { value, type, comment: header.comment, range: [start, end, end] };
6320
6308
  }
6321
6309
  let trimIndent = scalar.indent + header.indent;
6322
6310
  let offset = scalar.offset + header.length;
@@ -6486,7 +6474,7 @@ var require_resolve_block_scalar = __commonJS((exports) => {
6486
6474
  });
6487
6475
 
6488
6476
  // node_modules/yaml/dist/compose/resolve-flow-scalar.js
6489
- var require_resolve_flow_scalar = __commonJS((exports) => {
6477
+ var require_resolve_flow_scalar = __commonJS(function(exports) {
6490
6478
  var Scalar = require_Scalar();
6491
6479
  var resolveEnd = require_resolve_end();
6492
6480
  function resolveFlowScalar(scalar, strict, onError) {
@@ -6702,7 +6690,7 @@ var require_resolve_flow_scalar = __commonJS((exports) => {
6702
6690
  });
6703
6691
 
6704
6692
  // node_modules/yaml/dist/compose/compose-scalar.js
6705
- var require_compose_scalar = __commonJS((exports) => {
6693
+ var require_compose_scalar = __commonJS(function(exports) {
6706
6694
  var identity = require_identity();
6707
6695
  var Scalar = require_Scalar();
6708
6696
  var resolveBlockScalar = require_resolve_block_scalar();
@@ -6764,9 +6752,9 @@ var require_compose_scalar = __commonJS((exports) => {
6764
6752
  return schema[identity.SCALAR];
6765
6753
  }
6766
6754
  function findScalarTagByTest({ atKey, directives, schema }, value, token, onError) {
6767
- const tag = schema.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value)) || schema[identity.SCALAR];
6755
+ const tag = schema.tags.find((tag) => (tag.default === true || atKey && tag.default === "key") && tag.test?.test(value)) || schema[identity.SCALAR];
6768
6756
  if (schema.compat) {
6769
- const compat = schema.compat.find((tag2) => tag2.default && tag2.test?.test(value)) ?? schema[identity.SCALAR];
6757
+ const compat = schema.compat.find((tag) => tag.default && tag.test?.test(value)) ?? schema[identity.SCALAR];
6770
6758
  if (tag.tag !== compat.tag) {
6771
6759
  const ts = directives.tagString(tag.tag);
6772
6760
  const cs = directives.tagString(compat.tag);
@@ -6780,7 +6768,7 @@ var require_compose_scalar = __commonJS((exports) => {
6780
6768
  });
6781
6769
 
6782
6770
  // node_modules/yaml/dist/compose/util-empty-scalar-position.js
6783
- var require_util_empty_scalar_position = __commonJS((exports) => {
6771
+ var require_util_empty_scalar_position = __commonJS(function(exports) {
6784
6772
  function emptyScalarPosition(offset, before, pos) {
6785
6773
  if (before) {
6786
6774
  pos ?? (pos = before.length);
@@ -6807,7 +6795,7 @@ var require_util_empty_scalar_position = __commonJS((exports) => {
6807
6795
  });
6808
6796
 
6809
6797
  // node_modules/yaml/dist/compose/compose-node.js
6810
- var require_compose_node = __commonJS((exports) => {
6798
+ var require_compose_node = __commonJS(function(exports) {
6811
6799
  var Alias = require_Alias();
6812
6800
  var identity = require_identity();
6813
6801
  var composeCollection = require_compose_collection();
@@ -6905,7 +6893,7 @@ var require_compose_node = __commonJS((exports) => {
6905
6893
  });
6906
6894
 
6907
6895
  // node_modules/yaml/dist/compose/compose-doc.js
6908
- var require_compose_doc = __commonJS((exports) => {
6896
+ var require_compose_doc = __commonJS(function(exports) {
6909
6897
  var Document = require_Document();
6910
6898
  var composeNode = require_compose_node();
6911
6899
  var resolveEnd = require_resolve_end();
@@ -6945,7 +6933,7 @@ var require_compose_doc = __commonJS((exports) => {
6945
6933
  });
6946
6934
 
6947
6935
  // node_modules/yaml/dist/compose/composer.js
6948
- var require_composer = __commonJS((exports) => {
6936
+ var require_composer = __commonJS(function(exports) {
6949
6937
  var node_process = __require("process");
6950
6938
  var directives = require_directives();
6951
6939
  var Document = require_Document();
@@ -7134,7 +7122,7 @@ ${end.comment}` : end.comment;
7134
7122
  });
7135
7123
 
7136
7124
  // node_modules/yaml/dist/parse/cst-scalar.js
7137
- var require_cst_scalar = __commonJS((exports) => {
7125
+ var require_cst_scalar = __commonJS(function(exports) {
7138
7126
  var resolveBlockScalar = require_resolve_block_scalar();
7139
7127
  var resolveFlowScalar = require_resolve_flow_scalar();
7140
7128
  var errors = require_errors();
@@ -7324,7 +7312,7 @@ var require_cst_scalar = __commonJS((exports) => {
7324
7312
  });
7325
7313
 
7326
7314
  // node_modules/yaml/dist/parse/cst-stringify.js
7327
- var require_cst_stringify = __commonJS((exports) => {
7315
+ var require_cst_stringify = __commonJS(function(exports) {
7328
7316
  var stringify = (cst) => ("type" in cst) ? stringifyToken(cst) : stringifyItem(cst);
7329
7317
  function stringifyToken(token) {
7330
7318
  switch (token.type) {
@@ -7382,7 +7370,7 @@ var require_cst_stringify = __commonJS((exports) => {
7382
7370
  });
7383
7371
 
7384
7372
  // node_modules/yaml/dist/parse/cst-visit.js
7385
- var require_cst_visit = __commonJS((exports) => {
7373
+ var require_cst_visit = __commonJS(function(exports) {
7386
7374
  var BREAK = Symbol("break visit");
7387
7375
  var SKIP = Symbol("skip children");
7388
7376
  var REMOVE = Symbol("remove item");
@@ -7441,7 +7429,7 @@ var require_cst_visit = __commonJS((exports) => {
7441
7429
  });
7442
7430
 
7443
7431
  // node_modules/yaml/dist/parse/cst.js
7444
- var require_cst = __commonJS((exports) => {
7432
+ var require_cst = __commonJS(function(exports) {
7445
7433
  var cstScalar = require_cst_scalar();
7446
7434
  var cstStringify = require_cst_stringify();
7447
7435
  var cstVisit = require_cst_visit();
@@ -7542,7 +7530,7 @@ var require_cst = __commonJS((exports) => {
7542
7530
  });
7543
7531
 
7544
7532
  // node_modules/yaml/dist/parse/lexer.js
7545
- var require_lexer = __commonJS((exports) => {
7533
+ var require_lexer = __commonJS(function(exports) {
7546
7534
  var cst = require_cst();
7547
7535
  function isEmpty(ch) {
7548
7536
  switch (ch) {
@@ -7915,18 +7903,18 @@ var require_lexer = __commonJS((exports) => {
7915
7903
  let indent = 0;
7916
7904
  let ch;
7917
7905
  loop:
7918
- for (let i2 = this.pos;ch = this.buffer[i2]; ++i2) {
7906
+ for (let i = this.pos;ch = this.buffer[i]; ++i) {
7919
7907
  switch (ch) {
7920
7908
  case " ":
7921
7909
  indent += 1;
7922
7910
  break;
7923
7911
  case `
7924
7912
  `:
7925
- nl = i2;
7913
+ nl = i;
7926
7914
  indent = 0;
7927
7915
  break;
7928
7916
  case "\r": {
7929
- const next = this.buffer[i2 + 1];
7917
+ const next = this.buffer[i + 1];
7930
7918
  if (!next && !this.atEnd)
7931
7919
  return this.setNext("block-scalar");
7932
7920
  if (next === `
@@ -7969,16 +7957,16 @@ var require_lexer = __commonJS((exports) => {
7969
7957
  nl = i - 1;
7970
7958
  } else if (!this.blockScalarKeep) {
7971
7959
  do {
7972
- let i2 = nl - 1;
7973
- let ch2 = this.buffer[i2];
7974
- if (ch2 === "\r")
7975
- ch2 = this.buffer[--i2];
7976
- const lastChar = i2;
7977
- while (ch2 === " ")
7978
- ch2 = this.buffer[--i2];
7979
- if (ch2 === `
7980
- ` && i2 >= this.pos && i2 + 1 + indent > lastChar)
7981
- nl = i2;
7960
+ let i = nl - 1;
7961
+ let ch = this.buffer[i];
7962
+ if (ch === "\r")
7963
+ ch = this.buffer[--i];
7964
+ const lastChar = i;
7965
+ while (ch === " ")
7966
+ ch = this.buffer[--i];
7967
+ if (ch === `
7968
+ ` && i >= this.pos && i + 1 + indent > lastChar)
7969
+ nl = i;
7982
7970
  else
7983
7971
  break;
7984
7972
  } while (true);
@@ -8128,7 +8116,7 @@ var require_lexer = __commonJS((exports) => {
8128
8116
  });
8129
8117
 
8130
8118
  // node_modules/yaml/dist/parse/line-counter.js
8131
- var require_line_counter = __commonJS((exports) => {
8119
+ var require_line_counter = __commonJS(function(exports) {
8132
8120
  class LineCounter {
8133
8121
  constructor() {
8134
8122
  this.lineStarts = [];
@@ -8156,7 +8144,7 @@ var require_line_counter = __commonJS((exports) => {
8156
8144
  });
8157
8145
 
8158
8146
  // node_modules/yaml/dist/parse/parser.js
8159
- var require_parser = __commonJS((exports) => {
8147
+ var require_parser = __commonJS(function(exports) {
8160
8148
  var node_process = __require("process");
8161
8149
  var cst = require_cst();
8162
8150
  var lexer = require_lexer();
@@ -8647,12 +8635,12 @@ var require_parser = __commonJS((exports) => {
8647
8635
  if (includesToken(it.start, "newline")) {
8648
8636
  Object.assign(it, { key: null, sep: [this.sourceToken] });
8649
8637
  } else {
8650
- const start2 = getFirstKeyStartProps(it.start);
8638
+ const start = getFirstKeyStartProps(it.start);
8651
8639
  this.stack.push({
8652
8640
  type: "block-map",
8653
8641
  offset: this.offset,
8654
8642
  indent: this.indent,
8655
- items: [{ start: start2, key: null, sep: [this.sourceToken] }]
8643
+ items: [{ start, key: null, sep: [this.sourceToken] }]
8656
8644
  });
8657
8645
  }
8658
8646
  } else if (it.value) {
@@ -8665,7 +8653,7 @@ var require_parser = __commonJS((exports) => {
8665
8653
  items: [{ start, key: null, sep: [this.sourceToken] }]
8666
8654
  });
8667
8655
  } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) {
8668
- const start2 = getFirstKeyStartProps(it.start);
8656
+ const start = getFirstKeyStartProps(it.start);
8669
8657
  const key = it.key;
8670
8658
  const sep = it.sep;
8671
8659
  sep.push(this.sourceToken);
@@ -8675,7 +8663,7 @@ var require_parser = __commonJS((exports) => {
8675
8663
  type: "block-map",
8676
8664
  offset: this.offset,
8677
8665
  indent: this.indent,
8678
- items: [{ start: start2, key, sep }]
8666
+ items: [{ start, key, sep }]
8679
8667
  });
8680
8668
  } else if (start.length > 0) {
8681
8669
  it.sep = it.sep.concat(start, this.sourceToken);
@@ -9005,7 +8993,7 @@ var require_parser = __commonJS((exports) => {
9005
8993
  });
9006
8994
 
9007
8995
  // node_modules/yaml/dist/public-api.js
9008
- var require_public_api = __commonJS((exports) => {
8996
+ var require_public_api = __commonJS(function(exports) {
9009
8997
  var composer = require_composer();
9010
8998
  var Document = require_Document();
9011
8999
  var errors = require_errors();
@@ -9019,22 +9007,22 @@ var require_public_api = __commonJS((exports) => {
9019
9007
  return { lineCounter: lineCounter$1, prettyErrors };
9020
9008
  }
9021
9009
  function parseAllDocuments(source, options = {}) {
9022
- const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options);
9023
- const parser$1 = new parser.Parser(lineCounter2?.addNewLine);
9010
+ const { lineCounter, prettyErrors } = parseOptions(options);
9011
+ const parser$1 = new parser.Parser(lineCounter?.addNewLine);
9024
9012
  const composer$1 = new composer.Composer(options);
9025
9013
  const docs = Array.from(composer$1.compose(parser$1.parse(source)));
9026
- if (prettyErrors && lineCounter2)
9014
+ if (prettyErrors && lineCounter)
9027
9015
  for (const doc of docs) {
9028
- doc.errors.forEach(errors.prettifyError(source, lineCounter2));
9029
- doc.warnings.forEach(errors.prettifyError(source, lineCounter2));
9016
+ doc.errors.forEach(errors.prettifyError(source, lineCounter));
9017
+ doc.warnings.forEach(errors.prettifyError(source, lineCounter));
9030
9018
  }
9031
9019
  if (docs.length > 0)
9032
9020
  return docs;
9033
9021
  return Object.assign([], { empty: true }, composer$1.streamInfo());
9034
9022
  }
9035
9023
  function parseDocument(source, options = {}) {
9036
- const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options);
9037
- const parser$1 = new parser.Parser(lineCounter2?.addNewLine);
9024
+ const { lineCounter, prettyErrors } = parseOptions(options);
9025
+ const parser$1 = new parser.Parser(lineCounter?.addNewLine);
9038
9026
  const composer$1 = new composer.Composer(options);
9039
9027
  let doc = null;
9040
9028
  for (const _doc of composer$1.compose(parser$1.parse(source), true, source.length)) {
@@ -9045,9 +9033,9 @@ var require_public_api = __commonJS((exports) => {
9045
9033
  break;
9046
9034
  }
9047
9035
  }
9048
- if (prettyErrors && lineCounter2) {
9049
- doc.errors.forEach(errors.prettifyError(source, lineCounter2));
9050
- doc.warnings.forEach(errors.prettifyError(source, lineCounter2));
9036
+ if (prettyErrors && lineCounter) {
9037
+ doc.errors.forEach(errors.prettifyError(source, lineCounter));
9038
+ doc.warnings.forEach(errors.prettifyError(source, lineCounter));
9051
9039
  }
9052
9040
  return doc;
9053
9041
  }
@@ -9394,27 +9382,27 @@ async function* parseGenericSSE(body) {
9394
9382
  for (const rawLine of lines) {
9395
9383
  const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
9396
9384
  if (line === "") {
9397
- const evt2 = flush();
9398
- if (evt2)
9399
- yield evt2;
9385
+ const evt = flush();
9386
+ if (evt)
9387
+ yield evt;
9400
9388
  continue;
9401
9389
  }
9402
9390
  if (line.startsWith(":"))
9403
9391
  continue;
9404
9392
  const colon = line.indexOf(":");
9405
9393
  const field = colon === -1 ? line : line.slice(0, colon);
9406
- let value2 = colon === -1 ? "" : line.slice(colon + 1);
9407
- if (value2.startsWith(" "))
9408
- value2 = value2.slice(1);
9394
+ let value = colon === -1 ? "" : line.slice(colon + 1);
9395
+ if (value.startsWith(" "))
9396
+ value = value.slice(1);
9409
9397
  switch (field) {
9410
9398
  case "event":
9411
- event = value2;
9399
+ event = value;
9412
9400
  break;
9413
9401
  case "data":
9414
- dataLines.push(value2);
9402
+ dataLines.push(value);
9415
9403
  break;
9416
9404
  case "id":
9417
- id = value2;
9405
+ id = value;
9418
9406
  break;
9419
9407
  }
9420
9408
  }
@@ -9488,7 +9476,6 @@ function parseDataLine(data) {
9488
9476
  // src/lib/api-client.ts
9489
9477
  var exports_api_client = {};
9490
9478
  __export(exports_api_client, {
9491
- sameHostRedirect: () => sameHostRedirect,
9492
9479
  MarthaAPIClient: () => MarthaAPIClient
9493
9480
  });
9494
9481
  import fs3 from "node:fs";
@@ -9530,11 +9517,22 @@ class MarthaAPIClient {
9530
9517
  getAccessToken;
9531
9518
  defaultTimeout;
9532
9519
  verbose;
9520
+ tenantFor;
9533
9521
  constructor(config) {
9534
9522
  this.baseUrl = config.baseUrl.replace(/\/+$/, "");
9535
9523
  this.getAccessToken = config.getAccessToken;
9536
9524
  this.defaultTimeout = config.timeout ?? 30000;
9537
9525
  this.verbose = config.verbose ?? false;
9526
+ this.tenantFor = config.tenantFor ?? (() => {
9527
+ return;
9528
+ });
9529
+ }
9530
+ authHeaders(token) {
9531
+ const tenant = this.tenantFor(token);
9532
+ return {
9533
+ Authorization: `Bearer ${token}`,
9534
+ ...tenant ? { "X-Martha-Tenant": tenant } : {}
9535
+ };
9538
9536
  }
9539
9537
  log(msg) {
9540
9538
  if (this.verbose)
@@ -9562,24 +9560,24 @@ class MarthaAPIClient {
9562
9560
  }
9563
9561
  return res;
9564
9562
  }
9565
- async get(path3, opts) {
9566
- return this.request("GET", path3, opts);
9563
+ async get(path, opts) {
9564
+ return this.request("GET", path, opts);
9567
9565
  }
9568
- async post(path3, body, opts) {
9569
- return this.request("POST", path3, { ...opts, body });
9566
+ async post(path, body, opts) {
9567
+ return this.request("POST", path, { ...opts, body });
9570
9568
  }
9571
- async put(path3, body, opts) {
9572
- return this.request("PUT", path3, { ...opts, body });
9569
+ async put(path, body, opts) {
9570
+ return this.request("PUT", path, { ...opts, body });
9573
9571
  }
9574
- async patch(path3, body, opts) {
9575
- return this.request("PATCH", path3, { ...opts, body });
9572
+ async patch(path, body, opts) {
9573
+ return this.request("PATCH", path, { ...opts, body });
9576
9574
  }
9577
- async del(path3, opts) {
9578
- return this.request("DELETE", path3, opts);
9575
+ async del(path, opts) {
9576
+ return this.request("DELETE", path, opts);
9579
9577
  }
9580
- async upload(path3, filePath, opts) {
9578
+ async upload(path, filePath, opts) {
9581
9579
  const token = await this.getAccessToken();
9582
- const url = this.buildUrl(path3, opts?.params);
9580
+ const url = this.buildUrl(path, opts?.params);
9583
9581
  const timeout = opts?.timeout ?? 120000;
9584
9582
  const fileBuffer = fs3.readFileSync(filePath);
9585
9583
  const fileName = nodePath.basename(filePath);
@@ -9592,7 +9590,7 @@ class MarthaAPIClient {
9592
9590
  res = await this.fetchSameHost(url, {
9593
9591
  method: "POST",
9594
9592
  headers: {
9595
- Authorization: `Bearer ${token}`,
9593
+ ...this.authHeaders(token),
9596
9594
  ...opts?.headers
9597
9595
  },
9598
9596
  body: formData,
@@ -9613,16 +9611,16 @@ class MarthaAPIClient {
9613
9611
  }
9614
9612
  return await res.json();
9615
9613
  }
9616
- async getRaw(path3, opts) {
9614
+ async getRaw(path, opts) {
9617
9615
  const token = await this.getAccessToken();
9618
- const url = this.buildUrl(path3, opts?.params);
9616
+ const url = this.buildUrl(path, opts?.params);
9619
9617
  const timeout = opts?.timeout ?? this.defaultTimeout;
9620
9618
  let res;
9621
9619
  try {
9622
9620
  res = await this.fetchSameHost(url, {
9623
9621
  method: "GET",
9624
9622
  headers: {
9625
- Authorization: `Bearer ${token}`,
9623
+ ...this.authHeaders(token),
9626
9624
  ...opts?.headers
9627
9625
  },
9628
9626
  signal: opts?.signal ?? AbortSignal.timeout(timeout)
@@ -9642,16 +9640,16 @@ class MarthaAPIClient {
9642
9640
  }
9643
9641
  return res;
9644
9642
  }
9645
- async postRaw(path3, body, opts) {
9643
+ async postRaw(path, body, opts) {
9646
9644
  const token = await this.getAccessToken();
9647
- const url = this.buildUrl(path3, opts?.params);
9645
+ const url = this.buildUrl(path, opts?.params);
9648
9646
  const timeout = opts?.timeout ?? 120000;
9649
9647
  let res;
9650
9648
  try {
9651
9649
  res = await this.fetchSameHost(url, {
9652
9650
  method: "POST",
9653
9651
  headers: {
9654
- Authorization: `Bearer ${token}`,
9652
+ ...this.authHeaders(token),
9655
9653
  "Content-Type": "application/json",
9656
9654
  ...opts?.headers
9657
9655
  },
@@ -9673,14 +9671,14 @@ class MarthaAPIClient {
9673
9671
  }
9674
9672
  return res;
9675
9673
  }
9676
- async* streamSSE(path3, body, opts) {
9674
+ async* streamSSE(path, body, opts) {
9677
9675
  const token = await this.getAccessToken();
9678
- const url = this.buildUrl(path3, opts?.params);
9676
+ const url = this.buildUrl(path, opts?.params);
9679
9677
  const timeout = opts?.timeout ?? 120000;
9680
9678
  const res = await this.fetchSameHost(url, {
9681
9679
  method: "POST",
9682
9680
  headers: {
9683
- Authorization: `Bearer ${token}`,
9681
+ ...this.authHeaders(token),
9684
9682
  "Content-Type": "application/json",
9685
9683
  ...opts?.headers
9686
9684
  },
@@ -9696,12 +9694,12 @@ class MarthaAPIClient {
9696
9694
  }
9697
9695
  yield* parseSSEStream(res.body);
9698
9696
  }
9699
- async request(method, path3, opts) {
9700
- const url = this.buildUrl(path3, opts?.params);
9697
+ async request(method, path, opts) {
9698
+ const url = this.buildUrl(path, opts?.params);
9701
9699
  const timeout = opts?.timeout ?? this.defaultTimeout;
9702
- const attempt = async (token2) => {
9700
+ const attempt = async (token) => {
9703
9701
  const headers = {
9704
- Authorization: `Bearer ${token2}`,
9702
+ ...this.authHeaders(token),
9705
9703
  ...opts?.headers
9706
9704
  };
9707
9705
  if (opts?.body !== undefined) {
@@ -9746,11 +9744,11 @@ class MarthaAPIClient {
9746
9744
  return;
9747
9745
  return await res.json();
9748
9746
  }
9749
- buildUrl(path3, params) {
9750
- if (/^(https?:)?\/\//i.test(path3)) {
9747
+ buildUrl(path, params) {
9748
+ if (/^(https?:)?\/\//i.test(path)) {
9751
9749
  throw new CLIError("Absolute URL paths are not allowed", 1 /* Error */);
9752
9750
  }
9753
- const url = new URL(path3, this.baseUrl);
9751
+ const url = new URL(path, this.baseUrl);
9754
9752
  if (params) {
9755
9753
  for (const [key, value] of Object.entries(params)) {
9756
9754
  url.searchParams.set(key, value);
@@ -9783,21 +9781,64 @@ var init_api_client = __esm(() => {
9783
9781
  };
9784
9782
  });
9785
9783
 
9784
+ // node_modules/commander/index.js
9785
+ var exports_commander = {};
9786
+ __exportCjs(exports_commander, {
9787
+ program: () => $program,
9788
+ createCommand: () => $createCommand,
9789
+ createOption: () => $createOption,
9790
+ createArgument: () => $createArgument,
9791
+ Command: () => $Command,
9792
+ Option: () => $Option,
9793
+ Argument: () => $Argument,
9794
+ Help: () => $Help,
9795
+ CommanderError: () => $CommanderError,
9796
+ InvalidArgumentError: () => $InvalidArgumentError,
9797
+ InvalidOptionArgumentError: () => $InvalidOptionArgumentError
9798
+ }, {
9799
+ program: (value) => $program = value,
9800
+ createCommand: (value) => $createCommand = value,
9801
+ createOption: (value) => $createOption = value,
9802
+ createArgument: (value) => $createArgument = value,
9803
+ Command: (value) => $Command = value,
9804
+ Option: (value) => $Option = value,
9805
+ Argument: (value) => $Argument = value,
9806
+ Help: (value) => $Help = value,
9807
+ CommanderError: (value) => $CommanderError = value,
9808
+ InvalidArgumentError: (value) => $InvalidArgumentError = value,
9809
+ InvalidOptionArgumentError: (value) => $InvalidOptionArgumentError = value
9810
+ });
9811
+ var { Argument } = require_argument();
9812
+ var { Command } = require_command();
9813
+ var { CommanderError, InvalidArgumentError } = require_error();
9814
+ var { Help } = require_help();
9815
+ var { Option } = require_option();
9816
+ var $program = new Command;
9817
+ var $createCommand = (name) => new Command(name);
9818
+ var $createOption = (flags, description) => new Option(flags, description);
9819
+ var $createArgument = (name, description) => new Argument(name, description);
9820
+ var $Command = Command;
9821
+ var $Option = Option;
9822
+ var $Argument = Argument;
9823
+ var $Help = Help;
9824
+ var $CommanderError = CommanderError;
9825
+ var $InvalidArgumentError = InvalidArgumentError;
9826
+ var $InvalidOptionArgumentError = InvalidArgumentError;
9827
+
9786
9828
  // node_modules/commander/esm.mjs
9787
- var import__ = __toESM(require_commander(), 1);
9788
9829
  var {
9789
9830
  program,
9790
9831
  createCommand,
9791
9832
  createArgument,
9792
9833
  createOption,
9793
- CommanderError,
9794
- InvalidArgumentError,
9834
+ CommanderError: CommanderError2,
9835
+ InvalidArgumentError: InvalidArgumentError2,
9795
9836
  InvalidOptionArgumentError,
9796
- Command,
9797
- Argument,
9798
- Option,
9799
- Help
9800
- } = import__.default;
9837
+ Command: Command2,
9838
+ Argument: Argument2,
9839
+ Option: Option2,
9840
+ Help: Help2
9841
+ } = exports_commander;
9801
9842
 
9802
9843
  // src/index.ts
9803
9844
  init_errors();
@@ -10346,9 +10387,9 @@ import { randomBytes, createHash } from "node:crypto";
10346
10387
  async function openBrowser(url) {
10347
10388
  const { execFile } = await import("node:child_process");
10348
10389
  const { platform } = await import("node:os");
10349
- const os3 = platform();
10390
+ const os = platform();
10350
10391
  return new Promise((resolve, reject) => {
10351
- if (os3 === "win32") {
10392
+ if (os === "win32") {
10352
10393
  execFile("cmd", ["/c", "start", "", url], (err) => {
10353
10394
  if (err)
10354
10395
  reject(err);
@@ -10356,7 +10397,7 @@ async function openBrowser(url) {
10356
10397
  resolve();
10357
10398
  });
10358
10399
  } else {
10359
- const cmd = os3 === "darwin" ? "open" : "xdg-open";
10400
+ const cmd = os === "darwin" ? "open" : "xdg-open";
10360
10401
  execFile(cmd, [url], (err) => {
10361
10402
  if (err)
10362
10403
  reject(err);
@@ -10764,6 +10805,21 @@ function belongsToClient(tokens, clientId) {
10764
10805
  const azp = claims?.azp ?? claims?.client_id;
10765
10806
  return azp ? azp === clientId : true;
10766
10807
  }
10808
+ var selection = {};
10809
+ var clean = (v) => typeof v === "string" && v.trim() ? v.trim() : undefined;
10810
+ function registerOrgSelection(program) {
10811
+ program.hook("preAction", (_root, action) => {
10812
+ const opts = action.optsWithGlobals();
10813
+ selection = { org: clean(opts.org), commandTenant: clean(opts.tenant) };
10814
+ });
10815
+ }
10816
+ function organizationsFromClaims(payload) {
10817
+ const orgs = payload.organizations;
10818
+ if (orgs && typeof orgs === "object" && !Array.isArray(orgs)) {
10819
+ return Object.keys(orgs);
10820
+ }
10821
+ return [];
10822
+ }
10767
10823
  function tenantFromClaims(payload) {
10768
10824
  const tid = payload.tenant_id;
10769
10825
  if (typeof tid === "string" && tid)
@@ -10798,43 +10854,59 @@ function createContext(opts) {
10798
10854
  return existing.access_token;
10799
10855
  }
10800
10856
  }
10801
- const { loginClientCredentials: loginClientCredentials2 } = await Promise.resolve().then(() => (init_client_credentials(), exports_client_credentials));
10802
- const tokens2 = await loginClientCredentials2({
10857
+ await Promise.resolve().then(() => init_client_credentials());
10858
+ const tokens = await loginClientCredentials({
10803
10859
  keycloakUrl: profile.keycloak_url,
10804
10860
  realm: profile.keycloak_realm,
10805
10861
  clientId,
10806
10862
  clientSecret
10807
10863
  });
10808
- tokenStore.saveTokens(profileName, tokens2);
10809
- return tokens2.access_token;
10864
+ tokenStore.saveTokens(profileName, tokens);
10865
+ return tokens.access_token;
10810
10866
  }
10811
10867
  if (!tokenStore.needsRefresh(profileName)) {
10812
- const tokens2 = tokenStore.getTokens(profileName);
10813
- if (tokens2)
10814
- return tokens2.access_token;
10868
+ const tokens = tokenStore.getTokens(profileName);
10869
+ if (tokens)
10870
+ return tokens.access_token;
10815
10871
  }
10816
10872
  const tokens = tokenStore.getTokens(profileName);
10817
10873
  if (tokens?.refresh_token && !tokenStore.isRefreshExpired(profileName)) {
10818
- const clientId2 = tokens.auth_type === "client_credentials" ? profile.client_id : "martha-cli";
10874
+ const clientId = tokens.auth_type === "client_credentials" ? profile.client_id : "martha-cli";
10819
10875
  const refreshed = await refreshAccessToken({
10820
10876
  keycloakUrl: profile.keycloak_url,
10821
10877
  realm: profile.keycloak_realm,
10822
10878
  refreshToken: tokens.refresh_token,
10823
- clientId: clientId2
10879
+ clientId
10824
10880
  });
10825
10881
  tokenStore.saveTokens(profileName, refreshed);
10826
10882
  return refreshed.access_token;
10827
10883
  }
10828
10884
  throw new CLIError("Not authenticated.", 2 /* Auth */, "Run `martha auth login` to authenticate.");
10829
10885
  };
10886
+ const explicitOrg = selection.org ?? clean(process.env.MARTHA_ORG);
10887
+ const { commandTenant } = selection;
10888
+ const tenantFor = (token) => {
10889
+ if (explicitOrg)
10890
+ return explicitOrg;
10891
+ if (commandTenant) {
10892
+ let orgs = [];
10893
+ try {
10894
+ orgs = organizationsFromClaims(decodeJwtPayload(token));
10895
+ } catch {}
10896
+ if (orgs.includes(commandTenant))
10897
+ return commandTenant;
10898
+ }
10899
+ return profile.org?.trim() || undefined;
10900
+ };
10830
10901
  const api = new MarthaAPIClient({
10831
10902
  baseUrl: profile.api_url,
10832
10903
  getAccessToken,
10833
- verbose: opts.verbose
10904
+ verbose: opts.verbose,
10905
+ tenantFor
10834
10906
  });
10835
10907
  const getTenantId = async () => {
10836
10908
  const token = await getAccessToken();
10837
- const tid = tenantFromClaims(decodeJwtPayload(token));
10909
+ const tid = tenantFor(token) ?? tenantFromClaims(decodeJwtPayload(token));
10838
10910
  if (!tid) {
10839
10911
  throw new CLIError("No tenant_id or organizations claim in access token.", 2 /* Auth */);
10840
10912
  }
@@ -10848,7 +10920,8 @@ function createContext(opts) {
10848
10920
  api,
10849
10921
  configDir: opts.configDir,
10850
10922
  getTenantId,
10851
- getAccessToken
10923
+ getAccessToken,
10924
+ tenantFor
10852
10925
  };
10853
10926
  }
10854
10927
 
@@ -10941,20 +11014,20 @@ init_errors();
10941
11014
  function an(word) {
10942
11015
  return /^[aeiou]/i.test(word) ? `an ${word}` : `a ${word}`;
10943
11016
  }
10944
- function registerDefinitionCommands(program2, config) {
10945
- const cmd = program2.command(config.typeNamePlural).description(`Manage ${config.typeName} definitions`);
11017
+ function registerDefinitionCommands(program, config) {
11018
+ const cmd = program.command(config.typeNamePlural).description(`Manage ${config.typeName} definitions`);
10946
11019
  function getCtx() {
10947
11020
  const ctx = createContext({
10948
- profileOverride: program2.opts().profile,
10949
- verbose: program2.opts().verbose
11021
+ profileOverride: program.opts().profile,
11022
+ verbose: program.opts().verbose
10950
11023
  });
10951
- if (program2.opts().apiUrl) {
10952
- ctx.profile.api_url = program2.opts().apiUrl;
11024
+ if (program.opts().apiUrl) {
11025
+ ctx.profile.api_url = program.opts().apiUrl;
10953
11026
  }
10954
11027
  return ctx;
10955
11028
  }
10956
11029
  function isJson() {
10957
- return !!program2.opts().json;
11030
+ return !!program.opts().json;
10958
11031
  }
10959
11032
  const listCmd = cmd.command("list").description(`List ${config.typeNamePlural}`).option("--inactive", "Include inactive items").option("--limit <n>", "Max results per page", "50").option("--search <term>", "Case-insensitive substring filter on name (server-side)").option("--all", "Auto-paginate until every matching item is fetched (server caps at 500/page)");
10960
11033
  if (config.extraListOptions) {
@@ -11171,7 +11244,7 @@ init_config();
11171
11244
  init_errors();
11172
11245
 
11173
11246
  // src/version.ts
11174
- var CLI_VERSION = "0.61.2";
11247
+ var CLI_VERSION = "0.63.0";
11175
11248
 
11176
11249
  // src/commands/sessions.ts
11177
11250
  function relativeTime(iso) {
@@ -11246,20 +11319,20 @@ function printSessionTable(sessions) {
11246
11319
  }).join(" "));
11247
11320
  }
11248
11321
  }
11249
- function registerSessionCommands(program2) {
11250
- const cmd = program2.command("sessions").description("Browse conversation history");
11322
+ function registerSessionCommands(program) {
11323
+ const cmd = program.command("sessions").description("Browse conversation history");
11251
11324
  function getCtx() {
11252
11325
  const ctx = createContext({
11253
- profileOverride: program2.opts().profile,
11254
- verbose: program2.opts().verbose
11326
+ profileOverride: program.opts().profile,
11327
+ verbose: program.opts().verbose
11255
11328
  });
11256
- if (program2.opts().apiUrl) {
11257
- ctx.profile.api_url = program2.opts().apiUrl;
11329
+ if (program.opts().apiUrl) {
11330
+ ctx.profile.api_url = program.opts().apiUrl;
11258
11331
  }
11259
11332
  return ctx;
11260
11333
  }
11261
11334
  function isJson() {
11262
- return !!program2.opts().json;
11335
+ return !!program.opts().json;
11263
11336
  }
11264
11337
  cmd.command("list").description("List your conversation sessions").option("--search <text>", "Filter sessions by title").option("--limit <n>", "Max results (default: 20)", "20").option("--skip <n>", "Offset for pagination", "0").option("--type <type>", "Filter by session type (api, sms, whatsapp)").option("--include-archived", "Include archived sessions").action(async (opts) => {
11265
11338
  const ctx = getCtx();
@@ -11884,8 +11957,8 @@ Attach it as this agent's host executor:
11884
11957
  });
11885
11958
  parentCmd.command("revoke-runner <agent>").description("Revoke a host runner's live channel connection(s) without rotating the " + "key (#802). Drops the live stream within one heartbeat and flips the " + "agent offline. Default revokes ALL connections; --connection targets one.").option("--connection <id>", "Revoke only this connection_id (default: all of the agent's connections)").action(async (agent, opts) => {
11886
11959
  const ctx = getCtx();
11887
- const path4 = `${API_PATH}/${encodeURIComponent(agent)}/revoke-runner` + (opts.connection ? `?connection=${encodeURIComponent(opts.connection)}` : "");
11888
- const result = await ctx.api.post(path4, {});
11960
+ const path = `${API_PATH}/${encodeURIComponent(agent)}/revoke-runner` + (opts.connection ? `?connection=${encodeURIComponent(opts.connection)}` : "");
11961
+ const result = await ctx.api.post(path, {});
11889
11962
  if (isJson()) {
11890
11963
  console.log(JSON.stringify(result, null, 2));
11891
11964
  return;
@@ -12046,8 +12119,8 @@ Attach it as this agent's host executor:
12046
12119
  });
12047
12120
  parentCmd.command("self-grant <agent>").description("View or configure an agent's self-provisioning policy (request-then-approve). " + "With no flags, prints the current policy.").option("--enable", "Allow the agent to REQUEST capability grants").option("--disable", "Disallow self-provisioning").option("--scope <scope>", "Scope ceiling: none | read_only | read_write").option("--allow <ref...>", "Add allow-list refs (function:NAME or mcp:integration/name)").option("--remove <ref...>", "Remove allow-list refs").option("--collection-root <id...>", "Add collection-subtree roots the agent may self-grant collection-scoped functions into").option("--remove-collection-root <id...>", "Remove collection roots").option("--max-pending <n>", "Max concurrently-pending requests").action(async (agent, opts) => {
12048
12121
  const ctx = getCtx();
12049
- const path4 = `${API_PATH}/${encodeURIComponent(agent)}`;
12050
- const current = await ctx.api.get(path4);
12122
+ const path = `${API_PATH}/${encodeURIComponent(agent)}`;
12123
+ const current = await ctx.api.get(path);
12051
12124
  const mutating = opts.enable || opts.disable || opts.scope !== undefined || (opts.allow?.length ?? 0) > 0 || (opts.remove?.length ?? 0) > 0 || (opts.collectionRoot?.length ?? 0) > 0 || (opts.removeCollectionRoot?.length ?? 0) > 0 || opts.maxPending !== undefined;
12052
12125
  if (!mutating) {
12053
12126
  if (isJson()) {
@@ -12099,7 +12172,7 @@ Attach it as this agent's host executor:
12099
12172
  roots.delete(c);
12100
12173
  body.self_grant_collection_roots = [...roots];
12101
12174
  }
12102
- const updated = await ctx.api.put(path4, body);
12175
+ const updated = await ctx.api.put(path, body);
12103
12176
  if (isJson()) {
12104
12177
  console.log(JSON.stringify(policyView(updated), null, 2));
12105
12178
  return;
@@ -12784,10 +12857,10 @@ class BrowserSession {
12784
12857
  let chromium;
12785
12858
  const candidates = [];
12786
12859
  try {
12787
- const { createRequire: createRequire2 } = await import("node:module");
12860
+ const { createRequire } = await import("node:module");
12788
12861
  const { pathToFileURL } = await import("node:url");
12789
- const path5 = await import("node:path");
12790
- const req = createRequire2(pathToFileURL(path5.join(process.cwd(), "noop.js")));
12862
+ const path = await import("node:path");
12863
+ const req = createRequire(pathToFileURL(path.join(process.cwd(), "noop.js")));
12791
12864
  candidates.push(pathToFileURL(req.resolve(moduleName)).href);
12792
12865
  } catch {}
12793
12866
  candidates.push(moduleName);
@@ -13037,19 +13110,19 @@ async function dispatchBackgroundJob(command, jobId, journal, opts) {
13037
13110
  const sentinelPath = path6.join(dir, `${jobId}.exit`);
13038
13111
  await fs7.writeFile(logPath, "");
13039
13112
  const fd = openSync2(logPath, "a");
13040
- const env2 = { ...process.env, MARTHA_JOB_SENTINEL: sentinelPath };
13113
+ const env = { ...process.env, MARTHA_JOB_SENTINEL: sentinelPath };
13041
13114
  const stdin = opts.stdinData != null ? "pipe" : "ignore";
13042
13115
  const child = opts.argv ? spawn2("/bin/sh", ["-c", `"$@"${SENTINEL_TAIL}`, "martha-job", ...opts.argv], {
13043
13116
  shell: false,
13044
13117
  cwd: opts.cwd,
13045
13118
  detached: true,
13046
- env: env2,
13119
+ env,
13047
13120
  stdio: [stdin, fd, fd]
13048
13121
  }) : spawn2("/bin/sh", ["-c", `( ${command} )${SENTINEL_TAIL}`], {
13049
13122
  shell: false,
13050
13123
  cwd: opts.cwd,
13051
13124
  detached: true,
13052
- env: env2,
13125
+ env,
13053
13126
  stdio: [stdin, fd, fd]
13054
13127
  });
13055
13128
  closeSync2(fd);
@@ -13827,11 +13900,11 @@ function formatToolStatus(data) {
13827
13900
  }
13828
13901
  }
13829
13902
  function promptPick(rl, count) {
13830
- return new Promise((resolve2) => {
13903
+ return new Promise((resolve) => {
13831
13904
  rl.question(source_default.dim(`Pick 1-${count} (or Enter to cancel): `), (ans) => {
13832
13905
  const trimmed = ans.trim();
13833
13906
  if (!trimmed) {
13834
- resolve2(-1);
13907
+ resolve(-1);
13835
13908
  return;
13836
13909
  }
13837
13910
  const n = parseInt(trimmed, 10);
@@ -13839,10 +13912,10 @@ function promptPick(rl, count) {
13839
13912
  process.stderr.write(source_default.yellow(`Invalid choice.
13840
13913
 
13841
13914
  `));
13842
- resolve2(-1);
13915
+ resolve(-1);
13843
13916
  return;
13844
13917
  }
13845
- resolve2(n - 1);
13918
+ resolve(n - 1);
13846
13919
  });
13847
13920
  });
13848
13921
  }
@@ -14224,16 +14297,16 @@ async function runOneShot(ctx, sessionId, message, isJson, clientId, agentName,
14224
14297
  console.log(stripApprovalWidgetTags(response));
14225
14298
  }
14226
14299
  }
14227
- function registerChatCommand(program2) {
14228
- program2.command("chat").description("Chat with a Martha agent").option("--session <id>", "Resume an existing session").option("--client <nameOrId>", "Use a specific client (name or ID)").option("--agent <name>", "Drive the chat with a specific copilot agent (defaults to profile.default_agent)").option("--message <text>", "Send a single message (non-interactive)").option("--show-tools", "Show tool calls and results during chat").option("--local-exec", "Allow the agent to run host tools on THIS machine (#568). Requires the server to have LOCAL_EXEC_ENABLED=1.").option("--yes", "Auto-approve host tool execution (required with --local-exec for non-interactive runs).").option("--local-agent <name>", "Which local coding agent `local_agent` delegates to: a preset (claude | codex | cursor-agent) or a raw command. Overrides MARTHA_LOCAL_AGENT_CMD and `config local_agent` for this run.").option("--timeout <seconds>", "Per-message HTTP timeout in seconds (default: 600)").action(async (opts) => {
14300
+ function registerChatCommand(program) {
14301
+ program.command("chat").description("Chat with a Martha agent").option("--session <id>", "Resume an existing session").option("--client <nameOrId>", "Use a specific client (name or ID)").option("--agent <name>", "Drive the chat with a specific copilot agent (defaults to profile.default_agent)").option("--message <text>", "Send a single message (non-interactive)").option("--show-tools", "Show tool calls and results during chat").option("--local-exec", "Allow the agent to run host tools on THIS machine (#568). Requires the server to have LOCAL_EXEC_ENABLED=1.").option("--yes", "Auto-approve host tool execution (required with --local-exec for non-interactive runs).").option("--local-agent <name>", "Which local coding agent `local_agent` delegates to: a preset (claude | codex | cursor-agent) or a raw command. Overrides MARTHA_LOCAL_AGENT_CMD and `config local_agent` for this run.").option("--timeout <seconds>", "Per-message HTTP timeout in seconds (default: 600)").action(async (opts) => {
14229
14302
  const ctx = createContext({
14230
- profileOverride: program2.opts().profile,
14231
- verbose: program2.opts().verbose
14303
+ profileOverride: program.opts().profile,
14304
+ verbose: program.opts().verbose
14232
14305
  });
14233
- if (program2.opts().apiUrl) {
14234
- ctx.profile.api_url = program2.opts().apiUrl;
14306
+ if (program.opts().apiUrl) {
14307
+ ctx.profile.api_url = program.opts().apiUrl;
14235
14308
  }
14236
- const isJson = !!program2.opts().json;
14309
+ const isJson = !!program.opts().json;
14237
14310
  let clientId;
14238
14311
  if (opts.client) {
14239
14312
  const parsed = parseInt(opts.client, 10);
@@ -14355,9 +14428,9 @@ async function deliverToChannel(buzzBin, target, text) {
14355
14428
  const args = ["messages", "send", "--channel", target.channelId, "--content", text];
14356
14429
  if (target.threadRef)
14357
14430
  args.push("--reply-to", target.threadRef);
14358
- const send = () => new Promise((resolve2) => {
14431
+ const send = () => new Promise((resolve) => {
14359
14432
  execFile(buzzBin, args, { timeout: 20000, maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
14360
- resolve2({
14433
+ resolve({
14361
14434
  ok: !err,
14362
14435
  out: stdout?.slice(0, 2000) ?? "",
14363
14436
  err: err ? `${err.message}
@@ -14389,9 +14462,9 @@ async function runAcpServer(ctx, input, output, opts) {
14389
14462
  const sessions = new Map;
14390
14463
  let writeChain = Promise.resolve();
14391
14464
  const writeLine = (msg) => {
14392
- writeChain = writeChain.then(() => new Promise((resolve2) => {
14465
+ writeChain = writeChain.then(() => new Promise((resolve) => {
14393
14466
  output.write(JSON.stringify(msg) + `
14394
- `, () => resolve2());
14467
+ `, () => resolve());
14395
14468
  }));
14396
14469
  return writeChain;
14397
14470
  };
@@ -14580,12 +14653,12 @@ async function probeStartup(ctx) {
14580
14653
  throw new CLIError(`ACP startup failed: cannot reach Martha API at ${ctx.profile.api_url}: ${message}`, 1 /* Error */, "Check the API URL (--api-url / profile) and that the Martha API is up.");
14581
14654
  }
14582
14655
  }
14583
- function registerAcpServeCommand(program2) {
14584
- program2.command("acp-serve").description("Serve the Agent Client Protocol over stdio (newline-delimited JSON-RPC 2.0) so an ACP harness like Buzz's buzz-acp can drive a Martha agent").option("--client <nameOrId>", "Use a specific client id for the Martha session").option("--agent <name>", "Drive turns with a specific Martha agent (defaults to the credential/profile binding)").option("--post-reply", "After each completed turn, post the final answer back to the triggering Buzz channel via the `buzz` CLI (parsed from the prompt's [Context] section)").option("--buzz-bin <path>", "Path to the buzz CLI for --post-reply", "buzz").option("--timeout <seconds>", "Per-prompt HTTP timeout in seconds (default: 600)").action(async (opts) => {
14656
+ function registerAcpServeCommand(program) {
14657
+ program.command("acp-serve").description("Serve the Agent Client Protocol over stdio (newline-delimited JSON-RPC 2.0) so an ACP harness like Buzz's buzz-acp can drive a Martha agent").option("--client <nameOrId>", "Use a specific client id for the Martha session").option("--agent <name>", "Drive turns with a specific Martha agent (defaults to the credential/profile binding)").option("--post-reply", "After each completed turn, post the final answer back to the triggering Buzz channel via the `buzz` CLI (parsed from the prompt's [Context] section)").option("--buzz-bin <path>", "Path to the buzz CLI for --post-reply", "buzz").option("--timeout <seconds>", "Per-prompt HTTP timeout in seconds (default: 600)").action(async (opts) => {
14585
14658
  const ctx = createContext({
14586
- profileOverride: program2.opts().profile,
14587
- apiUrlOverride: program2.opts().apiUrl,
14588
- verbose: program2.opts().verbose
14659
+ profileOverride: program.opts().profile,
14660
+ apiUrlOverride: program.opts().apiUrl,
14661
+ verbose: program.opts().verbose
14589
14662
  });
14590
14663
  const timeoutMs = opts.timeout ? Math.max(1, Number(opts.timeout)) * 1000 : undefined;
14591
14664
  logJson("info", "martha acp-serve starting", {
@@ -14737,15 +14810,15 @@ function printAgentPrincipalReady(r, savedProfile) {
14737
14810
  Then: buzz channels add-member --channel <id> --pubkey <agent pubkey> --role member
14738
14811
  ` + " and @mention the agent in the channel."));
14739
14812
  }
14740
- function registerPrincipalCommands(program2) {
14741
- const principals = program2.command("principals").description("Provision principals — who may act, with what credential (mirrors the API's principals/bootstrap)");
14813
+ function registerPrincipalCommands(program) {
14814
+ const principals = program.command("principals").description("Provision principals — who may act, with what credential (mirrors the API's principals/bootstrap)");
14742
14815
  principals.command("bootstrap").description("Provision a principal. --mode human: your run-as client (what `martha init` wraps). " + "--mode integration: headless service account. --mode agent: service account bound " + "to ONE Martha-hosted agent (chat takeover) so the credential acts as the agent — " + "the shape an external ACP driver (Buzz, Zed) needs.").requiredOption("--mode <mode>", "human | integration | agent").option("--agent <name>", "Agent to bind (agent mode)").option("--prompt <text>", "System prompt — creates the agent when it doesn't exist yet (agent mode)").option("--label <label>", "Label for the service-account client id (default: the agent name in agent mode)").option("--intents <list>", "Comma-separated tool intents to grant (rag, documents, workflows, tasks)").option("--collections <list>", "Comma-separated collections (name, slug or id) the agent may read. Intents grant the retrieval TOOLS; without this they return nothing").option("--save-profile <name>", "Save the minted credential as a Martha profile, so anything that runs as this agent needs only MARTHA_PROFILE=<name> — no secret to copy").action(async (opts) => {
14743
14816
  const ctx = createContext({
14744
- profileOverride: program2.opts().profile,
14745
- apiUrlOverride: program2.opts().apiUrl,
14746
- verbose: program2.opts().verbose
14817
+ profileOverride: program.opts().profile,
14818
+ apiUrlOverride: program.opts().apiUrl,
14819
+ verbose: program.opts().verbose
14747
14820
  });
14748
- const isJson = !!program2.opts().json;
14821
+ const isJson = !!program.opts().json;
14749
14822
  switch (opts.mode) {
14750
14823
  case "agent": {
14751
14824
  if (!opts.agent) {
@@ -14842,7 +14915,7 @@ function buzzHarnessDefinition(opts = {}) {
14842
14915
  function isValidHarnessId(id) {
14843
14916
  return /^[a-z0-9_][a-z0-9_-]*$/.test(id);
14844
14917
  }
14845
- function buzzAppDataCandidates(platform, env2, home) {
14918
+ function buzzAppDataCandidates(platform, env, home) {
14846
14919
  const ids = [
14847
14920
  { build: "release", id: "xyz.block.buzz.app" },
14848
14921
  { build: "dev", id: "xyz.block.buzz.app.dev" }
@@ -14851,8 +14924,8 @@ function buzzAppDataCandidates(platform, env2, home) {
14851
14924
  if (platform === "darwin")
14852
14925
  return join4(home, "Library", "Application Support");
14853
14926
  if (platform === "win32")
14854
- return env2.APPDATA ?? join4(home, "AppData", "Roaming");
14855
- return env2.XDG_DATA_HOME ?? join4(home, ".local", "share");
14927
+ return env.APPDATA ?? join4(home, "AppData", "Roaming");
14928
+ return env.XDG_DATA_HOME ?? join4(home, ".local", "share");
14856
14929
  };
14857
14930
  const root = base();
14858
14931
  return ids.map(({ build, id }) => ({ build, dir: join4(root, id) }));
@@ -14860,12 +14933,12 @@ function buzzAppDataCandidates(platform, env2, home) {
14860
14933
  function chooseAppDataDir(candidates, exists) {
14861
14934
  return candidates.find((c) => exists(c.dir)) ?? null;
14862
14935
  }
14863
- function buzzAppCandidates(platform, env2, home) {
14936
+ function buzzAppCandidates(platform, env, home) {
14864
14937
  if (platform === "darwin") {
14865
14938
  return ["/Applications/Buzz.app", join4(home, "Applications", "Buzz.app")];
14866
14939
  }
14867
14940
  if (platform === "win32") {
14868
- const base = env2.LOCALAPPDATA ?? join4(home, "AppData", "Local");
14941
+ const base = env.LOCALAPPDATA ?? join4(home, "AppData", "Local");
14869
14942
  return [join4(base, "Programs", "Buzz")];
14870
14943
  }
14871
14944
  return [
@@ -14875,12 +14948,12 @@ function buzzAppCandidates(platform, env2, home) {
14875
14948
  ];
14876
14949
  }
14877
14950
  var BUZZ_RELEASES_URL = "https://github.com/block/buzz/releases/latest";
14878
- function buzzSidecarDirs(platform, env2, home) {
14951
+ function buzzSidecarDirs(platform, env, home) {
14879
14952
  if (platform === "darwin") {
14880
- return buzzAppCandidates(platform, env2, home).map((app) => join4(app, "Contents", "MacOS"));
14953
+ return buzzAppCandidates(platform, env, home).map((app) => join4(app, "Contents", "MacOS"));
14881
14954
  }
14882
14955
  if (platform === "win32") {
14883
- return buzzAppCandidates(platform, env2, home);
14956
+ return buzzAppCandidates(platform, env, home);
14884
14957
  }
14885
14958
  return ["/opt/Buzz"];
14886
14959
  }
@@ -14918,7 +14991,7 @@ ${looked}
14918
14991
  }
14919
14992
  var DEFAULT_BUZZ_KINDS = "9,46010,40007,7";
14920
14993
  function buzzAcpEnv(opts) {
14921
- const env2 = {
14994
+ const env = {
14922
14995
  BUZZ_RELAY_URL: opts.relayUrl,
14923
14996
  BUZZ_ACP_AGENT_COMMAND: opts.marthaBin,
14924
14997
  BUZZ_ACP_AGENT_ARGS: "acp-serve,--post-reply",
@@ -14928,16 +15001,16 @@ function buzzAcpEnv(opts) {
14928
15001
  ...opts.profile ? { MARTHA_PROFILE: opts.profile } : {}
14929
15002
  };
14930
15003
  if (opts.subscribe === "all")
14931
- env2.BUZZ_ACP_KINDS = opts.kinds;
14932
- return env2;
15004
+ env.BUZZ_ACP_KINDS = opts.kinds;
15005
+ return env;
14933
15006
  }
14934
- function resolveOnPath(bin, env2, platform, isExecutable) {
15007
+ function resolveOnPath(bin, env, platform, isExecutable) {
14935
15008
  if (bin.includes("/") || bin.includes("\\")) {
14936
15009
  return isExecutable(bin) ? bin : null;
14937
15010
  }
14938
- const exts = platform === "win32" ? (env2.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean) : [""];
15011
+ const exts = platform === "win32" ? (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean) : [""];
14939
15012
  const sep = platform === "win32" ? ";" : ":";
14940
- for (const dir of (env2.PATH ?? "").split(sep).filter(Boolean)) {
15013
+ for (const dir of (env.PATH ?? "").split(sep).filter(Boolean)) {
14941
15014
  for (const ext of exts) {
14942
15015
  const candidate = join4(dir, bin + ext);
14943
15016
  if (isExecutable(candidate))
@@ -14965,11 +15038,11 @@ function whichBuzz(bin) {
14965
15038
  isExecutable: executableOnDisk
14966
15039
  });
14967
15040
  }
14968
- function runBin(bin, args, env2) {
14969
- return new Promise((resolve2) => {
14970
- execFile2(bin, args, { env: env2, timeout: 15000, maxBuffer: 4 * 1024 * 1024 }, (err, stdout, stderr) => {
15041
+ function runBin(bin, args, env) {
15042
+ return new Promise((resolve) => {
15043
+ execFile2(bin, args, { env, timeout: 15000, maxBuffer: 4 * 1024 * 1024 }, (err, stdout, stderr) => {
14971
15044
  const code = err && typeof err.code === "number" ? err.code ?? 1 : err ? 1 : 0;
14972
- resolve2({
15045
+ resolve({
14973
15046
  code,
14974
15047
  stdout: stdout ?? "",
14975
15048
  stderr: (stderr ?? "").slice(0, 2000)
@@ -15097,15 +15170,15 @@ async function preflightBuzz(ctx, opts) {
15097
15170
  detail: relayProbe.detail,
15098
15171
  fix: relayProbe.ok ? undefined : `start the relay, or correct --relay (${opts.relayUrl})`
15099
15172
  });
15100
- const identity2 = process.env.BUZZ_PRIVATE_KEY;
15173
+ const identity = process.env.BUZZ_PRIVATE_KEY;
15101
15174
  checks.push({
15102
- ok: !!identity2,
15175
+ ok: !!identity,
15103
15176
  label: "channel identity",
15104
- detail: identity2 ? "BUZZ_PRIVATE_KEY set (not shown)" : "BUZZ_PRIVATE_KEY not set",
15105
- fix: identity2 ? undefined : "export BUZZ_PRIVATE_KEY=<the agent's nsec> — Martha-issued identities land in #1119"
15177
+ detail: identity ? "BUZZ_PRIVATE_KEY set (not shown)" : "BUZZ_PRIVATE_KEY not set",
15178
+ fix: identity ? undefined : "export BUZZ_PRIVATE_KEY=<the agent's nsec> — Martha-issued identities land in #1119"
15106
15179
  });
15107
- if (identity2 && relayProbe.ok && buzzPath) {
15108
- checks.push(await checkMembership(buzzPath, opts.relayUrl, identity2, opts.channelId));
15180
+ if (identity && relayProbe.ok && buzzPath) {
15181
+ checks.push(await checkMembership(buzzPath, opts.relayUrl, identity, opts.channelId));
15109
15182
  } else {
15110
15183
  checks.push({
15111
15184
  ok: null,
@@ -15148,12 +15221,12 @@ async function checkAgentPrincipal(ctx, agent, def) {
15148
15221
  };
15149
15222
  }
15150
15223
  }
15151
- async function checkMembership(buzzBin, relayUrl, identity2, channelId) {
15224
+ async function checkMembership(buzzBin, relayUrl, identity, channelId) {
15152
15225
  const label = "channel membership";
15153
15226
  const res = await runBin(buzzBin, ["--format", "compact", "channels", "list", "--member"], {
15154
15227
  ...process.env,
15155
15228
  BUZZ_RELAY_URL: relayUrl,
15156
- BUZZ_PRIVATE_KEY: identity2
15229
+ BUZZ_PRIVATE_KEY: identity
15157
15230
  });
15158
15231
  if (res.code !== 0) {
15159
15232
  const why = res.code === 3 ? "the relay rejected this identity" : res.code === 2 ? "relay/network error" : `buzz exited ${res.code}`;
@@ -15190,13 +15263,13 @@ async function checkMembership(buzzBin, relayUrl, identity2, channelId) {
15190
15263
  fix: channels.length ? undefined : "buzz channels add-member --channel <id> --pubkey <the agent's pubkey> --role member"
15191
15264
  };
15192
15265
  }
15193
- function emitManifest(kind, env2, opts) {
15266
+ function emitManifest(kind, env, opts) {
15194
15267
  const secretKeys = [
15195
15268
  "BUZZ_PRIVATE_KEY",
15196
15269
  "MARTHA_CLIENT_ID",
15197
15270
  "MARTHA_CLIENT_SECRET"
15198
15271
  ];
15199
- const entries = Object.entries(env2);
15272
+ const entries = Object.entries(env);
15200
15273
  if (kind === "docker") {
15201
15274
  const lines = [
15202
15275
  "docker run --rm \\",
@@ -15253,8 +15326,8 @@ function assertSupportedChannel(kind) {
15253
15326
  throw new CLIError(`Channel type '${kind}' is not implemented.`, 4 /* Validation */, `Supported: ${SUPPORTED_CHANNELS.join(", ")}. Slack and others land as separate slices — the verb and the preflight generalize, the precondition list does not.`);
15254
15327
  }
15255
15328
  }
15256
- function registerChannelCommands(program2) {
15257
- const channels = program2.command("channels").description("Put a Martha agent in an external conversation channel — from Buzz (install-harness) or from Martha (connect)");
15329
+ function registerChannelCommands(program) {
15330
+ const channels = program.command("channels").description("Put a Martha agent in an external conversation channel — from Buzz (install-harness) or from Martha (connect)");
15258
15331
  channels.command("install-harness <type>").description("Register Martha as a runtime in Buzz Desktop (a tier-3 custom harness definition). " + "Desktop then owns the agent's keypair, attestation and lifecycle — we only declare how to start the adapter.").option("--app-data <dir>", "Buzz Desktop app-data dir (default: auto-detect)").option("--id <id>", "Harness id", BUZZ_HARNESS_ID).option("--label <label>", "Name shown in Buzz's runtime picker", "Martha").option("--command <bin>", "Executable Buzz should spawn", "martha").option("--use-profile <name>", "Bake MARTHA_PROFILE into the definition as the DEFAULT for every agent on this runtime, so Edit Agent needs nothing. A per-agent MARTHA_PROFILE in Edit Agent overrides it — that is how two Buzz agents become two different Martha agents. Named --use-profile because the global --profile picks which profile this COMMAND talks to.").option("--print", "Print the definition instead of writing it").option("--force", "Overwrite an existing definition").action(async (type, opts) => {
15259
15332
  assertSupportedChannel(type);
15260
15333
  const def = buzzHarnessDefinition({
@@ -15300,7 +15373,7 @@ function registerChannelCommands(program2) {
15300
15373
  });
15301
15374
  channels.command("preflight <type>").description("Check every precondition for an agent to answer in a channel, and name the one command that fixes each gap. Exits non-zero if any check fails.").requiredOption("--agent <name>", "The Martha agent that will answer").option("--relay <url>", "Relay URL", "ws://localhost:3030").option("--channel <uuid>", "Check membership of one specific channel").option("--buzz-acp-bin <path>", "buzz-acp binary", "buzz-acp").option("--buzz-bin <path>", "buzz CLI binary", "buzz").option("--martha-bin <path>", "martha binary buzz-acp will spawn", "martha").action(async (type, opts) => {
15302
15375
  assertSupportedChannel(type);
15303
- const ctx = contextFor(program2);
15376
+ const ctx = contextFor(program);
15304
15377
  const checks = await preflightBuzz(ctx, {
15305
15378
  agent: opts.agent,
15306
15379
  relayUrl: opts.relay,
@@ -15318,7 +15391,7 @@ function registerChannelCommands(program2) {
15318
15391
  if (opts.subscribe !== "mentions" && opts.subscribe !== "all") {
15319
15392
  throw new CLIError(`--subscribe must be 'mentions' or 'all' (got '${opts.subscribe}').`, 4 /* Validation */);
15320
15393
  }
15321
- const ctx = contextFor(program2);
15394
+ const ctx = contextFor(program);
15322
15395
  const checks = await preflightBuzz(ctx, {
15323
15396
  agent: opts.agent,
15324
15397
  relayUrl: opts.relay,
@@ -15328,20 +15401,20 @@ function registerChannelCommands(program2) {
15328
15401
  buzzBin: opts.buzzBin
15329
15402
  });
15330
15403
  reportPreflight(type, opts.agent, checks, opts.emit ? "stderr" : "stdout");
15331
- const env2 = buzzAcpEnv({
15404
+ const env = buzzAcpEnv({
15332
15405
  relayUrl: opts.relay,
15333
15406
  subscribe: opts.subscribe,
15334
15407
  kinds: opts.kinds,
15335
15408
  multipleEventHandling: "queue",
15336
15409
  respondTo: opts.respondTo,
15337
15410
  marthaBin: opts.marthaBin,
15338
- profile: program2.opts().profile
15411
+ profile: program.opts().profile
15339
15412
  });
15340
15413
  if (opts.emit) {
15341
15414
  if (!["docker", "compose", "k8s"].includes(opts.emit)) {
15342
15415
  throw new CLIError(`--emit must be docker, compose or k8s (got '${opts.emit}').`, 4 /* Validation */);
15343
15416
  }
15344
- console.log(emitManifest(opts.emit, env2, {
15417
+ console.log(emitManifest(opts.emit, env, {
15345
15418
  agent: opts.agent,
15346
15419
  image: opts.image
15347
15420
  }));
@@ -15361,7 +15434,7 @@ function registerChannelCommands(program2) {
15361
15434
  if (opts.dryRun) {
15362
15435
  console.log(source_default.bold(`Would launch:
15363
15436
  `));
15364
- for (const [k, v] of Object.entries(env2))
15437
+ for (const [k, v] of Object.entries(env))
15365
15438
  console.log(` ${k}=${v}`);
15366
15439
  console.log(` ${acp.path}
15367
15440
  `);
@@ -15371,10 +15444,10 @@ function registerChannelCommands(program2) {
15371
15444
  Connecting '${opts.agent}' to ${opts.relay} …
15372
15445
  `));
15373
15446
  const child = spawn3(acp.path, [], {
15374
- env: { ...process.env, PATH: childPath, ...env2 },
15447
+ env: { ...process.env, PATH: childPath, ...env },
15375
15448
  stdio: "inherit"
15376
15449
  });
15377
- await new Promise((resolve2) => {
15450
+ await new Promise((resolve) => {
15378
15451
  child.on("exit", (code, signal) => {
15379
15452
  if (signal) {
15380
15453
  console.log(source_default.dim(`
@@ -15383,21 +15456,21 @@ buzz-acp terminated by ${signal}`));
15383
15456
  } else if (code) {
15384
15457
  process.exitCode = code;
15385
15458
  }
15386
- resolve2();
15459
+ resolve();
15387
15460
  });
15388
15461
  child.on("error", (err) => {
15389
15462
  console.error(source_default.red(`failed to start ${acp}: ${err.message}`));
15390
15463
  process.exitCode = 1 /* Error */;
15391
- resolve2();
15464
+ resolve();
15392
15465
  });
15393
15466
  });
15394
15467
  });
15395
15468
  }
15396
- function contextFor(program2) {
15469
+ function contextFor(program) {
15397
15470
  return createContext({
15398
- profileOverride: program2.opts().profile,
15399
- apiUrlOverride: program2.opts().apiUrl,
15400
- verbose: program2.opts().verbose
15471
+ profileOverride: program.opts().profile,
15472
+ apiUrlOverride: program.opts().apiUrl,
15473
+ verbose: program.opts().verbose
15401
15474
  });
15402
15475
  }
15403
15476
  function reportPreflight(type, agent, checks, stream = "stdout") {
@@ -15458,9 +15531,9 @@ init_errors();
15458
15531
  import { createInterface as createInterface4 } from "node:readline";
15459
15532
  function prompt(rl, question, defaultValue) {
15460
15533
  const suffix = defaultValue ? ` [${defaultValue}]` : "";
15461
- return new Promise((resolve2) => {
15534
+ return new Promise((resolve) => {
15462
15535
  rl.question(`${question}${suffix}: `, (answer) => {
15463
- resolve2(answer.trim() || defaultValue || "");
15536
+ resolve(answer.trim() || defaultValue || "");
15464
15537
  });
15465
15538
  });
15466
15539
  }
@@ -15704,22 +15777,22 @@ function configUse(profileName, configDir) {
15704
15777
  saveConfig(config, configDir);
15705
15778
  console.log(`Switched to profile ${source_default.cyan(profileName)}`);
15706
15779
  }
15707
- function registerConfigCommand(program2) {
15708
- const configCmd = program2.command("config").description("Manage CLI configuration and profiles");
15780
+ function registerConfigCommand(program) {
15781
+ const configCmd = program.command("config").description("Manage CLI configuration and profiles");
15709
15782
  configCmd.command("init").description("Interactive config setup").action(async () => {
15710
15783
  await configInit();
15711
15784
  });
15712
15785
  configCmd.command("show").description("Print current config").action(() => {
15713
- configShow(!!program2.opts().json, undefined, program2.opts().profile);
15786
+ configShow(!!program.opts().json, undefined, program.opts().profile);
15714
15787
  });
15715
15788
  configCmd.command("get <key>").description("Get a config value").action((key) => {
15716
- configGet(key, !!program2.opts().json, undefined, program2.opts().profile);
15789
+ configGet(key, !!program.opts().json, undefined, program.opts().profile);
15717
15790
  });
15718
15791
  configCmd.command("set <key> <value>").description("Set a config value").action((key, value) => {
15719
- configSet(key, value, !!program2.opts().json, undefined, program2.opts().profile);
15792
+ configSet(key, value, !!program.opts().json, undefined, program.opts().profile);
15720
15793
  });
15721
15794
  configCmd.command("profiles").description("List all profiles").action(() => {
15722
- configProfiles(!!program2.opts().json);
15795
+ configProfiles(!!program.opts().json);
15723
15796
  });
15724
15797
  configCmd.command("use <profile>").description("Switch active profile").action((profile) => {
15725
15798
  configUse(profile);
@@ -15743,7 +15816,7 @@ function registerConfigCommand(program2) {
15743
15816
  config.current_profile = name;
15744
15817
  }
15745
15818
  saveConfig(config);
15746
- if (program2.opts().json) {
15819
+ if (program.opts().json) {
15747
15820
  console.log(JSON.stringify({
15748
15821
  name,
15749
15822
  profile,
@@ -15766,14 +15839,14 @@ function registerConfigCommand(program2) {
15766
15839
  if (!process.stdin.isTTY) {
15767
15840
  throw new CLIError("Cannot confirm in non-interactive mode.", 4 /* Validation */, "Use --yes to skip confirmation.");
15768
15841
  }
15769
- const ok = await new Promise((resolve2) => {
15842
+ const ok = await new Promise((resolve) => {
15770
15843
  const rl = createInterface4({
15771
15844
  input: process.stdin,
15772
15845
  output: process.stderr
15773
15846
  });
15774
15847
  rl.question(`Delete profile '${name}'? (y/N) `, (answer) => {
15775
15848
  rl.close();
15776
- resolve2(answer.trim().toLowerCase() === "y");
15849
+ resolve(answer.trim().toLowerCase() === "y");
15777
15850
  });
15778
15851
  });
15779
15852
  if (!ok) {
@@ -15787,7 +15860,7 @@ function registerConfigCommand(program2) {
15787
15860
  config.current_profile = remaining[0] ?? "default";
15788
15861
  }
15789
15862
  saveConfig(config);
15790
- if (program2.opts().json) {
15863
+ if (program.opts().json) {
15791
15864
  console.log(JSON.stringify({ name, deleted: true }));
15792
15865
  return;
15793
15866
  }
@@ -16466,10 +16539,10 @@ function renderResults(results, isJson, warnings) {
16466
16539
  ${failed.length} failed.`));
16467
16540
  }
16468
16541
  }
16469
- function registerDefinitionsApply(program2) {
16470
- let defCmd = program2.commands.find((c) => c.name() === "definitions");
16542
+ function registerDefinitionsApply(program) {
16543
+ let defCmd = program.commands.find((c) => c.name() === "definitions");
16471
16544
  if (!defCmd) {
16472
- defCmd = program2.command("definitions").description("Cross-type definition operations");
16545
+ defCmd = program.command("definitions").description("Cross-type definition operations");
16473
16546
  }
16474
16547
  defCmd.command("apply").description("Apply definitions from YAML/JSON files (create or update, never deletes)").requiredOption("-f, --file <path>", "Path to a YAML/JSON file or directory of definitions").option("--dry-run", "Preview changes without applying").option("--yes", "Skip confirmation prompt").addHelpText("after", `
16475
16548
  Examples:
@@ -16479,13 +16552,13 @@ Examples:
16479
16552
  $ martha definitions apply -f definitions/ --dry-run Preview only
16480
16553
  $ martha definitions apply -f definitions/ --yes Skip confirmation`).action(async (opts) => {
16481
16554
  const ctx = createContext({
16482
- profileOverride: program2.opts().profile,
16483
- verbose: program2.opts().verbose
16555
+ profileOverride: program.opts().profile,
16556
+ verbose: program.opts().verbose
16484
16557
  });
16485
- if (program2.opts().apiUrl) {
16486
- ctx.profile.api_url = program2.opts().apiUrl;
16558
+ if (program.opts().apiUrl) {
16559
+ ctx.profile.api_url = program.opts().apiUrl;
16487
16560
  }
16488
- const isJson = !!program2.opts().json;
16561
+ const isJson = !!program.opts().json;
16489
16562
  const defs = loadDefinitions(opts.file);
16490
16563
  if (defs.length === 0) {
16491
16564
  if (isJson) {
@@ -16605,22 +16678,22 @@ function renderStats(stats) {
16605
16678
  const wf = stats.workflows;
16606
16679
  console.log(`Workflows: ${wf.total} total (${wf.active} active, ${wf.inactive} inactive)`);
16607
16680
  }
16608
- function registerDefinitionsExport(program2) {
16609
- let defCmd = program2.commands.find((c) => c.name() === "definitions");
16681
+ function registerDefinitionsExport(program) {
16682
+ let defCmd = program.commands.find((c) => c.name() === "definitions");
16610
16683
  if (!defCmd) {
16611
- defCmd = program2.command("definitions").description("Cross-type definition operations");
16684
+ defCmd = program.command("definitions").description("Cross-type definition operations");
16612
16685
  }
16613
16686
  function getCtx() {
16614
16687
  const ctx = createContext({
16615
- profileOverride: program2.opts().profile,
16616
- verbose: program2.opts().verbose
16688
+ profileOverride: program.opts().profile,
16689
+ verbose: program.opts().verbose
16617
16690
  });
16618
- if (program2.opts().apiUrl)
16619
- ctx.profile.api_url = program2.opts().apiUrl;
16691
+ if (program.opts().apiUrl)
16692
+ ctx.profile.api_url = program.opts().apiUrl;
16620
16693
  return ctx;
16621
16694
  }
16622
16695
  function isJson() {
16623
- return !!program2.opts().json;
16696
+ return !!program.opts().json;
16624
16697
  }
16625
16698
  defCmd.command("export").description("Export all definitions (functions and workflows)").option("--format <format>", "Output format: yaml or json (default: yaml)", "yaml").option("--output <file>", "Write to file instead of stdout").option("--inactive", "Include inactive definitions").option("--functions-only", "Export functions only").option("--workflows-only", "Export workflows only").action(async (opts) => {
16626
16699
  if (opts.functionsOnly && opts.workflowsOnly) {
@@ -16665,14 +16738,14 @@ function registerDefinitionsExport(program2) {
16665
16738
  renderPlan(ops);
16666
16739
  }
16667
16740
  });
16668
- const fnCmd = program2.commands.find((c) => c.name() === "functions");
16741
+ const fnCmd = program.commands.find((c) => c.name() === "functions");
16669
16742
  if (fnCmd) {
16670
16743
  fnCmd.command("export").description("Export function definitions").option("--format <format>", "Output format: yaml or json (default: yaml)", "yaml").option("--output <file>", "Write to file instead of stdout").option("--inactive", "Include inactive definitions").action(async (opts) => {
16671
16744
  const ctx = getCtx();
16672
16745
  await exportDefinitions(ctx, { ...opts, functionsOnly: true }, isJson());
16673
16746
  });
16674
16747
  }
16675
- const wfCmd = program2.commands.find((c) => c.name() === "workflows");
16748
+ const wfCmd = program.commands.find((c) => c.name() === "workflows");
16676
16749
  if (wfCmd) {
16677
16750
  wfCmd.command("export").description("Export workflow definitions").option("--format <format>", "Output format: yaml or json (default: yaml)", "yaml").option("--output <file>", "Write to file instead of stdout").option("--inactive", "Include inactive definitions").action(async (opts) => {
16678
16751
  const ctx = getCtx();
@@ -16891,7 +16964,7 @@ function colorStatus(status) {
16891
16964
  return fn(status);
16892
16965
  }
16893
16966
  function sleep2(ms) {
16894
- return new Promise((resolve2) => setTimeout(resolve2, ms));
16967
+ return new Promise((resolve) => setTimeout(resolve, ms));
16895
16968
  }
16896
16969
  async function pollUntilDone(ctx, executionId, intervalMs = 2000, timeoutMs = 300000) {
16897
16970
  const deadline = Date.now() + timeoutMs;
@@ -17301,8 +17374,8 @@ function registerProjectionCommands(parentCmd, getCtx, isJson) {
17301
17374
  } catch {}
17302
17375
  }
17303
17376
  if (opts.output) {
17304
- const fs10 = await import("node:fs/promises");
17305
- await fs10.writeFile(opts.output, toWrite, "utf-8");
17377
+ const fs = await import("node:fs/promises");
17378
+ await fs.writeFile(opts.output, toWrite, "utf-8");
17306
17379
  if (!isJson()) {
17307
17380
  console.error(source_default.dim(`Wrote ${format} projection of '${name}' to ${opts.output}`));
17308
17381
  }
@@ -17407,21 +17480,21 @@ var promptsConfig = {
17407
17480
  accessor: (item) => item.is_protected ? "yes" : "no"
17408
17481
  }
17409
17482
  ],
17410
- renderDetail: (prompt2) => {
17411
- console.log(source_default.bold(`Prompt: ${prompt2.name}
17483
+ renderDetail: (prompt) => {
17484
+ console.log(source_default.bold(`Prompt: ${prompt.name}
17412
17485
  `));
17413
- if (prompt2.description)
17414
- console.log(` ${prompt2.description}
17486
+ if (prompt.description)
17487
+ console.log(` ${prompt.description}
17415
17488
  `);
17416
- console.log(` Scope: ${prompt2.scope ?? "-"}`);
17417
- console.log(` Protected: ${prompt2.is_protected ? source_default.yellow("yes") : "no"}`);
17418
- const prod = prompt2.production;
17419
- const staging = prompt2.staging;
17489
+ console.log(` Scope: ${prompt.scope ?? "-"}`);
17490
+ console.log(` Protected: ${prompt.is_protected ? source_default.yellow("yes") : "no"}`);
17491
+ const prod = prompt.production;
17492
+ const staging = prompt.staging;
17420
17493
  console.log(` Prod Ver: ${prod?.version ?? "-"}`);
17421
17494
  console.log(` Staging Ver: ${staging?.version ?? "-"}`);
17422
- if (prompt2.updated_at)
17423
- console.log(` Updated: ${prompt2.updated_at}`);
17424
- const content = prompt2.content;
17495
+ if (prompt.updated_at)
17496
+ console.log(` Updated: ${prompt.updated_at}`);
17497
+ const content = prompt.content;
17425
17498
  if (content) {
17426
17499
  console.log(`
17427
17500
  ${source_default.bold("Content:")}`);
@@ -17656,7 +17729,7 @@ function nextSpinner() {
17656
17729
  return frame;
17657
17730
  }
17658
17731
  function sleep3(ms) {
17659
- return new Promise((resolve2) => setTimeout(resolve2, ms));
17732
+ return new Promise((resolve) => setTimeout(resolve, ms));
17660
17733
  }
17661
17734
  function formatBytes(bytes) {
17662
17735
  if (bytes < 1024)
@@ -17811,19 +17884,19 @@ Detached. Check status with: martha documents status ${documentId}`));
17811
17884
  process.removeListener("SIGINT", sigintHandler);
17812
17885
  }
17813
17886
  }
17814
- function registerDocumentCommands(program2) {
17815
- const cmd = program2.command("documents").description("Manage document collections and ingestion");
17887
+ function registerDocumentCommands(program) {
17888
+ const cmd = program.command("documents").description("Manage document collections and ingestion");
17816
17889
  function getCtx() {
17817
17890
  const ctx = createContext({
17818
- profileOverride: program2.opts().profile,
17819
- verbose: program2.opts().verbose
17891
+ profileOverride: program.opts().profile,
17892
+ verbose: program.opts().verbose
17820
17893
  });
17821
- if (program2.opts().apiUrl)
17822
- ctx.profile.api_url = program2.opts().apiUrl;
17894
+ if (program.opts().apiUrl)
17895
+ ctx.profile.api_url = program.opts().apiUrl;
17823
17896
  return ctx;
17824
17897
  }
17825
17898
  function isJson() {
17826
- return !!program2.opts().json;
17899
+ return !!program.opts().json;
17827
17900
  }
17828
17901
  async function resolveCollection(ctx, ref) {
17829
17902
  const looksLikeUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(ref);
@@ -18423,19 +18496,19 @@ Ingestion status — source ${sourceId}`));
18423
18496
  }
18424
18497
  }
18425
18498
  }
18426
- function registerDocumentSyncCommands(program2) {
18427
- const cmd = program2.command("document-sync").description("Manage durable document sync sources (Google Drive, etc.)");
18499
+ function registerDocumentSyncCommands(program) {
18500
+ const cmd = program.command("document-sync").description("Manage durable document sync sources (Google Drive, etc.)");
18428
18501
  function getCtx() {
18429
18502
  const ctx = createContext({
18430
- profileOverride: program2.opts().profile,
18431
- verbose: program2.opts().verbose
18503
+ profileOverride: program.opts().profile,
18504
+ verbose: program.opts().verbose
18432
18505
  });
18433
- if (program2.opts().apiUrl)
18434
- ctx.profile.api_url = program2.opts().apiUrl;
18506
+ if (program.opts().apiUrl)
18507
+ ctx.profile.api_url = program.opts().apiUrl;
18435
18508
  return ctx;
18436
18509
  }
18437
18510
  function isJson() {
18438
- return !!program2.opts().json;
18511
+ return !!program.opts().json;
18439
18512
  }
18440
18513
  function printSummary(name, s) {
18441
18514
  const tag = s.dry_run ? source_default.yellow(" (dry-run)") : "";
@@ -18457,17 +18530,17 @@ ${name}${tag}`));
18457
18530
  throw new CLIError("--source and --all are mutually exclusive", 4 /* Validation */);
18458
18531
  }
18459
18532
  const params = { dry_run: String(dryRun) };
18460
- let sources2;
18533
+ let sources;
18461
18534
  if (opts.all) {
18462
18535
  const all = await ctx.api.get("/api/admin/document-sync/sources", { params: { provider: "google_drive" } });
18463
- sources2 = all;
18536
+ sources = all;
18464
18537
  } else {
18465
- sources2 = [
18538
+ sources = [
18466
18539
  { id: opts.source, name: opts.source, provider: "google_drive" }
18467
18540
  ];
18468
18541
  }
18469
18542
  const results = [];
18470
- for (const src of sources2) {
18543
+ for (const src of sources) {
18471
18544
  const summary = await ctx.api.post(`/api/admin/document-sync/sources/${encodeURIComponent(src.id)}/reconcile-tree`, undefined, { params });
18472
18545
  results.push(summary);
18473
18546
  if (!isJson())
@@ -18594,17 +18667,17 @@ No google_drive sources found.`));
18594
18667
 
18595
18668
  // src/commands/approvals.ts
18596
18669
  init_errors();
18597
- function registerApprovalCommands(program2) {
18598
- const cmd = program2.command("approvals").description("Manage approval cases");
18670
+ function registerApprovalCommands(program) {
18671
+ const cmd = program.command("approvals").description("Manage approval cases");
18599
18672
  function getCtx() {
18600
18673
  return createContext({
18601
- profileOverride: program2.opts().profile,
18602
- apiUrlOverride: program2.opts().apiUrl,
18603
- verbose: program2.opts().verbose
18674
+ profileOverride: program.opts().profile,
18675
+ apiUrlOverride: program.opts().apiUrl,
18676
+ verbose: program.opts().verbose
18604
18677
  });
18605
18678
  }
18606
18679
  function isJson() {
18607
- return !!program2.opts().json;
18680
+ return !!program.opts().json;
18608
18681
  }
18609
18682
  cmd.command("list").description("List approval cases").option("--status <status>", "Filter by status").option("--assigned-to <user>", "Filter by assignee").option("--limit <n>", "Max results", "50").action(async (opts) => {
18610
18683
  const ctx = getCtx();
@@ -18690,19 +18763,19 @@ function renderAsk(a) {
18690
18763
  return lines.join(`
18691
18764
  `);
18692
18765
  }
18693
- function registerAskCommands(program2) {
18694
- const cmd = program2.command("asks").description("Agent asks — questions/approval requests to the human queue (agent credentials)");
18766
+ function registerAskCommands(program) {
18767
+ const cmd = program.command("asks").description("Agent asks — questions/approval requests to the human queue (agent credentials)");
18695
18768
  function getCtx() {
18696
18769
  const ctx = createContext({
18697
- profileOverride: program2.opts().profile,
18698
- verbose: program2.opts().verbose
18770
+ profileOverride: program.opts().profile,
18771
+ verbose: program.opts().verbose
18699
18772
  });
18700
- if (program2.opts().apiUrl)
18701
- ctx.profile.api_url = program2.opts().apiUrl;
18773
+ if (program.opts().apiUrl)
18774
+ ctx.profile.api_url = program.opts().apiUrl;
18702
18775
  return ctx;
18703
18776
  }
18704
18777
  function isJson() {
18705
- return !!program2.opts().json;
18778
+ return !!program.opts().json;
18706
18779
  }
18707
18780
  cmd.command("create").description("File an ask (the server attributes it to the token's agent)").requiredOption("--reason <text>", "The question / what approval is requested").option("--kind <kind>", `${KINDS.join(" | ")} (default agent_question)`, "agent_question").option("--context <text>", "Context summary for the reviewer").option("--questions <json>", "Structured questions JSON array (ask_user shape: question/header/options/multiSelect)").option("--expires-in <seconds>", "Auto-expire the ask after N seconds").option("--idempotency-key <key>", "Dedup key — retries with the same key do not double-file").action(async (opts) => {
18708
18781
  if (!KINDS.includes(opts.kind)) {
@@ -18824,18 +18897,18 @@ async function buildCreateTaskBody(ctx, opts) {
18824
18897
  body.sticky_assignment = true;
18825
18898
  return body;
18826
18899
  }
18827
- var sleep4 = (ms, signal) => new Promise((resolve2) => {
18900
+ var sleep4 = (ms, signal) => new Promise((resolve) => {
18828
18901
  if (signal?.aborted) {
18829
- resolve2();
18902
+ resolve();
18830
18903
  return;
18831
18904
  }
18832
18905
  const t = setTimeout(() => {
18833
18906
  signal?.removeEventListener("abort", onAbort);
18834
- resolve2();
18907
+ resolve();
18835
18908
  }, ms);
18836
18909
  const onAbort = () => {
18837
18910
  clearTimeout(t);
18838
- resolve2();
18911
+ resolve();
18839
18912
  };
18840
18913
  signal?.addEventListener("abort", onAbort, { once: true });
18841
18914
  });
@@ -18872,19 +18945,19 @@ var priorityColor = (priority) => {
18872
18945
  return priority;
18873
18946
  }
18874
18947
  };
18875
- function registerTaskCommands(program2) {
18876
- const cmd = program2.command("tasks").description("Manage agent tasks");
18948
+ function registerTaskCommands(program) {
18949
+ const cmd = program.command("tasks").description("Manage agent tasks");
18877
18950
  function getCtx() {
18878
18951
  const ctx = createContext({
18879
- profileOverride: program2.opts().profile,
18880
- verbose: program2.opts().verbose
18952
+ profileOverride: program.opts().profile,
18953
+ verbose: program.opts().verbose
18881
18954
  });
18882
- if (program2.opts().apiUrl)
18883
- ctx.profile.api_url = program2.opts().apiUrl;
18955
+ if (program.opts().apiUrl)
18956
+ ctx.profile.api_url = program.opts().apiUrl;
18884
18957
  return ctx;
18885
18958
  }
18886
18959
  function isJson() {
18887
- return !!program2.opts().json;
18960
+ return !!program.opts().json;
18888
18961
  }
18889
18962
  cmd.command("list").description("List tasks").option("--status <status>", "Filter by status (open, running, completed, failed, cancelled)").option("--agent <id>", "Filter by agent definition ID").option("--priority <priority>", "Filter by priority (low, medium, high, urgent)").option("--search <query>", "Search in title and goal").option("--limit <n>", "Max results", "50").action(async (opts) => {
18890
18963
  const ctx = getCtx();
@@ -19298,9 +19371,9 @@ function sleepUnref(ms) {
19298
19371
  }
19299
19372
  var ACK_INTERVAL_MS = 5000;
19300
19373
  function startupEchoLine(who, opts) {
19301
- const identity2 = who ? who.kind === "agent" ? `agent ${who.agent_name ?? "?"} (${(who.agent_id ?? "").slice(0, 8)}…)` : `${who.kind} ${who.sub ?? ""}`.trim() : "identity unknown (whoami unavailable)";
19374
+ const identity = who ? who.kind === "agent" ? `agent ${who.agent_name ?? "?"} (${(who.agent_id ?? "").slice(0, 8)}…)` : `${who.kind} ${who.sub ?? ""}`.trim() : "identity unknown (whoami unavailable)";
19302
19375
  const exec = opts.allowHostExec ? "host exec allowed" : "host exec refused (pass --allow-host-exec)";
19303
- return `[runner] attached as ${identity2} — this machine is the agent's hands (host executor; the agent reasons in Martha's cloud loop), cwd ${opts.cwd}, ${exec}`;
19376
+ return `[runner] attached as ${identity} — this machine is the agent's hands (host executor; the agent reasons in Martha's cloud loop), cwd ${opts.cwd}, ${exec}`;
19304
19377
  }
19305
19378
  function rejectRemovedTaskModeFlags(opts) {
19306
19379
  const used = [
@@ -19438,13 +19511,13 @@ async function runChannelLoop(ctx, state, abort) {
19438
19511
  }
19439
19512
  }
19440
19513
  }
19441
- function registerRunnerCommand(program2) {
19442
- program2.command("runner").description("Attach this machine as a cloud agent's hands (#714): hold the per-agent " + "channel open and execute host-tool calls the agent's Martha-hosted " + "reasoning loop parks on (chat gates and assigned-task parks). Identity " + "comes from the API token (the agent's runner key). The runner never " + "reasons and never runs tasks — self-hosted agents drive the task REST " + "(`martha tasks poll/claim/complete`) with their own code.").option("--tools", "Accepted no-op: hands mode is the only mode (kept so printed " + "setup-host-runner commands stay valid).").option("--cwd <dir>", "Scoped workspace for host execution", process.cwd()).option("--allow-host-exec", "Consent to run host commands (required to execute)").option("--yes", "Deprecated alias for --allow-host-exec").option("--local-agent <name>", "Local coding agent for local_agent delegation over the channel", DEFAULT_LOCAL_AGENT).option("--tasks", "REMOVED (#714): the runner no longer runs tasks").option("--channel", "REMOVED (#714): deprecated pre-#822 alias").option("--once", "REMOVED (#714): belonged to the task-executor mode").option("--team <name>", "REMOVED (#714): belonged to the task-executor mode").option("--agent <id>", "REMOVED (#714): identity comes from the API token").option("--poll-interval <ms>", "REMOVED (#714): the runner no longer polls").action(async (opts) => {
19514
+ function registerRunnerCommand(program) {
19515
+ program.command("runner").description("Attach this machine as a cloud agent's hands (#714): hold the per-agent " + "channel open and execute host-tool calls the agent's Martha-hosted " + "reasoning loop parks on (chat gates and assigned-task parks). Identity " + "comes from the API token (the agent's runner key). The runner never " + "reasons and never runs tasks — self-hosted agents drive the task REST " + "(`martha tasks poll/claim/complete`) with their own code.").option("--tools", "Accepted no-op: hands mode is the only mode (kept so printed " + "setup-host-runner commands stay valid).").option("--cwd <dir>", "Scoped workspace for host execution", process.cwd()).option("--allow-host-exec", "Consent to run host commands (required to execute)").option("--yes", "Deprecated alias for --allow-host-exec").option("--local-agent <name>", "Local coding agent for local_agent delegation over the channel", DEFAULT_LOCAL_AGENT).option("--tasks", "REMOVED (#714): the runner no longer runs tasks").option("--channel", "REMOVED (#714): deprecated pre-#822 alias").option("--once", "REMOVED (#714): belonged to the task-executor mode").option("--team <name>", "REMOVED (#714): belonged to the task-executor mode").option("--agent <id>", "REMOVED (#714): identity comes from the API token").option("--poll-interval <ms>", "REMOVED (#714): the runner no longer polls").action(async (opts) => {
19443
19516
  rejectRemovedTaskModeFlags(opts);
19444
19517
  const ctx = createContext({
19445
- profileOverride: program2.opts().profile,
19446
- verbose: program2.opts().verbose,
19447
- apiUrlOverride: program2.opts().apiUrl
19518
+ profileOverride: program.opts().profile,
19519
+ verbose: program.opts().verbose,
19520
+ apiUrlOverride: program.opts().apiUrl
19448
19521
  });
19449
19522
  const allowHostExec = !!(opts.allowHostExec || opts.yes);
19450
19523
  let who;
@@ -19483,19 +19556,19 @@ function registerRunnerCommand(program2) {
19483
19556
  init_errors();
19484
19557
  var API_PATH3 = "/api/admin/teams";
19485
19558
  var fmtDate3 = (v) => typeof v === "string" ? new Date(v).toISOString().slice(0, 16).replace("T", " ") : "-";
19486
- function registerTeamCommands(program2) {
19487
- const cmd = program2.command("teams").description("Manage agent teams");
19559
+ function registerTeamCommands(program) {
19560
+ const cmd = program.command("teams").description("Manage agent teams");
19488
19561
  function getCtx() {
19489
19562
  const ctx = createContext({
19490
- profileOverride: program2.opts().profile,
19491
- verbose: program2.opts().verbose
19563
+ profileOverride: program.opts().profile,
19564
+ verbose: program.opts().verbose
19492
19565
  });
19493
- if (program2.opts().apiUrl)
19494
- ctx.profile.api_url = program2.opts().apiUrl;
19566
+ if (program.opts().apiUrl)
19567
+ ctx.profile.api_url = program.opts().apiUrl;
19495
19568
  return ctx;
19496
19569
  }
19497
19570
  function isJson() {
19498
- return !!program2.opts().json;
19571
+ return !!program.opts().json;
19499
19572
  }
19500
19573
  cmd.command("create").description("Create a new team").requiredOption("--name <name>", "Team name").option("--description <text>", "Team description").option("--routing <strategy>", "Routing strategy (manual or round_robin)", "manual").action(async (opts) => {
19501
19574
  const ctx = getCtx();
@@ -19660,19 +19733,19 @@ function healthColor(status) {
19660
19733
  return source_default.dim(status);
19661
19734
  }
19662
19735
  }
19663
- function registerIntegrationCommands(program2) {
19664
- const cmd = program2.command("integrations").description("Manage integrations and OpenAPI specs");
19736
+ function registerIntegrationCommands(program) {
19737
+ const cmd = program.command("integrations").description("Manage integrations and OpenAPI specs");
19665
19738
  function getCtx() {
19666
19739
  const ctx = createContext({
19667
- profileOverride: program2.opts().profile,
19668
- verbose: program2.opts().verbose
19740
+ profileOverride: program.opts().profile,
19741
+ verbose: program.opts().verbose
19669
19742
  });
19670
- if (program2.opts().apiUrl)
19671
- ctx.profile.api_url = program2.opts().apiUrl;
19743
+ if (program.opts().apiUrl)
19744
+ ctx.profile.api_url = program.opts().apiUrl;
19672
19745
  return ctx;
19673
19746
  }
19674
19747
  function isJson() {
19675
- return !!program2.opts().json;
19748
+ return !!program.opts().json;
19676
19749
  }
19677
19750
  cmd.command("list").description("List all integrations").action(async () => {
19678
19751
  const ctx = getCtx();
@@ -19811,12 +19884,12 @@ ${data.length} spec(s)`));
19811
19884
  const created = result.created ?? [];
19812
19885
  const updated = result.updated ?? [];
19813
19886
  const skipped = result.skipped ?? [];
19814
- const errors2 = result.errors ?? [];
19887
+ const errors = result.errors ?? [];
19815
19888
  console.log(` Created: ${source_default.green(created.length)} ` + `Updated: ${source_default.yellow(updated.length)} ` + `Skipped: ${source_default.dim(skipped.length)}`);
19816
- if (errors2.length > 0) {
19889
+ if (errors.length > 0) {
19817
19890
  console.log(source_default.red(`
19818
- Errors (${errors2.length}):`));
19819
- for (const err of errors2) {
19891
+ Errors (${errors.length}):`));
19892
+ for (const err of errors) {
19820
19893
  console.log(source_default.red(` - ${err}`));
19821
19894
  }
19822
19895
  }
@@ -19885,11 +19958,11 @@ ${data.length} spec(s)`));
19885
19958
  console.log(source_default.yellow(` - ${w}`));
19886
19959
  }
19887
19960
  }
19888
- const errors2 = result.errors ?? [];
19889
- if (errors2.length > 0) {
19961
+ const errors = result.errors ?? [];
19962
+ if (errors.length > 0) {
19890
19963
  console.log(source_default.red(`
19891
- Errors (${errors2.length}):`));
19892
- for (const e of errors2) {
19964
+ Errors (${errors.length}):`));
19965
+ for (const e of errors) {
19893
19966
  console.log(source_default.red(` - ${e}`));
19894
19967
  }
19895
19968
  }
@@ -19971,8 +20044,8 @@ ${data.length} spec(s)`));
19971
20044
  Resources:
19972
20045
  `));
19973
20046
  for (const r of resources) {
19974
- const path9 = r.path || `/${r.name}`;
19975
- console.log(` ${source_default.cyan(r.label || r.name)}` + source_default.dim(` → ${path9}`));
20047
+ const path = r.path || `/${r.name}`;
20048
+ console.log(` ${source_default.cyan(r.label || r.name)}` + source_default.dim(` → ${path}`));
19976
20049
  }
19977
20050
  }
19978
20051
  try {
@@ -19992,14 +20065,14 @@ Functions:
19992
20065
  console.log(source_default.dim(`
19993
20066
  Proxy: martha integrations proxy ${name} GET /<path>`));
19994
20067
  });
19995
- cmd.command("proxy <name> <method> <path>").description("Send a request through the plugin proxy").option("--data <json>", "JSON request body").option("--query <params>", "Query params as key=val&key=val").action(async (name, method, path9, opts) => {
20068
+ cmd.command("proxy <name> <method> <path>").description("Send a request through the plugin proxy").option("--data <json>", "JSON request body").option("--query <params>", "Query params as key=val&key=val").action(async (name, method, path, opts) => {
19996
20069
  const ctx = getCtx();
19997
20070
  const upperMethod = method.toUpperCase();
19998
20071
  const allowed = new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
19999
20072
  if (!allowed.has(upperMethod)) {
20000
20073
  throw new CLIError(`Invalid method: ${method}`, 4 /* Validation */, "Allowed: GET, POST, PUT, PATCH, DELETE");
20001
20074
  }
20002
- const cleanPath = path9.startsWith("/") ? path9.slice(1) : path9;
20075
+ const cleanPath = path.startsWith("/") ? path.slice(1) : path;
20003
20076
  const proxyUrl = `/api/admin/plugins/${encodeURIComponent(name)}/${cleanPath}`;
20004
20077
  const params = {};
20005
20078
  if (opts.query) {
@@ -20059,17 +20132,17 @@ function renderTable(columns, items, opts) {
20059
20132
 
20060
20133
  // src/commands/connections.ts
20061
20134
  init_errors();
20062
- function registerConnectionCommands(program2) {
20063
- const cmd = program2.command("connections").description("Manage Vault-backed integration connections (credentials live in Vault)");
20135
+ function registerConnectionCommands(program) {
20136
+ const cmd = program.command("connections").description("Manage Vault-backed integration connections (credentials live in Vault)");
20064
20137
  function getCtx() {
20065
20138
  return createContext({
20066
- profileOverride: program2.opts().profile,
20067
- apiUrlOverride: program2.opts().apiUrl,
20068
- verbose: program2.opts().verbose
20139
+ profileOverride: program.opts().profile,
20140
+ apiUrlOverride: program.opts().apiUrl,
20141
+ verbose: program.opts().verbose
20069
20142
  });
20070
20143
  }
20071
20144
  function isJson() {
20072
- return !!program2.opts().json;
20145
+ return !!program.opts().json;
20073
20146
  }
20074
20147
  cmd.command("list").description("List connections for the current tenant").option("--integration <name>", "Filter by integration name").option("--scope <scope>", "Filter by scope (tenant|client|system)").action(async (opts) => {
20075
20148
  const ctx = getCtx();
@@ -20210,8 +20283,8 @@ async function resolveCredentialValue(value) {
20210
20283
  if (value === "-")
20211
20284
  return readStdin();
20212
20285
  if (value.startsWith("@")) {
20213
- const fs11 = await import("node:fs/promises");
20214
- return (await fs11.readFile(value.slice(1), "utf-8")).trim();
20286
+ const fs = await import("node:fs/promises");
20287
+ return (await fs.readFile(value.slice(1), "utf-8")).trim();
20215
20288
  }
20216
20289
  return value;
20217
20290
  }
@@ -20246,19 +20319,19 @@ async function readStdin() {
20246
20319
 
20247
20320
  // src/commands/notifications.ts
20248
20321
  var CHANNEL_IDS = new Set(["resend", "slack_webhook", "webhook"]);
20249
- function registerNotificationCommands(program2) {
20250
- const cmd = program2.command("notifications").description("Manage notification channels (email/Slack/webhook) — issue #116");
20322
+ function registerNotificationCommands(program) {
20323
+ const cmd = program.command("notifications").description("Manage notification channels (email/Slack/webhook) — issue #116");
20251
20324
  function getCtx() {
20252
20325
  const ctx = createContext({
20253
- profileOverride: program2.opts().profile,
20254
- verbose: program2.opts().verbose
20326
+ profileOverride: program.opts().profile,
20327
+ verbose: program.opts().verbose
20255
20328
  });
20256
- if (program2.opts().apiUrl)
20257
- ctx.profile.api_url = program2.opts().apiUrl;
20329
+ if (program.opts().apiUrl)
20330
+ ctx.profile.api_url = program.opts().apiUrl;
20258
20331
  return ctx;
20259
20332
  }
20260
20333
  function isJson() {
20261
- return !!program2.opts().json;
20334
+ return !!program.opts().json;
20262
20335
  }
20263
20336
  cmd.command("channels").description("List available notification channel types").action(async () => {
20264
20337
  const ctx = getCtx();
@@ -20326,8 +20399,8 @@ Notification connections`));
20326
20399
  if (credentialValue === "-") {
20327
20400
  credentialValue = await readStdin2();
20328
20401
  } else if (credentialValue?.startsWith("@")) {
20329
- const fs11 = await import("node:fs/promises");
20330
- credentialValue = await fs11.readFile(credentialValue.slice(1), "utf-8");
20402
+ const fs = await import("node:fs/promises");
20403
+ credentialValue = await fs.readFile(credentialValue.slice(1), "utf-8");
20331
20404
  }
20332
20405
  if (!credentialValue) {
20333
20406
  throw new Error("--credential-value is required (use '-' for stdin or '@path' for file).");
@@ -20377,11 +20450,11 @@ async function readStdin2() {
20377
20450
 
20378
20451
  // src/commands/messaging.ts
20379
20452
  init_errors();
20380
- async function messagingFetch(baseUrl, path9, opts) {
20381
- if (/^(https?:)?\/\//i.test(path9)) {
20453
+ async function messagingFetch(baseUrl, path, opts) {
20454
+ if (/^(https?:)?\/\//i.test(path)) {
20382
20455
  throw new CLIError("Absolute URL paths are not allowed", 1 /* Error */);
20383
20456
  }
20384
- const url = new URL(path9, baseUrl);
20457
+ const url = new URL(path, baseUrl);
20385
20458
  const headers = {
20386
20459
  "Content-Type": "application/json"
20387
20460
  };
@@ -20407,19 +20480,19 @@ async function messagingFetch(baseUrl, path9, opts) {
20407
20480
  }
20408
20481
  return res.json();
20409
20482
  }
20410
- function registerMessagingCommands(program2) {
20411
- const cmd = program2.command("messaging").description("Messaging provider commands (SMS, WhatsApp)");
20483
+ function registerMessagingCommands(program) {
20484
+ const cmd = program.command("messaging").description("Messaging provider commands (SMS, WhatsApp)");
20412
20485
  function getCtx() {
20413
20486
  const ctx = createContext({
20414
- profileOverride: program2.opts().profile,
20415
- verbose: program2.opts().verbose
20487
+ profileOverride: program.opts().profile,
20488
+ verbose: program.opts().verbose
20416
20489
  });
20417
- if (program2.opts().apiUrl)
20418
- ctx.profile.api_url = program2.opts().apiUrl;
20490
+ if (program.opts().apiUrl)
20491
+ ctx.profile.api_url = program.opts().apiUrl;
20419
20492
  return ctx;
20420
20493
  }
20421
20494
  function isJson() {
20422
- return !!program2.opts().json;
20495
+ return !!program.opts().json;
20423
20496
  }
20424
20497
  cmd.command("health").description("Check messaging provider health").action(async () => {
20425
20498
  const ctx = getCtx();
@@ -20679,7 +20752,7 @@ function renderSnippet(options) {
20679
20752
  return renderEsmSnippet(options);
20680
20753
  }
20681
20754
  }
20682
- function parseKeyValueFlags(items, allowedKeys, label, parser2) {
20755
+ function parseKeyValueFlags(items, allowedKeys, label, parser) {
20683
20756
  const result = {};
20684
20757
  for (const item of items ?? []) {
20685
20758
  const idx = item.indexOf("=");
@@ -20694,7 +20767,7 @@ function parseKeyValueFlags(items, allowedKeys, label, parser2) {
20694
20767
  if (!allowedKeys.includes(key)) {
20695
20768
  throw new CLIError(`Unsupported ${label} key: ${key}`, 4 /* Validation */, `Allowed keys: ${allowedKeys.join(", ")}`);
20696
20769
  }
20697
- result[key] = parser2(value);
20770
+ result[key] = parser(value);
20698
20771
  }
20699
20772
  return result;
20700
20773
  }
@@ -20907,12 +20980,12 @@ function formatDate(val) {
20907
20980
  function clientKey(c) {
20908
20981
  return String(c.client_key ?? c.keycloak_client_id ?? "-");
20909
20982
  }
20910
- function setClientKeyPayload(body, clientKey2, keycloakClientId) {
20911
- if (clientKey2 && keycloakClientId && clientKey2 !== keycloakClientId) {
20983
+ function setClientKeyPayload(body, clientKey, keycloakClientId) {
20984
+ if (clientKey && keycloakClientId && clientKey !== keycloakClientId) {
20912
20985
  throw new CLIError("--client-key and --keycloak-client-id must match when both are provided.", 4 /* Validation */, "Use --client-key for new commands; --keycloak-client-id is deprecated.");
20913
20986
  }
20914
- if (clientKey2)
20915
- body.client_key = clientKey2;
20987
+ if (clientKey)
20988
+ body.client_key = clientKey;
20916
20989
  if (keycloakClientId)
20917
20990
  body.keycloak_client_id = keycloakClientId;
20918
20991
  }
@@ -21021,17 +21094,17 @@ async function revokeEmbedCredentials(ctx, clientId) {
21021
21094
  return ctx.api.del(`${API}/${clientId}/embed-credentials`);
21022
21095
  }
21023
21096
  async function createEmbedCredentialApi(ctx, credentials) {
21024
- const [{ MarthaAPIClient: MarthaAPIClient2 }, { loginClientCredentials: loginClientCredentials2 }] = await Promise.all([
21097
+ const [{ MarthaAPIClient }, { loginClientCredentials }] = await Promise.all([
21025
21098
  Promise.resolve().then(() => (init_api_client(), exports_api_client)),
21026
21099
  Promise.resolve().then(() => (init_client_credentials(), exports_client_credentials))
21027
21100
  ]);
21028
- const tokens = await loginClientCredentials2({
21101
+ const tokens = await loginClientCredentials({
21029
21102
  keycloakUrl: ctx.profile.keycloak_url,
21030
21103
  realm: ctx.profile.keycloak_realm,
21031
21104
  clientId: credentials.service_account_client_id,
21032
21105
  clientSecret: credentials.client_secret
21033
21106
  });
21034
- return new MarthaAPIClient2({
21107
+ return new MarthaAPIClient({
21035
21108
  baseUrl: ctx.profile.api_url,
21036
21109
  getAccessToken: async () => tokens.access_token
21037
21110
  });
@@ -21043,20 +21116,20 @@ async function grantAccess(ctx, clientId, type, defName) {
21043
21116
  const body = type === "function" ? { function_id: defId } : type === "workflow" ? { workflow_id: defId } : { agent_name: defId };
21044
21117
  await ctx.api.post(endpoint, body);
21045
21118
  }
21046
- function registerClientCommands(program2) {
21047
- const cmd = program2.command("clients").description("Manage chat clients and access control");
21119
+ function registerClientCommands(program) {
21120
+ const cmd = program.command("clients").description("Manage chat clients and access control");
21048
21121
  function getCtx() {
21049
21122
  const ctx = createContext({
21050
- profileOverride: program2.opts().profile,
21051
- verbose: program2.opts().verbose
21123
+ profileOverride: program.opts().profile,
21124
+ verbose: program.opts().verbose
21052
21125
  });
21053
- if (program2.opts().apiUrl) {
21054
- ctx.profile.api_url = program2.opts().apiUrl;
21126
+ if (program.opts().apiUrl) {
21127
+ ctx.profile.api_url = program.opts().apiUrl;
21055
21128
  }
21056
21129
  return ctx;
21057
21130
  }
21058
21131
  function isJson() {
21059
- return !!program2.opts().json;
21132
+ return !!program.opts().json;
21060
21133
  }
21061
21134
  cmd.command("list").description("List clients").option("--limit <n>", "Max results", "50").action(async (opts) => {
21062
21135
  const ctx = getCtx();
@@ -21475,10 +21548,10 @@ Embed-token mode needs backend credentials. Provision them with:
21475
21548
  let tempCredentials;
21476
21549
  try {
21477
21550
  if (opts.createTempClient) {
21478
- const key2 = `cli-smoke-${Date.now()}`;
21551
+ const key = `cli-smoke-${Date.now()}`;
21479
21552
  client = await ctx.api.post(API, {
21480
21553
  name: `CLI Smoke ${Date.now()}`,
21481
- client_key: key2,
21554
+ client_key: key,
21482
21555
  embed_enabled: true,
21483
21556
  embed_allowed_origins: [origin],
21484
21557
  embed_default_mode: "launcher",
@@ -21614,16 +21687,16 @@ ${rows.length} grant(s)`));
21614
21687
  }
21615
21688
 
21616
21689
  // src/commands/models.ts
21617
- function registerModelsCommand(program2) {
21618
- program2.command("models").description("List available LLM models").option("--provider <name>", "Filter by provider (e.g. anthropic, openai)").action(async (opts) => {
21690
+ function registerModelsCommand(program) {
21691
+ program.command("models").description("List available LLM models").option("--provider <name>", "Filter by provider (e.g. anthropic, openai)").action(async (opts) => {
21619
21692
  const ctx = createContext({
21620
- profileOverride: program2.opts().profile,
21621
- verbose: program2.opts().verbose
21693
+ profileOverride: program.opts().profile,
21694
+ verbose: program.opts().verbose
21622
21695
  });
21623
- if (program2.opts().apiUrl) {
21624
- ctx.profile.api_url = program2.opts().apiUrl;
21696
+ if (program.opts().apiUrl) {
21697
+ ctx.profile.api_url = program.opts().apiUrl;
21625
21698
  }
21626
- const isJson = !!program2.opts().json;
21699
+ const isJson = !!program.opts().json;
21627
21700
  const params = new URLSearchParams;
21628
21701
  if (opts.provider)
21629
21702
  params.set("provider", opts.provider.toLowerCase());
@@ -21671,20 +21744,20 @@ ${models.length} models`));
21671
21744
 
21672
21745
  // src/commands/spend.ts
21673
21746
  init_errors();
21674
- var GROUPINGS = ["day", "agent", "model", "surface", "billing_owner"];
21747
+ var GROUPINGS = ["day", "agent", "model", "surface", "billing_owner", "client"];
21675
21748
  function usd(value) {
21676
21749
  return value == null ? "-" : `$${Number(value).toFixed(4)}`;
21677
21750
  }
21678
- function registerSpendCommand(program2) {
21679
- program2.command("spend").description("LLM spend for a tenant, from Martha's own ledger").option("--tenant <id>", "Tenant (defaults to your own; others need super-admin)").option("--group-by <dim>", `One of: ${GROUPINGS.join(", ")}`, "day").option("--since <YYYY-MM-DD>", "Inclusive UTC start day").option("--until <YYYY-MM-DD>", "Exclusive UTC end day").action(async (opts) => {
21751
+ function registerSpendCommand(program) {
21752
+ program.command("spend").description("LLM spend for a tenant, from Martha's own ledger").option("--tenant <id>", "Tenant (defaults to your own; others need super-admin)").option("--group-by <dim>", `One of: ${GROUPINGS.join(", ")}`, "day").option("--since <YYYY-MM-DD>", "Inclusive UTC start day").option("--until <YYYY-MM-DD>", "Exclusive UTC end day").action(async (opts) => {
21680
21753
  const ctx = createContext({
21681
- profileOverride: program2.opts().profile,
21682
- verbose: program2.opts().verbose
21754
+ profileOverride: program.opts().profile,
21755
+ verbose: program.opts().verbose
21683
21756
  });
21684
- if (program2.opts().apiUrl) {
21685
- ctx.profile.api_url = program2.opts().apiUrl;
21757
+ if (program.opts().apiUrl) {
21758
+ ctx.profile.api_url = program.opts().apiUrl;
21686
21759
  }
21687
- const isJson = !!program2.opts().json;
21760
+ const isJson = !!program.opts().json;
21688
21761
  if (!GROUPINGS.includes(opts.groupBy)) {
21689
21762
  throw new CLIError(`--group-by must be one of: ${GROUPINGS.join(", ")}`, 4 /* Validation */);
21690
21763
  }
@@ -21730,27 +21803,34 @@ ${data.tenant_id}: ${t.calls} calls, ${usd(t.cost_usd)}` + (t.unpriced_calls ? `
21730
21803
  init_errors();
21731
21804
  var PERIODS = ["day", "month"];
21732
21805
  var ACTIONS = ["warn", "require_approval", "block"];
21806
+ function budgetScope(b) {
21807
+ const agent = b.agent_id ? `agent ${b.agent_name ?? b.agent_id}` : null;
21808
+ const client = b.client_id ? `client ${b.client_name ?? b.client_id}` : null;
21809
+ if (agent && client)
21810
+ return `${agent} via ${client}`;
21811
+ return agent ?? client ?? "tenant";
21812
+ }
21733
21813
  function oneOf(value, allowed, flag) {
21734
21814
  if (!allowed.includes(value)) {
21735
21815
  throw new CLIError(`${flag} must be one of: ${allowed.join(", ")}`, 4 /* Validation */);
21736
21816
  }
21737
21817
  }
21738
- function registerBudgetCommands(program2) {
21739
- const budget = program2.command("budget").description("LLM spend ceilings for a tenant");
21818
+ function registerBudgetCommands(program) {
21819
+ const budget = program.command("budget").description("LLM spend ceilings for a tenant");
21740
21820
  const context = () => {
21741
21821
  const ctx = createContext({
21742
- profileOverride: program2.opts().profile,
21743
- verbose: program2.opts().verbose
21822
+ profileOverride: program.opts().profile,
21823
+ verbose: program.opts().verbose
21744
21824
  });
21745
- if (program2.opts().apiUrl)
21746
- ctx.profile.api_url = program2.opts().apiUrl;
21825
+ if (program.opts().apiUrl)
21826
+ ctx.profile.api_url = program.opts().apiUrl;
21747
21827
  return ctx;
21748
21828
  };
21749
- const path9 = async (ctx, tenant) => `/api/admin/tenants/${encodeURIComponent(tenant ?? await ctx.getTenantId())}/llm-budgets`;
21829
+ const path = async (ctx, tenant) => `/api/admin/tenants/${encodeURIComponent(tenant ?? await ctx.getTenantId())}/llm-budgets`;
21750
21830
  budget.command("list").description("List the tenant's ceilings").option("--tenant <id>", "Tenant (defaults to your own)").action(async (opts) => {
21751
21831
  const ctx = context();
21752
- const data = await ctx.api.get(await path9(ctx, opts.tenant));
21753
- if (program2.opts().json) {
21832
+ const data = await ctx.api.get(await path(ctx, opts.tenant));
21833
+ if (program.opts().json) {
21754
21834
  console.log(JSON.stringify(data, null, 2));
21755
21835
  return;
21756
21836
  }
@@ -21759,33 +21839,36 @@ function registerBudgetCommands(program2) {
21759
21839
  return;
21760
21840
  }
21761
21841
  for (const b of data.budgets) {
21762
- const scope = b.agent_id ? `agent ${b.agent_id}` : "tenant";
21763
- console.log(`${b.id} ${scope.padEnd(42)} ${b.period.padEnd(6)} $${b.limit_usd} ${b.action}`);
21842
+ console.log(`${b.id} ${budgetScope(b).padEnd(42)} ${b.period.padEnd(6)} $${b.limit_usd} ${b.action}`);
21764
21843
  }
21765
21844
  });
21766
- budget.command("set").description("Create or replace a ceiling (one per tenant-or-agent + period)").requiredOption("--period <p>", `One of: ${PERIODS.join(", ")}`).requiredOption("--limit <usd>", "Ceiling in USD (cache reads included)").requiredOption("--action <a>", `One of: ${ACTIONS.join(", ")}`).option("--agent <uuid>", "Scope to one AI Agent (default: whole tenant)").option("--note <text>", "Why this ceiling exists").option("--tenant <id>", "Tenant (defaults to your own)").action(async (opts) => {
21845
+ budget.command("set").description("Create or replace a ceiling (one per scope + period)").requiredOption("--period <p>", `One of: ${PERIODS.join(", ")}`).requiredOption("--limit <usd>", "Ceiling in USD (cache reads included)").requiredOption("--action <a>", `One of: ${ACTIONS.join(", ")}`).option("--agent <uuid>", "Narrow to one AI Agent (default: whole tenant)").option("--client <id>", "Narrow to one API Client (with --agent: that agent within it)").option("--note <text>", "Why this ceiling exists").option("--tenant <id>", "Tenant (defaults to your own)").action(async (opts) => {
21767
21846
  oneOf(opts.period, PERIODS, "--period");
21768
21847
  oneOf(opts.action, ACTIONS, "--action");
21769
21848
  if (!/^\d+(\.\d{1,4})?$/.test(opts.limit)) {
21770
21849
  throw new CLIError("--limit must be a non-negative USD amount", 4 /* Validation */);
21771
21850
  }
21851
+ if (opts.client !== undefined && !/^[1-9]\d*$/.test(opts.client)) {
21852
+ throw new CLIError("--client must be an API Client id (a positive integer)", 4 /* Validation */);
21853
+ }
21772
21854
  const ctx = context();
21773
- const saved = await ctx.api.put(await path9(ctx, opts.tenant), {
21855
+ const saved = await ctx.api.put(await path(ctx, opts.tenant), {
21774
21856
  period: opts.period,
21775
21857
  limit_usd: opts.limit,
21776
21858
  action: opts.action,
21777
21859
  agent_id: opts.agent ?? null,
21860
+ client_id: opts.client !== undefined ? Number(opts.client) : null,
21778
21861
  note: opts.note ?? null
21779
21862
  });
21780
- if (program2.opts().json)
21863
+ if (program.opts().json)
21781
21864
  console.log(JSON.stringify(saved, null, 2));
21782
21865
  else
21783
21866
  console.log(`${saved.id} ${saved.period} $${saved.limit_usd} -> ${saved.action}`);
21784
21867
  });
21785
21868
  budget.command("rm <budgetId>").description("Delete a ceiling").option("--tenant <id>", "Tenant (defaults to your own)").action(async (budgetId, opts) => {
21786
21869
  const ctx = context();
21787
- await ctx.api.del(`${await path9(ctx, opts.tenant)}/${encodeURIComponent(budgetId)}`);
21788
- if (program2.opts().json)
21870
+ await ctx.api.del(`${await path(ctx, opts.tenant)}/${encodeURIComponent(budgetId)}`);
21871
+ if (program.opts().json)
21789
21872
  console.log(JSON.stringify({ deleted: budgetId }));
21790
21873
  else
21791
21874
  console.log(`deleted ${budgetId}`);
@@ -21830,19 +21913,19 @@ function parseCollectionRefs(csv) {
21830
21913
  return [];
21831
21914
  return csv.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
21832
21915
  }
21833
- function registerWikiCommands(program2) {
21834
- const cmd = program2.command("wiki").description("Manage wikis: list/create/delete wikis, browse pages, search, schema, settings (#631)");
21916
+ function registerWikiCommands(program) {
21917
+ const cmd = program.command("wiki").description("Manage wikis: list/create/delete wikis, browse pages, search, schema, settings (#631)");
21835
21918
  function getCtx() {
21836
21919
  const ctx = createContext({
21837
- profileOverride: program2.opts().profile,
21838
- verbose: program2.opts().verbose
21920
+ profileOverride: program.opts().profile,
21921
+ verbose: program.opts().verbose
21839
21922
  });
21840
- if (program2.opts().apiUrl)
21841
- ctx.profile.api_url = program2.opts().apiUrl;
21923
+ if (program.opts().apiUrl)
21924
+ ctx.profile.api_url = program.opts().apiUrl;
21842
21925
  return ctx;
21843
21926
  }
21844
21927
  function isJson() {
21845
- return !!program2.opts().json;
21928
+ return !!program.opts().json;
21846
21929
  }
21847
21930
  cmd.command("list").description("List the tenant's wikis (only those you can see)").action(async () => {
21848
21931
  const ctx = getCtx();
@@ -21942,16 +22025,16 @@ ${wikis.length} wiki${wikis.length === 1 ? "" : "s"}`));
21942
22025
  console.log(source_default.dim(`
21943
22026
  ${pages.length} pages`));
21944
22027
  });
21945
- cmd.command("get <path>").description("Fetch the raw markdown body of a wiki page").option("--wiki <slug>", "Wiki slug (default: the tenant default wiki)").option("--out <file>", "Write body to file instead of stdout").action(async (path9, opts) => {
22028
+ cmd.command("get <path>").description("Fetch the raw markdown body of a wiki page").option("--wiki <slug>", "Wiki slug (default: the tenant default wiki)").option("--out <file>", "Write body to file instead of stdout").action(async (path, opts) => {
21946
22029
  const ctx = getCtx();
21947
- const safe = path9.split("/").map(encodeURIComponent).join("/");
22030
+ const safe = path.split("/").map(encodeURIComponent).join("/");
21948
22031
  const slug = encodeURIComponent(opts.wiki ?? DEFAULT_WIKI_SLUG);
21949
22032
  const endpoint = `/api/wiki/${slug}/pages/${safe}`;
21950
22033
  const resp = await ctx.api.getRaw(endpoint, {
21951
22034
  headers: { Accept: "text/markdown,*/*" }
21952
22035
  });
21953
22036
  if (resp.status === 404) {
21954
- throw new CLIError(`page not found: ${path9}`, 3 /* NotFound */);
22037
+ throw new CLIError(`page not found: ${path}`, 3 /* NotFound */);
21955
22038
  }
21956
22039
  if (!resp.ok) {
21957
22040
  const detail = await resp.text();
@@ -21963,12 +22046,12 @@ ${pages.length} pages`));
21963
22046
  if (!isJson()) {
21964
22047
  console.log(source_default.dim(`wrote ${body.length} bytes to ${opts.out}`));
21965
22048
  } else {
21966
- console.log(JSON.stringify({ path: path9, bytes: body.length, file: opts.out }));
22049
+ console.log(JSON.stringify({ path, bytes: body.length, file: opts.out }));
21967
22050
  }
21968
22051
  return;
21969
22052
  }
21970
22053
  if (isJson()) {
21971
- console.log(JSON.stringify({ path: path9, body, etag: resp.headers.get("ETag") }));
22054
+ console.log(JSON.stringify({ path, body, etag: resp.headers.get("ETag") }));
21972
22055
  } else {
21973
22056
  process.stdout.write(body);
21974
22057
  }
@@ -22145,17 +22228,17 @@ ${pages.length} pages`));
22145
22228
 
22146
22229
  // src/commands/mcp.ts
22147
22230
  init_errors();
22148
- function registerMCPCommands(program2) {
22149
- const cmd = program2.command("mcp").description("Discover and call MCP tools");
22231
+ function registerMCPCommands(program) {
22232
+ const cmd = program.command("mcp").description("Discover and call MCP tools");
22150
22233
  function getCtx() {
22151
22234
  return createContext({
22152
- profileOverride: program2.opts().profile,
22153
- apiUrlOverride: program2.opts().apiUrl,
22154
- verbose: program2.opts().verbose
22235
+ profileOverride: program.opts().profile,
22236
+ apiUrlOverride: program.opts().apiUrl,
22237
+ verbose: program.opts().verbose
22155
22238
  });
22156
22239
  }
22157
22240
  function isJson() {
22158
- return !!program2.opts().json;
22241
+ return !!program.opts().json;
22159
22242
  }
22160
22243
  cmd.command("discover").description("Discover tools from an MCP server").option("--url <serverUrl>", "Direct MCP Streamable HTTP URL").option("--connection <connectionId>", "Martha connection UUID").option("--connection-ref <connectionRef>", "Martha connection reference").option("--force-refresh", "Bypass cached discovery").action(async (opts) => {
22161
22244
  const ctx = getCtx();
@@ -22449,7 +22532,7 @@ async function pollConnectionActive(ctx, connectionId) {
22449
22532
  });
22450
22533
  if (conn?.status === "active")
22451
22534
  return;
22452
- await new Promise((resolve2) => setTimeout(resolve2, intervalMs));
22535
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
22453
22536
  }
22454
22537
  throw new CLIError(`Timed out waiting for OAuth authorization (${Math.round(timeoutMs / 1000)}s).`, 1 /* Error */, "The browser consent may not have completed. Re-run to try again, or check " + "the connection status in the admin UI.");
22455
22538
  }
@@ -22511,7 +22594,7 @@ async function pollExecution(ctx, executionId, timeoutMs) {
22511
22594
  if (["completed", "failed", "cancelled", "timeout"].includes(last.status)) {
22512
22595
  return last;
22513
22596
  }
22514
- await new Promise((resolve2) => setTimeout(resolve2, 1000));
22597
+ await new Promise((resolve) => setTimeout(resolve, 1000));
22515
22598
  }
22516
22599
  throw new CLIError(`Timed out waiting for MCP workflow execution ${executionId}`, 1 /* Error */, last ? `Last status: ${last.status}` : undefined);
22517
22600
  }
@@ -22639,8 +22722,8 @@ async function resolveCredentialFlag(value) {
22639
22722
  return Buffer.concat(chunks).toString("utf-8").trim();
22640
22723
  }
22641
22724
  if (value.startsWith("@")) {
22642
- const fs12 = await import("node:fs/promises");
22643
- return (await fs12.readFile(value.slice(1), "utf-8")).trim();
22725
+ const fs = await import("node:fs/promises");
22726
+ return (await fs.readFile(value.slice(1), "utf-8")).trim();
22644
22727
  }
22645
22728
  return value;
22646
22729
  }
@@ -22656,16 +22739,16 @@ function assertOneOf(value, allowed, flag) {
22656
22739
  throw new CLIError(`${flag} must be one of: ${allowed.join(", ")}`, 4 /* Validation */);
22657
22740
  }
22658
22741
  }
22659
- function registerPolicyCommands(program2) {
22660
- const cmd = program2.command("policy").description("Manage the tenant's invoke-time capability policy");
22742
+ function registerPolicyCommands(program) {
22743
+ const cmd = program.command("policy").description("Manage the tenant's invoke-time capability policy");
22661
22744
  function getCtx() {
22662
22745
  return createContext({
22663
- profileOverride: program2.opts().profile,
22664
- apiUrlOverride: program2.opts().apiUrl,
22665
- verbose: program2.opts().verbose
22746
+ profileOverride: program.opts().profile,
22747
+ apiUrlOverride: program.opts().apiUrl,
22748
+ verbose: program.opts().verbose
22666
22749
  });
22667
22750
  }
22668
- const isJson = () => !!program2.opts().json;
22751
+ const isJson = () => !!program.opts().json;
22669
22752
  cmd.command("show").description("Show the current policy: settings + rules").action(async () => {
22670
22753
  const ctx = getCtx();
22671
22754
  const cfg = await ctx.api.get("/api/admin/policy");
@@ -22778,11 +22861,11 @@ var BASE = "/api/admin/agent-step/trust-roots";
22778
22861
  var FLEET_BASE = "/api/admin/agent-step/fleet";
22779
22862
  function resolveKeyMaterial(value) {
22780
22863
  if (value.startsWith("@")) {
22781
- const path9 = value.slice(1);
22864
+ const path = value.slice(1);
22782
22865
  try {
22783
- return readFileSync3(path9, "utf8").trim();
22866
+ return readFileSync3(path, "utf8").trim();
22784
22867
  } catch (e) {
22785
- throw new CLIError(`Could not read public key file '${path9}': ${e.message}`, 4 /* Validation */);
22868
+ throw new CLIError(`Could not read public key file '${path}': ${e.message}`, 4 /* Validation */);
22786
22869
  }
22787
22870
  }
22788
22871
  return value;
@@ -22805,17 +22888,17 @@ function printOne(tr) {
22805
22888
  if (tr.updated_at)
22806
22889
  console.log(` Updated: ${tr.updated_at}`);
22807
22890
  }
22808
- function registerAgentStepCommands(program2) {
22809
- const cmd = program2.command("agent-step").description("Author agent_step assets (execution_proof trust roots)");
22891
+ function registerAgentStepCommands(program) {
22892
+ const cmd = program.command("agent-step").description("Author agent_step assets (execution_proof trust roots)");
22810
22893
  const roots = cmd.command("trust-roots").description("Manage per-tenant/per-runner attestation trust roots (#1083)");
22811
22894
  function getCtx() {
22812
22895
  return createContext({
22813
- profileOverride: program2.opts().profile,
22814
- apiUrlOverride: program2.opts().apiUrl,
22815
- verbose: program2.opts().verbose
22896
+ profileOverride: program.opts().profile,
22897
+ apiUrlOverride: program.opts().apiUrl,
22898
+ verbose: program.opts().verbose
22816
22899
  });
22817
22900
  }
22818
- const isJson = () => !!program2.opts().json;
22901
+ const isJson = () => !!program.opts().json;
22819
22902
  roots.command("list").description("List the tenant's trust roots").action(async () => {
22820
22903
  const ctx = getCtx();
22821
22904
  const rows = await ctx.api.get(BASE);
@@ -23134,21 +23217,21 @@ var DEFAULT_ENTITY = "document_collection";
23134
23217
  var DEFAULT_ACTION = "read";
23135
23218
  var APPROVAL_ENTITY = "approval";
23136
23219
  var RESOLVE_ACTION = "resolve";
23137
- function registerAuthzCommands(program2) {
23220
+ function registerAuthzCommands(program) {
23138
23221
  function getCtx() {
23139
23222
  const ctx = createContext({
23140
- profileOverride: program2.opts().profile,
23141
- verbose: program2.opts().verbose
23223
+ profileOverride: program.opts().profile,
23224
+ verbose: program.opts().verbose
23142
23225
  });
23143
- if (program2.opts().apiUrl)
23144
- ctx.profile.api_url = program2.opts().apiUrl;
23226
+ if (program.opts().apiUrl)
23227
+ ctx.profile.api_url = program.opts().apiUrl;
23145
23228
  return ctx;
23146
23229
  }
23147
- const isJson = () => !!program2.opts().json;
23148
- registerCollections(program2, getCtx, isJson);
23149
- registerAccess(program2, getCtx, isJson);
23150
- registerGroups(program2, getCtx, isJson);
23151
- registerApprovers(program2, getCtx, isJson);
23230
+ const isJson = () => !!program.opts().json;
23231
+ registerCollections(program, getCtx, isJson);
23232
+ registerAccess(program, getCtx, isJson);
23233
+ registerGroups(program, getCtx, isJson);
23234
+ registerApprovers(program, getCtx, isJson);
23152
23235
  }
23153
23236
  function renderGrantsTable(resp) {
23154
23237
  if (resp.grants.length === 0) {
@@ -23163,8 +23246,8 @@ function renderGrantsTable(resp) {
23163
23246
  ` + lines.join(`
23164
23247
  `);
23165
23248
  }
23166
- function registerCollections(program2, getCtx, isJson) {
23167
- const cmd = program2.command("collections").description("Manage who can read a document collection (UMS authz)");
23249
+ function registerCollections(program, getCtx, isJson) {
23250
+ const cmd = program.command("collections").description("Manage who can read a document collection (UMS authz)");
23168
23251
  cmd.command("grant <collection>").description("Grant read access on a collection to a principal").requiredOption("--to <type:id>", "user|client|agent|group:<id>").option("--action <action>", "Action to grant", DEFAULT_ACTION).option("--tenant <tenant>", "Target tenant (super-admin only)").action(async (collection, opts) => {
23169
23252
  const ctx = getCtx();
23170
23253
  const json = isJson();
@@ -23234,8 +23317,8 @@ function registerCollections(program2, getCtx, isJson) {
23234
23317
  }
23235
23318
  });
23236
23319
  }
23237
- function registerAccess(program2, getCtx, isJson) {
23238
- const cmd = program2.command("access").description("Generic two-axis grant management (any entity type)");
23320
+ function registerAccess(program, getCtx, isJson) {
23321
+ const cmd = program.command("access").description("Generic two-axis grant management (any entity type)");
23239
23322
  cmd.command("grant").description("Grant access to a principal on an entity/object").requiredOption("--to <type:id>", "user|client|agent|group:<id>").option("--entity <entity_type>", "Entity type", DEFAULT_ENTITY).option("--object <id>", "Object id (omit for a tenant-root see-all grant)").option("--action <action>", "Action", DEFAULT_ACTION).option("--tenant <tenant>", "Target tenant (super-admin only)").action(async (opts) => {
23240
23323
  const ctx = getCtx();
23241
23324
  const json = isJson();
@@ -23309,8 +23392,8 @@ function registerAccess(program2, getCtx, isJson) {
23309
23392
  }
23310
23393
  });
23311
23394
  }
23312
- function registerGroups(program2, getCtx, isJson) {
23313
- const cmd = program2.command("groups").description("Manage UMS-native authz groups (#644)");
23395
+ function registerGroups(program, getCtx, isJson) {
23396
+ const cmd = program.command("groups").description("Manage UMS-native authz groups (#644)");
23314
23397
  cmd.command("create <name>").description("Create a group").option("--tenant <tenant>", "Target tenant (super-admin only)").action(async (name, opts) => {
23315
23398
  const ctx = getCtx();
23316
23399
  const json = isJson();
@@ -23406,8 +23489,8 @@ function registerGroups(program2, getCtx, isJson) {
23406
23489
  }
23407
23490
  });
23408
23491
  }
23409
- function registerApprovers(program2, getCtx, isJson) {
23410
- const cmd = program2.command("approvers").description("Manage who may resolve approval cases in the tenant (UMS approval/resolve). " + "Noun-first sugar over `access` on the approval entity.");
23492
+ function registerApprovers(program, getCtx, isJson) {
23493
+ const cmd = program.command("approvers").description("Manage who may resolve approval cases in the tenant (UMS approval/resolve). " + "Noun-first sugar over `access` on the approval entity.");
23411
23494
  cmd.command("add <group>").description("Make a group a tenant approver (its members can resolve approvals)").option("--tenant <tenant>", "Target tenant (super-admin only)").action(async (group, opts) => {
23412
23495
  const ctx = getCtx();
23413
23496
  const json = isJson();
@@ -23834,8 +23917,8 @@ async function askIntents() {
23834
23917
  });
23835
23918
  return parseIntents2(raw);
23836
23919
  }
23837
- function registerInitCommand(program2) {
23838
- program2.command("init").description("Create or update a profile, and optionally bootstrap an access principal").option("--preset <name>", "Preset: cloud or local", "cloud").option("--name <name>", "Profile name (defaults to preset name)").option("--force", "Overwrite an existing profile").option("--api-url <url>", "Override the API URL").option("--keycloak-url <url>", "Override the Keycloak URL").option("--keycloak-realm <realm>", "Override the Keycloak realm").option("--no-interactive", "Skip prompts; use defaults / overrides only").option("--bootstrap", "Provision an intent-scoped principal + grants after saving the profile").option("--mode <mode>", "Bootstrap mode: 'human' (your own client) or 'integration' (service account)").option("--intent <intents...>", "Usage buckets to grant: rag, documents, workflows, custom").option("--workflow <names...>", "Workflow name(s) to grant (workflows/custom intent)").option("--function <names...>", "Extra function name(s) to grant (custom intent)").option("--label <name>", "Integration mode: label for the SA client id").option("--agent", "Also provision a personal chat copilot (human mode) and set it as the default").option("--agent-name <name>", "Copilot agent name (defaults to copilot-{user})").option("--model <id>", "Copilot LLM model id (defaults to the platform default)").option("--host-runner", "Also set the copilot up to run host tools on THIS machine (mints a runner key + prints the `martha runner` command)").option("--yes", "Acknowledge non-interactive bootstrap side effects").action(async (opts, command) => {
23920
+ function registerInitCommand(program) {
23921
+ program.command("init").description("Create or update a profile, and optionally bootstrap an access principal").option("--preset <name>", "Preset: cloud or local", "cloud").option("--name <name>", "Profile name (defaults to preset name)").option("--force", "Overwrite an existing profile").option("--api-url <url>", "Override the API URL").option("--keycloak-url <url>", "Override the Keycloak URL").option("--keycloak-realm <realm>", "Override the Keycloak realm").option("--no-interactive", "Skip prompts; use defaults / overrides only").option("--bootstrap", "Provision an intent-scoped principal + grants after saving the profile").option("--mode <mode>", "Bootstrap mode: 'human' (your own client) or 'integration' (service account)").option("--intent <intents...>", "Usage buckets to grant: rag, documents, workflows, custom").option("--workflow <names...>", "Workflow name(s) to grant (workflows/custom intent)").option("--function <names...>", "Extra function name(s) to grant (custom intent)").option("--label <name>", "Integration mode: label for the SA client id").option("--agent", "Also provision a personal chat copilot (human mode) and set it as the default").option("--agent-name <name>", "Copilot agent name (defaults to copilot-{user})").option("--model <id>", "Copilot LLM model id (defaults to the platform default)").option("--host-runner", "Also set the copilot up to run host tools on THIS machine (mints a runner key + prints the `martha runner` command)").option("--yes", "Acknowledge non-interactive bootstrap side effects").action(async (opts, command) => {
23839
23922
  const globals = command.parent?.opts() ?? {};
23840
23923
  await initCommand({ ...opts, json: !!globals.json });
23841
23924
  });
@@ -23843,11 +23926,18 @@ function registerInitCommand(program2) {
23843
23926
 
23844
23927
  // src/commands/doctor.ts
23845
23928
  var FETCH_TIMEOUT_MS = 5000;
23846
- function resolveApiUrl(base, path9) {
23847
- return new URL(path9, base).toString();
23929
+ function resolveApiUrl(base, path) {
23930
+ return new URL(path, base).toString();
23931
+ }
23932
+ function authHeaders(ctx, token) {
23933
+ const tenant = ctx.tenantFor(token);
23934
+ return {
23935
+ Authorization: `Bearer ${token}`,
23936
+ ...tenant ? { "X-Martha-Tenant": tenant } : {}
23937
+ };
23848
23938
  }
23849
- function apiUrl(ctx, path9) {
23850
- return resolveApiUrl(ctx.profile.api_url, path9);
23939
+ function apiUrl(ctx, path) {
23940
+ return resolveApiUrl(ctx.profile.api_url, path);
23851
23941
  }
23852
23942
  async function fetchJSON(url, init) {
23853
23943
  const res = await fetch(url, {
@@ -24002,7 +24092,7 @@ async function checkAuthenticatedRequest(ctx) {
24002
24092
  const url = apiUrl(ctx, "/api/admin/definitions/agents");
24003
24093
  try {
24004
24094
  const { ok, status } = await fetchJSON(url, {
24005
- headers: { Authorization: `Bearer ${tokens.access_token}` }
24095
+ headers: authHeaders(ctx, tokens.access_token)
24006
24096
  });
24007
24097
  if (ok) {
24008
24098
  return { name: "API auth", status: "pass", detail: "token accepted" };
@@ -24047,7 +24137,7 @@ async function checkHostRunners(ctx) {
24047
24137
  const url = apiUrl(ctx, "/api/admin/definitions/agents/runner-presence");
24048
24138
  try {
24049
24139
  const { ok, status, json } = await fetchJSON(url, {
24050
- headers: { Authorization: `Bearer ${tokens.access_token}` }
24140
+ headers: authHeaders(ctx, tokens.access_token)
24051
24141
  });
24052
24142
  if (!ok) {
24053
24143
  return {
@@ -24129,14 +24219,14 @@ async function doctorCommand(ctx) {
24129
24219
  console.log(source_default.green(` All checks passed.`));
24130
24220
  }
24131
24221
  }
24132
- function registerDoctorCommand(program2) {
24133
- program2.command("doctor").description("Run diagnostic checks against the active profile").action(async () => {
24222
+ function registerDoctorCommand(program) {
24223
+ program.command("doctor").description("Run diagnostic checks against the active profile").action(async () => {
24134
24224
  const ctx = createContext({
24135
- profileOverride: program2.opts().profile,
24136
- verbose: program2.opts().verbose
24225
+ profileOverride: program.opts().profile,
24226
+ verbose: program.opts().verbose
24137
24227
  });
24138
- if (program2.opts().apiUrl) {
24139
- ctx.profile.api_url = program2.opts().apiUrl;
24228
+ if (program.opts().apiUrl) {
24229
+ ctx.profile.api_url = program.opts().apiUrl;
24140
24230
  }
24141
24231
  await doctorCommand(ctx);
24142
24232
  });
@@ -24169,8 +24259,8 @@ async function skillCommand() {
24169
24259
  const body = fs12.readFileSync(skillPath, "utf-8");
24170
24260
  process.stdout.write(body);
24171
24261
  }
24172
- function registerSkillCommand(program2) {
24173
- program2.command("skill").description("Print the bundled agent skill reference (SKILL.md) to stdout").action(async () => {
24262
+ function registerSkillCommand(program) {
24263
+ program.command("skill").description("Print the bundled agent skill reference (SKILL.md) to stdout").action(async () => {
24174
24264
  await skillCommand();
24175
24265
  });
24176
24266
  }
@@ -24240,9 +24330,9 @@ function resolveManager(explicit) {
24240
24330
  return fromInstall;
24241
24331
  return process.versions?.bun ? "bun" : "npm";
24242
24332
  }
24243
- function registerUpdateCommand(program2) {
24244
- program2.command("update").description("Update the Martha CLI to the latest published version").option("--check", "Report whether a newer version is available; don't install").option("--yes", "Skip the confirmation prompt").option("--manager <pm>", "Package manager to use: npm | bun (default: auto)").action(async (opts) => {
24245
- const isJson = !!program2.opts().json;
24333
+ function registerUpdateCommand(program) {
24334
+ program.command("update").description("Update the Martha CLI to the latest published version").option("--check", "Report whether a newer version is available; don't install").option("--yes", "Skip the confirmation prompt").option("--manager <pm>", "Package manager to use: npm | bun (default: auto)").action(async (opts) => {
24335
+ const isJson = !!program.opts().json;
24246
24336
  const latest = await fetchLatest();
24247
24337
  if (!latest) {
24248
24338
  throw new CLIError(`Could not reach the npm registry to determine the latest version (${LATEST_URL}). Check your network.`, 1 /* Error */);
@@ -24305,8 +24395,9 @@ function registerUpdateCommand(program2) {
24305
24395
  }
24306
24396
 
24307
24397
  // src/index.ts
24308
- var program2 = new Command;
24309
- program2.name("martha").description("Terminal-first client for the Martha AI platform").version(CLI_VERSION).option("--profile <name>", "Use a named profile").option("--json", "Machine-readable JSON output").option("--quiet", "Suppress non-essential output").option("--verbose", "Verbose logging").option("--no-color", "Disable color output").option("--api-url <url>", "Override API base URL");
24398
+ var program2 = new Command2;
24399
+ program2.name("martha").description("Terminal-first client for the Martha AI platform").version(CLI_VERSION).option("--profile <name>", "Use a named profile").option("--json", "Machine-readable JSON output").option("--quiet", "Suppress non-essential output").option("--verbose", "Verbose logging").option("--no-color", "Disable color output").option("--api-url <url>", "Override API base URL").option("--org <tenant>", "Organization to act in (X-Martha-Tenant); needed when your token authorizes several");
24400
+ registerOrgSelection(program2);
24310
24401
  program2.command("status").description("Check connection and auth status").action(async () => {
24311
24402
  const ctx = createContext({
24312
24403
  profileOverride: program2.opts().profile,