baro-ai 0.70.14 → 0.70.15

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.
@@ -307,7 +307,7 @@ var require_p_retry = __commonJS({
307
307
  return error;
308
308
  };
309
309
  var isNetworkError = (errorMessage) => networkErrorMsgs.includes(errorMessage);
310
- var pRetry2 = (input, options) => new Promise((resolve, reject) => {
310
+ var pRetry2 = (input, options) => new Promise((resolve2, reject) => {
311
311
  options = {
312
312
  onFailedAttempt: () => {
313
313
  },
@@ -317,7 +317,7 @@ var require_p_retry = __commonJS({
317
317
  const operation = retry.operation(options);
318
318
  operation.attempt(async (attemptNumber) => {
319
319
  try {
320
- resolve(await input(attemptNumber));
320
+ resolve2(await input(attemptNumber));
321
321
  } catch (error) {
322
322
  if (!(error instanceof Error)) {
323
323
  reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));
@@ -853,8 +853,8 @@ var require_retry3 = __commonJS({
853
853
  }
854
854
  const delay = getNextRetryDelay(config);
855
855
  err.config.retryConfig.currentRetryAttempt += 1;
856
- const backoff = config.retryBackoff ? config.retryBackoff(err, delay) : new Promise((resolve) => {
857
- setTimeout(resolve, delay);
856
+ const backoff = config.retryBackoff ? config.retryBackoff(err, delay) : new Promise((resolve2) => {
857
+ setTimeout(resolve2, delay);
858
858
  });
859
859
  if (config.onRetryAttempt) {
860
860
  await config.onRetryAttempt(err);
@@ -1744,8 +1744,8 @@ var require_helpers = __commonJS({
1744
1744
  function req(url, opts = {}) {
1745
1745
  const href = typeof url === "string" ? url : url.href;
1746
1746
  const req2 = (href.startsWith("https:") ? https2 : http3).request(url, opts);
1747
- const promise = new Promise((resolve, reject) => {
1748
- req2.once("response", resolve).once("error", reject).end();
1747
+ const promise = new Promise((resolve2, reject) => {
1748
+ req2.once("response", resolve2).once("error", reject).end();
1749
1749
  });
1750
1750
  req2.then = promise.then.bind(promise);
1751
1751
  return req2;
@@ -1922,7 +1922,7 @@ var require_parse_proxy_response = __commonJS({
1922
1922
  var debug_1 = __importDefault(require_src());
1923
1923
  var debug = (0, debug_1.default)("https-proxy-agent:parse-proxy-response");
1924
1924
  function parseProxyResponse(socket) {
1925
- return new Promise((resolve, reject) => {
1925
+ return new Promise((resolve2, reject) => {
1926
1926
  let buffersLength = 0;
1927
1927
  const buffers = [];
1928
1928
  function read() {
@@ -1988,7 +1988,7 @@ var require_parse_proxy_response = __commonJS({
1988
1988
  }
1989
1989
  debug("got proxy server response: %o %o", firstLine, headers);
1990
1990
  cleanup();
1991
- resolve({
1991
+ resolve2({
1992
1992
  connect: {
1993
1993
  statusCode,
1994
1994
  statusText,
@@ -2232,7 +2232,7 @@ var require_ponyfill_es2018 = __commonJS({
2232
2232
  return new originalPromise(executor);
2233
2233
  }
2234
2234
  function promiseResolvedWith(value) {
2235
- return newPromise((resolve) => resolve(value));
2235
+ return newPromise((resolve2) => resolve2(value));
2236
2236
  }
2237
2237
  function promiseRejectedWith(reason) {
2238
2238
  return originalPromiseReject(reason);
@@ -2402,8 +2402,8 @@ var require_ponyfill_es2018 = __commonJS({
2402
2402
  return new TypeError("Cannot " + name + " a stream using a released reader");
2403
2403
  }
2404
2404
  function defaultReaderClosedPromiseInitialize(reader) {
2405
- reader._closedPromise = newPromise((resolve, reject) => {
2406
- reader._closedPromise_resolve = resolve;
2405
+ reader._closedPromise = newPromise((resolve2, reject) => {
2406
+ reader._closedPromise_resolve = resolve2;
2407
2407
  reader._closedPromise_reject = reject;
2408
2408
  });
2409
2409
  }
@@ -2577,8 +2577,8 @@ var require_ponyfill_es2018 = __commonJS({
2577
2577
  }
2578
2578
  let resolvePromise;
2579
2579
  let rejectPromise;
2580
- const promise = newPromise((resolve, reject) => {
2581
- resolvePromise = resolve;
2580
+ const promise = newPromise((resolve2, reject) => {
2581
+ resolvePromise = resolve2;
2582
2582
  rejectPromise = reject;
2583
2583
  });
2584
2584
  const readRequest = {
@@ -2683,8 +2683,8 @@ var require_ponyfill_es2018 = __commonJS({
2683
2683
  const reader = this._reader;
2684
2684
  let resolvePromise;
2685
2685
  let rejectPromise;
2686
- const promise = newPromise((resolve, reject) => {
2687
- resolvePromise = resolve;
2686
+ const promise = newPromise((resolve2, reject) => {
2687
+ resolvePromise = resolve2;
2688
2688
  rejectPromise = reject;
2689
2689
  });
2690
2690
  const readRequest = {
@@ -3703,8 +3703,8 @@ var require_ponyfill_es2018 = __commonJS({
3703
3703
  }
3704
3704
  let resolvePromise;
3705
3705
  let rejectPromise;
3706
- const promise = newPromise((resolve, reject) => {
3707
- resolvePromise = resolve;
3706
+ const promise = newPromise((resolve2, reject) => {
3707
+ resolvePromise = resolve2;
3708
3708
  rejectPromise = reject;
3709
3709
  });
3710
3710
  const readIntoRequest = {
@@ -4016,10 +4016,10 @@ var require_ponyfill_es2018 = __commonJS({
4016
4016
  wasAlreadyErroring = true;
4017
4017
  reason = void 0;
4018
4018
  }
4019
- const promise = newPromise((resolve, reject) => {
4019
+ const promise = newPromise((resolve2, reject) => {
4020
4020
  stream._pendingAbortRequest = {
4021
4021
  _promise: void 0,
4022
- _resolve: resolve,
4022
+ _resolve: resolve2,
4023
4023
  _reject: reject,
4024
4024
  _reason: reason,
4025
4025
  _wasAlreadyErroring: wasAlreadyErroring
@@ -4036,9 +4036,9 @@ var require_ponyfill_es2018 = __commonJS({
4036
4036
  if (state === "closed" || state === "errored") {
4037
4037
  return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`));
4038
4038
  }
4039
- const promise = newPromise((resolve, reject) => {
4039
+ const promise = newPromise((resolve2, reject) => {
4040
4040
  const closeRequest = {
4041
- _resolve: resolve,
4041
+ _resolve: resolve2,
4042
4042
  _reject: reject
4043
4043
  };
4044
4044
  stream._closeRequest = closeRequest;
@@ -4051,9 +4051,9 @@ var require_ponyfill_es2018 = __commonJS({
4051
4051
  return promise;
4052
4052
  }
4053
4053
  function WritableStreamAddWriteRequest(stream) {
4054
- const promise = newPromise((resolve, reject) => {
4054
+ const promise = newPromise((resolve2, reject) => {
4055
4055
  const writeRequest = {
4056
- _resolve: resolve,
4056
+ _resolve: resolve2,
4057
4057
  _reject: reject
4058
4058
  };
4059
4059
  stream._writeRequests.push(writeRequest);
@@ -4669,8 +4669,8 @@ var require_ponyfill_es2018 = __commonJS({
4669
4669
  return new TypeError("Cannot " + name + " a stream using a released writer");
4670
4670
  }
4671
4671
  function defaultWriterClosedPromiseInitialize(writer) {
4672
- writer._closedPromise = newPromise((resolve, reject) => {
4673
- writer._closedPromise_resolve = resolve;
4672
+ writer._closedPromise = newPromise((resolve2, reject) => {
4673
+ writer._closedPromise_resolve = resolve2;
4674
4674
  writer._closedPromise_reject = reject;
4675
4675
  writer._closedPromiseState = "pending";
4676
4676
  });
@@ -4706,8 +4706,8 @@ var require_ponyfill_es2018 = __commonJS({
4706
4706
  writer._closedPromiseState = "resolved";
4707
4707
  }
4708
4708
  function defaultWriterReadyPromiseInitialize(writer) {
4709
- writer._readyPromise = newPromise((resolve, reject) => {
4710
- writer._readyPromise_resolve = resolve;
4709
+ writer._readyPromise = newPromise((resolve2, reject) => {
4710
+ writer._readyPromise_resolve = resolve2;
4711
4711
  writer._readyPromise_reject = reject;
4712
4712
  });
4713
4713
  writer._readyPromiseState = "pending";
@@ -4794,7 +4794,7 @@ var require_ponyfill_es2018 = __commonJS({
4794
4794
  source._disturbed = true;
4795
4795
  let shuttingDown = false;
4796
4796
  let currentWrite = promiseResolvedWith(void 0);
4797
- return newPromise((resolve, reject) => {
4797
+ return newPromise((resolve2, reject) => {
4798
4798
  let abortAlgorithm;
4799
4799
  if (signal !== void 0) {
4800
4800
  abortAlgorithm = () => {
@@ -4939,7 +4939,7 @@ var require_ponyfill_es2018 = __commonJS({
4939
4939
  if (isError) {
4940
4940
  reject(error);
4941
4941
  } else {
4942
- resolve(void 0);
4942
+ resolve2(void 0);
4943
4943
  }
4944
4944
  return null;
4945
4945
  }
@@ -5220,8 +5220,8 @@ var require_ponyfill_es2018 = __commonJS({
5220
5220
  let branch1;
5221
5221
  let branch2;
5222
5222
  let resolveCancelPromise;
5223
- const cancelPromise = newPromise((resolve) => {
5224
- resolveCancelPromise = resolve;
5223
+ const cancelPromise = newPromise((resolve2) => {
5224
+ resolveCancelPromise = resolve2;
5225
5225
  });
5226
5226
  function pullAlgorithm() {
5227
5227
  if (reading) {
@@ -5312,8 +5312,8 @@ var require_ponyfill_es2018 = __commonJS({
5312
5312
  let branch1;
5313
5313
  let branch2;
5314
5314
  let resolveCancelPromise;
5315
- const cancelPromise = newPromise((resolve) => {
5316
- resolveCancelPromise = resolve;
5315
+ const cancelPromise = newPromise((resolve2) => {
5316
+ resolveCancelPromise = resolve2;
5317
5317
  });
5318
5318
  function forwardReaderError(thisReader) {
5319
5319
  uponRejection(thisReader._closedPromise, (r2) => {
@@ -6093,8 +6093,8 @@ var require_ponyfill_es2018 = __commonJS({
6093
6093
  const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);
6094
6094
  const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);
6095
6095
  let startPromise_resolve;
6096
- const startPromise = newPromise((resolve) => {
6097
- startPromise_resolve = resolve;
6096
+ const startPromise = newPromise((resolve2) => {
6097
+ startPromise_resolve = resolve2;
6098
6098
  });
6099
6099
  InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
6100
6100
  SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);
@@ -6187,8 +6187,8 @@ var require_ponyfill_es2018 = __commonJS({
6187
6187
  if (stream._backpressureChangePromise !== void 0) {
6188
6188
  stream._backpressureChangePromise_resolve();
6189
6189
  }
6190
- stream._backpressureChangePromise = newPromise((resolve) => {
6191
- stream._backpressureChangePromise_resolve = resolve;
6190
+ stream._backpressureChangePromise = newPromise((resolve2) => {
6191
+ stream._backpressureChangePromise_resolve = resolve2;
6192
6192
  });
6193
6193
  stream._backpressure = backpressure;
6194
6194
  }
@@ -6356,8 +6356,8 @@ var require_ponyfill_es2018 = __commonJS({
6356
6356
  return controller._finishPromise;
6357
6357
  }
6358
6358
  const readable = stream._readable;
6359
- controller._finishPromise = newPromise((resolve, reject) => {
6360
- controller._finishPromise_resolve = resolve;
6359
+ controller._finishPromise = newPromise((resolve2, reject) => {
6360
+ controller._finishPromise_resolve = resolve2;
6361
6361
  controller._finishPromise_reject = reject;
6362
6362
  });
6363
6363
  const cancelPromise = controller._cancelAlgorithm(reason);
@@ -6383,8 +6383,8 @@ var require_ponyfill_es2018 = __commonJS({
6383
6383
  return controller._finishPromise;
6384
6384
  }
6385
6385
  const readable = stream._readable;
6386
- controller._finishPromise = newPromise((resolve, reject) => {
6387
- controller._finishPromise_resolve = resolve;
6386
+ controller._finishPromise = newPromise((resolve2, reject) => {
6387
+ controller._finishPromise_resolve = resolve2;
6388
6388
  controller._finishPromise_reject = reject;
6389
6389
  });
6390
6390
  const flushPromise = controller._flushAlgorithm();
@@ -6414,8 +6414,8 @@ var require_ponyfill_es2018 = __commonJS({
6414
6414
  return controller._finishPromise;
6415
6415
  }
6416
6416
  const writable = stream._writable;
6417
- controller._finishPromise = newPromise((resolve, reject) => {
6418
- controller._finishPromise_resolve = resolve;
6417
+ controller._finishPromise = newPromise((resolve2, reject) => {
6418
+ controller._finishPromise_resolve = resolve2;
6419
6419
  controller._finishPromise_reject = reject;
6420
6420
  });
6421
6421
  const cancelPromise = controller._cancelAlgorithm(reason);
@@ -6971,22 +6971,22 @@ var init_from = __esm({
6971
6971
  init_file();
6972
6972
  init_fetch_blob();
6973
6973
  ({ stat } = fs);
6974
- blobFromSync = (path4, type) => fromBlob(statSync(path4), path4, type);
6975
- blobFrom = (path4, type) => stat(path4).then((stat2) => fromBlob(stat2, path4, type));
6976
- fileFrom = (path4, type) => stat(path4).then((stat2) => fromFile(stat2, path4, type));
6977
- fileFromSync = (path4, type) => fromFile(statSync(path4), path4, type);
6978
- fromBlob = (stat2, path4, type = "") => new fetch_blob_default([new BlobDataItem({
6979
- path: path4,
6974
+ blobFromSync = (path5, type) => fromBlob(statSync(path5), path5, type);
6975
+ blobFrom = (path5, type) => stat(path5).then((stat2) => fromBlob(stat2, path5, type));
6976
+ fileFrom = (path5, type) => stat(path5).then((stat2) => fromFile(stat2, path5, type));
6977
+ fileFromSync = (path5, type) => fromFile(statSync(path5), path5, type);
6978
+ fromBlob = (stat2, path5, type = "") => new fetch_blob_default([new BlobDataItem({
6979
+ path: path5,
6980
6980
  size: stat2.size,
6981
6981
  lastModified: stat2.mtimeMs,
6982
6982
  start: 0
6983
6983
  })], { type });
6984
- fromFile = (stat2, path4, type = "") => new file_default([new BlobDataItem({
6985
- path: path4,
6984
+ fromFile = (stat2, path5, type = "") => new file_default([new BlobDataItem({
6985
+ path: path5,
6986
6986
  size: stat2.size,
6987
6987
  lastModified: stat2.mtimeMs,
6988
6988
  start: 0
6989
- })], basename(path4), { type, lastModified: stat2.mtimeMs });
6989
+ })], basename(path5), { type, lastModified: stat2.mtimeMs });
6990
6990
  BlobDataItem = class _BlobDataItem {
6991
6991
  #path;
6992
6992
  #start;
@@ -8384,7 +8384,7 @@ import zlib from "zlib";
8384
8384
  import Stream4, { PassThrough as PassThrough2, pipeline as pump } from "stream";
8385
8385
  import { Buffer as Buffer3 } from "buffer";
8386
8386
  async function fetch2(url, options_) {
8387
- return new Promise((resolve, reject) => {
8387
+ return new Promise((resolve2, reject) => {
8388
8388
  const request = new Request(url, options_);
8389
8389
  const { parsedURL, options } = getNodeRequestOptions(request);
8390
8390
  if (!supportedSchemas.has(parsedURL.protocol)) {
@@ -8393,7 +8393,7 @@ async function fetch2(url, options_) {
8393
8393
  if (parsedURL.protocol === "data:") {
8394
8394
  const data = dist_default(request.url);
8395
8395
  const response2 = new Response2(data, { headers: { "Content-Type": data.typeFull } });
8396
- resolve(response2);
8396
+ resolve2(response2);
8397
8397
  return;
8398
8398
  }
8399
8399
  const send = (parsedURL.protocol === "https:" ? https : http2).request;
@@ -8515,7 +8515,7 @@ async function fetch2(url, options_) {
8515
8515
  if (responseReferrerPolicy) {
8516
8516
  requestOptions.referrerPolicy = responseReferrerPolicy;
8517
8517
  }
8518
- resolve(fetch2(new Request(locationURL, requestOptions)));
8518
+ resolve2(fetch2(new Request(locationURL, requestOptions)));
8519
8519
  finalize();
8520
8520
  return;
8521
8521
  }
@@ -8548,7 +8548,7 @@ async function fetch2(url, options_) {
8548
8548
  const codings = headers.get("Content-Encoding");
8549
8549
  if (!request.compress || request.method === "HEAD" || codings === null || response_.statusCode === 204 || response_.statusCode === 304) {
8550
8550
  response = new Response2(body, responseOptions);
8551
- resolve(response);
8551
+ resolve2(response);
8552
8552
  return;
8553
8553
  }
8554
8554
  const zlibOptions = {
@@ -8562,7 +8562,7 @@ async function fetch2(url, options_) {
8562
8562
  }
8563
8563
  });
8564
8564
  response = new Response2(body, responseOptions);
8565
- resolve(response);
8565
+ resolve2(response);
8566
8566
  return;
8567
8567
  }
8568
8568
  if (codings === "deflate" || codings === "x-deflate") {
@@ -8586,12 +8586,12 @@ async function fetch2(url, options_) {
8586
8586
  });
8587
8587
  }
8588
8588
  response = new Response2(body, responseOptions);
8589
- resolve(response);
8589
+ resolve2(response);
8590
8590
  });
8591
8591
  raw.once("end", () => {
8592
8592
  if (!response) {
8593
8593
  response = new Response2(body, responseOptions);
8594
- resolve(response);
8594
+ resolve2(response);
8595
8595
  }
8596
8596
  });
8597
8597
  return;
@@ -8603,11 +8603,11 @@ async function fetch2(url, options_) {
8603
8603
  }
8604
8604
  });
8605
8605
  response = new Response2(body, responseOptions);
8606
- resolve(response);
8606
+ resolve2(response);
8607
8607
  return;
8608
8608
  }
8609
8609
  response = new Response2(body, responseOptions);
8610
- resolve(response);
8610
+ resolve2(response);
8611
8611
  });
8612
8612
  writeToStream(request_, request).catch(reject);
8613
8613
  });
@@ -12180,9 +12180,9 @@ var require_util2 = __commonJS({
12180
12180
  exports.removeUndefinedValuesInObject = removeUndefinedValuesInObject;
12181
12181
  exports.isValidFile = isValidFile;
12182
12182
  exports.getWellKnownCertificateConfigFileLocation = getWellKnownCertificateConfigFileLocation;
12183
- var fs2 = __require("fs");
12183
+ var fs3 = __require("fs");
12184
12184
  var os = __require("os");
12185
- var path4 = __require("path");
12185
+ var path5 = __require("path");
12186
12186
  var WELL_KNOWN_CERTIFICATE_CONFIG_FILE = "certificate_config.json";
12187
12187
  var CLOUDSDK_CONFIG_DIRECTORY = "gcloud";
12188
12188
  function snakeToCamel(str2) {
@@ -12268,15 +12268,15 @@ var require_util2 = __commonJS({
12268
12268
  }
12269
12269
  async function isValidFile(filePath) {
12270
12270
  try {
12271
- const stats = await fs2.promises.lstat(filePath);
12271
+ const stats = await fs3.promises.lstat(filePath);
12272
12272
  return stats.isFile();
12273
12273
  } catch (e2) {
12274
12274
  return false;
12275
12275
  }
12276
12276
  }
12277
12277
  function getWellKnownCertificateConfigFileLocation() {
12278
- const configDir = process.env.CLOUDSDK_CONFIG || (_isWindows() ? path4.join(process.env.APPDATA || "", CLOUDSDK_CONFIG_DIRECTORY) : path4.join(process.env.HOME || "", ".config", CLOUDSDK_CONFIG_DIRECTORY));
12279
- return path4.join(configDir, WELL_KNOWN_CERTIFICATE_CONFIG_FILE);
12278
+ const configDir = process.env.CLOUDSDK_CONFIG || (_isWindows() ? path5.join(process.env.APPDATA || "", CLOUDSDK_CONFIG_DIRECTORY) : path5.join(process.env.HOME || "", ".config", CLOUDSDK_CONFIG_DIRECTORY));
12279
+ return path5.join(configDir, WELL_KNOWN_CERTIFICATE_CONFIG_FILE);
12280
12280
  }
12281
12281
  function _isWindows() {
12282
12282
  return os.platform().startsWith("win");
@@ -14230,11 +14230,11 @@ var require_getCredentials = __commonJS({
14230
14230
  "use strict";
14231
14231
  Object.defineProperty(exports, "__esModule", { value: true });
14232
14232
  exports.getCredentials = getCredentials;
14233
- var path4 = __require("path");
14234
- var fs2 = __require("fs");
14233
+ var path5 = __require("path");
14234
+ var fs3 = __require("fs");
14235
14235
  var util_1 = __require("util");
14236
14236
  var errorWithCode_1 = require_errorWithCode();
14237
- var readFile = fs2.readFile ? (0, util_1.promisify)(fs2.readFile) : async () => {
14237
+ var readFile = fs3.readFile ? (0, util_1.promisify)(fs3.readFile) : async () => {
14238
14238
  throw new errorWithCode_1.ErrorWithCode("use key rather than keyFile.", "MISSING_CREDENTIALS");
14239
14239
  };
14240
14240
  var ExtensionFiles;
@@ -14302,7 +14302,7 @@ var require_getCredentials = __commonJS({
14302
14302
  * @returns An instance of a class that implements ICredentialsProvider.
14303
14303
  */
14304
14304
  static create(keyFilePath) {
14305
- const keyFileExtension = path4.extname(keyFilePath);
14305
+ const keyFileExtension = path5.extname(keyFilePath);
14306
14306
  switch (keyFileExtension) {
14307
14307
  case ExtensionFiles.JSON:
14308
14308
  return new JsonCredentialsProvider(keyFilePath);
@@ -14689,7 +14689,7 @@ var require_jwtaccess = __commonJS({
14689
14689
  }
14690
14690
  }
14691
14691
  fromStreamAsync(inputStream) {
14692
- return new Promise((resolve, reject) => {
14692
+ return new Promise((resolve2, reject) => {
14693
14693
  if (!inputStream) {
14694
14694
  reject(new Error("Must pass in a stream containing the service account auth settings."));
14695
14695
  }
@@ -14698,7 +14698,7 @@ var require_jwtaccess = __commonJS({
14698
14698
  try {
14699
14699
  const data = JSON.parse(s2);
14700
14700
  this.fromJSON(data);
14701
- resolve();
14701
+ resolve2();
14702
14702
  } catch (err) {
14703
14703
  reject(err);
14704
14704
  }
@@ -14937,7 +14937,7 @@ var require_jwtclient = __commonJS({
14937
14937
  }
14938
14938
  }
14939
14939
  fromStreamAsync(inputStream) {
14940
- return new Promise((resolve, reject) => {
14940
+ return new Promise((resolve2, reject) => {
14941
14941
  if (!inputStream) {
14942
14942
  throw new Error("Must pass in a stream containing the service account auth settings.");
14943
14943
  }
@@ -14946,7 +14946,7 @@ var require_jwtclient = __commonJS({
14946
14946
  try {
14947
14947
  const data = JSON.parse(s2);
14948
14948
  this.fromJSON(data);
14949
- resolve();
14949
+ resolve2();
14950
14950
  } catch (e2) {
14951
14951
  reject(e2);
14952
14952
  }
@@ -15079,7 +15079,7 @@ var require_refreshclient = __commonJS({
15079
15079
  }
15080
15080
  }
15081
15081
  async fromStreamAsync(inputStream) {
15082
- return new Promise((resolve, reject) => {
15082
+ return new Promise((resolve2, reject) => {
15083
15083
  if (!inputStream) {
15084
15084
  return reject(new Error("Must pass in a stream containing the user refresh token."));
15085
15085
  }
@@ -15088,7 +15088,7 @@ var require_refreshclient = __commonJS({
15088
15088
  try {
15089
15089
  const data = JSON.parse(s2);
15090
15090
  this.fromJSON(data);
15091
- return resolve();
15091
+ return resolve2();
15092
15092
  } catch (err) {
15093
15093
  return reject(err);
15094
15094
  }
@@ -15911,12 +15911,12 @@ var require_filesubjecttokensupplier = __commonJS({
15911
15911
  Object.defineProperty(exports, "__esModule", { value: true });
15912
15912
  exports.FileSubjectTokenSupplier = void 0;
15913
15913
  var util_1 = __require("util");
15914
- var fs2 = __require("fs");
15915
- var readFile = (0, util_1.promisify)(fs2.readFile ?? (() => {
15914
+ var fs3 = __require("fs");
15915
+ var readFile = (0, util_1.promisify)(fs3.readFile ?? (() => {
15916
15916
  }));
15917
- var realpath = (0, util_1.promisify)(fs2.realpath ?? (() => {
15917
+ var realpath = (0, util_1.promisify)(fs3.realpath ?? (() => {
15918
15918
  }));
15919
- var lstat = (0, util_1.promisify)(fs2.lstat ?? (() => {
15919
+ var lstat = (0, util_1.promisify)(fs3.lstat ?? (() => {
15920
15920
  }));
15921
15921
  var FileSubjectTokenSupplier = class {
15922
15922
  filePath;
@@ -16034,7 +16034,7 @@ var require_certificatesubjecttokensupplier = __commonJS({
16034
16034
  Object.defineProperty(exports, "__esModule", { value: true });
16035
16035
  exports.CertificateSubjectTokenSupplier = exports.InvalidConfigurationError = exports.CertificateSourceUnavailableError = exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = void 0;
16036
16036
  var util_1 = require_util2();
16037
- var fs2 = __require("fs");
16037
+ var fs3 = __require("fs");
16038
16038
  var crypto_1 = __require("crypto");
16039
16039
  var https2 = __require("https");
16040
16040
  exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = "GOOGLE_API_CERTIFICATE_CONFIG";
@@ -16128,7 +16128,7 @@ var require_certificatesubjecttokensupplier = __commonJS({
16128
16128
  const configPath = this.certificateConfigPath;
16129
16129
  let fileContents;
16130
16130
  try {
16131
- fileContents = await fs2.promises.readFile(configPath, "utf8");
16131
+ fileContents = await fs3.promises.readFile(configPath, "utf8");
16132
16132
  } catch (err) {
16133
16133
  throw new CertificateSourceUnavailableError(`Failed to read certificate config file at: ${configPath}`);
16134
16134
  }
@@ -16153,14 +16153,14 @@ var require_certificatesubjecttokensupplier = __commonJS({
16153
16153
  async #getKeyAndCert(certPath, keyPath) {
16154
16154
  let cert, key;
16155
16155
  try {
16156
- cert = await fs2.promises.readFile(certPath);
16156
+ cert = await fs3.promises.readFile(certPath);
16157
16157
  new crypto_1.X509Certificate(cert);
16158
16158
  } catch (err) {
16159
16159
  const message = err instanceof Error ? err.message : String(err);
16160
16160
  throw new CertificateSourceUnavailableError(`Failed to read certificate file at ${certPath}: ${message}`);
16161
16161
  }
16162
16162
  try {
16163
- key = await fs2.promises.readFile(keyPath);
16163
+ key = await fs3.promises.readFile(keyPath);
16164
16164
  (0, crypto_1.createPrivateKey)(key);
16165
16165
  } catch (err) {
16166
16166
  const message = err instanceof Error ? err.message : String(err);
@@ -16179,7 +16179,7 @@ var require_certificatesubjecttokensupplier = __commonJS({
16179
16179
  return JSON.stringify([leafCert.raw.toString("base64")]);
16180
16180
  }
16181
16181
  try {
16182
- const chainPems = await fs2.promises.readFile(this.trustChainPath, "utf8");
16182
+ const chainPems = await fs3.promises.readFile(this.trustChainPath, "utf8");
16183
16183
  const pemBlocks = chainPems.match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g) ?? [];
16184
16184
  const chainCerts = pemBlocks.map((pem, index) => {
16185
16185
  try {
@@ -16881,7 +16881,7 @@ var require_pluggable_auth_handler = __commonJS({
16881
16881
  exports.PluggableAuthHandler = exports.ExecutableError = void 0;
16882
16882
  var executable_response_1 = require_executable_response();
16883
16883
  var childProcess = __require("child_process");
16884
- var fs2 = __require("fs");
16884
+ var fs3 = __require("fs");
16885
16885
  var ExecutableError = class extends Error {
16886
16886
  /**
16887
16887
  * The exit code returned by the executable.
@@ -16921,7 +16921,7 @@ var require_pluggable_auth_handler = __commonJS({
16921
16921
  * @return A promise that resolves with the executable response.
16922
16922
  */
16923
16923
  retrieveResponseFromExecutable(envMap) {
16924
- return new Promise((resolve, reject) => {
16924
+ return new Promise((resolve2, reject) => {
16925
16925
  const child = childProcess.spawn(this.commandComponents[0], this.commandComponents.slice(1), {
16926
16926
  env: { ...process.env, ...Object.fromEntries(envMap) }
16927
16927
  });
@@ -16943,7 +16943,7 @@ var require_pluggable_auth_handler = __commonJS({
16943
16943
  try {
16944
16944
  const responseJson = JSON.parse(output);
16945
16945
  const response = new executable_response_1.ExecutableResponse(responseJson);
16946
- return resolve(response);
16946
+ return resolve2(response);
16947
16947
  } catch (error) {
16948
16948
  if (error instanceof executable_response_1.ExecutableResponseError) {
16949
16949
  return reject(error);
@@ -16966,14 +16966,14 @@ var require_pluggable_auth_handler = __commonJS({
16966
16966
  }
16967
16967
  let filePath;
16968
16968
  try {
16969
- filePath = await fs2.promises.realpath(this.outputFile);
16969
+ filePath = await fs3.promises.realpath(this.outputFile);
16970
16970
  } catch {
16971
16971
  return void 0;
16972
16972
  }
16973
- if (!(await fs2.promises.lstat(filePath)).isFile()) {
16973
+ if (!(await fs3.promises.lstat(filePath)).isFile()) {
16974
16974
  return void 0;
16975
16975
  }
16976
- const responseString = await fs2.promises.readFile(filePath, {
16976
+ const responseString = await fs3.promises.readFile(filePath, {
16977
16977
  encoding: "utf8"
16978
16978
  });
16979
16979
  if (responseString === "") {
@@ -17384,11 +17384,11 @@ var require_googleauth = __commonJS({
17384
17384
  Object.defineProperty(exports, "__esModule", { value: true });
17385
17385
  exports.GoogleAuth = exports.GoogleAuthExceptionMessages = void 0;
17386
17386
  var child_process_1 = __require("child_process");
17387
- var fs2 = __require("fs");
17387
+ var fs3 = __require("fs");
17388
17388
  var gaxios_1 = require_src2();
17389
17389
  var gcpMetadata = require_src4();
17390
17390
  var os = __require("os");
17391
- var path4 = __require("path");
17391
+ var path5 = __require("path");
17392
17392
  var crypto_1 = require_crypto3();
17393
17393
  var computeclient_1 = require_computeclient();
17394
17394
  var idtokenclient_1 = require_idtokenclient();
@@ -17674,12 +17674,12 @@ var require_googleauth = __commonJS({
17674
17674
  } else {
17675
17675
  const home = process.env["HOME"];
17676
17676
  if (home) {
17677
- location = path4.join(home, ".config");
17677
+ location = path5.join(home, ".config");
17678
17678
  }
17679
17679
  }
17680
17680
  if (location) {
17681
- location = path4.join(location, "gcloud", "application_default_credentials.json");
17682
- if (!fs2.existsSync(location)) {
17681
+ location = path5.join(location, "gcloud", "application_default_credentials.json");
17682
+ if (!fs3.existsSync(location)) {
17683
17683
  location = null;
17684
17684
  }
17685
17685
  }
@@ -17700,8 +17700,8 @@ var require_googleauth = __commonJS({
17700
17700
  throw new Error("The file path is invalid.");
17701
17701
  }
17702
17702
  try {
17703
- filePath = fs2.realpathSync(filePath);
17704
- if (!fs2.lstatSync(filePath).isFile()) {
17703
+ filePath = fs3.realpathSync(filePath);
17704
+ if (!fs3.lstatSync(filePath).isFile()) {
17705
17705
  throw new Error();
17706
17706
  }
17707
17707
  } catch (err) {
@@ -17710,7 +17710,7 @@ var require_googleauth = __commonJS({
17710
17710
  }
17711
17711
  throw err;
17712
17712
  }
17713
- const readStream = fs2.createReadStream(filePath);
17713
+ const readStream = fs3.createReadStream(filePath);
17714
17714
  return this.fromStream(readStream, options);
17715
17715
  }
17716
17716
  /**
@@ -17846,7 +17846,7 @@ var require_googleauth = __commonJS({
17846
17846
  }
17847
17847
  }
17848
17848
  fromStreamAsync(inputStream, options) {
17849
- return new Promise((resolve, reject) => {
17849
+ return new Promise((resolve2, reject) => {
17850
17850
  if (!inputStream) {
17851
17851
  throw new Error("Must pass in a stream containing the Google auth settings.");
17852
17852
  }
@@ -17856,7 +17856,7 @@ var require_googleauth = __commonJS({
17856
17856
  try {
17857
17857
  const data = JSON.parse(chunks.join(""));
17858
17858
  const r2 = this._cacheClientFromJSON(data, options);
17859
- return resolve(r2);
17859
+ return resolve2(r2);
17860
17860
  } catch (err) {
17861
17861
  if (!this.keyFilename)
17862
17862
  throw err;
@@ -17866,7 +17866,7 @@ var require_googleauth = __commonJS({
17866
17866
  });
17867
17867
  this.cachedCredential = client;
17868
17868
  this.setGapicJWTValues(client);
17869
- return resolve(client);
17869
+ return resolve2(client);
17870
17870
  }
17871
17871
  } catch (err) {
17872
17872
  return reject(err);
@@ -17902,17 +17902,17 @@ var require_googleauth = __commonJS({
17902
17902
  * Run the Google Cloud SDK command that prints the default project ID
17903
17903
  */
17904
17904
  async getDefaultServiceProjectId() {
17905
- return new Promise((resolve) => {
17905
+ return new Promise((resolve2) => {
17906
17906
  (0, child_process_1.exec)("gcloud config config-helper --format json", (err, stdout) => {
17907
17907
  if (!err && stdout) {
17908
17908
  try {
17909
17909
  const projectId = JSON.parse(stdout).configuration.properties.core.project;
17910
- resolve(projectId);
17910
+ resolve2(projectId);
17911
17911
  return;
17912
17912
  } catch (e2) {
17913
17913
  }
17914
17914
  }
17915
- resolve(null);
17915
+ resolve2(null);
17916
17916
  });
17917
17917
  });
17918
17918
  }
@@ -18022,8 +18022,8 @@ var require_googleauth = __commonJS({
18022
18022
  if (this.jsonContent) {
18023
18023
  return this._cacheClientFromJSON(this.jsonContent, this.clientOptions);
18024
18024
  } else if (this.keyFilename) {
18025
- const filePath = path4.resolve(this.keyFilename);
18026
- const stream = fs2.createReadStream(filePath);
18025
+ const filePath = path5.resolve(this.keyFilename);
18026
+ const stream = fs3.createReadStream(filePath);
18027
18027
  return await this.fromStreamAsync(stream, this.clientOptions);
18028
18028
  } else if (this.apiKey) {
18029
18029
  const client = await this.fromAPIKey(this.apiKey, this.clientOptions);
@@ -22241,10 +22241,607 @@ var require_websocket_server = __commonJS({
22241
22241
  }
22242
22242
  });
22243
22243
 
22244
+ // ../baro-orchestrator/scripts/run-planner.ts
22245
+ import { readFileSync as readFileSync2 } from "fs";
22246
+
22244
22247
  // ../baro-orchestrator/src/planning/planner-claude.ts
22245
22248
  import { execFile } from "child_process";
22246
22249
  import { promisify } from "util";
22250
+
22251
+ // ../baro-orchestrator/src/planning/planner-prompts.ts
22252
+ var PLANNER_SYSTEM_PROMPT = `You are an expert software architect. Break down the user's project goal into concrete user stories that form a dependency DAG.
22253
+
22254
+ You MUST explore the existing codebase first using your tools (read files, list directories, etc.) before generating the plan.
22255
+
22256
+ TRIAGE FIRST \u2014 DO NOT SKIP THIS STEP:
22257
+ Before you decompose, decide whether the goal is TRIVIAL or NON-TRIVIAL.
22258
+
22259
+ A goal is TRIVIAL when ALL of these hold:
22260
+ - It names a single concept (one bug, one rename, one typo, one small addition).
22261
+ - It can plausibly be done by touching a small number of files in one focused
22262
+ edit, with no cross-cutting decisions and no new dependencies.
22263
+ - Splitting it would just create artificial seams (e.g. "Story 1: locate the typo,
22264
+ Story 2: fix the typo" is wrong \u2014 that's one story).
22265
+ - It does NOT introduce a new feature surface, schema, or API contract.
22266
+
22267
+ Examples of TRIVIAL goals:
22268
+ - "Fix the typo in the README footer"
22269
+ - "Rename \`getUser\` to \`fetchUser\` across the auth module"
22270
+ - "Bump axios to 1.7.x"
22271
+ - "Add a \`created_at\` index on the orders table"
22272
+ - "Fix the off-by-one in pagination.ts"
22273
+
22274
+ If the goal is TRIVIAL: output EXACTLY ONE story. Set its description to the user's
22275
+ goal restated in implementation terms. Set acceptance to a single, tight criterion
22276
+ (e.g. "the typo is fixed in README.md"). Use the minimum useful test command
22277
+ (typically just \`npm run build\` or \`cargo check\`, not a full test suite). Do NOT
22278
+ decompose further. Do NOT invent a "verify" story \u2014 verification is part of the
22279
+ single story's acceptance.
22280
+
22281
+ If the goal is NON-TRIVIAL: decompose normally per the rules below.
22282
+
22283
+ When in doubt, prefer FEWER stories over more. A single 2-file story is better
22284
+ than two artificially-split 1-file stories.
22285
+
22286
+ RUN SHAPE:
22287
+ baro can run focused, sequential, or parallel work. Parallelism is valuable only
22288
+ when stories have independent write surfaces. Do NOT create parallel stories
22289
+ that edit the same file, component, state machine, schema, or API contract.
22290
+
22291
+ Mode semantics:
22292
+ - focused: exactly one story. Use this for one bug, one UI/component issue,
22293
+ one failing build/runtime error, or anything likely centered on a shared
22294
+ file/surface. The story should carry enough context to finish the PR.
22295
+ - sequential: several small stories with real dependencies. Use this when the
22296
+ work is one feature that must be implemented in ordered steps.
22297
+ - parallel: a DAG with sibling stories only where you can prove independence
22298
+ (different files/modules/contracts). Parallelism requires a reason; do not
22299
+ fan out just to use agents.
22300
+
22301
+ Dependency rules:
22302
+ - Stories touching disjoint files/modules may run in parallel.
22303
+ - Stories touching the same file/component/state/API must be sequential or one
22304
+ focused story.
22305
+ - Only add dependsOn when story B literally cannot start until A is merged
22306
+ because B imports a symbol A defines, modifies a file A creates, or relies
22307
+ on a schema/API A introduces.
22308
+ - Decorative chains are bad, but unsafe parallel edits are worse.
22309
+
22310
+ Output ONLY valid JSON matching this exact schema (no markdown, no explanation, just JSON):
22311
+ {
22312
+ "project": "short project name",
22313
+ "branchName": "kebab-case-branch-name",
22314
+ "description": "one-line description",
22315
+ "userStories": [
22316
+ {
22317
+ "id": "S1",
22318
+ "priority": 1,
22319
+ "title": "short title",
22320
+ "description": "what to implement",
22321
+ "dependsOn": [],
22322
+ "retries": 2,
22323
+ "acceptance": ["testable criterion"],
22324
+ "tests": ["npm test"],
22325
+ "model": "opus"
22326
+ }
22327
+ ]
22328
+ }
22329
+
22330
+ Rules:
22331
+ - Each story: ONE focused unit of work for one AI agent. Hard cap:
22332
+ * touches at most ~10 files
22333
+ * fits in a single Claude turn (a few minutes of execution, not an hour)
22334
+ Stories that read like "Strip all X" / "Refactor everything that touches Y"
22335
+ are TOO BIG. Split them by directory, by feature, or by file group:
22336
+ "Delete backend SEF module"
22337
+ "Delete frontend SEF wiring"
22338
+ "Rename pib\u2192taxId in schema + DTOs"
22339
+ "Rename pib\u2192taxId in services + frontend forms"
22340
+ Prefer 12-15 small stories over 5 big ones.
22341
+ - TIER EVERY STORY by blast radius \u2014 set "model" on EVERY story to one
22342
+ of "haiku" | "sonnet" | "opus". You are the tech lead assigning work
22343
+ to a team; pick the tier by asking "if an agent gets THIS story wrong,
22344
+ what breaks?" \u2014 NOT by raw difficulty:
22345
+ * "haiku" \u2192 nothing important breaks. Mechanical, single-concern,
22346
+ self-contained: a rename, boilerplate, a barrel/index
22347
+ file, one DTO, a config tweak, a doc edit, scaffolding.
22348
+ * "sonnet" \u2192 one feature breaks but the damage is contained to its
22349
+ own module: a scoped service method, a component, a
22350
+ focused refactor, tests for non-trivial logic.
22351
+ * "opus" \u2192 other features / the architecture / data integrity
22352
+ break: schema or migration changes, cross-cutting
22353
+ refactors, public API/contract design, integration and
22354
+ wiring stories, anything that several other stories
22355
+ depend on (a hub node in the DAG).
22356
+ Tiers are how the operator routes cost: a downstream tier map may send
22357
+ "haiku"/"sonnet" to a cheaper backend and keep "opus" on the strongest
22358
+ model. Misclassifying UP wastes money; misclassifying DOWN risks a
22359
+ broken merge \u2014 when genuinely unsure between two tiers, pick the
22360
+ HIGHER one. A foundational story that many others depend on is "opus"
22361
+ even if it looks small.
22362
+ - Use dependsOn for dependencies; same-priority stories with no deps run IN PARALLEL
22363
+ - Include testable acceptance criteria and test commands
22364
+ - No circular dependencies
22365
+ - Start with foundational stories, build up
22366
+ - IDs: S1, S2, S3...
22367
+ - Build on existing code, don't recreate what exists
22368
+ - Output ONLY the JSON, nothing else`;
22369
+ function heuristicModeContract(args) {
22370
+ if (args.quick) {
22371
+ return {
22372
+ mode: "focused",
22373
+ confidence: 1,
22374
+ reason: "Quick mode was explicitly requested.",
22375
+ maxStories: 1,
22376
+ parallelism: 1
22377
+ };
22378
+ }
22379
+ const goal = args.goal.toLowerCase();
22380
+ const bugLike = /\b(fix|bug|error|crash|broken|console|build|doesn'?t|isn'?t|still|again|issue|problem|wrong|shifted|display|render)\b/.test(goal);
22381
+ const uiLike = /\b(ui|frontend|react|component|button|card|tab|modal|page|screen|css|style|layout|episode|season)\b/.test(goal);
22382
+ const bigLike = /\b(refactor|rewrite|migrate|redesign|implement|add support|multiple|several|backend|frontend|database|api|tests|docs)\b/.test(goal);
22383
+ if (bugLike || uiLike && !bigLike) {
22384
+ return {
22385
+ mode: "focused",
22386
+ confidence: 0.7,
22387
+ reason: "The goal looks like a localized bugfix/follow-up likely centered on shared UI or one code surface.",
22388
+ maxStories: 1,
22389
+ parallelism: 1
22390
+ };
22391
+ }
22392
+ if (bigLike) {
22393
+ return {
22394
+ mode: "sequential",
22395
+ confidence: 0.55,
22396
+ reason: "The goal may need multiple steps, but no LLM intake proved independent write surfaces.",
22397
+ maxStories: 5,
22398
+ parallelism: 1
22399
+ };
22400
+ }
22401
+ return {
22402
+ mode: "focused",
22403
+ confidence: 0.5,
22404
+ reason: "Uncertain goals default to focused mode to avoid unsafe parallel decomposition.",
22405
+ maxStories: 1,
22406
+ parallelism: 1
22407
+ };
22408
+ }
22409
+ function renderModeContract(decision) {
22410
+ const lines = [
22411
+ `mode: ${decision.mode}`,
22412
+ `confidence: ${decision.confidence}`,
22413
+ `reason: ${decision.reason}`
22414
+ ];
22415
+ if (decision.maxStories) lines.push(`maxStories: ${decision.maxStories}`);
22416
+ if (decision.parallelism) lines.push(`parallelism: ${decision.parallelism}`);
22417
+ if (decision.mode === "focused") {
22418
+ lines.push(
22419
+ 'Planner rules: output EXACTLY ONE story. Do not split. Set model to "opus" so this focused run uses the strong route.',
22420
+ "The story must include enough implementation context and acceptance criteria for one agent to finish the PR."
22421
+ );
22422
+ } else if (decision.mode === "sequential") {
22423
+ lines.push(
22424
+ "Planner rules: output a small ordered chain. Use dependsOn for real shared-surface dependencies.",
22425
+ "Do not create parallel siblings that edit the same file/component/state/API. Keep each story cheap-model-capable."
22426
+ );
22427
+ } else {
22428
+ lines.push(
22429
+ "Planner rules: output parallel siblings only where write surfaces are independent.",
22430
+ "For each sibling story, name its expected write surface in the description. Shared files/components must be sequential."
22431
+ );
22432
+ }
22433
+ return lines.join("\n");
22434
+ }
22435
+ function buildIntakePrompt(args) {
22436
+ if (args.quick) {
22437
+ return JSON.stringify({
22438
+ mode: "focused",
22439
+ confidence: 1,
22440
+ reason: "Quick mode was explicitly requested.",
22441
+ maxStories: 1,
22442
+ parallelism: 1
22443
+ });
22444
+ }
22445
+ return [
22446
+ "You are Baro Intake. Choose the execution shape BEFORE planning.",
22447
+ "",
22448
+ "Return ONLY valid JSON with this schema:",
22449
+ '{"mode":"focused|sequential|parallel","confidence":0.0,"reason":"short","maxStories":1,"parallelism":1}',
22450
+ "",
22451
+ "Definitions:",
22452
+ "- focused: one strong agent/story. Use for small bugfixes, UI tweaks, build/runtime errors, one component/file/surface, or unclear shared-write work.",
22453
+ "- sequential: multiple small ordered stories. Use when one feature naturally requires steps that touch shared code.",
22454
+ "- parallel: only when there are independent write surfaces (different modules/files/contracts) that can safely run at the same time.",
22455
+ "",
22456
+ "Bias rules:",
22457
+ "- If several agents would edit the same file/component/state/schema, choose focused or sequential, not parallel.",
22458
+ "- If the prompt is a follow-up bug report from screenshots/console output, choose focused unless it clearly spans independent surfaces.",
22459
+ "- If uncertain, choose focused. Unsafe parallelism is worse than leaving speed on the table.",
22460
+ "- maxStories is a cap for the planner, not a target.",
22461
+ "",
22462
+ args.projectContext?.trim() ? `Project context summary:
22463
+ ${args.projectContext.trim().slice(0, 3e3)}
22464
+ ` : "",
22465
+ args.decisionDocument?.trim() ? `Architect decision exists; prefer a compact plan that implements it.
22466
+ ${args.decisionDocument.trim().slice(0, 3e3)}
22467
+ ` : "",
22468
+ `User goal:
22469
+ ${args.goal.trim()}`
22470
+ ].filter(Boolean).join("\n");
22471
+ }
22472
+ function parseModeContract(text) {
22473
+ const json = JSON.parse(extractJsonObject(text));
22474
+ const mode = json.mode === "parallel" || json.mode === "sequential" || json.mode === "focused" ? json.mode : "focused";
22475
+ const confidence = Number.isFinite(Number(json.confidence)) ? Math.max(0, Math.min(1, Number(json.confidence))) : 0.5;
22476
+ return {
22477
+ mode,
22478
+ confidence,
22479
+ reason: typeof json.reason === "string" && json.reason.trim() ? json.reason.trim() : "No reason supplied by intake.",
22480
+ maxStories: Number.isFinite(Number(json.maxStories)) ? Math.max(1, Math.floor(Number(json.maxStories))) : void 0,
22481
+ parallelism: Number.isFinite(Number(json.parallelism)) ? Math.max(1, Math.floor(Number(json.parallelism))) : void 0,
22482
+ source: typeof json.source === "string" ? json.source : void 0
22483
+ };
22484
+ }
22485
+ function extractJsonObject(text) {
22486
+ const trimmed = text.trim();
22487
+ if (trimmed.startsWith("{") && trimmed.endsWith("}")) return trimmed;
22488
+ const fence = trimmed.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/);
22489
+ if (fence) return fence[1];
22490
+ const start = trimmed.indexOf("{");
22491
+ if (start < 0) throw new Error(`no JSON object in response: ${trimmed.slice(0, 200)}`);
22492
+ let depth = 0;
22493
+ for (let i2 = start; i2 < trimmed.length; i2++) {
22494
+ const ch = trimmed[i2];
22495
+ if (ch === "{") depth++;
22496
+ else if (ch === "}") {
22497
+ depth--;
22498
+ if (depth === 0) return trimmed.slice(start, i2 + 1);
22499
+ }
22500
+ }
22501
+ throw new Error(`unbalanced JSON in response: ${trimmed.slice(0, 200)}`);
22502
+ }
22503
+ function buildPlannerUserMessage(args) {
22504
+ const sections = [];
22505
+ if (args.projectContext && args.projectContext.trim().length > 0) {
22506
+ sections.push("## Project context (CLAUDE.md / equivalent)");
22507
+ sections.push("");
22508
+ sections.push(args.projectContext.trim());
22509
+ sections.push("");
22510
+ sections.push("---");
22511
+ sections.push("");
22512
+ }
22513
+ if (args.decisionDocument && args.decisionDocument.trim().length > 0) {
22514
+ sections.push(
22515
+ "AUTHORITATIVE DESIGN SPEC (already decided by the Architect \u2014 every story you produce must implement THESE specific file paths, names, and shapes; do NOT invent alternatives):"
22516
+ );
22517
+ sections.push("");
22518
+ sections.push(args.decisionDocument.trim());
22519
+ sections.push("");
22520
+ sections.push("---");
22521
+ sections.push("");
22522
+ }
22523
+ const modeContract = typeof args.modeContract === "string" ? args.modeContract : args.modeContract ? renderModeContract(args.modeContract) : void 0;
22524
+ if (modeContract && modeContract.trim().length > 0) {
22525
+ sections.push("EXECUTION MODE CONTRACT (chosen by Baro Intake \u2014 obey it):");
22526
+ sections.push("");
22527
+ sections.push(modeContract.trim());
22528
+ sections.push("");
22529
+ sections.push("---");
22530
+ sections.push("");
22531
+ }
22532
+ if (args.quick) {
22533
+ sections.push(
22534
+ "QUICK MODE OVERRIDE \u2014 the user invoked `baro --quick`. They have told us this goal is trivial. You MUST output EXACTLY ONE story. Do not split. Do not decompose. Do not add a `verify` story. If you genuinely cannot do this in one story, emit the one story anyway with a description that explains what's missing; the user will rerun without --quick. One story, tight acceptance, minimum useful test command."
22535
+ );
22536
+ sections.push("");
22537
+ }
22538
+ sections.push("User goal:");
22539
+ sections.push(args.goal.trim());
22540
+ return sections.join("\n");
22541
+ }
22542
+
22543
+ // ../baro-orchestrator/src/planning/planner-claude.ts
22247
22544
  var execFileAsync = promisify(execFile);
22545
+ function effortTimeoutMs(effort) {
22546
+ switch (effort) {
22547
+ case "max":
22548
+ return 12e5;
22549
+ // 20 min
22550
+ case "xhigh":
22551
+ return 9e5;
22552
+ // 15 min
22553
+ case "high":
22554
+ return 48e4;
22555
+ // 8 min
22556
+ default:
22557
+ return 24e4;
22558
+ }
22559
+ }
22560
+ async function runPlannerClaude(opts) {
22561
+ const modeContract = opts.modeContract ?? await runClaudeIntake(opts).catch((e2) => {
22562
+ process.stderr.write(`[planner-claude] intake failed (${e2?.message ?? String(e2)}) \u2014 using heuristic mode contract
22563
+ `);
22564
+ return heuristicModeContract(opts);
22565
+ });
22566
+ process.stderr.write(`[planner-claude] intake mode=${modeContract.mode} confidence=${modeContract.confidence}
22567
+ `);
22568
+ const userMessage = buildPlannerUserMessage({
22569
+ goal: opts.goal,
22570
+ decisionDocument: opts.decisionDocument,
22571
+ quick: opts.quick,
22572
+ projectContext: opts.projectContext,
22573
+ modeContract
22574
+ });
22575
+ const { stdout } = await execFileAsync(
22576
+ opts.claudeBin ?? "claude",
22577
+ [
22578
+ "--print",
22579
+ "--output-format",
22580
+ "json",
22581
+ ...opts.model ? ["--model", opts.model] : [],
22582
+ ...opts.effort ? ["--effort", opts.effort] : [],
22583
+ "--permission-mode",
22584
+ "bypassPermissions",
22585
+ "--system-prompt",
22586
+ PLANNER_SYSTEM_PROMPT,
22587
+ "-p",
22588
+ userMessage
22589
+ ],
22590
+ {
22591
+ cwd: opts.cwd,
22592
+ timeout: opts.timeoutMs ?? effortTimeoutMs(opts.effort),
22593
+ maxBuffer: 16 * 1024 * 1024
22594
+ }
22595
+ );
22596
+ const wrapper = JSON.parse(stdout);
22597
+ const planText = typeof wrapper.result === "string" ? wrapper.result.trim() : "";
22598
+ if (!planText) {
22599
+ throw new Error("PlannerClaude: claude returned empty result");
22600
+ }
22601
+ return extractJsonObject2(planText);
22602
+ }
22603
+ async function runClaudeIntake(opts) {
22604
+ if (opts.quick) return heuristicModeContract(opts);
22605
+ const { stdout } = await execFileAsync(
22606
+ opts.claudeBin ?? "claude",
22607
+ [
22608
+ "--print",
22609
+ "--output-format",
22610
+ "json",
22611
+ ...opts.model ? ["--model", opts.model] : [],
22612
+ ...opts.effort ? ["--effort", opts.effort] : [],
22613
+ "--permission-mode",
22614
+ "bypassPermissions",
22615
+ "--system-prompt",
22616
+ "You classify software tasks for an autonomous PR workflow. Output JSON only.",
22617
+ "-p",
22618
+ buildIntakePrompt(opts)
22619
+ ],
22620
+ {
22621
+ cwd: opts.cwd,
22622
+ timeout: Math.min(opts.timeoutMs ?? effortTimeoutMs(opts.effort), 18e4),
22623
+ maxBuffer: 2 * 1024 * 1024
22624
+ }
22625
+ );
22626
+ const wrapper = JSON.parse(stdout);
22627
+ const text = typeof wrapper.result === "string" ? wrapper.result.trim() : "";
22628
+ if (!text) throw new Error("empty intake result");
22629
+ return parseModeContract(text);
22630
+ }
22631
+ function extractJsonObject2(text) {
22632
+ const trimmed = text.trim();
22633
+ if (trimmed.startsWith("{") && trimmed.endsWith("}")) return trimmed;
22634
+ const fence = trimmed.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/);
22635
+ if (fence) return fence[1];
22636
+ const start = trimmed.indexOf("{");
22637
+ if (start < 0) {
22638
+ throw new Error(
22639
+ `PlannerClaude: no JSON object in response: ${trimmed.slice(0, 200)}`
22640
+ );
22641
+ }
22642
+ let depth = 0;
22643
+ for (let i2 = start; i2 < trimmed.length; i2++) {
22644
+ const ch = trimmed[i2];
22645
+ if (ch === "{") depth++;
22646
+ else if (ch === "}") {
22647
+ depth--;
22648
+ if (depth === 0) return trimmed.slice(start, i2 + 1);
22649
+ }
22650
+ }
22651
+ throw new Error(
22652
+ `PlannerClaude: unbalanced JSON in response: ${trimmed.slice(0, 200)}`
22653
+ );
22654
+ }
22655
+
22656
+ // ../baro-orchestrator/src/codex-one-shot.ts
22657
+ import { spawn } from "child_process";
22658
+ async function runCodexOneShot(opts) {
22659
+ const label = opts.label ?? "codex";
22660
+ const args = ["exec", "--json"];
22661
+ if (opts.skipGitRepoCheck) args.push("--skip-git-repo-check");
22662
+ if (opts.bypassSandbox !== false) {
22663
+ args.push("--dangerously-bypass-approvals-and-sandbox");
22664
+ }
22665
+ if (opts.model) args.push("--model", opts.model);
22666
+ args.push(opts.prompt);
22667
+ const timeoutMs = opts.timeoutMs ?? 6e5;
22668
+ return await new Promise((resolve2, reject) => {
22669
+ let proc;
22670
+ try {
22671
+ proc = spawn(opts.codexBin ?? "codex", args, {
22672
+ cwd: opts.cwd,
22673
+ stdio: ["ignore", "pipe", "pipe"]
22674
+ });
22675
+ } catch (e2) {
22676
+ reject(e2 instanceof Error ? e2 : new Error(String(e2)));
22677
+ return;
22678
+ }
22679
+ let agentMessage = "";
22680
+ let stdoutBuffer = "";
22681
+ const eventTypesSeen = [];
22682
+ const itemTypesSeen = [];
22683
+ let timedOut = false;
22684
+ const startedAt = Date.now();
22685
+ const timer = setTimeout(() => {
22686
+ timedOut = true;
22687
+ try {
22688
+ proc.kill("SIGTERM");
22689
+ } catch {
22690
+ }
22691
+ }, timeoutMs);
22692
+ proc.stdout.setEncoding("utf8");
22693
+ proc.stdout.on("data", (chunk) => {
22694
+ stdoutBuffer += chunk;
22695
+ let nl;
22696
+ while ((nl = stdoutBuffer.indexOf("\n")) >= 0) {
22697
+ const line = stdoutBuffer.slice(0, nl).trim();
22698
+ stdoutBuffer = stdoutBuffer.slice(nl + 1);
22699
+ if (!line) continue;
22700
+ let event;
22701
+ try {
22702
+ event = JSON.parse(line);
22703
+ } catch {
22704
+ continue;
22705
+ }
22706
+ const type = typeof event.type === "string" ? event.type : "";
22707
+ if (type) eventTypesSeen.push(type);
22708
+ if (type === "turn.completed") {
22709
+ const usage = event.usage;
22710
+ if (usage) {
22711
+ process.stderr.write(
22712
+ `[${label}] usage: in=${usage.input_tokens ?? 0} out=${usage.output_tokens ?? 0}
22713
+ `
22714
+ );
22715
+ }
22716
+ continue;
22717
+ }
22718
+ if (type === "item.completed") {
22719
+ const item = event.item;
22720
+ if (item) {
22721
+ const innerType = typeof item.type === "string" ? item.type : "?";
22722
+ itemTypesSeen.push(innerType);
22723
+ if (item.type === "agent_message" && typeof item.text === "string") {
22724
+ agentMessage = agentMessage ? `${agentMessage}
22725
+ ${item.text}` : item.text;
22726
+ } else if (innerType === "command_execution") {
22727
+ const cmd = typeof item.command === "string" ? item.command.slice(0, 120) : "?";
22728
+ process.stderr.write(`[${label}] $ ${cmd}
22729
+ `);
22730
+ }
22731
+ }
22732
+ continue;
22733
+ }
22734
+ }
22735
+ });
22736
+ proc.stderr.setEncoding("utf8");
22737
+ proc.stderr.on("data", (chunk) => {
22738
+ const trimmed = chunk.trimEnd();
22739
+ if (trimmed) {
22740
+ process.stderr.write(`[${label}/stderr] ${trimmed}
22741
+ `);
22742
+ }
22743
+ });
22744
+ proc.on("error", (err) => {
22745
+ clearTimeout(timer);
22746
+ reject(err);
22747
+ });
22748
+ proc.on("exit", (code, signal) => {
22749
+ clearTimeout(timer);
22750
+ const elapsedMs = Date.now() - startedAt;
22751
+ if (agentMessage.trim()) {
22752
+ resolve2(agentMessage);
22753
+ return;
22754
+ }
22755
+ const ctx = [
22756
+ `elapsed=${elapsedMs}ms`,
22757
+ `exit=${code}`,
22758
+ signal ? `signal=${signal}` : null,
22759
+ timedOut ? `timedOut=true (cap=${timeoutMs}ms)` : null,
22760
+ `events=${eventTypesSeen.length}`,
22761
+ `items=${itemTypesSeen.length}`,
22762
+ eventTypesSeen.length > 0 ? `event_types=[${[...new Set(eventTypesSeen)].join(",")}]` : null,
22763
+ itemTypesSeen.length > 0 ? `item_types=[${[...new Set(itemTypesSeen)].join(",")}]` : null
22764
+ ].filter((x2) => x2 !== null).join(" ");
22765
+ reject(
22766
+ new Error(
22767
+ `runCodexOneShot: codex produced no agent_message (${ctx})`
22768
+ )
22769
+ );
22770
+ });
22771
+ });
22772
+ }
22773
+
22774
+ // ../baro-orchestrator/src/planning/planner-codex.ts
22775
+ async function runPlannerCodex(opts) {
22776
+ const modeContract = opts.modeContract ?? await runCodexIntake(opts).catch((e2) => {
22777
+ process.stderr.write(`[planner-codex] intake failed (${e2?.message ?? String(e2)}) \u2014 using heuristic mode contract
22778
+ `);
22779
+ return heuristicModeContract(opts);
22780
+ });
22781
+ process.stderr.write(`[planner-codex] intake mode=${modeContract.mode} confidence=${modeContract.confidence}
22782
+ `);
22783
+ const userMessage = buildPlannerUserMessage({
22784
+ goal: opts.goal,
22785
+ decisionDocument: opts.decisionDocument,
22786
+ quick: opts.quick,
22787
+ projectContext: opts.projectContext,
22788
+ modeContract
22789
+ });
22790
+ const prompt = `${PLANNER_SYSTEM_PROMPT}
22791
+
22792
+ ${userMessage}`;
22793
+ const text = await runCodexOneShot({
22794
+ prompt,
22795
+ cwd: opts.cwd,
22796
+ model: opts.model,
22797
+ codexBin: opts.codexBin,
22798
+ timeoutMs: opts.timeoutMs ?? 9e5,
22799
+ label: "codex-planner"
22800
+ });
22801
+ const planText = text.trim();
22802
+ if (!planText) {
22803
+ throw new Error("PlannerCodex: codex returned empty result");
22804
+ }
22805
+ return extractJsonObject3(planText);
22806
+ }
22807
+ async function runCodexIntake(opts) {
22808
+ if (opts.quick) return heuristicModeContract(opts);
22809
+ const text = await runCodexOneShot({
22810
+ prompt: `You classify software tasks for an autonomous PR workflow. Output JSON only.
22811
+
22812
+ ${buildIntakePrompt(opts)}`,
22813
+ cwd: opts.cwd,
22814
+ model: opts.model,
22815
+ codexBin: opts.codexBin,
22816
+ timeoutMs: Math.min(opts.timeoutMs ?? 9e5, 18e4),
22817
+ label: "codex-intake"
22818
+ });
22819
+ return parseModeContract(text.trim());
22820
+ }
22821
+ function extractJsonObject3(text) {
22822
+ const trimmed = text.trim();
22823
+ if (trimmed.startsWith("{") && trimmed.endsWith("}")) return trimmed;
22824
+ const fence = trimmed.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/);
22825
+ if (fence) return fence[1];
22826
+ const start = trimmed.indexOf("{");
22827
+ if (start < 0) {
22828
+ throw new Error(
22829
+ `PlannerCodex: no JSON object in response: ${trimmed.slice(0, 200)}`
22830
+ );
22831
+ }
22832
+ let depth = 0;
22833
+ for (let i2 = start; i2 < trimmed.length; i2++) {
22834
+ const ch = trimmed[i2];
22835
+ if (ch === "{") depth++;
22836
+ else if (ch === "}") {
22837
+ depth--;
22838
+ if (depth === 0) return trimmed.slice(start, i2 + 1);
22839
+ }
22840
+ }
22841
+ throw new Error(
22842
+ `PlannerCodex: unbalanced JSON in response: ${trimmed.slice(0, 200)}`
22843
+ );
22844
+ }
22248
22845
 
22249
22846
  // ../../node_modules/openai/internal/tslib.mjs
22250
22847
  function __classPrivateFieldSet(receiver, state, value, kind, f3) {
@@ -22485,7 +23082,7 @@ var safeJSON = (text) => {
22485
23082
  };
22486
23083
 
22487
23084
  // ../../node_modules/openai/internal/utils/sleep.mjs
22488
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
23085
+ var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
22489
23086
 
22490
23087
  // ../../node_modules/openai/version.mjs
22491
23088
  var VERSION = "6.38.0";
@@ -23564,8 +24161,8 @@ function addRequestID(value, response) {
23564
24161
  var _APIPromise_client;
23565
24162
  var APIPromise = class _APIPromise extends Promise {
23566
24163
  constructor(client, responsePromise, parseResponse2 = defaultParseResponse) {
23567
- super((resolve) => {
23568
- resolve(null);
24164
+ super((resolve2) => {
24165
+ resolve2(null);
23569
24166
  });
23570
24167
  this.responsePromise = responsePromise;
23571
24168
  this.parseResponse = parseResponse2;
@@ -24027,12 +24624,12 @@ function encodeURIPath(str2) {
24027
24624
  return str2.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
24028
24625
  }
24029
24626
  var EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
24030
- var createPathTagFunction = (pathEncoder = encodeURIPath) => function path4(statics, ...params) {
24627
+ var createPathTagFunction = (pathEncoder = encodeURIPath) => function path5(statics, ...params) {
24031
24628
  if (statics.length === 1)
24032
24629
  return statics[0];
24033
24630
  let postPath = false;
24034
24631
  const invalidSegments = [];
24035
- const path5 = statics.reduce((previousValue, currentValue, index) => {
24632
+ const path6 = statics.reduce((previousValue, currentValue, index) => {
24036
24633
  if (/[?#]/.test(currentValue)) {
24037
24634
  postPath = true;
24038
24635
  }
@@ -24049,7 +24646,7 @@ var createPathTagFunction = (pathEncoder = encodeURIPath) => function path4(stat
24049
24646
  }
24050
24647
  return previousValue + currentValue + (index === params.length ? "" : encoded);
24051
24648
  }, "");
24052
- const pathOnly = path5.split(/[?#]/, 1)[0];
24649
+ const pathOnly = path6.split(/[?#]/, 1)[0];
24053
24650
  const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
24054
24651
  let match;
24055
24652
  while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {
@@ -24070,10 +24667,10 @@ var createPathTagFunction = (pathEncoder = encodeURIPath) => function path4(stat
24070
24667
  }, "");
24071
24668
  throw new OpenAIError(`Path parameters result in path with invalid segments:
24072
24669
  ${invalidSegments.map((e2) => e2.error).join("\n")}
24073
- ${path5}
24670
+ ${path6}
24074
24671
  ${underline}`);
24075
24672
  }
24076
- return path5;
24673
+ return path6;
24077
24674
  };
24078
24675
  var path = /* @__PURE__ */ createPathTagFunction(encodeURIPath);
24079
24676
 
@@ -24246,12 +24843,12 @@ var EventStream = class {
24246
24843
  _EventStream_errored.set(this, false);
24247
24844
  _EventStream_aborted.set(this, false);
24248
24845
  _EventStream_catchingPromiseCreated.set(this, false);
24249
- __classPrivateFieldSet(this, _EventStream_connectedPromise, new Promise((resolve, reject) => {
24250
- __classPrivateFieldSet(this, _EventStream_resolveConnectedPromise, resolve, "f");
24846
+ __classPrivateFieldSet(this, _EventStream_connectedPromise, new Promise((resolve2, reject) => {
24847
+ __classPrivateFieldSet(this, _EventStream_resolveConnectedPromise, resolve2, "f");
24251
24848
  __classPrivateFieldSet(this, _EventStream_rejectConnectedPromise, reject, "f");
24252
24849
  }), "f");
24253
- __classPrivateFieldSet(this, _EventStream_endPromise, new Promise((resolve, reject) => {
24254
- __classPrivateFieldSet(this, _EventStream_resolveEndPromise, resolve, "f");
24850
+ __classPrivateFieldSet(this, _EventStream_endPromise, new Promise((resolve2, reject) => {
24851
+ __classPrivateFieldSet(this, _EventStream_resolveEndPromise, resolve2, "f");
24255
24852
  __classPrivateFieldSet(this, _EventStream_rejectEndPromise, reject, "f");
24256
24853
  }), "f");
24257
24854
  __classPrivateFieldGet(this, _EventStream_connectedPromise, "f").catch(() => {
@@ -24335,11 +24932,11 @@ var EventStream = class {
24335
24932
  * const message = await stream.emitted('message') // rejects if the stream errors
24336
24933
  */
24337
24934
  emitted(event) {
24338
- return new Promise((resolve, reject) => {
24935
+ return new Promise((resolve2, reject) => {
24339
24936
  __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f");
24340
24937
  if (event !== "error")
24341
24938
  this.once("error", reject);
24342
- this.once(event, resolve);
24939
+ this.once(event, resolve2);
24343
24940
  });
24344
24941
  }
24345
24942
  async done() {
@@ -25278,7 +25875,7 @@ var ChatCompletionStream = class _ChatCompletionStream extends AbstractChatCompl
25278
25875
  if (done) {
25279
25876
  return { value: void 0, done: true };
25280
25877
  }
25281
- return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
25878
+ return new Promise((resolve2, reject) => readQueue.push({ resolve: resolve2, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
25282
25879
  }
25283
25880
  const chunk = pushQueue.shift();
25284
25881
  return { value: chunk, done: false };
@@ -27792,7 +28389,7 @@ var AssistantStream = class extends EventStream {
27792
28389
  if (done) {
27793
28390
  return { value: void 0, done: true };
27794
28391
  }
27795
- return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
28392
+ return new Promise((resolve2, reject) => readQueue.push({ resolve: resolve2, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
27796
28393
  }
27797
28394
  const chunk = pushQueue.shift();
27798
28395
  return { value: chunk, done: false };
@@ -29861,7 +30458,7 @@ var ResponseStream = class _ResponseStream extends EventStream {
29861
30458
  if (done) {
29862
30459
  return { value: void 0, done: true };
29863
30460
  }
29864
- return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((event2) => event2 ? { value: event2, done: false } : { value: void 0, done: true });
30461
+ return new Promise((resolve2, reject) => readQueue.push({ resolve: resolve2, reject })).then((event2) => event2 ? { value: event2, done: false } : { value: void 0, done: true });
29865
30462
  }
29866
30463
  const event = pushQueue.shift();
29867
30464
  return { value: event, done: false };
@@ -30964,9 +31561,9 @@ var OpenAI = class {
30964
31561
  this.apiKey = token;
30965
31562
  return true;
30966
31563
  }
30967
- buildURL(path4, query, defaultBaseURL) {
31564
+ buildURL(path5, query, defaultBaseURL) {
30968
31565
  const baseURL = !__classPrivateFieldGet(this, _OpenAI_instances, "m", _OpenAI_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL;
30969
- const url = isAbsoluteURL(path4) ? new URL(path4) : new URL(baseURL + (baseURL.endsWith("/") && path4.startsWith("/") ? path4.slice(1) : path4));
31566
+ const url = isAbsoluteURL(path5) ? new URL(path5) : new URL(baseURL + (baseURL.endsWith("/") && path5.startsWith("/") ? path5.slice(1) : path5));
30970
31567
  const defaultQuery = this.defaultQuery();
30971
31568
  const pathQuery = Object.fromEntries(url.searchParams);
30972
31569
  if (!isEmptyObj(defaultQuery) || !isEmptyObj(pathQuery)) {
@@ -30994,24 +31591,24 @@ var OpenAI = class {
30994
31591
  */
30995
31592
  async prepareRequest(request, { url, options }) {
30996
31593
  }
30997
- get(path4, opts) {
30998
- return this.methodRequest("get", path4, opts);
31594
+ get(path5, opts) {
31595
+ return this.methodRequest("get", path5, opts);
30999
31596
  }
31000
- post(path4, opts) {
31001
- return this.methodRequest("post", path4, opts);
31597
+ post(path5, opts) {
31598
+ return this.methodRequest("post", path5, opts);
31002
31599
  }
31003
- patch(path4, opts) {
31004
- return this.methodRequest("patch", path4, opts);
31600
+ patch(path5, opts) {
31601
+ return this.methodRequest("patch", path5, opts);
31005
31602
  }
31006
- put(path4, opts) {
31007
- return this.methodRequest("put", path4, opts);
31603
+ put(path5, opts) {
31604
+ return this.methodRequest("put", path5, opts);
31008
31605
  }
31009
- delete(path4, opts) {
31010
- return this.methodRequest("delete", path4, opts);
31606
+ delete(path5, opts) {
31607
+ return this.methodRequest("delete", path5, opts);
31011
31608
  }
31012
- methodRequest(method, path4, opts) {
31609
+ methodRequest(method, path5, opts) {
31013
31610
  return this.request(Promise.resolve(opts).then((opts2) => {
31014
- return { method, path: path4, ...opts2 };
31611
+ return { method, path: path5, ...opts2 };
31015
31612
  }));
31016
31613
  }
31017
31614
  request(options, remainingRetries = null) {
@@ -31130,8 +31727,8 @@ var OpenAI = class {
31130
31727
  }));
31131
31728
  return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
31132
31729
  }
31133
- getAPIList(path4, Page3, opts) {
31134
- return this.requestAPIList(Page3, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path4, ...opts2 })) : { method: "get", path: path4, ...opts });
31730
+ getAPIList(path5, Page3, opts) {
31731
+ return this.requestAPIList(Page3, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path5, ...opts2 })) : { method: "get", path: path5, ...opts });
31135
31732
  }
31136
31733
  requestAPIList(Page3, options) {
31137
31734
  const request = this.makeRequest(options, null, void 0);
@@ -31225,8 +31822,8 @@ var OpenAI = class {
31225
31822
  }
31226
31823
  async buildRequest(inputOptions, { retryCount = 0 } = {}) {
31227
31824
  const options = { ...inputOptions };
31228
- const { method, path: path4, query, defaultBaseURL } = options;
31229
- const url = this.buildURL(path4, query, defaultBaseURL);
31825
+ const { method, path: path5, query, defaultBaseURL } = options;
31826
+ const url = this.buildURL(path5, query, defaultBaseURL);
31230
31827
  if ("timeout" in options)
31231
31828
  validatePositiveInteger("timeout", options.timeout);
31232
31829
  options.timeout = options.timeout ?? this.timeout;
@@ -31548,7 +32145,7 @@ var safeJSON2 = (text) => {
31548
32145
  };
31549
32146
 
31550
32147
  // ../../node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs
31551
- var sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
32148
+ var sleep2 = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
31552
32149
 
31553
32150
  // ../../node_modules/@anthropic-ai/sdk/version.mjs
31554
32151
  var VERSION2 = "0.74.0";
@@ -32247,8 +32844,8 @@ function addRequestID2(value, response) {
32247
32844
  var _APIPromise_client2;
32248
32845
  var APIPromise2 = class _APIPromise extends Promise {
32249
32846
  constructor(client, responsePromise, parseResponse2 = defaultParseResponse2) {
32250
- super((resolve) => {
32251
- resolve(null);
32847
+ super((resolve2) => {
32848
+ resolve2(null);
32252
32849
  });
32253
32850
  this.responsePromise = responsePromise;
32254
32851
  this.parseResponse = parseResponse2;
@@ -32690,12 +33287,12 @@ function encodeURIPath2(str2) {
32690
33287
  return str2.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
32691
33288
  }
32692
33289
  var EMPTY2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
32693
- var createPathTagFunction2 = (pathEncoder = encodeURIPath2) => function path4(statics, ...params) {
33290
+ var createPathTagFunction2 = (pathEncoder = encodeURIPath2) => function path5(statics, ...params) {
32694
33291
  if (statics.length === 1)
32695
33292
  return statics[0];
32696
33293
  let postPath = false;
32697
33294
  const invalidSegments = [];
32698
- const path5 = statics.reduce((previousValue, currentValue, index) => {
33295
+ const path6 = statics.reduce((previousValue, currentValue, index) => {
32699
33296
  if (/[?#]/.test(currentValue)) {
32700
33297
  postPath = true;
32701
33298
  }
@@ -32712,7 +33309,7 @@ var createPathTagFunction2 = (pathEncoder = encodeURIPath2) => function path4(st
32712
33309
  }
32713
33310
  return previousValue + currentValue + (index === params.length ? "" : encoded);
32714
33311
  }, "");
32715
- const pathOnly = path5.split(/[?#]/, 1)[0];
33312
+ const pathOnly = path6.split(/[?#]/, 1)[0];
32716
33313
  const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
32717
33314
  let match;
32718
33315
  while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {
@@ -32733,10 +33330,10 @@ var createPathTagFunction2 = (pathEncoder = encodeURIPath2) => function path4(st
32733
33330
  }, "");
32734
33331
  throw new AnthropicError(`Path parameters result in path with invalid segments:
32735
33332
  ${invalidSegments.map((e2) => e2.error).join("\n")}
32736
- ${path5}
33333
+ ${path6}
32737
33334
  ${underline}`);
32738
33335
  }
32739
- return path5;
33336
+ return path6;
32740
33337
  };
32741
33338
  var path2 = /* @__PURE__ */ createPathTagFunction2(encodeURIPath2);
32742
33339
 
@@ -33285,12 +33882,12 @@ var BetaMessageStream = class _BetaMessageStream {
33285
33882
  }
33286
33883
  return this._emit("error", new AnthropicError(String(error)));
33287
33884
  });
33288
- __classPrivateFieldSet2(this, _BetaMessageStream_connectedPromise, new Promise((resolve, reject) => {
33289
- __classPrivateFieldSet2(this, _BetaMessageStream_resolveConnectedPromise, resolve, "f");
33885
+ __classPrivateFieldSet2(this, _BetaMessageStream_connectedPromise, new Promise((resolve2, reject) => {
33886
+ __classPrivateFieldSet2(this, _BetaMessageStream_resolveConnectedPromise, resolve2, "f");
33290
33887
  __classPrivateFieldSet2(this, _BetaMessageStream_rejectConnectedPromise, reject, "f");
33291
33888
  }), "f");
33292
- __classPrivateFieldSet2(this, _BetaMessageStream_endPromise, new Promise((resolve, reject) => {
33293
- __classPrivateFieldSet2(this, _BetaMessageStream_resolveEndPromise, resolve, "f");
33889
+ __classPrivateFieldSet2(this, _BetaMessageStream_endPromise, new Promise((resolve2, reject) => {
33890
+ __classPrivateFieldSet2(this, _BetaMessageStream_resolveEndPromise, resolve2, "f");
33294
33891
  __classPrivateFieldSet2(this, _BetaMessageStream_rejectEndPromise, reject, "f");
33295
33892
  }), "f");
33296
33893
  __classPrivateFieldGet2(this, _BetaMessageStream_connectedPromise, "f").catch(() => {
@@ -33460,11 +34057,11 @@ var BetaMessageStream = class _BetaMessageStream {
33460
34057
  * const message = await stream.emitted('message') // rejects if the stream errors
33461
34058
  */
33462
34059
  emitted(event) {
33463
- return new Promise((resolve, reject) => {
34060
+ return new Promise((resolve2, reject) => {
33464
34061
  __classPrivateFieldSet2(this, _BetaMessageStream_catchingPromiseCreated, true, "f");
33465
34062
  if (event !== "error")
33466
34063
  this.once("error", reject);
33467
- this.once(event, resolve);
34064
+ this.once(event, resolve2);
33468
34065
  });
33469
34066
  }
33470
34067
  async done() {
@@ -33807,7 +34404,7 @@ var BetaMessageStream = class _BetaMessageStream {
33807
34404
  if (done) {
33808
34405
  return { value: void 0, done: true };
33809
34406
  }
33810
- return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
34407
+ return new Promise((resolve2, reject) => readQueue.push({ resolve: resolve2, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
33811
34408
  }
33812
34409
  const chunk = pushQueue.shift();
33813
34410
  return { value: chunk, done: false };
@@ -33879,13 +34476,13 @@ var _BetaToolRunner_iterationCount;
33879
34476
  var _BetaToolRunner_checkAndCompact;
33880
34477
  var _BetaToolRunner_generateToolResponse;
33881
34478
  function promiseWithResolvers() {
33882
- let resolve;
34479
+ let resolve2;
33883
34480
  let reject;
33884
34481
  const promise = new Promise((res, rej) => {
33885
- resolve = res;
34482
+ resolve2 = res;
33886
34483
  reject = rej;
33887
34484
  });
33888
- return { promise, resolve, reject };
34485
+ return { promise, resolve: resolve2, reject };
33889
34486
  }
33890
34487
  var BetaToolRunner = class {
33891
34488
  constructor(client, params, options) {
@@ -34903,12 +35500,12 @@ var MessageStream = class _MessageStream {
34903
35500
  }
34904
35501
  return this._emit("error", new AnthropicError(String(error)));
34905
35502
  });
34906
- __classPrivateFieldSet2(this, _MessageStream_connectedPromise, new Promise((resolve, reject) => {
34907
- __classPrivateFieldSet2(this, _MessageStream_resolveConnectedPromise, resolve, "f");
35503
+ __classPrivateFieldSet2(this, _MessageStream_connectedPromise, new Promise((resolve2, reject) => {
35504
+ __classPrivateFieldSet2(this, _MessageStream_resolveConnectedPromise, resolve2, "f");
34908
35505
  __classPrivateFieldSet2(this, _MessageStream_rejectConnectedPromise, reject, "f");
34909
35506
  }), "f");
34910
- __classPrivateFieldSet2(this, _MessageStream_endPromise, new Promise((resolve, reject) => {
34911
- __classPrivateFieldSet2(this, _MessageStream_resolveEndPromise, resolve, "f");
35507
+ __classPrivateFieldSet2(this, _MessageStream_endPromise, new Promise((resolve2, reject) => {
35508
+ __classPrivateFieldSet2(this, _MessageStream_resolveEndPromise, resolve2, "f");
34912
35509
  __classPrivateFieldSet2(this, _MessageStream_rejectEndPromise, reject, "f");
34913
35510
  }), "f");
34914
35511
  __classPrivateFieldGet2(this, _MessageStream_connectedPromise, "f").catch(() => {
@@ -35078,11 +35675,11 @@ var MessageStream = class _MessageStream {
35078
35675
  * const message = await stream.emitted('message') // rejects if the stream errors
35079
35676
  */
35080
35677
  emitted(event) {
35081
- return new Promise((resolve, reject) => {
35678
+ return new Promise((resolve2, reject) => {
35082
35679
  __classPrivateFieldSet2(this, _MessageStream_catchingPromiseCreated, true, "f");
35083
35680
  if (event !== "error")
35084
35681
  this.once("error", reject);
35085
- this.once(event, resolve);
35682
+ this.once(event, resolve2);
35086
35683
  });
35087
35684
  }
35088
35685
  async done() {
@@ -35400,7 +35997,7 @@ var MessageStream = class _MessageStream {
35400
35997
  if (done) {
35401
35998
  return { value: void 0, done: true };
35402
35999
  }
35403
- return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
36000
+ return new Promise((resolve2, reject) => readQueue.push({ resolve: resolve2, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
35404
36001
  }
35405
36002
  const chunk = pushQueue.shift();
35406
36003
  return { value: chunk, done: false };
@@ -35847,9 +36444,9 @@ var BaseAnthropic = class {
35847
36444
  makeStatusError(status, error, message, headers) {
35848
36445
  return APIError2.generate(status, error, message, headers);
35849
36446
  }
35850
- buildURL(path4, query, defaultBaseURL) {
36447
+ buildURL(path5, query, defaultBaseURL) {
35851
36448
  const baseURL = !__classPrivateFieldGet2(this, _BaseAnthropic_instances, "m", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL;
35852
- const url = isAbsoluteURL2(path4) ? new URL(path4) : new URL(baseURL + (baseURL.endsWith("/") && path4.startsWith("/") ? path4.slice(1) : path4));
36449
+ const url = isAbsoluteURL2(path5) ? new URL(path5) : new URL(baseURL + (baseURL.endsWith("/") && path5.startsWith("/") ? path5.slice(1) : path5));
35853
36450
  const defaultQuery = this.defaultQuery();
35854
36451
  if (!isEmptyObj2(defaultQuery)) {
35855
36452
  query = { ...defaultQuery, ...query };
@@ -35880,24 +36477,24 @@ var BaseAnthropic = class {
35880
36477
  */
35881
36478
  async prepareRequest(request, { url, options }) {
35882
36479
  }
35883
- get(path4, opts) {
35884
- return this.methodRequest("get", path4, opts);
36480
+ get(path5, opts) {
36481
+ return this.methodRequest("get", path5, opts);
35885
36482
  }
35886
- post(path4, opts) {
35887
- return this.methodRequest("post", path4, opts);
36483
+ post(path5, opts) {
36484
+ return this.methodRequest("post", path5, opts);
35888
36485
  }
35889
- patch(path4, opts) {
35890
- return this.methodRequest("patch", path4, opts);
36486
+ patch(path5, opts) {
36487
+ return this.methodRequest("patch", path5, opts);
35891
36488
  }
35892
- put(path4, opts) {
35893
- return this.methodRequest("put", path4, opts);
36489
+ put(path5, opts) {
36490
+ return this.methodRequest("put", path5, opts);
35894
36491
  }
35895
- delete(path4, opts) {
35896
- return this.methodRequest("delete", path4, opts);
36492
+ delete(path5, opts) {
36493
+ return this.methodRequest("delete", path5, opts);
35897
36494
  }
35898
- methodRequest(method, path4, opts) {
36495
+ methodRequest(method, path5, opts) {
35899
36496
  return this.request(Promise.resolve(opts).then((opts2) => {
35900
- return { method, path: path4, ...opts2 };
36497
+ return { method, path: path5, ...opts2 };
35901
36498
  }));
35902
36499
  }
35903
36500
  request(options, remainingRetries = null) {
@@ -36001,8 +36598,8 @@ var BaseAnthropic = class {
36001
36598
  }));
36002
36599
  return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
36003
36600
  }
36004
- getAPIList(path4, Page3, opts) {
36005
- return this.requestAPIList(Page3, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path4, ...opts2 })) : { method: "get", path: path4, ...opts });
36601
+ getAPIList(path5, Page3, opts) {
36602
+ return this.requestAPIList(Page3, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path5, ...opts2 })) : { method: "get", path: path5, ...opts });
36006
36603
  }
36007
36604
  requestAPIList(Page3, options) {
36008
36605
  const request = this.makeRequest(options, null, void 0);
@@ -36090,8 +36687,8 @@ var BaseAnthropic = class {
36090
36687
  }
36091
36688
  async buildRequest(inputOptions, { retryCount = 0 } = {}) {
36092
36689
  const options = { ...inputOptions };
36093
- const { method, path: path4, query, defaultBaseURL } = options;
36094
- const url = this.buildURL(path4, query, defaultBaseURL);
36690
+ const { method, path: path5, query, defaultBaseURL } = options;
36691
+ const url = this.buildURL(path5, query, defaultBaseURL);
36095
36692
  if ("timeout" in options)
36096
36693
  validatePositiveInteger2("timeout", options.timeout);
36097
36694
  options.timeout = options.timeout ?? this.timeout;
@@ -36862,14 +37459,14 @@ function __asyncValues(o) {
36862
37459
  }, i2);
36863
37460
  function verb(n) {
36864
37461
  i2[n] = o[n] && function(v) {
36865
- return new Promise(function(resolve, reject) {
36866
- v = o[n](v), settle(resolve, reject, v.done, v.value);
37462
+ return new Promise(function(resolve2, reject) {
37463
+ v = o[n](v), settle(resolve2, reject, v.done, v.value);
36867
37464
  });
36868
37465
  };
36869
37466
  }
36870
- function settle(resolve, reject, d, v) {
37467
+ function settle(resolve2, reject, d, v) {
36871
37468
  Promise.resolve(v).then(function(v2) {
36872
- resolve({ value: v2, done: d });
37469
+ resolve2({ value: v2, done: d });
36873
37470
  }, reject);
36874
37471
  }
36875
37472
  }
@@ -37038,7 +37635,7 @@ var safeJSON3 = (text) => {
37038
37635
  return void 0;
37039
37636
  }
37040
37637
  };
37041
- var sleep$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
37638
+ var sleep$1 = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
37042
37639
  function getDefaultFetch3() {
37043
37640
  if (typeof fetch !== "undefined") {
37044
37641
  return fetch;
@@ -37222,12 +37819,12 @@ function encodeURIPath3(str2) {
37222
37819
  return str2.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
37223
37820
  }
37224
37821
  var EMPTY3 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
37225
- var createPathTagFunction3 = (pathEncoder = encodeURIPath3) => (function path4(statics, ...params) {
37822
+ var createPathTagFunction3 = (pathEncoder = encodeURIPath3) => (function path5(statics, ...params) {
37226
37823
  if (statics.length === 1)
37227
37824
  return statics[0];
37228
37825
  let postPath = false;
37229
37826
  const invalidSegments = [];
37230
- const path5 = statics.reduce((previousValue, currentValue, index) => {
37827
+ const path6 = statics.reduce((previousValue, currentValue, index) => {
37231
37828
  var _a5, _b, _c;
37232
37829
  if (/[?#]/.test(currentValue)) {
37233
37830
  postPath = true;
@@ -37245,7 +37842,7 @@ var createPathTagFunction3 = (pathEncoder = encodeURIPath3) => (function path4(s
37245
37842
  }
37246
37843
  return previousValue + currentValue + (index === params.length ? "" : encoded);
37247
37844
  }, "");
37248
- const pathOnly = path5.split(/[?#]/, 1)[0];
37845
+ const pathOnly = path6.split(/[?#]/, 1)[0];
37249
37846
  const invalidSegmentPattern = /(^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
37250
37847
  let match;
37251
37848
  while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {
@@ -37269,10 +37866,10 @@ var createPathTagFunction3 = (pathEncoder = encodeURIPath3) => (function path4(s
37269
37866
  }, "");
37270
37867
  throw new GeminiNextGenAPIClientError(`Path parameters result in path with invalid segments:
37271
37868
  ${invalidSegments.map((e2) => e2.error).join("\n")}
37272
- ${path5}
37869
+ ${path6}
37273
37870
  ${underline}`);
37274
37871
  }
37275
- return path5;
37872
+ return path6;
37276
37873
  });
37277
37874
  var path3 = /* @__PURE__ */ createPathTagFunction3(encodeURIPath3);
37278
37875
  var BaseAgents = class extends APIResource3 {
@@ -38076,8 +38673,8 @@ async function defaultParseResponse3(client, props) {
38076
38673
  }
38077
38674
  var APIPromise3 = class _APIPromise extends Promise {
38078
38675
  constructor(client, responsePromise, parseResponse2 = defaultParseResponse3) {
38079
- super((resolve) => {
38080
- resolve(null);
38676
+ super((resolve2) => {
38677
+ resolve2(null);
38081
38678
  });
38082
38679
  this.responsePromise = responsePromise;
38083
38680
  this.parseResponse = parseResponse2;
@@ -38294,9 +38891,9 @@ var BaseGeminiNextGenAPIClient = class _BaseGeminiNextGenAPIClient {
38294
38891
  makeStatusError(status, error, message, headers) {
38295
38892
  return APIError3.generate(status, error, message, headers);
38296
38893
  }
38297
- buildURL(path4, query, defaultBaseURL) {
38894
+ buildURL(path5, query, defaultBaseURL) {
38298
38895
  const baseURL = !this.baseURLOverridden() && defaultBaseURL || this.baseURL;
38299
- const url = isAbsoluteURL3(path4) ? new URL(path4) : new URL(baseURL + (baseURL.endsWith("/") && path4.startsWith("/") ? path4.slice(1) : path4));
38896
+ const url = isAbsoluteURL3(path5) ? new URL(path5) : new URL(baseURL + (baseURL.endsWith("/") && path5.startsWith("/") ? path5.slice(1) : path5));
38300
38897
  const defaultQuery = this.defaultQuery();
38301
38898
  const pathQuery = Object.fromEntries(url.searchParams);
38302
38899
  if (!isEmptyObj3(defaultQuery) || !isEmptyObj3(pathQuery)) {
@@ -38325,24 +38922,24 @@ var BaseGeminiNextGenAPIClient = class _BaseGeminiNextGenAPIClient {
38325
38922
  */
38326
38923
  async prepareRequest(request, { url, options }) {
38327
38924
  }
38328
- get(path4, opts) {
38329
- return this.methodRequest("get", path4, opts);
38925
+ get(path5, opts) {
38926
+ return this.methodRequest("get", path5, opts);
38330
38927
  }
38331
- post(path4, opts) {
38332
- return this.methodRequest("post", path4, opts);
38928
+ post(path5, opts) {
38929
+ return this.methodRequest("post", path5, opts);
38333
38930
  }
38334
- patch(path4, opts) {
38335
- return this.methodRequest("patch", path4, opts);
38931
+ patch(path5, opts) {
38932
+ return this.methodRequest("patch", path5, opts);
38336
38933
  }
38337
- put(path4, opts) {
38338
- return this.methodRequest("put", path4, opts);
38934
+ put(path5, opts) {
38935
+ return this.methodRequest("put", path5, opts);
38339
38936
  }
38340
- delete(path4, opts) {
38341
- return this.methodRequest("delete", path4, opts);
38937
+ delete(path5, opts) {
38938
+ return this.methodRequest("delete", path5, opts);
38342
38939
  }
38343
- methodRequest(method, path4, opts) {
38940
+ methodRequest(method, path5, opts) {
38344
38941
  return this.request(Promise.resolve(opts).then((opts2) => {
38345
- return Object.assign({ method, path: path4 }, opts2);
38942
+ return Object.assign({ method, path: path5 }, opts2);
38346
38943
  }));
38347
38944
  }
38348
38945
  request(options, remainingRetries = null) {
@@ -38516,8 +39113,8 @@ var BaseGeminiNextGenAPIClient = class _BaseGeminiNextGenAPIClient {
38516
39113
  async buildRequest(inputOptions, { retryCount = 0 } = {}) {
38517
39114
  var _b, _c, _d;
38518
39115
  const options = Object.assign({}, inputOptions);
38519
- const { method, path: path4, query, defaultBaseURL } = options;
38520
- const url = this.buildURL(path4, query, defaultBaseURL);
39116
+ const { method, path: path5, query, defaultBaseURL } = options;
39117
+ const url = this.buildURL(path5, query, defaultBaseURL);
38521
39118
  if ("timeout" in options)
38522
39119
  validatePositiveInteger3("timeout", options.timeout);
38523
39120
  options.timeout = (_b = options.timeout) !== null && _b !== void 0 ? _b : this.timeout;
@@ -38604,6 +39201,1966 @@ GeminiNextGenAPIClient.Interactions = Interactions;
38604
39201
  GeminiNextGenAPIClient.Webhooks = Webhooks2;
38605
39202
  GeminiNextGenAPIClient.Agents = Agents;
38606
39203
  var MAX_CHUNK_SIZE = 1024 * 1024 * 8;
39204
+
39205
+ // ../../node_modules/@mozaik-ai/core/dist/index.mjs
39206
+ var ModelContext = class _ModelContext {
39207
+ constructor(id, projectId, items) {
39208
+ this.projectId = projectId;
39209
+ this.id = id;
39210
+ this.items = items;
39211
+ }
39212
+ addContextItem(item) {
39213
+ this.items.push(item);
39214
+ return this;
39215
+ }
39216
+ applyModelOutput(items) {
39217
+ for (const item of items) {
39218
+ const itemType = item.getType();
39219
+ if (itemType !== "function_call" && itemType !== "message" && itemType !== "reasoning") {
39220
+ throw new Error(`Invalid item type: ${itemType}`);
39221
+ }
39222
+ }
39223
+ this.items.push(...items);
39224
+ return this;
39225
+ }
39226
+ getItems() {
39227
+ return this.items;
39228
+ }
39229
+ getLastItem() {
39230
+ if (this.items.length === 0) {
39231
+ throw new Error("No items in context");
39232
+ }
39233
+ return this.items[this.items.length - 1];
39234
+ }
39235
+ static create(projectId) {
39236
+ const id = crypto.randomUUID();
39237
+ return new _ModelContext(id, projectId, []);
39238
+ }
39239
+ static rehydrate(data) {
39240
+ return new _ModelContext(data.id, data.projectId, data.items);
39241
+ }
39242
+ toJSON() {
39243
+ return this.items.map((item) => item.toJSON());
39244
+ }
39245
+ };
39246
+ var ContextItem = class {
39247
+ getType() {
39248
+ return this.type;
39249
+ }
39250
+ };
39251
+ var ItemContent = class {
39252
+ };
39253
+ var InputText = class _InputText extends ItemContent {
39254
+ constructor(text) {
39255
+ super();
39256
+ this.text = text;
39257
+ this.type = "input_text";
39258
+ }
39259
+ static create(text) {
39260
+ return new _InputText(text);
39261
+ }
39262
+ static rehydrate(data) {
39263
+ return new _InputText(data.text);
39264
+ }
39265
+ toJSON() {
39266
+ return [
39267
+ {
39268
+ type: this.type,
39269
+ text: this.text
39270
+ }
39271
+ ];
39272
+ }
39273
+ };
39274
+ var UserMessageItem = class _UserMessageItem extends ContextItem {
39275
+ constructor(content) {
39276
+ super();
39277
+ this.type = "message";
39278
+ this.role = "user";
39279
+ this.content = content;
39280
+ }
39281
+ static create(text) {
39282
+ const content = InputText.create(text);
39283
+ return new _UserMessageItem(content);
39284
+ }
39285
+ static rehydrate(data) {
39286
+ const content = InputText.rehydrate(data);
39287
+ return new _UserMessageItem(content);
39288
+ }
39289
+ toJSON() {
39290
+ return {
39291
+ type: this.type,
39292
+ role: this.role,
39293
+ content: this.content.toJSON()
39294
+ };
39295
+ }
39296
+ };
39297
+ var DeveloperMessageItem = class _DeveloperMessageItem extends ContextItem {
39298
+ constructor(content) {
39299
+ super();
39300
+ this.type = "message";
39301
+ this.role = "developer";
39302
+ this.content = content;
39303
+ }
39304
+ toJSON() {
39305
+ return {
39306
+ type: this.type,
39307
+ role: this.role,
39308
+ content: this.content.toJSON()
39309
+ };
39310
+ }
39311
+ static create(text) {
39312
+ const content = InputText.create(text);
39313
+ return new _DeveloperMessageItem(content);
39314
+ }
39315
+ static rehydrate(data) {
39316
+ const content = InputText.rehydrate(data);
39317
+ return new _DeveloperMessageItem(content);
39318
+ }
39319
+ };
39320
+ var OutputText = class _OutputText extends ItemContent {
39321
+ constructor(text) {
39322
+ super();
39323
+ this.text = text;
39324
+ this.type = "output_text";
39325
+ }
39326
+ static rehydrate(data) {
39327
+ return new _OutputText(data.text);
39328
+ }
39329
+ toJSON() {
39330
+ return [
39331
+ {
39332
+ type: this.type,
39333
+ text: this.text
39334
+ }
39335
+ ];
39336
+ }
39337
+ };
39338
+ var ModelMessageItem = class _ModelMessageItem extends ContextItem {
39339
+ constructor(content) {
39340
+ super();
39341
+ this.type = "message";
39342
+ this.role = "assistant";
39343
+ this.content = content;
39344
+ }
39345
+ static rehydrate(data) {
39346
+ const content = OutputText.rehydrate(data);
39347
+ return new _ModelMessageItem(content);
39348
+ }
39349
+ toJSON() {
39350
+ return {
39351
+ type: this.type,
39352
+ role: this.role,
39353
+ content: this.content.toJSON()
39354
+ };
39355
+ }
39356
+ };
39357
+ var FunctionCallItem = class _FunctionCallItem extends ContextItem {
39358
+ constructor(callId, name, args) {
39359
+ super();
39360
+ this.type = "function_call";
39361
+ this.callId = callId;
39362
+ this.name = name;
39363
+ this.args = args;
39364
+ }
39365
+ static rehydrate(data) {
39366
+ return new _FunctionCallItem(data.callId, data.name, data.args);
39367
+ }
39368
+ toJSON() {
39369
+ return {
39370
+ type: this.type,
39371
+ call_id: this.callId,
39372
+ name: this.name,
39373
+ arguments: this.args
39374
+ };
39375
+ }
39376
+ };
39377
+ var ReasoningItem = class _ReasoningItem extends ContextItem {
39378
+ constructor(content, encryptedContent, summary = []) {
39379
+ super();
39380
+ this.type = "reasoning";
39381
+ this.content = content;
39382
+ this.encryptedContent = encryptedContent;
39383
+ this.summary = summary;
39384
+ }
39385
+ static rehydrate(data) {
39386
+ return new _ReasoningItem(data.content, data.encryptedContent, data.summary);
39387
+ }
39388
+ toJSON() {
39389
+ var _a5;
39390
+ return {
39391
+ type: this.type,
39392
+ content: (_a5 = this.content) == null ? void 0 : _a5.toJSON(),
39393
+ encryptedContent: this.encryptedContent,
39394
+ summary: this.summary.map((s2) => s2.toJSON())
39395
+ };
39396
+ }
39397
+ };
39398
+ var FunctionCallOutputItem = class _FunctionCallOutputItem extends ContextItem {
39399
+ constructor(callId, output) {
39400
+ super();
39401
+ this.type = "function_call_output";
39402
+ this.callId = callId;
39403
+ this.output = output;
39404
+ }
39405
+ static create(callId, output) {
39406
+ const outputText = InputText.create(output);
39407
+ return new _FunctionCallOutputItem(callId, outputText);
39408
+ }
39409
+ static rehydrate(data) {
39410
+ return new _FunctionCallOutputItem(data.callId, data.output);
39411
+ }
39412
+ toJSON() {
39413
+ return {
39414
+ type: this.type,
39415
+ call_id: this.callId,
39416
+ output: this.output.toJSON()
39417
+ };
39418
+ }
39419
+ };
39420
+ var OpenAIReasoningEffort = class {
39421
+ constructor(reasoningEffort) {
39422
+ this.reasoningEffort = reasoningEffort;
39423
+ }
39424
+ setReasoningEffort(effort) {
39425
+ this.reasoningEffort = effort;
39426
+ }
39427
+ getReasoningEffort() {
39428
+ if (!this.reasoningEffort) {
39429
+ throw new Error("Reasoning effort not supported");
39430
+ }
39431
+ return this.reasoningEffort;
39432
+ }
39433
+ };
39434
+ var Gpt54Nano = class {
39435
+ constructor() {
39436
+ this.specification = {
39437
+ name: "gpt-5.4-nano",
39438
+ supportReasoningEffort: true,
39439
+ defaultReasoningEffort: "none",
39440
+ supportStreaming: true,
39441
+ contextWindowSize: 4e5,
39442
+ maxOutputTokens: 128e3,
39443
+ supportFunctionCalling: true
39444
+ };
39445
+ this.tools = [];
39446
+ this.streaming = false;
39447
+ this.effort = new OpenAIReasoningEffort(
39448
+ this.specification.defaultReasoningEffort
39449
+ );
39450
+ }
39451
+ setStreaming(streaming) {
39452
+ this.streaming = streaming;
39453
+ }
39454
+ getStreaming() {
39455
+ return this.streaming;
39456
+ }
39457
+ setTools(tools) {
39458
+ this.tools = tools;
39459
+ }
39460
+ getTools() {
39461
+ return this.tools;
39462
+ }
39463
+ setReasoningEffort(effort) {
39464
+ this.effort.setReasoningEffort(effort);
39465
+ }
39466
+ getReasoningEffort() {
39467
+ return this.effort.getReasoningEffort();
39468
+ }
39469
+ };
39470
+ var Gpt54 = class {
39471
+ constructor() {
39472
+ this.specification = {
39473
+ name: "gpt-5.4",
39474
+ supportReasoningEffort: true,
39475
+ defaultReasoningEffort: "none",
39476
+ supportStreaming: true,
39477
+ contextWindowSize: 105e4,
39478
+ maxOutputTokens: 128e3,
39479
+ supportFunctionCalling: true
39480
+ };
39481
+ this.tools = [];
39482
+ this.streaming = false;
39483
+ this.effort = new OpenAIReasoningEffort(
39484
+ this.specification.defaultReasoningEffort
39485
+ );
39486
+ }
39487
+ setStreaming(streaming) {
39488
+ this.streaming = streaming;
39489
+ }
39490
+ getStreaming() {
39491
+ return this.streaming;
39492
+ }
39493
+ setTools(tools) {
39494
+ this.tools = tools;
39495
+ }
39496
+ getTools() {
39497
+ return this.tools;
39498
+ }
39499
+ setReasoningEffort(effort) {
39500
+ this.effort.setReasoningEffort(effort);
39501
+ }
39502
+ getReasoningEffort() {
39503
+ return this.effort.getReasoningEffort();
39504
+ }
39505
+ };
39506
+ var Gpt54Mini = class {
39507
+ constructor() {
39508
+ this.specification = {
39509
+ name: "gpt-5.4-mini",
39510
+ supportReasoningEffort: true,
39511
+ defaultReasoningEffort: "none",
39512
+ supportStreaming: true,
39513
+ contextWindowSize: 4e5,
39514
+ maxOutputTokens: 128e3,
39515
+ supportFunctionCalling: true
39516
+ };
39517
+ this.tools = [];
39518
+ this.streaming = false;
39519
+ this.effort = new OpenAIReasoningEffort(
39520
+ this.specification.defaultReasoningEffort
39521
+ );
39522
+ }
39523
+ setStreaming(streaming) {
39524
+ this.streaming = streaming;
39525
+ }
39526
+ getStreaming() {
39527
+ return this.streaming;
39528
+ }
39529
+ setReasoningEffort(effort) {
39530
+ this.effort.setReasoningEffort(effort);
39531
+ }
39532
+ getReasoningEffort() {
39533
+ return this.effort.getReasoningEffort();
39534
+ }
39535
+ setTools(tools) {
39536
+ this.tools = tools;
39537
+ }
39538
+ getTools() {
39539
+ return this.tools;
39540
+ }
39541
+ };
39542
+ var InputTokenDetails = class {
39543
+ constructor(cached_tokens) {
39544
+ this.cached_tokens = cached_tokens;
39545
+ }
39546
+ };
39547
+ var OutputTokenDetails = class {
39548
+ constructor(reasoning_tokens) {
39549
+ this.reasoning_tokens = reasoning_tokens;
39550
+ }
39551
+ };
39552
+ var TokenUsage = class {
39553
+ constructor(inputTokens, outputTokens, totalTokens, inputTokenDetails, outputTokenDetails) {
39554
+ this.inputTokens = inputTokens;
39555
+ this.outputTokens = outputTokens;
39556
+ this.totalTokens = totalTokens;
39557
+ this.inputTokenDetails = inputTokenDetails;
39558
+ this.outputTokenDetails = outputTokenDetails;
39559
+ }
39560
+ };
39561
+ var SystemMessageItem = class _SystemMessageItem extends ContextItem {
39562
+ constructor(content) {
39563
+ super();
39564
+ this.type = "message";
39565
+ this.role = "system";
39566
+ this.content = content;
39567
+ }
39568
+ toJSON() {
39569
+ return {
39570
+ type: this.type,
39571
+ role: this.role,
39572
+ content: this.content.toJSON()
39573
+ };
39574
+ }
39575
+ static create(text) {
39576
+ const content = InputText.create(text);
39577
+ return new _SystemMessageItem(content);
39578
+ }
39579
+ static rehydrate(data) {
39580
+ const content = InputText.rehydrate(data);
39581
+ return new _SystemMessageItem(content);
39582
+ }
39583
+ };
39584
+ var SemanticEvent = class {
39585
+ constructor(type, data) {
39586
+ this.type = type;
39587
+ this.data = data;
39588
+ }
39589
+ getType() {
39590
+ return this.type;
39591
+ }
39592
+ };
39593
+ var InferenceRequest = class {
39594
+ constructor(model, context) {
39595
+ this.model = model;
39596
+ this.context = context;
39597
+ }
39598
+ };
39599
+ var Gpt55 = class {
39600
+ constructor() {
39601
+ this.specification = {
39602
+ name: "gpt-5.5",
39603
+ supportReasoningEffort: true,
39604
+ defaultReasoningEffort: "none",
39605
+ supportStreaming: true,
39606
+ contextWindowSize: 105e4,
39607
+ maxOutputTokens: 128e3,
39608
+ supportFunctionCalling: true
39609
+ };
39610
+ this.tools = [];
39611
+ this.streaming = false;
39612
+ this.effort = new OpenAIReasoningEffort(
39613
+ this.specification.defaultReasoningEffort
39614
+ );
39615
+ }
39616
+ setStreaming(streaming) {
39617
+ this.streaming = streaming;
39618
+ }
39619
+ getStreaming() {
39620
+ return this.streaming;
39621
+ }
39622
+ setTools(tools) {
39623
+ this.tools = tools;
39624
+ }
39625
+ getTools() {
39626
+ return this.tools;
39627
+ }
39628
+ setReasoningEffort(effort) {
39629
+ this.effort.setReasoningEffort(effort);
39630
+ }
39631
+ getReasoningEffort() {
39632
+ return this.effort.getReasoningEffort();
39633
+ }
39634
+ };
39635
+ var InferenceResponse = class {
39636
+ constructor(contextItems, tokenUsage) {
39637
+ this.contextItems = contextItems;
39638
+ this.tokenUsage = tokenUsage;
39639
+ }
39640
+ };
39641
+ var OpenAIResponses = class {
39642
+ constructor() {
39643
+ this.client = new OpenAI();
39644
+ }
39645
+ async infer(inferenceRequest) {
39646
+ const request = this.buildRequest(inferenceRequest);
39647
+ const response = await this.client.responses.create(request);
39648
+ const contextItems = this.extractContextItems(response);
39649
+ const tokenUsage = this.extractTokenUsage(response);
39650
+ return new InferenceResponse(contextItems, tokenUsage);
39651
+ }
39652
+ async *stream(inferenceRequest, signal) {
39653
+ const specification = inferenceRequest.model.specification;
39654
+ if (!specification.supportStreaming) {
39655
+ throw new Error("Streaming is not supported for this model");
39656
+ }
39657
+ const request = { ...this.buildRequest(inferenceRequest), stream: true };
39658
+ const response = await this.client.responses.create(request);
39659
+ for await (const event of response) {
39660
+ if (signal == null ? void 0 : signal.aborted) {
39661
+ break;
39662
+ }
39663
+ yield new SemanticEvent(event.type, event);
39664
+ }
39665
+ }
39666
+ buildRequest(inferenceRequest) {
39667
+ const specification = inferenceRequest.model.specification;
39668
+ const input = this.mapContextToRequest(inferenceRequest.context);
39669
+ const request = {
39670
+ model: specification.name,
39671
+ input
39672
+ };
39673
+ if (specification.supportFunctionCalling && inferenceRequest.model.getTools().length > 0) {
39674
+ request.tools = inferenceRequest.model.getTools().map((tool) => {
39675
+ return {
39676
+ type: tool.type,
39677
+ name: tool.name,
39678
+ description: tool.description,
39679
+ parameters: tool.parameters
39680
+ };
39681
+ });
39682
+ }
39683
+ if (specification.supportReasoningEffort) {
39684
+ request.reasoning = {
39685
+ effort: inferenceRequest.model.getReasoningEffort()
39686
+ };
39687
+ }
39688
+ return request;
39689
+ }
39690
+ extractTokenUsage(response) {
39691
+ if (!response.usage) {
39692
+ return void 0;
39693
+ }
39694
+ return new TokenUsage(
39695
+ response.usage.input_tokens,
39696
+ response.usage.output_tokens,
39697
+ response.usage.total_tokens,
39698
+ new InputTokenDetails(response.usage.input_tokens_details.cached_tokens),
39699
+ new OutputTokenDetails(response.usage.output_tokens_details.reasoning_tokens)
39700
+ );
39701
+ }
39702
+ mapContextToRequest(context) {
39703
+ return context.getItems().map((item) => item.toJSON());
39704
+ }
39705
+ extractContextItems(response) {
39706
+ return response.output.map((item) => {
39707
+ if (item.type === "message" && item.role === "assistant") {
39708
+ return ModelMessageItem.rehydrate(item.content[0]);
39709
+ }
39710
+ if (item.type === "function_call") {
39711
+ return FunctionCallItem.rehydrate({
39712
+ callId: item.call_id,
39713
+ name: item.name,
39714
+ args: item.arguments
39715
+ });
39716
+ }
39717
+ if (item.type === "reasoning") {
39718
+ return ReasoningItem.rehydrate(item);
39719
+ }
39720
+ });
39721
+ }
39722
+ };
39723
+ var OpenAICompatibleChatCompletions = class {
39724
+ constructor(config = {}) {
39725
+ var _a5;
39726
+ this.client = new OpenAI({
39727
+ baseURL: config.baseURL,
39728
+ apiKey: config.apiKey
39729
+ });
39730
+ this.extraBody = (_a5 = config.extraBody) != null ? _a5 : {};
39731
+ }
39732
+ async infer(inferenceRequest) {
39733
+ const response = await this.client.chat.completions.create(this.buildRequest(inferenceRequest));
39734
+ const contextItems = this.extractContextItems(response);
39735
+ const tokenUsage = this.extractTokenUsage(response);
39736
+ return new InferenceResponse(contextItems, tokenUsage);
39737
+ }
39738
+ async *stream(inferenceRequest, signal) {
39739
+ var _a5;
39740
+ const stream = await this.client.chat.completions.create({
39741
+ ...this.buildRequest(inferenceRequest),
39742
+ stream: true
39743
+ });
39744
+ for await (const event of stream) {
39745
+ if (signal == null ? void 0 : signal.aborted) {
39746
+ break;
39747
+ }
39748
+ yield new SemanticEvent((_a5 = event.object) != null ? _a5 : "chat.completion.chunk", event);
39749
+ }
39750
+ }
39751
+ buildRequest(inferenceRequest) {
39752
+ const specification = inferenceRequest.model.specification;
39753
+ const request = {
39754
+ ...this.extraBody,
39755
+ model: specification.name,
39756
+ messages: this.mapContextToRequest(inferenceRequest.context)
39757
+ };
39758
+ if (specification.supportFunctionCalling && inferenceRequest.model.getTools().length > 0) {
39759
+ request.tools = inferenceRequest.model.getTools().map((tool) => {
39760
+ return {
39761
+ type: "function",
39762
+ function: {
39763
+ name: tool.name,
39764
+ description: tool.description,
39765
+ parameters: tool.parameters
39766
+ }
39767
+ };
39768
+ });
39769
+ }
39770
+ if (specification.supportReasoningEffort) {
39771
+ request.reasoning_effort = inferenceRequest.model.getReasoningEffort();
39772
+ }
39773
+ return request;
39774
+ }
39775
+ extractTokenUsage(response) {
39776
+ var _a5, _b, _c, _d;
39777
+ if (!response.usage) {
39778
+ return void 0;
39779
+ }
39780
+ return new TokenUsage(
39781
+ response.usage.prompt_tokens,
39782
+ response.usage.completion_tokens,
39783
+ response.usage.total_tokens,
39784
+ new InputTokenDetails((_b = (_a5 = response.usage.prompt_tokens_details) == null ? void 0 : _a5.cached_tokens) != null ? _b : 0),
39785
+ new OutputTokenDetails((_d = (_c = response.usage.completion_tokens_details) == null ? void 0 : _c.reasoning_tokens) != null ? _d : 0)
39786
+ );
39787
+ }
39788
+ mapContextToRequest(context) {
39789
+ var _a5;
39790
+ const messages = [];
39791
+ for (const item of context.getItems()) {
39792
+ if (item instanceof DeveloperMessageItem || item instanceof SystemMessageItem) {
39793
+ messages.push({ role: "system", content: item.content.text });
39794
+ continue;
39795
+ }
39796
+ if (item instanceof UserMessageItem) {
39797
+ messages.push({ role: "user", content: item.content.text });
39798
+ continue;
39799
+ }
39800
+ if (item instanceof ModelMessageItem) {
39801
+ messages.push({ role: "assistant", content: item.content.text });
39802
+ continue;
39803
+ }
39804
+ if (item instanceof FunctionCallItem) {
39805
+ const toolCall = {
39806
+ id: item.callId,
39807
+ type: "function",
39808
+ function: { name: item.name, arguments: item.args }
39809
+ };
39810
+ const last = messages[messages.length - 1];
39811
+ if ((last == null ? void 0 : last.role) === "assistant") {
39812
+ last.tool_calls = (_a5 = last.tool_calls) != null ? _a5 : [];
39813
+ last.tool_calls.push(toolCall);
39814
+ } else {
39815
+ messages.push({ role: "assistant", content: null, tool_calls: [toolCall] });
39816
+ }
39817
+ continue;
39818
+ }
39819
+ if (item instanceof FunctionCallOutputItem) {
39820
+ messages.push({ role: "tool", tool_call_id: item.callId, content: item.output.text });
39821
+ }
39822
+ }
39823
+ return messages;
39824
+ }
39825
+ extractContextItems(response) {
39826
+ var _a5, _b, _c;
39827
+ const items = [];
39828
+ const message = (_b = (_a5 = response.choices) == null ? void 0 : _a5[0]) == null ? void 0 : _b.message;
39829
+ if (!message) {
39830
+ return items;
39831
+ }
39832
+ if (message.reasoning_content) {
39833
+ items.push(
39834
+ ReasoningItem.rehydrate({
39835
+ content: InputText.rehydrate({ text: message.reasoning_content }),
39836
+ encryptedContent: void 0,
39837
+ summary: []
39838
+ })
39839
+ );
39840
+ }
39841
+ if (message.content) {
39842
+ items.push(ModelMessageItem.rehydrate({ text: message.content }));
39843
+ }
39844
+ for (const toolCall of (_c = message.tool_calls) != null ? _c : []) {
39845
+ items.push(
39846
+ FunctionCallItem.rehydrate({
39847
+ callId: toolCall.id,
39848
+ name: toolCall.function.name,
39849
+ args: toolCall.function.arguments
39850
+ })
39851
+ );
39852
+ }
39853
+ return items;
39854
+ }
39855
+ };
39856
+
39857
+ // ../baro-orchestrator/src/planning/openai-runtime.ts
39858
+ var GenericOpenAIModel = class {
39859
+ specification;
39860
+ /** Per-story endpoint: `runInferenceRound` routes to this baseURL/apiKey
39861
+ * instead of the env default — lets one DAG hit several endpoints. */
39862
+ connection;
39863
+ _tools = [];
39864
+ _reasoningEffort = "medium";
39865
+ _streaming = false;
39866
+ constructor(name, connection) {
39867
+ this.connection = connection;
39868
+ this.specification = {
39869
+ name,
39870
+ supportReasoningEffort: false,
39871
+ defaultReasoningEffort: void 0,
39872
+ supportStreaming: false,
39873
+ contextWindowSize: 128e3,
39874
+ maxOutputTokens: 16384,
39875
+ supportFunctionCalling: true
39876
+ };
39877
+ }
39878
+ setTools(tools) {
39879
+ this._tools = tools;
39880
+ }
39881
+ getTools() {
39882
+ return this._tools;
39883
+ }
39884
+ // Effectively no-ops: with `supportReasoningEffort: false` the runtime
39885
+ // sends no reasoning_effort field for a generic chat model.
39886
+ setReasoningEffort(effort) {
39887
+ this._reasoningEffort = effort;
39888
+ }
39889
+ getReasoningEffort() {
39890
+ return this._reasoningEffort;
39891
+ }
39892
+ setStreaming(streaming) {
39893
+ this._streaming = streaming;
39894
+ }
39895
+ getStreaming() {
39896
+ return this._streaming;
39897
+ }
39898
+ };
39899
+ var chatRuntimeCache = /* @__PURE__ */ new Map();
39900
+ function getChatRuntime(conn) {
39901
+ const key = `${conn?.baseURL ?? ""}|${conn?.apiKey ?? ""}`;
39902
+ let rt = chatRuntimeCache.get(key);
39903
+ if (!rt) {
39904
+ rt = conn?.baseURL || conn?.apiKey ? new OpenAICompatibleChatCompletions({
39905
+ baseURL: conn.baseURL,
39906
+ apiKey: conn.apiKey
39907
+ }) : new OpenAICompatibleChatCompletions();
39908
+ chatRuntimeCache.set(key, rt);
39909
+ }
39910
+ return rt;
39911
+ }
39912
+ var responsesRuntime;
39913
+ function getResponsesRuntime() {
39914
+ if (!responsesRuntime) responsesRuntime = new OpenAIResponses();
39915
+ return responsesRuntime;
39916
+ }
39917
+ function isOpenAINativeModel(name) {
39918
+ return /^(gpt[-\d]|o[1-9]|chatgpt|text-|davinci)/i.test(name.trim());
39919
+ }
39920
+ async function runInferenceRound(context, model) {
39921
+ const conn = model.connection;
39922
+ const name = model.specification?.name ?? "";
39923
+ const runtime = isOpenAINativeModel(name) && !conn?.baseURL ? getResponsesRuntime() : getChatRuntime(conn);
39924
+ const response = await runtime.infer(new InferenceRequest(model, context));
39925
+ return { items: response.contextItems, usage: response.tokenUsage };
39926
+ }
39927
+ var UsageAccumulator = class {
39928
+ input = 0;
39929
+ output = 0;
39930
+ total = 0;
39931
+ cached = 0;
39932
+ reasoning = 0;
39933
+ rounds = 0;
39934
+ add(usage) {
39935
+ if (!usage) return;
39936
+ this.rounds += 1;
39937
+ this.input += usage.inputTokens ?? 0;
39938
+ this.output += usage.outputTokens ?? 0;
39939
+ this.total += usage.totalTokens ?? 0;
39940
+ this.cached += usage.inputTokenDetails?.cached_tokens ?? 0;
39941
+ this.reasoning += usage.outputTokenDetails?.reasoning_tokens ?? 0;
39942
+ }
39943
+ get isEmpty() {
39944
+ return this.rounds === 0;
39945
+ }
39946
+ get totalTokens() {
39947
+ return this.total;
39948
+ }
39949
+ /** Snake_case keys line up with what the Claude side's stream-json
39950
+ * mapper produces from Anthropic usage frames. */
39951
+ toJSON() {
39952
+ return {
39953
+ input_tokens: this.input,
39954
+ output_tokens: this.output,
39955
+ total_tokens: this.total,
39956
+ cached_input_tokens: this.cached,
39957
+ reasoning_tokens: this.reasoning,
39958
+ rounds: this.rounds
39959
+ };
39960
+ }
39961
+ summary() {
39962
+ if (this.isEmpty) return "(no token usage reported)";
39963
+ return `${this.total} total tokens (${this.input} in, ${this.output} out${this.cached ? `, ${this.cached} cached` : ""}${this.reasoning ? `, ${this.reasoning} reasoning` : ""}) across ${this.rounds} round(s)`;
39964
+ }
39965
+ };
39966
+
39967
+ // ../baro-orchestrator/src/planning/codebase-tools.ts
39968
+ import { execSync } from "child_process";
39969
+ import * as fs2 from "fs";
39970
+ import * as path4 from "path";
39971
+ var IGNORE = /* @__PURE__ */ new Set([
39972
+ "node_modules",
39973
+ ".git",
39974
+ "dist",
39975
+ "build",
39976
+ ".next",
39977
+ ".nuxt",
39978
+ "coverage",
39979
+ ".cache",
39980
+ "__pycache__",
39981
+ "target",
39982
+ ".output",
39983
+ ".vercel"
39984
+ ]);
39985
+ var MAX_FILE_BYTES = 15e3;
39986
+ var MAX_GREP_LINES = 80;
39987
+ var MAX_BASH_OUTPUT_BYTES = 8e3;
39988
+ function createCodebaseTools(cwd) {
39989
+ return [
39990
+ readFileTool(cwd),
39991
+ listFilesTool(cwd),
39992
+ fileTreeTool(cwd),
39993
+ grepTool(cwd),
39994
+ globTool(cwd),
39995
+ bashTool(cwd)
39996
+ ];
39997
+ }
39998
+ function readFileTool(cwd) {
39999
+ return {
40000
+ type: "function",
40001
+ name: "read_file",
40002
+ description: "Read the full contents of a file by path relative to the project root. Returns up to 15000 characters (truncates past that). Use to inspect package.json, source files, config files, READMEs, etc.",
40003
+ strict: true,
40004
+ parameters: {
40005
+ type: "object",
40006
+ properties: {
40007
+ path: {
40008
+ type: "string",
40009
+ description: "Path relative to the project root (e.g. 'src/index.ts')."
40010
+ }
40011
+ },
40012
+ required: ["path"],
40013
+ additionalProperties: false
40014
+ },
40015
+ async invoke(args) {
40016
+ const target = safePath(cwd, args.path);
40017
+ if (!target) return `Error: path '${args.path}' escapes the project root.`;
40018
+ if (!fs2.existsSync(target)) return `File not found: ${args.path}`;
40019
+ const stat2 = fs2.statSync(target);
40020
+ if (stat2.isDirectory()) {
40021
+ return `${args.path} is a directory \u2014 use list_files or file_tree.`;
40022
+ }
40023
+ if (stat2.size > 5e5) {
40024
+ return `File too large (${(stat2.size / 1024).toFixed(0)} KB) \u2014 skip or grep instead.`;
40025
+ }
40026
+ let content = fs2.readFileSync(target, "utf-8");
40027
+ if (content.length > MAX_FILE_BYTES) {
40028
+ content = content.slice(0, MAX_FILE_BYTES) + "\n... (truncated)";
40029
+ }
40030
+ return content;
40031
+ }
40032
+ };
40033
+ }
40034
+ function listFilesTool(cwd) {
40035
+ return {
40036
+ type: "function",
40037
+ name: "list_files",
40038
+ description: "List files and directories at a path. Use path='' for the project root. Skips node_modules, .git, dist, build, target, and other dependency dirs.",
40039
+ strict: true,
40040
+ parameters: {
40041
+ type: "object",
40042
+ properties: {
40043
+ path: {
40044
+ type: "string",
40045
+ description: "Directory path relative to the project root. Empty for root."
40046
+ },
40047
+ recursive: {
40048
+ type: "boolean",
40049
+ description: "Walk subdirectories up to 4 deep, capped at 200 entries."
40050
+ }
40051
+ },
40052
+ required: ["path", "recursive"],
40053
+ additionalProperties: false
40054
+ },
40055
+ async invoke(args) {
40056
+ const target = safePath(cwd, args.path || ".");
40057
+ if (!target) return `Error: path '${args.path}' escapes the project root.`;
40058
+ if (!fs2.existsSync(target)) return `Directory not found: ${args.path}`;
40059
+ const stat2 = fs2.statSync(target);
40060
+ if (!stat2.isDirectory()) return `${args.path} is not a directory \u2014 use read_file.`;
40061
+ const results = [];
40062
+ function walk(dir, prefix, depth) {
40063
+ if (results.length >= 200 || depth > 4) return;
40064
+ for (const entry of fs2.readdirSync(dir, { withFileTypes: true })) {
40065
+ if (IGNORE.has(entry.name) || entry.name.startsWith(".")) continue;
40066
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
40067
+ if (entry.isDirectory()) {
40068
+ results.push(rel + "/");
40069
+ if (args.recursive) walk(path4.join(dir, entry.name), rel, depth + 1);
40070
+ } else {
40071
+ results.push(rel);
40072
+ }
40073
+ }
40074
+ }
40075
+ walk(target, "", 0);
40076
+ return results.join("\n") || "(empty directory)";
40077
+ }
40078
+ };
40079
+ }
40080
+ function fileTreeTool(cwd) {
40081
+ return {
40082
+ type: "function",
40083
+ name: "file_tree",
40084
+ description: "Show a condensed ASCII tree of the project structure up to 3 levels deep. Cheapest way to get a first overview before deciding which files to read.",
40085
+ strict: true,
40086
+ parameters: {
40087
+ type: "object",
40088
+ properties: {},
40089
+ required: [],
40090
+ additionalProperties: false
40091
+ },
40092
+ async invoke() {
40093
+ const lines = [path4.basename(cwd) + "/"];
40094
+ function walk(dir, prefix, depth) {
40095
+ if (lines.length >= 150 || depth > 3) return;
40096
+ let entries;
40097
+ try {
40098
+ entries = fs2.readdirSync(dir, { withFileTypes: true });
40099
+ } catch {
40100
+ return;
40101
+ }
40102
+ entries.sort((a, b) => {
40103
+ if (a.isDirectory() && !b.isDirectory()) return -1;
40104
+ if (!a.isDirectory() && b.isDirectory()) return 1;
40105
+ return a.name.localeCompare(b.name);
40106
+ });
40107
+ for (let i2 = 0; i2 < entries.length; i2++) {
40108
+ const entry = entries[i2];
40109
+ if (IGNORE.has(entry.name) || entry.name.startsWith(".")) continue;
40110
+ const isLast = i2 === entries.length - 1;
40111
+ const connector = isLast ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 ";
40112
+ const childPrefix = isLast ? " " : "\u2502 ";
40113
+ if (entry.isDirectory()) {
40114
+ lines.push(`${prefix}${connector}${entry.name}/`);
40115
+ walk(path4.join(dir, entry.name), prefix + childPrefix, depth + 1);
40116
+ } else {
40117
+ lines.push(`${prefix}${connector}${entry.name}`);
40118
+ }
40119
+ }
40120
+ }
40121
+ walk(cwd, "", 0);
40122
+ return lines.join("\n");
40123
+ }
40124
+ };
40125
+ }
40126
+ function grepTool(cwd) {
40127
+ return {
40128
+ type: "function",
40129
+ name: "grep",
40130
+ description: "Search for a text pattern across project files. Returns matching lines with their file paths. Case-insensitive. Skips dependency directories. Caps results at 80 lines.",
40131
+ strict: true,
40132
+ parameters: {
40133
+ type: "object",
40134
+ properties: {
40135
+ pattern: {
40136
+ type: "string",
40137
+ description: "Text or regex (POSIX) to search for."
40138
+ },
40139
+ path: {
40140
+ type: "string",
40141
+ description: "Directory to search in. Default: entire project."
40142
+ },
40143
+ file_pattern: {
40144
+ type: "string",
40145
+ description: "File glob filter (e.g. '*.ts', '*.tsx'). Default: all files."
40146
+ }
40147
+ },
40148
+ required: ["pattern", "path", "file_pattern"],
40149
+ additionalProperties: false
40150
+ },
40151
+ async invoke(args) {
40152
+ const searchDir = safePath(cwd, args.path || ".");
40153
+ if (!searchDir) return `Error: path '${args.path}' escapes the project root.`;
40154
+ if (!fs2.existsSync(searchDir)) return `Directory not found: ${args.path}`;
40155
+ try {
40156
+ const excludes = Array.from(IGNORE).map((d) => `--exclude-dir=${d}`).join(" ");
40157
+ const include = args.file_pattern ? `--include='${args.file_pattern}'` : "";
40158
+ const cmd = `grep -rn -i ${excludes} ${include} --max-count=50 -- ${JSON.stringify(
40159
+ args.pattern
40160
+ )} ${JSON.stringify(searchDir)} 2>/dev/null || true`;
40161
+ const output = execSync(cmd, { encoding: "utf-8", maxBuffer: 2 * 1024 * 1024 });
40162
+ const lines = output.split("\n").filter(Boolean).map((line) => line.startsWith(cwd) ? line.slice(cwd.length + 1) : line);
40163
+ return lines.slice(0, MAX_GREP_LINES).join("\n") || "No matches found.";
40164
+ } catch {
40165
+ return "No matches found.";
40166
+ }
40167
+ }
40168
+ };
40169
+ }
40170
+ function globTool(cwd) {
40171
+ return {
40172
+ type: "function",
40173
+ name: "glob",
40174
+ description: "List files matching a glob pattern (e.g. 'src/**/*.ts'). Useful when you want every file of a type without scanning the whole tree.",
40175
+ strict: true,
40176
+ parameters: {
40177
+ type: "object",
40178
+ properties: {
40179
+ pattern: {
40180
+ type: "string",
40181
+ description: "Glob pattern relative to the project root."
40182
+ }
40183
+ },
40184
+ required: ["pattern"],
40185
+ additionalProperties: false
40186
+ },
40187
+ async invoke(args) {
40188
+ try {
40189
+ const cmd = `cd ${JSON.stringify(cwd)} && find . -path './node_modules' -prune -o -path './.git' -prune -o -path './target' -prune -o -path './dist' -prune -o -path './build' -prune -o -type f -print | grep -E ${JSON.stringify(
40190
+ globToRegex(args.pattern)
40191
+ )} 2>/dev/null | head -200 || true`;
40192
+ const output = execSync(cmd, { encoding: "utf-8", maxBuffer: 1024 * 1024 });
40193
+ const lines = output.split("\n").filter(Boolean).map((l) => l.replace(/^\.\//, ""));
40194
+ return lines.join("\n") || "(no matches)";
40195
+ } catch {
40196
+ return "(glob failed)";
40197
+ }
40198
+ }
40199
+ };
40200
+ }
40201
+ function bashTool(cwd) {
40202
+ return {
40203
+ type: "function",
40204
+ name: "bash",
40205
+ description: "Run a non-destructive read-only shell command in the project root. Use for inspections like 'cat package.json | head', 'git log --oneline | head', 'wc -l src/**/*.ts'. Caps output at 8 KB. Do NOT use for writes, edits, or installs.",
40206
+ strict: true,
40207
+ parameters: {
40208
+ type: "object",
40209
+ properties: {
40210
+ command: {
40211
+ type: "string",
40212
+ description: "The shell command to execute. Read-only operations only."
40213
+ }
40214
+ },
40215
+ required: ["command"],
40216
+ additionalProperties: false
40217
+ },
40218
+ async invoke(args) {
40219
+ try {
40220
+ const output = execSync(args.command, {
40221
+ cwd,
40222
+ encoding: "utf-8",
40223
+ maxBuffer: 4 * 1024 * 1024,
40224
+ // Real builds/test suites take minutes; 30s was far too short.
40225
+ timeout: Number(process.env.BARO_BASH_TIMEOUT_MS) || 3e5,
40226
+ stdio: ["ignore", "pipe", "pipe"]
40227
+ });
40228
+ if (output.length > MAX_BASH_OUTPUT_BYTES) {
40229
+ return output.slice(0, MAX_BASH_OUTPUT_BYTES) + `
40230
+ ... (truncated, ${output.length - MAX_BASH_OUTPUT_BYTES} bytes elided)`;
40231
+ }
40232
+ return output || "(empty output)";
40233
+ } catch (e2) {
40234
+ const err = e2;
40235
+ const stderr = err.stderr instanceof Buffer ? err.stderr.toString() : err.stderr ?? "";
40236
+ return `bash exited with status ${err.status ?? "?"}: ${stderr || err.message || "unknown error"}`;
40237
+ }
40238
+ }
40239
+ };
40240
+ }
40241
+ function safePath(cwd, filePath) {
40242
+ const resolved = path4.resolve(cwd, filePath);
40243
+ if (!resolved.startsWith(path4.resolve(cwd))) return null;
40244
+ return resolved;
40245
+ }
40246
+ function globToRegex(glob) {
40247
+ let regex = "^";
40248
+ let i2 = 0;
40249
+ while (i2 < glob.length) {
40250
+ const ch = glob[i2];
40251
+ if (ch === "*") {
40252
+ if (glob[i2 + 1] === "*") {
40253
+ regex += ".*";
40254
+ i2 += 2;
40255
+ if (glob[i2] === "/") i2++;
40256
+ continue;
40257
+ }
40258
+ regex += "[^/]*";
40259
+ i2++;
40260
+ continue;
40261
+ }
40262
+ if (ch === "?") {
40263
+ regex += "[^/]";
40264
+ i2++;
40265
+ continue;
40266
+ }
40267
+ if (ch === ".") {
40268
+ regex += "\\.";
40269
+ i2++;
40270
+ continue;
40271
+ }
40272
+ if ("()[]{}+|^$\\".includes(ch)) {
40273
+ regex += "\\" + ch;
40274
+ i2++;
40275
+ continue;
40276
+ }
40277
+ regex += ch;
40278
+ i2++;
40279
+ }
40280
+ regex += "$";
40281
+ return regex;
40282
+ }
40283
+
40284
+ // ../baro-orchestrator/src/planning/planner-openai.ts
40285
+ function pickModel(name) {
40286
+ switch (name) {
40287
+ case "gpt-5.5":
40288
+ return new Gpt55();
40289
+ case "gpt-5.4":
40290
+ return new Gpt54();
40291
+ case "gpt-5.4-mini":
40292
+ return new Gpt54Mini();
40293
+ case "gpt-5.4-nano":
40294
+ return new Gpt54Nano();
40295
+ default:
40296
+ process.stderr.write(
40297
+ `[pickModel] Using model "${name}" as-is with the OpenAI API.
40298
+ `
40299
+ );
40300
+ return new GenericOpenAIModel(name);
40301
+ }
40302
+ }
40303
+ async function runPlannerOpenAI(opts) {
40304
+ const model = pickModel(opts.model ?? "gpt-5.5");
40305
+ const intake = opts.modeContract ?? await decideExecutionMode(opts, model).catch((e2) => {
40306
+ process.stderr.write(`[planner-openai] intake failed (${e2?.message ?? String(e2)}) \u2014 using heuristic mode contract
40307
+ `);
40308
+ return heuristicModeContract(opts);
40309
+ });
40310
+ process.stderr.write(`[planner-openai] intake mode=${intake.mode} confidence=${intake.confidence} reason=${oneLine(intake.reason).slice(0, 180)}
40311
+ `);
40312
+ const tools = createCodebaseTools(opts.cwd);
40313
+ setModelTools(model, tools);
40314
+ let context = ModelContext.create("planner").addContextItem(SystemMessageItem.create(PLANNER_SYSTEM_PROMPT)).addContextItem(
40315
+ UserMessageItem.create(
40316
+ buildPlannerUserMessage({
40317
+ goal: opts.goal,
40318
+ decisionDocument: opts.decisionDocument,
40319
+ quick: opts.quick,
40320
+ projectContext: opts.projectContext,
40321
+ modeContract: renderModeContract(intake)
40322
+ })
40323
+ )
40324
+ );
40325
+ const maxRounds = opts.maxRounds ?? 8;
40326
+ const defaultExploration = opts.decisionDocument?.trim() ? 1 : 2;
40327
+ const maxExplorationRounds = Math.max(1, Math.min(opts.maxExplorationRounds ?? numberEnv("BARO_PLANNER_MAX_EXPLORATION_ROUNDS", defaultExploration), maxRounds - 1));
40328
+ const maxTokens = Math.max(5e4, opts.maxTokens ?? numberEnv("BARO_PLANNER_MAX_TOKENS", 15e4));
40329
+ const perRoundTimeoutMs = (opts.perRoundTimeoutSecs ?? 600) * 1e3;
40330
+ const usage = new UsageAccumulator();
40331
+ let finalRequested = false;
40332
+ for (let round = 1; round <= maxRounds; round++) {
40333
+ const newItems = [];
40334
+ if (finalRequested) setModelTools(model, []);
40335
+ const roundPromise = runInferenceRound(context, model);
40336
+ let timer;
40337
+ const timeoutPromise = new Promise((_, rej) => {
40338
+ timer = setTimeout(() => rej(new Error(`round ${round} timed out after ${perRoundTimeoutMs}ms`)), perRoundTimeoutMs);
40339
+ });
40340
+ const result = await Promise.race([roundPromise, timeoutPromise]).finally(() => clearTimeout(timer));
40341
+ usage.add(result.usage);
40342
+ for (const item of result.items) {
40343
+ if (item.type === "function_call") {
40344
+ const fc = item;
40345
+ newItems.push({
40346
+ type: "function_call",
40347
+ callId: fc.callId,
40348
+ name: fc.name,
40349
+ args: fc.args
40350
+ });
40351
+ context = context.addContextItem(item);
40352
+ } else if (item.type === "message") {
40353
+ const json = item.toJSON();
40354
+ const text = json.content?.[0]?.text ?? "";
40355
+ newItems.push({ type: "message", text });
40356
+ context = context.addContextItem(item);
40357
+ } else if (item.type === "reasoning") {
40358
+ context = context.addContextItem(item);
40359
+ }
40360
+ }
40361
+ if (newItems.length === 0) {
40362
+ throw new Error(`PlannerOpenAI: round ${round} returned no items. Aborting.`);
40363
+ }
40364
+ const calls = newItems.filter((i2) => i2.type === "function_call");
40365
+ for (const call of calls) {
40366
+ const tool = tools.find((t2) => t2.name === call.name);
40367
+ const output = tool ? await runToolSafely(tool, call.args ?? "{}") : `Error: tool '${call.name}' not registered`;
40368
+ context = context.addContextItem(
40369
+ FunctionCallOutputItem.create(call.callId ?? "", output)
40370
+ );
40371
+ }
40372
+ if (calls.length > 0) {
40373
+ if (!finalRequested && (round >= maxExplorationRounds || usage.totalTokens >= maxTokens)) {
40374
+ finalRequested = true;
40375
+ setModelTools(model, []);
40376
+ context = context.addContextItem(UserMessageItem.create(finalPlanInstruction(usage.summary(), round, maxExplorationRounds, maxTokens)));
40377
+ }
40378
+ } else {
40379
+ const messages = newItems.filter((i2) => i2.type === "message");
40380
+ if (messages.length === 0) {
40381
+ throw new Error(
40382
+ `PlannerOpenAI: round ${round} had no tool calls and no message \u2014 stuck.`
40383
+ );
40384
+ }
40385
+ const raw = messages.map((m2) => m2.text ?? "").join("\n").trim();
40386
+ if (!raw) throw new Error("PlannerOpenAI: empty final response");
40387
+ process.stderr.write(`[planner-openai] ${usage.summary()}
40388
+ `);
40389
+ try {
40390
+ return extractJsonObject(raw);
40391
+ } catch (e2) {
40392
+ process.stderr.write(`[planner-openai] invalid final JSON (${e2?.message ?? String(e2)}) \u2014 using fallback PRD
40393
+ `);
40394
+ return fallbackPrdJson(opts.goal, "Planner returned invalid JSON after exploration.");
40395
+ }
40396
+ }
40397
+ }
40398
+ process.stderr.write(`[planner-openai] ${usage.summary()} \u2014 exceeded maxRounds=${maxRounds}, using fallback PRD
40399
+ `);
40400
+ return fallbackPrdJson(opts.goal, `Planner exceeded maxRounds=${maxRounds} without producing a final plan.`);
40401
+ }
40402
+ async function decideExecutionMode(opts, plannerModel) {
40403
+ if (opts.quick) {
40404
+ return {
40405
+ mode: "focused",
40406
+ confidence: 1,
40407
+ reason: "The user explicitly invoked quick mode.",
40408
+ maxStories: 1,
40409
+ parallelism: 1
40410
+ };
40411
+ }
40412
+ const intakeModel = pickModel(process.env.BARO_INTAKE_MODEL || plannerModel.specification.name);
40413
+ setModelTools(intakeModel, []);
40414
+ const prompt = buildIntakePrompt(opts);
40415
+ const context = ModelContext.create("intake").addContextItem(SystemMessageItem.create("You classify software tasks for an autonomous PR workflow. Output JSON only.")).addContextItem(UserMessageItem.create(prompt));
40416
+ const result = await runInferenceRound(context, intakeModel);
40417
+ const raw = result.items.filter((i2) => i2.type === "message").map((i2) => i2.toJSON().content?.[0]?.text ?? "").join("\n").trim();
40418
+ return parseModeContract(raw);
40419
+ }
40420
+ function numberEnv(name, fallback) {
40421
+ const n = Number(process.env[name]);
40422
+ return Number.isFinite(n) && n > 0 ? n : fallback;
40423
+ }
40424
+ function finalPlanInstruction(summary, round, maxExplorationRounds, maxTokens) {
40425
+ return [
40426
+ "You have explored enough. Stop calling tools.",
40427
+ `Exploration round ${round}/${maxExplorationRounds}; planning budget ${maxTokens} tokens; usage so far: ${summary}.`,
40428
+ "Now output ONLY the final PRD JSON matching the required schema. No markdown, no prose, no more inspection.",
40429
+ "If some details remain uncertain, encode them as acceptance criteria/tests inside the relevant story instead of continuing exploration."
40430
+ ].join("\n");
40431
+ }
40432
+ function fallbackPrdJson(goal, reason) {
40433
+ const title = oneLine(goal).slice(0, 80) || "Implement requested change";
40434
+ return JSON.stringify({
40435
+ project: "baro-run",
40436
+ branchName: `baro/${slug(title)}`,
40437
+ description: title,
40438
+ userStories: [
40439
+ {
40440
+ id: "S1",
40441
+ priority: 1,
40442
+ title,
40443
+ description: `${goal.trim()}
40444
+
40445
+ Planner fallback: ${reason}`,
40446
+ dependsOn: [],
40447
+ retries: 2,
40448
+ acceptance: ["The requested change is implemented without regressing existing behavior."],
40449
+ tests: [`echo "planner fallback: run the project's relevant checks"`],
40450
+ model: "opus"
40451
+ }
40452
+ ]
40453
+ });
40454
+ }
40455
+ function oneLine(s2) {
40456
+ return s2.replace(/\s+/g, " ").trim();
40457
+ }
40458
+ function slug(s2) {
40459
+ const out = s2.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48);
40460
+ return out || "planner-fallback";
40461
+ }
40462
+ async function runToolSafely(tool, argsJson) {
40463
+ let parsed;
40464
+ try {
40465
+ parsed = JSON.parse(argsJson);
40466
+ } catch (e2) {
40467
+ return `Error: tool args were not valid JSON: ${e2?.message ?? String(e2)}`;
40468
+ }
40469
+ try {
40470
+ const result = await tool.invoke(parsed);
40471
+ return typeof result === "string" ? result : JSON.stringify(result);
40472
+ } catch (e2) {
40473
+ return `Error running ${tool.name}: ${e2?.message ?? String(e2)}`;
40474
+ }
40475
+ }
40476
+ function setModelTools(model, tools) {
40477
+ const m2 = model;
40478
+ if (typeof m2.setTools !== "function") {
40479
+ throw new Error(
40480
+ `PlannerOpenAI: model ${model.specification.name} does not implement ToolCallingCapability`
40481
+ );
40482
+ }
40483
+ m2.setTools(tools);
40484
+ }
40485
+
40486
+ // ../baro-orchestrator/src/opencode-one-shot.ts
40487
+ import { spawn as spawn2 } from "child_process";
40488
+ async function runOpenCodeOneShot(opts) {
40489
+ const label = opts.label ?? "opencode";
40490
+ const args = ["run", "--format", "json", "--dangerously-skip-permissions"];
40491
+ if (opts.model) args.push("-m", opts.model);
40492
+ if (opts.cwd) args.push("--dir", opts.cwd);
40493
+ args.push(opts.prompt);
40494
+ const timeoutMs = opts.timeoutMs ?? 6e5;
40495
+ return await new Promise((resolve2, reject) => {
40496
+ let proc;
40497
+ try {
40498
+ proc = spawn2(opts.opencodeBin ?? "opencode", args, {
40499
+ cwd: opts.cwd,
40500
+ stdio: ["ignore", "pipe", "pipe"]
40501
+ });
40502
+ } catch (e2) {
40503
+ reject(e2 instanceof Error ? e2 : new Error(String(e2)));
40504
+ return;
40505
+ }
40506
+ let assistantText = "";
40507
+ let stdoutBuffer = "";
40508
+ const eventTypesSeen = [];
40509
+ let timedOut = false;
40510
+ const startedAt = Date.now();
40511
+ const timer = setTimeout(() => {
40512
+ timedOut = true;
40513
+ try {
40514
+ proc.kill("SIGTERM");
40515
+ } catch {
40516
+ }
40517
+ }, timeoutMs);
40518
+ proc.stdout.setEncoding("utf8");
40519
+ proc.stdout.on("data", (chunk) => {
40520
+ stdoutBuffer += chunk;
40521
+ let nl;
40522
+ while ((nl = stdoutBuffer.indexOf("\n")) >= 0) {
40523
+ const line = stdoutBuffer.slice(0, nl).trim();
40524
+ stdoutBuffer = stdoutBuffer.slice(nl + 1);
40525
+ if (!line) continue;
40526
+ let event;
40527
+ try {
40528
+ event = JSON.parse(line);
40529
+ } catch {
40530
+ continue;
40531
+ }
40532
+ const type = typeof event.type === "string" ? event.type : "";
40533
+ if (type) eventTypesSeen.push(type);
40534
+ if (type === "step_finish") {
40535
+ const part = event.part;
40536
+ const tokens = part?.tokens;
40537
+ if (tokens) {
40538
+ process.stderr.write(
40539
+ `[${label}] usage: in=${tokens.input ?? 0} out=${tokens.output ?? 0}
40540
+ `
40541
+ );
40542
+ }
40543
+ continue;
40544
+ }
40545
+ if (type === "text") {
40546
+ const part = event.part;
40547
+ if (part && typeof part.text === "string") {
40548
+ assistantText = assistantText ? `${assistantText}
40549
+ ${part.text}` : part.text;
40550
+ }
40551
+ continue;
40552
+ }
40553
+ if (type === "tool_use" || type === "tool_call") {
40554
+ const part = event.part;
40555
+ const tool = typeof part?.tool === "string" ? part.tool.slice(0, 120) : "?";
40556
+ process.stderr.write(`[${label}] tool: ${tool}
40557
+ `);
40558
+ continue;
40559
+ }
40560
+ }
40561
+ });
40562
+ proc.stderr.setEncoding("utf8");
40563
+ proc.stderr.on("data", (chunk) => {
40564
+ const trimmed = chunk.trimEnd();
40565
+ if (trimmed) {
40566
+ process.stderr.write(`[${label}/stderr] ${trimmed}
40567
+ `);
40568
+ }
40569
+ });
40570
+ proc.on("error", (err) => {
40571
+ clearTimeout(timer);
40572
+ reject(err);
40573
+ });
40574
+ proc.on("exit", (code, signal) => {
40575
+ clearTimeout(timer);
40576
+ const elapsedMs = Date.now() - startedAt;
40577
+ const ctx = [
40578
+ `elapsed=${elapsedMs}ms`,
40579
+ `exit=${code}`,
40580
+ signal ? `signal=${signal}` : null,
40581
+ timedOut ? `timedOut=true (cap=${timeoutMs}ms)` : null,
40582
+ `events=${eventTypesSeen.length}`,
40583
+ eventTypesSeen.length > 0 ? `event_types=[${[...new Set(eventTypesSeen)].join(",")}]` : null
40584
+ ].filter((x2) => x2 !== null).join(" ");
40585
+ if (timedOut || signal != null || code != null && code !== 0) {
40586
+ reject(
40587
+ new Error(
40588
+ `runOpenCodeOneShot: opencode terminated abnormally before completing (${ctx})`
40589
+ )
40590
+ );
40591
+ return;
40592
+ }
40593
+ if (assistantText.trim()) {
40594
+ resolve2(assistantText);
40595
+ return;
40596
+ }
40597
+ reject(
40598
+ new Error(
40599
+ `runOpenCodeOneShot: opencode produced no text output (${ctx})`
40600
+ )
40601
+ );
40602
+ });
40603
+ });
40604
+ }
40605
+
40606
+ // ../baro-orchestrator/src/planning/planner-opencode.ts
40607
+ async function runPlannerOpenCode(opts) {
40608
+ const modeContract = opts.modeContract ?? await runOpenCodeIntake(opts).catch((e2) => {
40609
+ process.stderr.write(`[planner-opencode] intake failed (${e2?.message ?? String(e2)}) \u2014 using heuristic mode contract
40610
+ `);
40611
+ return heuristicModeContract(opts);
40612
+ });
40613
+ process.stderr.write(`[planner-opencode] intake mode=${modeContract.mode} confidence=${modeContract.confidence}
40614
+ `);
40615
+ const userMessage = buildPlannerUserMessage({
40616
+ goal: opts.goal,
40617
+ decisionDocument: opts.decisionDocument,
40618
+ quick: opts.quick,
40619
+ projectContext: opts.projectContext,
40620
+ modeContract
40621
+ });
40622
+ const prompt = `${PLANNER_SYSTEM_PROMPT}
40623
+
40624
+ ${userMessage}`;
40625
+ const text = await runOpenCodeOneShot({
40626
+ prompt,
40627
+ cwd: opts.cwd,
40628
+ model: opts.model,
40629
+ opencodeBin: opts.opencodeBin,
40630
+ timeoutMs: opts.timeoutMs ?? 9e5,
40631
+ label: "opencode-planner"
40632
+ });
40633
+ const planText = text.trim();
40634
+ if (!planText) {
40635
+ throw new Error("PlannerOpenCode: opencode returned empty result");
40636
+ }
40637
+ return extractJsonObject4(planText);
40638
+ }
40639
+ async function runOpenCodeIntake(opts) {
40640
+ if (opts.quick) return heuristicModeContract(opts);
40641
+ const text = await runOpenCodeOneShot({
40642
+ prompt: `You classify software tasks for an autonomous PR workflow. Output JSON only.
40643
+
40644
+ ${buildIntakePrompt(opts)}`,
40645
+ cwd: opts.cwd,
40646
+ model: opts.model,
40647
+ opencodeBin: opts.opencodeBin,
40648
+ timeoutMs: Math.min(opts.timeoutMs ?? 9e5, 18e4),
40649
+ label: "opencode-intake"
40650
+ });
40651
+ return parseModeContract(text.trim());
40652
+ }
40653
+ function extractJsonObject4(text) {
40654
+ const trimmed = text.trim();
40655
+ if (trimmed.startsWith("{") && trimmed.endsWith("}")) return trimmed;
40656
+ const fence = trimmed.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/);
40657
+ if (fence) return fence[1];
40658
+ const start = trimmed.indexOf("{");
40659
+ if (start < 0) {
40660
+ throw new Error(
40661
+ `PlannerOpenCode: no JSON object in response: ${trimmed.slice(0, 200)}`
40662
+ );
40663
+ }
40664
+ let depth = 0;
40665
+ for (let i2 = start; i2 < trimmed.length; i2++) {
40666
+ const ch = trimmed[i2];
40667
+ if (ch === "{") depth++;
40668
+ else if (ch === "}") {
40669
+ depth--;
40670
+ if (depth === 0) return trimmed.slice(start, i2 + 1);
40671
+ }
40672
+ }
40673
+ throw new Error(
40674
+ `PlannerOpenCode: unbalanced JSON in response: ${trimmed.slice(0, 200)}`
40675
+ );
40676
+ }
40677
+
40678
+ // ../baro-orchestrator/src/pi-one-shot.ts
40679
+ import { spawn as spawn3 } from "child_process";
40680
+ async function runPiOneShot(opts) {
40681
+ const label = opts.label ?? "pi";
40682
+ const args = ["--mode", "json", "-p", "--no-session"];
40683
+ if (opts.provider) args.push("--provider", opts.provider);
40684
+ if (opts.model) args.push("--model", opts.model);
40685
+ args.push(opts.prompt);
40686
+ const timeoutMs = opts.timeoutMs ?? 6e5;
40687
+ return await new Promise((resolve2, reject) => {
40688
+ let proc;
40689
+ try {
40690
+ proc = spawn3(opts.piBin ?? "pi", args, {
40691
+ cwd: opts.cwd,
40692
+ stdio: ["ignore", "pipe", "pipe"]
40693
+ });
40694
+ } catch (e2) {
40695
+ reject(e2 instanceof Error ? e2 : new Error(String(e2)));
40696
+ return;
40697
+ }
40698
+ let assistantText = "";
40699
+ let stdoutBuffer = "";
40700
+ const eventTypesSeen = [];
40701
+ let timedOut = false;
40702
+ let killTimer = null;
40703
+ const clearTimers = () => {
40704
+ clearTimeout(timer);
40705
+ if (killTimer !== null) {
40706
+ clearTimeout(killTimer);
40707
+ killTimer = null;
40708
+ }
40709
+ };
40710
+ const startedAt = Date.now();
40711
+ const timer = setTimeout(() => {
40712
+ timedOut = true;
40713
+ try {
40714
+ proc.kill("SIGTERM");
40715
+ } catch {
40716
+ }
40717
+ killTimer = setTimeout(() => {
40718
+ killTimer = null;
40719
+ try {
40720
+ proc.kill("SIGKILL");
40721
+ } catch {
40722
+ }
40723
+ }, 5e3);
40724
+ killTimer.unref?.();
40725
+ }, timeoutMs);
40726
+ const maxBufferBytes = 16 * 1024 * 1024;
40727
+ const processLine = (rawLine) => {
40728
+ const line = rawLine.trim();
40729
+ if (!line) return;
40730
+ let event;
40731
+ try {
40732
+ event = JSON.parse(line);
40733
+ } catch {
40734
+ return;
40735
+ }
40736
+ const type = typeof event.type === "string" ? event.type : "";
40737
+ if (type) eventTypesSeen.push(type);
40738
+ if (type === "message_end") {
40739
+ const message = event.message;
40740
+ if (message?.role === "assistant") {
40741
+ const usage = message.usage;
40742
+ if (usage) {
40743
+ process.stderr.write(
40744
+ `[${label}] usage: in=${usage.input ?? 0} out=${usage.output ?? 0}
40745
+ `
40746
+ );
40747
+ }
40748
+ const content = message.content;
40749
+ if (Array.isArray(content)) {
40750
+ for (const block of content) {
40751
+ if (block.type === "text" && typeof block.text === "string") {
40752
+ assistantText = assistantText ? `${assistantText}
40753
+ ${block.text}` : block.text;
40754
+ }
40755
+ }
40756
+ }
40757
+ }
40758
+ return;
40759
+ }
40760
+ if (type === "tool_execution_start") {
40761
+ const toolName = typeof event.toolName === "string" ? event.toolName.slice(0, 120) : typeof event.tool === "string" ? event.tool.slice(0, 120) : typeof event.name === "string" ? event.name.slice(0, 120) : "?";
40762
+ process.stderr.write(`[${label}] tool: ${toolName}
40763
+ `);
40764
+ return;
40765
+ }
40766
+ if (type === "message_update") {
40767
+ const ame = event.assistantMessageEvent;
40768
+ if (ame?.type === "toolcall_start") {
40769
+ const block = ame.toolCall;
40770
+ const toolName = typeof block?.name === "string" ? block.name.slice(0, 120) : typeof ame.toolName === "string" ? ame.toolName.slice(0, 120) : typeof ame.name === "string" ? ame.name.slice(0, 120) : "?";
40771
+ process.stderr.write(`[${label}] tool: ${toolName}
40772
+ `);
40773
+ }
40774
+ return;
40775
+ }
40776
+ };
40777
+ proc.stdout.setEncoding("utf8");
40778
+ proc.stdout.on("data", (chunk) => {
40779
+ stdoutBuffer += chunk;
40780
+ let nl;
40781
+ while ((nl = stdoutBuffer.indexOf("\n")) >= 0) {
40782
+ const line = stdoutBuffer.slice(0, nl);
40783
+ stdoutBuffer = stdoutBuffer.slice(nl + 1);
40784
+ processLine(line);
40785
+ }
40786
+ if (stdoutBuffer.length > maxBufferBytes) {
40787
+ process.stderr.write(
40788
+ `[${label}] stdout buffer exceeded ${maxBufferBytes} bytes without a newline \u2014 discarding partial line
40789
+ `
40790
+ );
40791
+ stdoutBuffer = "";
40792
+ }
40793
+ });
40794
+ proc.stdout.on("end", () => {
40795
+ if (stdoutBuffer.length > 0) {
40796
+ processLine(stdoutBuffer);
40797
+ stdoutBuffer = "";
40798
+ }
40799
+ });
40800
+ proc.stderr.setEncoding("utf8");
40801
+ proc.stderr.on("data", (chunk) => {
40802
+ const trimmed = chunk.trimEnd();
40803
+ if (trimmed) {
40804
+ process.stderr.write(`[${label}/stderr] ${trimmed}
40805
+ `);
40806
+ }
40807
+ });
40808
+ proc.on("error", (err) => {
40809
+ clearTimers();
40810
+ reject(err);
40811
+ });
40812
+ proc.on("exit", (code, signal) => {
40813
+ clearTimers();
40814
+ const elapsedMs = Date.now() - startedAt;
40815
+ const ctx = [
40816
+ `elapsed=${elapsedMs}ms`,
40817
+ `exit=${code}`,
40818
+ signal ? `signal=${signal}` : null,
40819
+ timedOut ? `timedOut=true (cap=${timeoutMs}ms)` : null,
40820
+ `events=${eventTypesSeen.length}`,
40821
+ eventTypesSeen.length > 0 ? `event_types=[${[...new Set(eventTypesSeen)].join(",")}]` : null
40822
+ ].filter((x2) => x2 !== null).join(" ");
40823
+ if (timedOut || signal != null || code != null && code !== 0) {
40824
+ reject(
40825
+ new Error(
40826
+ `runPiOneShot: pi terminated abnormally before completing (${ctx})`
40827
+ )
40828
+ );
40829
+ return;
40830
+ }
40831
+ if (assistantText.trim()) {
40832
+ resolve2(assistantText);
40833
+ return;
40834
+ }
40835
+ reject(
40836
+ new Error(
40837
+ `runPiOneShot: pi produced no text output (${ctx})`
40838
+ )
40839
+ );
40840
+ });
40841
+ });
40842
+ }
40843
+
40844
+ // ../baro-orchestrator/src/planning/planner-pi.ts
40845
+ async function runPlannerPi(opts) {
40846
+ const modeContract = opts.modeContract ?? await runPiIntake(opts).catch((e2) => {
40847
+ process.stderr.write(`[planner-pi] intake failed (${e2?.message ?? String(e2)}) \u2014 using heuristic mode contract
40848
+ `);
40849
+ return heuristicModeContract(opts);
40850
+ });
40851
+ process.stderr.write(`[planner-pi] intake mode=${modeContract.mode} confidence=${modeContract.confidence}
40852
+ `);
40853
+ const userMessage = buildPlannerUserMessage({
40854
+ goal: opts.goal,
40855
+ decisionDocument: opts.decisionDocument,
40856
+ quick: opts.quick,
40857
+ projectContext: opts.projectContext,
40858
+ modeContract
40859
+ });
40860
+ const prompt = `${PLANNER_SYSTEM_PROMPT}
40861
+
40862
+ ${userMessage}`;
40863
+ const text = await runPiOneShot({
40864
+ prompt,
40865
+ cwd: opts.cwd,
40866
+ provider: opts.provider,
40867
+ model: opts.model,
40868
+ piBin: opts.piBin,
40869
+ timeoutMs: opts.timeoutMs ?? 9e5,
40870
+ label: "pi-planner"
40871
+ });
40872
+ const planText = text.trim();
40873
+ if (!planText) {
40874
+ throw new Error("PlannerPi: pi returned empty result");
40875
+ }
40876
+ return extractJsonObject5(planText);
40877
+ }
40878
+ async function runPiIntake(opts) {
40879
+ if (opts.quick) return heuristicModeContract(opts);
40880
+ const text = await runPiOneShot({
40881
+ prompt: `You classify software tasks for an autonomous PR workflow. Output JSON only.
40882
+
40883
+ ${buildIntakePrompt(opts)}`,
40884
+ cwd: opts.cwd,
40885
+ provider: opts.provider,
40886
+ model: opts.model,
40887
+ piBin: opts.piBin,
40888
+ timeoutMs: Math.min(opts.timeoutMs ?? 9e5, 18e4),
40889
+ label: "pi-intake"
40890
+ });
40891
+ return parseModeContract(text.trim());
40892
+ }
40893
+ function extractJsonObject5(text) {
40894
+ const trimmed = text.trim();
40895
+ if (trimmed.startsWith("{") && trimmed.endsWith("}")) return trimmed;
40896
+ const fence = trimmed.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/);
40897
+ if (fence) return fence[1];
40898
+ const start = trimmed.indexOf("{");
40899
+ if (start < 0) {
40900
+ throw new Error(
40901
+ `PlannerPi: no JSON object in response: ${trimmed.slice(0, 200)}`
40902
+ );
40903
+ }
40904
+ let depth = 0;
40905
+ for (let i2 = start; i2 < trimmed.length; i2++) {
40906
+ const ch = trimmed[i2];
40907
+ if (ch === "{") depth++;
40908
+ else if (ch === "}") {
40909
+ depth--;
40910
+ if (depth === 0) return trimmed.slice(start, i2 + 1);
40911
+ }
40912
+ }
40913
+ throw new Error(
40914
+ `PlannerPi: unbalanced JSON in response: ${trimmed.slice(0, 200)}`
40915
+ );
40916
+ }
40917
+
40918
+ // ../baro-orchestrator/src/planning/mode-enforcement.ts
40919
+ function enforceModeContract(prdJson, contract, goal) {
40920
+ let prd;
40921
+ try {
40922
+ prd = JSON.parse(prdJson);
40923
+ } catch {
40924
+ return prdJson;
40925
+ }
40926
+ if (!Array.isArray(prd.userStories)) return prdJson;
40927
+ let stories = prd.userStories;
40928
+ if (contract.mode === "focused" && stories.length > 1) {
40929
+ process.stderr.write(
40930
+ `[run-planner] contract violation: focused mode but planner emitted ${stories.length} stories \u2014 collapsing to one
40931
+ `
40932
+ );
40933
+ const first = stories[0];
40934
+ const steps = stories.map((s2) => `- ${s2.title}${s2.description ? `: ${s2.description}` : ""}`).join("\n");
40935
+ stories = [
40936
+ {
40937
+ ...first,
40938
+ id: "S1",
40939
+ priority: 1,
40940
+ title: first.title,
40941
+ description: `${goal.trim()}
40942
+
40943
+ Implement all of the following as ONE coherent change:
40944
+ ${steps}`,
40945
+ dependsOn: [],
40946
+ acceptance: [...new Set(stories.flatMap((s2) => s2.acceptance ?? []))],
40947
+ tests: [...new Set(stories.flatMap((s2) => s2.tests ?? []))],
40948
+ model: first.model ?? "opus"
40949
+ }
40950
+ ];
40951
+ } else if (contract.maxStories && stories.length > contract.maxStories) {
40952
+ process.stderr.write(
40953
+ `[run-planner] contract violation: ${stories.length} stories > maxStories=${contract.maxStories} \u2014 trimming
40954
+ `
40955
+ );
40956
+ const kept = [];
40957
+ const keptIds = /* @__PURE__ */ new Set();
40958
+ for (const s2 of [...stories].sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0))) {
40959
+ if (kept.length >= contract.maxStories) break;
40960
+ if ((s2.dependsOn ?? []).every((d) => keptIds.has(d))) {
40961
+ kept.push(s2);
40962
+ keptIds.add(s2.id);
40963
+ }
40964
+ }
40965
+ if (kept.length > 0) stories = kept;
40966
+ }
40967
+ prd.userStories = stories;
40968
+ prd.executionMode = {
40969
+ mode: contract.mode,
40970
+ reason: contract.reason,
40971
+ confidence: contract.confidence,
40972
+ maxStories: contract.maxStories,
40973
+ parallelism: contract.parallelism,
40974
+ source: contract.source ?? "contract"
40975
+ };
40976
+ return JSON.stringify(prd);
40977
+ }
40978
+
40979
+ // ../baro-orchestrator/scripts/run-planner.ts
40980
+ function parseArgs(argv) {
40981
+ let goal;
40982
+ let cwd;
40983
+ let llm;
40984
+ let model;
40985
+ let effort;
40986
+ let contextFile;
40987
+ let decisionFile;
40988
+ let modeFile;
40989
+ let quick = false;
40990
+ for (let i2 = 0; i2 < argv.length; i2++) {
40991
+ const a = argv[i2];
40992
+ switch (a) {
40993
+ case "--goal":
40994
+ goal = required(argv, ++i2, "--goal");
40995
+ break;
40996
+ case "--cwd":
40997
+ cwd = required(argv, ++i2, "--cwd");
40998
+ break;
40999
+ case "--llm": {
41000
+ const v = required(argv, ++i2, "--llm");
41001
+ if (v !== "claude" && v !== "openai" && v !== "codex" && v !== "opencode" && v !== "pi") {
41002
+ fatal(`--llm must be 'claude' | 'openai' | 'codex' | 'opencode' | 'pi', got '${v}'`);
41003
+ }
41004
+ llm = v;
41005
+ break;
41006
+ }
41007
+ case "--model":
41008
+ model = required(argv, ++i2, "--model");
41009
+ break;
41010
+ case "--effort":
41011
+ effort = required(argv, ++i2, "--effort");
41012
+ break;
41013
+ case "--context-file":
41014
+ contextFile = required(argv, ++i2, "--context-file");
41015
+ break;
41016
+ case "--decision-file":
41017
+ decisionFile = required(argv, ++i2, "--decision-file");
41018
+ break;
41019
+ case "--mode-file":
41020
+ modeFile = required(argv, ++i2, "--mode-file");
41021
+ break;
41022
+ case "--quick":
41023
+ quick = true;
41024
+ break;
41025
+ default:
41026
+ fatal(`unknown flag: ${a}`);
41027
+ }
41028
+ }
41029
+ if (!goal) fatal("--goal is required");
41030
+ if (!cwd) fatal("--cwd is required");
41031
+ if (!llm) fatal("--llm is required");
41032
+ return {
41033
+ goal,
41034
+ cwd,
41035
+ llm,
41036
+ model,
41037
+ effort,
41038
+ contextFile,
41039
+ decisionFile,
41040
+ modeFile,
41041
+ quick
41042
+ };
41043
+ }
41044
+ function required(argv, i2, flag) {
41045
+ const v = argv[i2];
41046
+ if (v == null) fatal(`flag ${flag} requires a value`);
41047
+ return v;
41048
+ }
41049
+ function fatal(msg) {
41050
+ process.stderr.write(`[run-planner] ${msg}
41051
+ `);
41052
+ process.exit(2);
41053
+ }
41054
+ function tryRead(path5) {
41055
+ if (!path5) return void 0;
41056
+ try {
41057
+ return readFileSync2(path5, "utf-8");
41058
+ } catch (e2) {
41059
+ process.stderr.write(
41060
+ `[run-planner] warning: could not read ${path5}: ${e2.message}
41061
+ `
41062
+ );
41063
+ return void 0;
41064
+ }
41065
+ }
41066
+ async function main() {
41067
+ const args = parseArgs(process.argv.slice(2));
41068
+ const projectContext = tryRead(args.contextFile);
41069
+ const decisionDocument = tryRead(args.decisionFile);
41070
+ let modeContract;
41071
+ const modeJson = tryRead(args.modeFile);
41072
+ if (modeJson) {
41073
+ try {
41074
+ modeContract = parseModeContract(modeJson);
41075
+ } catch (e2) {
41076
+ process.stderr.write(
41077
+ `[run-planner] warning: invalid --mode-file (${e2.message}) \u2014 planner will run its own intake
41078
+ `
41079
+ );
41080
+ }
41081
+ }
41082
+ process.stderr.write(
41083
+ `[run-planner] llm=${args.llm} model=${args.model ?? "(default)"} quick=${args.quick}` + (modeContract ? ` mode=${modeContract.mode} (pre-decided)` : "") + "\n"
41084
+ );
41085
+ let prdJson;
41086
+ const t0 = Date.now();
41087
+ try {
41088
+ if (args.llm === "openai") {
41089
+ if (!process.env.OPENAI_API_KEY) {
41090
+ fatal("--llm openai requires OPENAI_API_KEY to be set");
41091
+ }
41092
+ prdJson = await runPlannerOpenAI({
41093
+ goal: args.goal,
41094
+ cwd: args.cwd,
41095
+ model: args.model,
41096
+ projectContext,
41097
+ decisionDocument,
41098
+ quick: args.quick,
41099
+ modeContract
41100
+ });
41101
+ } else if (args.llm === "codex") {
41102
+ prdJson = await runPlannerCodex({
41103
+ goal: args.goal,
41104
+ cwd: args.cwd,
41105
+ model: args.model,
41106
+ projectContext,
41107
+ decisionDocument,
41108
+ quick: args.quick,
41109
+ modeContract
41110
+ });
41111
+ } else if (args.llm === "opencode") {
41112
+ prdJson = await runPlannerOpenCode({
41113
+ goal: args.goal,
41114
+ cwd: args.cwd,
41115
+ model: args.model,
41116
+ projectContext,
41117
+ decisionDocument,
41118
+ quick: args.quick,
41119
+ modeContract
41120
+ });
41121
+ } else if (args.llm === "pi") {
41122
+ prdJson = await runPlannerPi({
41123
+ goal: args.goal,
41124
+ cwd: args.cwd,
41125
+ model: args.model,
41126
+ projectContext,
41127
+ decisionDocument,
41128
+ quick: args.quick,
41129
+ modeContract
41130
+ });
41131
+ } else {
41132
+ prdJson = await runPlannerClaude({
41133
+ goal: args.goal,
41134
+ cwd: args.cwd,
41135
+ model: args.model,
41136
+ effort: args.effort,
41137
+ projectContext,
41138
+ decisionDocument,
41139
+ quick: args.quick,
41140
+ modeContract
41141
+ });
41142
+ }
41143
+ } catch (e2) {
41144
+ process.stderr.write(
41145
+ `[run-planner] FAILED after ${Date.now() - t0}ms: ${e2?.message ?? String(e2)}
41146
+ `
41147
+ );
41148
+ process.exit(1);
41149
+ }
41150
+ if (modeContract) {
41151
+ prdJson = enforceModeContract(prdJson, modeContract, args.goal);
41152
+ }
41153
+ process.stderr.write(
41154
+ `[run-planner] ok in ${Date.now() - t0}ms (${prdJson.length} chars)
41155
+ `
41156
+ );
41157
+ process.stdout.write(prdJson);
41158
+ }
41159
+ main().catch((e2) => {
41160
+ process.stderr.write(`[run-planner] crashed: ${e2?.stack ?? String(e2)}
41161
+ `);
41162
+ process.exit(3);
41163
+ });
38607
41164
  /*! Bundled license information:
38608
41165
 
38609
41166
  web-streams-polyfill/dist/ponyfill.es2018.js: