@waitcher/cli 0.2.24 → 0.2.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -2976,12 +2976,12 @@ var require_diagnostics = __commonJS({
2976
2976
  diagnosticsChannel.subscribe(
2977
2977
  "undici:websocket:close",
2978
2978
  (evt) => {
2979
- const { websocket, code, reason } = evt;
2979
+ const { websocket, code, reason: reason2 } = evt;
2980
2980
  debugLog(
2981
2981
  "closed connection to %s - %s %s",
2982
2982
  websocket.url,
2983
2983
  code,
2984
- reason
2984
+ reason2
2985
2985
  );
2986
2986
  }
2987
2987
  );
@@ -4296,7 +4296,7 @@ var require_util2 = __commonJS({
4296
4296
  var { redirectStatusSet, referrerPolicyTokens, badPortsSet } = require_constants2();
4297
4297
  var { getGlobalOrigin } = require_global();
4298
4298
  var { collectAnHTTPQuotedString, parseMIMEType } = require_data_url();
4299
- var { performance: performance6 } = __require("node:perf_hooks");
4299
+ var { performance: performance7 } = __require("node:perf_hooks");
4300
4300
  var { isValidHTTPToken, normalizedMethodRecordsBase } = require_util();
4301
4301
  var assert2 = __require("node:assert");
4302
4302
  var { isUint8Array } = __require("node:util/types");
@@ -4454,7 +4454,7 @@ var require_util2 = __commonJS({
4454
4454
  };
4455
4455
  }
4456
4456
  function coarsenedSharedCurrentTime(crossOriginIsolatedCapability) {
4457
- return coarsenTime(performance6.now(), crossOriginIsolatedCapability);
4457
+ return coarsenTime(performance7.now(), crossOriginIsolatedCapability);
4458
4458
  }
4459
4459
  function createOpaqueTimingInfo(timingInfo) {
4460
4460
  return {
@@ -5358,11 +5358,11 @@ var require_request = __commonJS({
5358
5358
  this[kResume]?.();
5359
5359
  }
5360
5360
  }
5361
- abort(reason) {
5361
+ abort(reason2) {
5362
5362
  if (!this.#aborted) {
5363
5363
  this.#aborted = true;
5364
- this.#reason = reason;
5365
- this.#abort(reason);
5364
+ this.#reason = reason2;
5365
+ this.#abort(reason2);
5366
5366
  }
5367
5367
  }
5368
5368
  get aborted() {
@@ -9070,9 +9070,9 @@ var require_parser_h1 = __commonJS({
9070
9070
  const errorCode = this.parserFields[this.milo.ParserFields.ERROR_CODE];
9071
9071
  const errorName = this.milo.Errors[errorCode];
9072
9072
  const errorDescription = errorName === "UNEXPECTED_EOF" ? "Invalid EOF state" : this.milo.getErrorDescription(this.parser);
9073
- const reason = errorName === "UNEXPECTED_EOF" ? errorDescription : errorDescription ? `[ERROR_${errorName}] ${errorDescription}` : `ERROR_${errorName}`;
9073
+ const reason2 = errorName === "UNEXPECTED_EOF" ? errorDescription : errorDescription ? `[ERROR_${errorName}] ${errorDescription}` : `ERROR_${errorName}`;
9074
9074
  return new HTTPParserError(
9075
- `Response does not match the HTTP/1.1 protocol (${reason})`,
9075
+ `Response does not match the HTTP/1.1 protocol (${reason2})`,
9076
9076
  errorName,
9077
9077
  data
9078
9078
  );
@@ -9882,8 +9882,8 @@ var require_body = __commonJS({
9882
9882
  }
9883
9883
  }
9884
9884
  },
9885
- cancel(reason) {
9886
- return action()[Symbol.asyncIterator]?.().return(reason);
9885
+ cancel(reason2) {
9886
+ return action()[Symbol.asyncIterator]?.().return(reason2);
9887
9887
  },
9888
9888
  type: "bytes"
9889
9889
  });
@@ -14399,7 +14399,7 @@ var require_dispatcher1_wrapper = __commonJS({
14399
14399
  this.#handler = handler;
14400
14400
  }
14401
14401
  onRequestStart(controller2, context) {
14402
- this.#handler.onConnect?.((reason) => controller2.abort(reason), context);
14402
+ this.#handler.onConnect?.((reason2) => controller2.abort(reason2), context);
14403
14403
  }
14404
14404
  onRequestUpgrade(controller2, statusCode, headers, socket) {
14405
14405
  const rawHeaders = Array.isArray(controller2?.rawHeaders) ? controller2.rawHeaders : toRawHeaders(controller2?.rawHeaders ?? headers ?? {});
@@ -15769,9 +15769,9 @@ var require_retry_handler = __commonJS({
15769
15769
  this.#paused = false;
15770
15770
  this.#target?.resume();
15771
15771
  }
15772
- abort(reason) {
15773
- this.#target?.abort(reason);
15774
- this.#onAbort(reason);
15772
+ abort(reason2) {
15773
+ this.#target?.abort(reason2);
15774
+ this.#onAbort(reason2);
15775
15775
  }
15776
15776
  get paused() {
15777
15777
  return this.#paused || (this.#target?.paused ?? false);
@@ -15855,7 +15855,7 @@ var require_retry_handler = __commonJS({
15855
15855
  this.etag = null;
15856
15856
  this.statusCode = null;
15857
15857
  this.headers = null;
15858
- this.controllerProxy = new RetryController((reason) => this.#onAbort(reason));
15858
+ this.controllerProxy = new RetryController((reason2) => this.#onAbort(reason2));
15859
15859
  this.retryPending = false;
15860
15860
  this.retryTimer = null;
15861
15861
  this.pendingResponseData = null;
@@ -16182,7 +16182,7 @@ var require_retry_handler = __commonJS({
16182
16182
  shouldRetry.bind(this)
16183
16183
  ) ?? null;
16184
16184
  }
16185
- #onAbort(reason) {
16185
+ #onAbort(reason2) {
16186
16186
  if (!this.retryPending) {
16187
16187
  return;
16188
16188
  }
@@ -16193,7 +16193,7 @@ var require_retry_handler = __commonJS({
16193
16193
  this.pendingResponseData = null;
16194
16194
  this.pendingResponseTrailers = null;
16195
16195
  this.pendingResponseEnded = false;
16196
- this.handler.onResponseError?.(this.controllerProxy, reason ?? new RequestAbortedError());
16196
+ this.handler.onResponseError?.(this.controllerProxy, reason2 ?? new RequestAbortedError());
16197
16197
  }
16198
16198
  };
16199
16199
  function isReplacedHeader(key, etag) {
@@ -16815,7 +16815,7 @@ var require_api_request = __commonJS({
16815
16815
  }
16816
16816
  assert2(this.callback);
16817
16817
  this.controller = controller2;
16818
- this.abort = (reason) => controller2.abort(reason);
16818
+ this.abort = (reason2) => controller2.abort(reason2);
16819
16819
  this.context = context;
16820
16820
  }
16821
16821
  onResponseStart(controller2, statusCode, headers, statusText) {
@@ -16833,7 +16833,7 @@ var require_api_request = __commonJS({
16833
16833
  const contentLength = parsedHeaders?.["content-length"];
16834
16834
  const res = new Readable({
16835
16835
  resume: () => controller2.resume(),
16836
- abort: (reason) => controller2.abort(reason),
16836
+ abort: (reason2) => controller2.abort(reason2),
16837
16837
  contentType,
16838
16838
  contentLength: this.method !== "HEAD" && contentLength ? Number(contentLength) : null,
16839
16839
  highWaterMark
@@ -17095,7 +17095,7 @@ var require_api_stream = __commonJS({
17095
17095
  }
17096
17096
  assert2(this.callback);
17097
17097
  this.controller = controller2;
17098
- this.abort = (reason) => controller2.abort(reason);
17098
+ this.abort = (reason2) => controller2.abort(reason2);
17099
17099
  this.context = context;
17100
17100
  }
17101
17101
  onResponseStart(controller2, statusCode, headers, _statusMessage) {
@@ -17328,7 +17328,7 @@ var require_api_pipeline = __commonJS({
17328
17328
  return;
17329
17329
  }
17330
17330
  assert2(!res, "pipeline cannot be retried");
17331
- this.abort = (reason) => controller2.abort(reason);
17331
+ this.abort = (reason2) => controller2.abort(reason2);
17332
17332
  this.context = context;
17333
17333
  }
17334
17334
  onResponseStart(controller2, statusCode, headers, _statusMessage) {
@@ -17445,7 +17445,7 @@ var require_api_upgrade = __commonJS({
17445
17445
  return;
17446
17446
  }
17447
17447
  assert2(this.callback);
17448
- this.abort = (reason) => controller2.abort(reason);
17448
+ this.abort = (reason2) => controller2.abort(reason2);
17449
17449
  this.context = context;
17450
17450
  }
17451
17451
  onResponseStart() {
@@ -17543,7 +17543,7 @@ var require_api_connect = __commonJS({
17543
17543
  return;
17544
17544
  }
17545
17545
  assert2(this.callback);
17546
- this.abort = (reason) => controller2.abort(reason);
17546
+ this.abort = (reason2) => controller2.abort(reason2);
17547
17547
  this.context = context;
17548
17548
  }
17549
17549
  onResponseStart() {
@@ -17967,7 +17967,7 @@ var require_mock_utils = __commonJS({
17967
17967
  resume() {
17968
17968
  this.paused = false;
17969
17969
  },
17970
- abort: (reason) => {
17970
+ abort: (reason2) => {
17971
17971
  if (aborted2) {
17972
17972
  return;
17973
17973
  }
@@ -17976,7 +17976,7 @@ var require_mock_utils = __commonJS({
17976
17976
  clearTimeout(timer);
17977
17977
  timer = null;
17978
17978
  }
17979
- handler.onResponseError?.(controller2, reason);
17979
+ handler.onResponseError?.(controller2, reason2);
17980
17980
  }
17981
17981
  };
17982
17982
  let replyOpts = opts;
@@ -19605,9 +19605,9 @@ var require_snapshot_agent = __commonJS({
19605
19605
  },
19606
19606
  resume() {
19607
19607
  },
19608
- abort(reason) {
19608
+ abort(reason2) {
19609
19609
  this.aborted = true;
19610
- this.reason = reason;
19610
+ this.reason = reason2;
19611
19611
  },
19612
19612
  aborted: false,
19613
19613
  paused: false
@@ -20234,9 +20234,9 @@ var require_dump = __commonJS({
20234
20234
  super(handler);
20235
20235
  this.#maxSize = maxSize ?? this.#maxSize;
20236
20236
  }
20237
- #abort(reason) {
20237
+ #abort(reason2) {
20238
20238
  this.aborted = true;
20239
- this.reason = reason;
20239
+ this.reason = reason2;
20240
20240
  }
20241
20241
  onRequestStart(controller2, context) {
20242
20242
  controller2.abort = this.#abort.bind(this);
@@ -21835,8 +21835,8 @@ var require_cache_handler = __commonJS({
21835
21835
  this.target.resume();
21836
21836
  }
21837
21837
  }
21838
- abort(reason) {
21839
- this.target.abort(reason);
21838
+ abort(reason2) {
21839
+ this.target.abort(reason2);
21840
21840
  }
21841
21841
  get paused() {
21842
21842
  return this.#downstreamPaused;
@@ -22955,9 +22955,9 @@ var require_cache2 = __commonJS({
22955
22955
  resume() {
22956
22956
  this.paused = false;
22957
22957
  },
22958
- abort: (reason) => {
22958
+ abort: (reason2) => {
22959
22959
  aborted2 = true;
22960
- handler.onResponseError?.(controller2, reason ?? new AbortError());
22960
+ handler.onResponseError?.(controller2, reason2 ?? new AbortError());
22961
22961
  }
22962
22962
  };
22963
22963
  try {
@@ -23003,12 +23003,12 @@ var require_cache2 = __commonJS({
23003
23003
  get reason() {
23004
23004
  return abortReason;
23005
23005
  },
23006
- abort(reason) {
23006
+ abort(reason2) {
23007
23007
  if (aborted2) {
23008
23008
  return;
23009
23009
  }
23010
23010
  aborted2 = true;
23011
- abortReason = reason ?? new AbortError();
23011
+ abortReason = reason2 ?? new AbortError();
23012
23012
  stream.destroy(abortReason);
23013
23013
  }
23014
23014
  };
@@ -23274,9 +23274,9 @@ var require_decompress = __commonJS({
23274
23274
  this.#paused = false;
23275
23275
  this.#onResume();
23276
23276
  }
23277
- abort(reason) {
23278
- this.target?.abort(reason);
23279
- this.#onAbort(reason);
23277
+ abort(reason2) {
23278
+ this.target?.abort(reason2);
23279
+ this.#onAbort(reason2);
23280
23280
  }
23281
23281
  get paused() {
23282
23282
  return this.#paused;
@@ -23380,9 +23380,9 @@ var require_decompress = __commonJS({
23380
23380
  this.#controller = new DecompressController(
23381
23381
  () => this.#onDownstreamPause(),
23382
23382
  () => this.#onDownstreamResume(),
23383
- (reason) => {
23383
+ (reason2) => {
23384
23384
  if (this.#inputEnded && !this.#terminated) {
23385
- this.onResponseError(this.#controller, reason);
23385
+ this.onResponseError(this.#controller, reason2);
23386
23386
  }
23387
23387
  }
23388
23388
  );
@@ -24038,12 +24038,12 @@ var require_deduplication_handler = __commonJS({
24038
24038
  get reason() {
24039
24039
  return state.reason;
24040
24040
  },
24041
- abort: (reason) => {
24041
+ abort: (reason2) => {
24042
24042
  if (state.aborted) {
24043
24043
  return;
24044
24044
  }
24045
24045
  state.aborted = true;
24046
- state.reason = reason ?? null;
24046
+ state.reason = reason2 ?? null;
24047
24047
  waitingHandler.done = true;
24048
24048
  waitingHandler.pendingTrailers = null;
24049
24049
  waitingHandler.bufferedChunks = [];
@@ -25329,13 +25329,13 @@ var require_response = __commonJS({
25329
25329
  urlList: init?.urlList ? [...init.urlList] : []
25330
25330
  };
25331
25331
  }
25332
- function makeNetworkError(reason) {
25333
- const isError = isErrorLike(reason);
25332
+ function makeNetworkError(reason2) {
25333
+ const isError = isErrorLike(reason2);
25334
25334
  return makeResponse({
25335
25335
  type: "error",
25336
25336
  status: 0,
25337
- error: isError ? reason : new Error(reason ? String(reason) : reason),
25338
- aborted: reason && reason.name === "AbortError"
25337
+ error: isError ? reason2 : new Error(reason2 ? String(reason2) : reason2),
25338
+ aborted: reason2 && reason2.name === "AbortError"
25339
25339
  });
25340
25340
  }
25341
25341
  function isNetworkError(response) {
@@ -26490,13 +26490,13 @@ var require_fetch = __commonJS({
26490
26490
  this.dump = false;
26491
26491
  this.state = "ongoing";
26492
26492
  }
26493
- terminate(reason) {
26493
+ terminate(reason2) {
26494
26494
  if (this.state !== "ongoing") {
26495
26495
  return;
26496
26496
  }
26497
26497
  this.state = "terminated";
26498
- this.connection?.destroy(reason);
26499
- this.emit("terminated", reason);
26498
+ this.connection?.destroy(reason2);
26499
+ this.emit("terminated", reason2);
26500
26500
  }
26501
26501
  // https://fetch.spec.whatwg.org/#fetch-controller-abort
26502
26502
  abort(error62) {
@@ -26785,7 +26785,7 @@ var require_fetch = __commonJS({
26785
26785
  fetchParams.controller.dump = true;
26786
26786
  }
26787
26787
  if (request2.integrity) {
26788
- const processBodyError = (reason) => fetchFinale(fetchParams, makeNetworkError(reason));
26788
+ const processBodyError = (reason2) => fetchFinale(fetchParams, makeNetworkError(reason2));
26789
26789
  if (request2.responseTainting === "opaque" || response.body == null) {
26790
26790
  processBodyError(response.error);
26791
26791
  return;
@@ -27305,9 +27305,9 @@ var require_fetch = __commonJS({
27305
27305
  const pullAlgorithm = () => {
27306
27306
  return fetchParams.controller.resume();
27307
27307
  };
27308
- const cancelAlgorithm = (reason) => {
27308
+ const cancelAlgorithm = (reason2) => {
27309
27309
  if (!isCancelled(fetchParams)) {
27310
- fetchParams.controller.abort(reason);
27310
+ fetchParams.controller.abort(reason2);
27311
27311
  }
27312
27312
  };
27313
27313
  const stream = new ReadableStream(
@@ -27365,7 +27365,7 @@ var require_fetch = __commonJS({
27365
27365
  }
27366
27366
  }
27367
27367
  };
27368
- function onAborted(reason) {
27368
+ function onAborted(reason2) {
27369
27369
  if (isAborted(fetchParams)) {
27370
27370
  response.aborted = true;
27371
27371
  if (isReadable(stream)) {
@@ -27376,7 +27376,7 @@ var require_fetch = __commonJS({
27376
27376
  } else {
27377
27377
  if (isReadable(stream)) {
27378
27378
  fetchParams.controller.controller.error(new TypeError("terminated", {
27379
- cause: isErrorLike(reason) ? reason : void 0
27379
+ cause: isErrorLike(reason2) ? reason2 : void 0
27380
27380
  }));
27381
27381
  }
27382
27382
  }
@@ -27409,7 +27409,7 @@ var require_fetch = __commonJS({
27409
27409
  onRequestStart(controller2) {
27410
27410
  const { connection } = fetchParams.controller;
27411
27411
  timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(void 0, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability);
27412
- const abort = (reason) => controller2.abort(reason);
27412
+ const abort = (reason2) => controller2.abort(reason2);
27413
27413
  if (connection.destroyed) {
27414
27414
  abort(new DOMException("The operation was aborted.", "AbortError"));
27415
27415
  } else {
@@ -29228,14 +29228,14 @@ var require_util5 = __commonJS({
29228
29228
  }
29229
29229
  return urlRecord;
29230
29230
  }
29231
- function validateCloseCodeAndReason(code, reason) {
29231
+ function validateCloseCodeAndReason(code, reason2) {
29232
29232
  if (code !== null) {
29233
29233
  if (code !== 1e3 && (code < 3e3 || code > 4999)) {
29234
29234
  throw new DOMException("invalid code", "InvalidAccessError");
29235
29235
  }
29236
29236
  }
29237
- if (reason !== null) {
29238
- const reasonBytesLength = Buffer.byteLength(reason);
29237
+ if (reason2 !== null) {
29238
+ const reasonBytesLength = Buffer.byteLength(reason2);
29239
29239
  if (reasonBytesLength > 123) {
29240
29240
  throw new DOMException(`Reason must be less than 123 bytes; received ${reasonBytesLength}`, "SyntaxError");
29241
29241
  }
@@ -29485,29 +29485,29 @@ var require_connection = __commonJS({
29485
29485
  });
29486
29486
  return controller2;
29487
29487
  }
29488
- function closeWebSocketConnection(object2, code, reason, validate2 = false) {
29488
+ function closeWebSocketConnection(object2, code, reason2, validate2 = false) {
29489
29489
  code ??= null;
29490
- reason ??= "";
29491
- if (validate2) validateCloseCodeAndReason(code, reason);
29490
+ reason2 ??= "";
29491
+ if (validate2) validateCloseCodeAndReason(code, reason2);
29492
29492
  if (isClosed(object2.readyState) || isClosing(object2.readyState)) {
29493
29493
  } else if (!isEstablished(object2.readyState)) {
29494
29494
  failWebsocketConnection(object2);
29495
29495
  object2.readyState = states.CLOSING;
29496
29496
  } else if (!object2.closeState.has(sentCloseFrameState.SENT) && !object2.closeState.has(sentCloseFrameState.RECEIVED)) {
29497
29497
  const frame = new WebsocketFrameSend();
29498
- if (reason.length !== 0 && code === null) {
29498
+ if (reason2.length !== 0 && code === null) {
29499
29499
  code = 1e3;
29500
29500
  }
29501
29501
  assert2(code === null || Number.isInteger(code));
29502
- if (code === null && reason.length === 0) {
29502
+ if (code === null && reason2.length === 0) {
29503
29503
  frame.frameData = emptyBuffer;
29504
- } else if (code !== null && reason === null) {
29504
+ } else if (code !== null && reason2 === null) {
29505
29505
  frame.frameData = Buffer.allocUnsafe(2);
29506
29506
  frame.frameData.writeUInt16BE(code, 0);
29507
- } else if (code !== null && reason !== null) {
29508
- frame.frameData = Buffer.allocUnsafe(2 + Buffer.byteLength(reason));
29507
+ } else if (code !== null && reason2 !== null) {
29508
+ frame.frameData = Buffer.allocUnsafe(2 + Buffer.byteLength(reason2));
29509
29509
  frame.frameData.writeUInt16BE(code, 0);
29510
- frame.frameData.write(reason, 2, "utf-8");
29510
+ frame.frameData.write(reason2, 2, "utf-8");
29511
29511
  } else {
29512
29512
  frame.frameData = emptyBuffer;
29513
29513
  }
@@ -29518,15 +29518,15 @@ var require_connection = __commonJS({
29518
29518
  object2.readyState = states.CLOSING;
29519
29519
  }
29520
29520
  }
29521
- function failHandshake(handler, response, code, reason, cause) {
29521
+ function failHandshake(handler, response, code, reason2, cause) {
29522
29522
  if (response.socket?.session != null && !response.socket.destroyed) {
29523
29523
  response.socket.destroy();
29524
29524
  }
29525
- failWebsocketConnection(handler, code, reason, cause);
29525
+ failWebsocketConnection(handler, code, reason2, cause);
29526
29526
  }
29527
- function failWebsocketConnection(handler, code, reason, cause) {
29527
+ function failWebsocketConnection(handler, code, reason2, cause) {
29528
29528
  if (isEstablished(handler.readyState)) {
29529
- closeWebSocketConnection(handler, code, reason, false);
29529
+ closeWebSocketConnection(handler, code, reason2, false);
29530
29530
  }
29531
29531
  handler.controller.abort();
29532
29532
  if (isConnecting(handler.readyState)) {
@@ -29936,16 +29936,16 @@ var require_receiver = __commonJS({
29936
29936
  if (code !== void 0 && !isValidStatusCode(code)) {
29937
29937
  return { code: 1002, reason: "Invalid status code", error: true };
29938
29938
  }
29939
- let reason = data.subarray(2);
29940
- if (reason[0] === 239 && reason[1] === 187 && reason[2] === 191) {
29941
- reason = reason.subarray(3);
29939
+ let reason2 = data.subarray(2);
29940
+ if (reason2[0] === 239 && reason2[1] === 187 && reason2[2] === 191) {
29941
+ reason2 = reason2.subarray(3);
29942
29942
  }
29943
29943
  try {
29944
- reason = utf8Decode(reason);
29944
+ reason2 = utf8Decode(reason2);
29945
29945
  } catch {
29946
29946
  return { code: 1007, reason: "Invalid UTF-8", error: true };
29947
29947
  }
29948
- return { code, reason, error: false };
29948
+ return { code, reason: reason2, error: false };
29949
29949
  }
29950
29950
  /**
29951
29951
  * Parses control frames.
@@ -29960,8 +29960,8 @@ var require_receiver = __commonJS({
29960
29960
  }
29961
29961
  this.#info.closeInfo = this.parseCloseBody(body2);
29962
29962
  if (this.#info.closeInfo.error) {
29963
- const { code, reason } = this.#info.closeInfo;
29964
- failWebsocketConnection(this.#handler, code, reason);
29963
+ const { code, reason: reason2 } = this.#info.closeInfo;
29964
+ failWebsocketConnection(this.#handler, code, reason2);
29965
29965
  return false;
29966
29966
  }
29967
29967
  if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
@@ -30233,18 +30233,18 @@ var require_websocket = __commonJS({
30233
30233
  * @param {number|undefined} code
30234
30234
  * @param {string|undefined} reason
30235
30235
  */
30236
- close(code = void 0, reason = void 0) {
30236
+ close(code = void 0, reason2 = void 0) {
30237
30237
  webidl.brandCheck(this, webidl.is.WebSocket);
30238
30238
  const prefix = "WebSocket.close";
30239
30239
  if (code !== void 0) {
30240
30240
  code = webidl.converters["unsigned short"](code, prefix, "code", webidl.attributes.Clamp);
30241
30241
  }
30242
- if (reason !== void 0) {
30243
- reason = webidl.converters.USVString(reason);
30242
+ if (reason2 !== void 0) {
30243
+ reason2 = webidl.converters.USVString(reason2);
30244
30244
  }
30245
30245
  code ??= null;
30246
- reason ??= "";
30247
- closeWebSocketConnection(this.#handler, code, reason, true);
30246
+ reason2 ??= "";
30247
+ closeWebSocketConnection(this.#handler, code, reason2, true);
30248
30248
  }
30249
30249
  /**
30250
30250
  * @see https://websockets.spec.whatwg.org/#dom-websocket-send
@@ -30461,29 +30461,29 @@ var require_websocket = __commonJS({
30461
30461
  #onSocketClose() {
30462
30462
  const wasClean = this.#handler.closeState.has(sentCloseFrameState.SENT) && this.#handler.closeState.has(sentCloseFrameState.RECEIVED);
30463
30463
  let code = 1005;
30464
- let reason = "";
30464
+ let reason2 = "";
30465
30465
  const result2 = this.#parser?.closingInfo;
30466
30466
  if (result2 && !result2.error) {
30467
30467
  code = result2.code ?? 1005;
30468
- reason = result2.reason;
30468
+ reason2 = result2.reason;
30469
30469
  }
30470
30470
  this.#handler.readyState = states.CLOSED;
30471
30471
  if (!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
30472
30472
  code = 1006;
30473
30473
  fireEvent("error", this, (type, init) => new ErrorEvent(type, init), {
30474
- error: new TypeError(reason)
30474
+ error: new TypeError(reason2)
30475
30475
  });
30476
30476
  }
30477
30477
  fireEvent("close", this, (type, init) => new CloseEvent(type, init), {
30478
30478
  wasClean,
30479
30479
  code,
30480
- reason
30480
+ reason: reason2
30481
30481
  });
30482
30482
  if (channels.close.hasSubscribers) {
30483
30483
  channels.close.publish({
30484
30484
  websocket: this,
30485
30485
  code,
30486
- reason
30486
+ reason: reason2
30487
30487
  });
30488
30488
  }
30489
30489
  }
@@ -30628,13 +30628,13 @@ var require_websocketerror = __commonJS({
30628
30628
  init = webidl.converters.WebSocketCloseInfo(init);
30629
30629
  }
30630
30630
  let code = init.closeCode ?? null;
30631
- const reason = init.reason ?? "";
30632
- validateCloseCodeAndReason(code, reason);
30633
- if (reason.length !== 0 && code === null) {
30631
+ const reason2 = init.reason ?? "";
30632
+ validateCloseCodeAndReason(code, reason2);
30633
+ if (reason2.length !== 0 && code === null) {
30634
30634
  code = 1e3;
30635
30635
  }
30636
30636
  this.#closeCode = code;
30637
- this.#reason = reason;
30637
+ this.#reason = reason2;
30638
30638
  }
30639
30639
  get closeCode() {
30640
30640
  return this.#closeCode;
@@ -30643,10 +30643,10 @@ var require_websocketerror = __commonJS({
30643
30643
  return this.#reason;
30644
30644
  }
30645
30645
  static {
30646
- createUnvalidatedWebSocketError = (message, code, reason) => {
30646
+ createUnvalidatedWebSocketError = (message, code, reason2) => {
30647
30647
  const error62 = new _WebSocketError(message, kConstruct);
30648
30648
  error62.#closeCode = code;
30649
- error62.#reason = reason;
30649
+ error62.#reason = reason2;
30650
30650
  return error62;
30651
30651
  };
30652
30652
  webidl.is.WebSocketError = (arg) => {
@@ -30807,8 +30807,8 @@ var require_websocketstream = __commonJS({
30807
30807
  closeInfo = webidl.converters.WebSocketCloseInfo(closeInfo);
30808
30808
  }
30809
30809
  const code = closeInfo.closeCode ?? null;
30810
- const reason = closeInfo.reason;
30811
- closeWebSocketConnection(this.#handler, code, reason, true);
30810
+ const reason2 = closeInfo.reason;
30811
+ closeWebSocketConnection(this.#handler, code, reason2, true);
30812
30812
  }
30813
30813
  #write(chunk) {
30814
30814
  chunk = webidl.converters.WebSocketStreamWrite(chunk);
@@ -30859,7 +30859,7 @@ var require_websocketstream = __commonJS({
30859
30859
  this.#readableStreamController = controller2;
30860
30860
  },
30861
30861
  pull: () => this.#pull(),
30862
- cancel: (reason) => this.#cancel(reason)
30862
+ cancel: (reason2) => this.#cancel(reason2)
30863
30863
  });
30864
30864
  const writable = new WritableStream({
30865
30865
  start: (controller2) => {
@@ -30867,7 +30867,7 @@ var require_websocketstream = __commonJS({
30867
30867
  },
30868
30868
  write: (chunk) => this.#write(chunk),
30869
30869
  close: () => closeWebSocketConnection(this.#handler, null, null),
30870
- abort: (reason) => this.#closeUsingReason(reason)
30870
+ abort: (reason2) => this.#closeUsingReason(reason2)
30871
30871
  });
30872
30872
  this.#readableStream = readable;
30873
30873
  this.#openedPromise.resolve({
@@ -30913,27 +30913,27 @@ var require_websocketstream = __commonJS({
30913
30913
  if (!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
30914
30914
  code = 1006;
30915
30915
  }
30916
- const reason = result2?.reason == null ? "" : utf8DecodeBytes(Buffer.from(result2.reason));
30916
+ const reason2 = result2?.reason == null ? "" : utf8DecodeBytes(Buffer.from(result2.reason));
30917
30917
  if (wasClean) {
30918
30918
  readableStreamClose(this.#readableStreamController);
30919
30919
  this.#writableStreamController.error(new DOMException("A closed WebSocketStream cannot be written to", "InvalidStateError"));
30920
30920
  this.#closedPromise.resolve({
30921
30921
  closeCode: code,
30922
- reason
30922
+ reason: reason2
30923
30923
  });
30924
30924
  } else {
30925
- const error62 = createUnvalidatedWebSocketError("unclean close", code, reason);
30925
+ const error62 = createUnvalidatedWebSocketError("unclean close", code, reason2);
30926
30926
  this.#readableStreamController?.error(error62);
30927
30927
  this.#writableStreamController?.error(error62);
30928
30928
  this.#closedPromise.reject(error62);
30929
30929
  }
30930
30930
  }
30931
- #closeUsingReason(reason) {
30931
+ #closeUsingReason(reason2) {
30932
30932
  let code = null;
30933
30933
  let reasonString = "";
30934
- if (webidl.is.WebSocketError(reason)) {
30935
- code = reason.closeCode;
30936
- reasonString = reason.reason;
30934
+ if (webidl.is.WebSocketError(reason2)) {
30935
+ code = reason2.closeCode;
30936
+ reasonString = reason2.reason;
30937
30937
  }
30938
30938
  closeWebSocketConnection(this.#handler, code, reasonString);
30939
30939
  }
@@ -30942,8 +30942,8 @@ var require_websocketstream = __commonJS({
30942
30942
  this.#handler.socket.resume();
30943
30943
  }
30944
30944
  // To cancel a WebSocketStream stream given reason , close using reason giving stream and reason .
30945
- #cancel(reason) {
30946
- this.#closeUsingReason(reason);
30945
+ #cancel(reason2) {
30946
+ this.#closeUsingReason(reason2);
30947
30947
  }
30948
30948
  };
30949
30949
  Object.defineProperties(WebSocketStream.prototype, {
@@ -35664,7 +35664,7 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
35664
35664
  }
35665
35665
  return propValues;
35666
35666
  });
35667
- const isObject2 = isObject;
35667
+ const isObject3 = isObject;
35668
35668
  const catchall = def.catchall;
35669
35669
  let value2;
35670
35670
  const memo2 = globalConfig.memoizer;
@@ -35672,7 +35672,7 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
35672
35672
  inst._zod.parse = (payload, ctx) => {
35673
35673
  value2 ?? (value2 = _normalized.value);
35674
35674
  const input2 = payload.value;
35675
- if (!isObject2(input2)) {
35675
+ if (!isObject3(input2)) {
35676
35676
  payload.issues.push({
35677
35677
  expected: "object",
35678
35678
  code: "invalid_type",
@@ -35808,7 +35808,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
35808
35808
  return doc.compile();
35809
35809
  };
35810
35810
  let fastpass;
35811
- const isObject2 = isObject;
35811
+ const isObject3 = isObject;
35812
35812
  const jit = !globalConfig.jitless;
35813
35813
  const allowsEval2 = allowsEval;
35814
35814
  const fastEnabled = jit && allowsEval2.value;
@@ -35817,7 +35817,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
35817
35817
  inst._zod.parse = (payload, ctx) => {
35818
35818
  value2 ?? (value2 = _normalized.value);
35819
35819
  const input2 = payload.value;
35820
- if (!isObject2(input2)) {
35820
+ if (!isObject3(input2)) {
35821
35821
  payload.issues.push({
35822
35822
  expected: "object",
35823
35823
  code: "invalid_type",
@@ -41452,8 +41452,8 @@ function ko_default() {
41452
41452
  }
41453
41453
 
41454
41454
  // ../../node_modules/zod/v4/locales/lt.js
41455
- var capitalizeFirstCharacter = (text3) => {
41456
- return text3.charAt(0).toUpperCase() + text3.slice(1);
41455
+ var capitalizeFirstCharacter = (text4) => {
41456
+ return text4.charAt(0).toUpperCase() + text4.slice(1);
41457
41457
  };
41458
41458
  function getUnitTypeFromNumber(number4) {
41459
41459
  const abs = Math.abs(number4);
@@ -45323,9 +45323,9 @@ function codePointLengthVar(doc, ctx, accessor, inDoubt) {
45323
45323
  doc.write(`const ${v} = typeof ${accessor} === "string" && ${inDoubt} ? ${cpLen}(${accessor}) : ${accessor}.length;`);
45324
45324
  return v;
45325
45325
  }
45326
- function numericOperand(value2, label) {
45326
+ function numericOperand(value2, label2) {
45327
45327
  if (typeof value2 !== "number" || !Number.isFinite(value2)) {
45328
- throw new ZodCompileUnsupportedError(`${label} bound of type ${typeof value2}`);
45328
+ throw new ZodCompileUnsupportedError(`${label2} bound of type ${typeof value2}`);
45329
45329
  }
45330
45330
  return `${value2}`;
45331
45331
  }
@@ -51846,19 +51846,78 @@ var httpTargetOriginSchema = external_exports.string().trim().min(1).max(2e3).re
51846
51846
  }, "Use a public HTTPS hostname origin on port 443 without a path, query, credentials or fragment").transform((value2) => new URL(value2).origin);
51847
51847
  var httpTargetCreateSchema = external_exports.object({ name, origin: httpTargetOriginSchema }).strict();
51848
51848
  var httpTargetRevisionSchema = external_exports.object({ expectedRevision: external_exports.number().int().positive() }).strict();
51849
+ var FORBIDDEN_CREDENTIAL_HEADERS = /* @__PURE__ */ new Set([
51850
+ "accept",
51851
+ "accept-encoding",
51852
+ "connection",
51853
+ "content-length",
51854
+ "content-type",
51855
+ "cookie",
51856
+ "expect",
51857
+ "host",
51858
+ "keep-alive",
51859
+ "mcp-protocol-version",
51860
+ "mcp-session-id",
51861
+ "origin",
51862
+ "range",
51863
+ "referer",
51864
+ "set-cookie",
51865
+ "te",
51866
+ "trailer",
51867
+ "transfer-encoding",
51868
+ "upgrade",
51869
+ "user-agent",
51870
+ "via"
51871
+ ]);
51872
+ var httpCredentialHeaderSchema = external_exports.string().min(1).max(64).regex(/^[A-Za-z0-9-]+$/, "Use letters, digits and hyphens in the header name").refine((value2) => {
51873
+ const key = value2.toLowerCase();
51874
+ return !(FORBIDDEN_CREDENTIAL_HEADERS.has(key) || /^(proxy-|sec-|x-forwarded-|cf-|if-)/.test(key));
51875
+ }, "This header is set by Waitcher or the transport and cannot carry a credential");
51849
51876
  var httpCredentialValueSchema = external_exports.string().min(1).max(HTTP_TARGET_LIMITS.credentialBytes).regex(
51850
51877
  /^[\x20-\x7e]+$/,
51851
51878
  "Use a printable ASCII credential without line breaks"
51852
51879
  );
51853
- var httpCredentialCreateSchema = external_exports.object({
51854
- targetId: external_exports.uuid(),
51855
- name,
51856
- header: external_exports.enum(["Authorization", "X-Api-Key"]),
51857
- value: httpCredentialValueSchema
51880
+ var OAUTH_GRANTS = ["client_credentials", "refresh_token"];
51881
+ var oauthTokenUrlSchema = external_exports.string().trim().min(1).max(2e3).refine((value2) => {
51882
+ try {
51883
+ const url3 = new URL(value2), host = url3.hostname;
51884
+ return url3.protocol === "https:" && (!url3.port || url3.port === "443") && !url3.username && !url3.password && !url3.hash && host.includes(".") && !host.startsWith("[") && !host.endsWith(".") && !/^[0-9.]+$/.test(host) && !/\.(localhost|local|internal|test|invalid)$/.test(host);
51885
+ } catch {
51886
+ return false;
51887
+ }
51888
+ }, "Use a public HTTPS token endpoint on port 443 without credentials or a fragment");
51889
+ var oauthText = (max) => external_exports.string().min(1).max(max).regex(/^[\x20-\x7e]+$/);
51890
+ var oauthSettingsSchema = external_exports.object({
51891
+ grant: external_exports.enum(OAUTH_GRANTS),
51892
+ tokenUrl: oauthTokenUrlSchema,
51893
+ clientId: oauthText(256),
51894
+ scope: oauthText(512).optional(),
51895
+ clientAuth: external_exports.enum(["post", "basic"]).default("post")
51858
51896
  }).strict();
51897
+ var oauthSecretSchema = external_exports.object({
51898
+ clientSecret: oauthText(2048).optional(),
51899
+ refreshToken: oauthText(2048).optional()
51900
+ }).strict();
51901
+ var oauthValueSchema = external_exports.string().min(1).max(5e3).regex(/^[\x20-\x7e]+$/, "Use a printable ASCII credential without line breaks");
51902
+ var httpCredentialCreateSchema = external_exports.union([
51903
+ external_exports.object({
51904
+ targetId: external_exports.uuid(),
51905
+ name,
51906
+ header: httpCredentialHeaderSchema,
51907
+ value: httpCredentialValueSchema
51908
+ }).strict(),
51909
+ external_exports.object({
51910
+ targetId: external_exports.uuid(),
51911
+ name,
51912
+ kind: external_exports.literal("oauth2"),
51913
+ oauth: oauthSettingsSchema,
51914
+ value: oauthValueSchema
51915
+ }).strict()
51916
+ ]);
51859
51917
  var httpCredentialRotateSchema = external_exports.object({
51860
51918
  expectedRevision: external_exports.number().int().positive(),
51861
- value: httpCredentialValueSchema
51919
+ // A static header value is limited to 4096 bytes by the service.
51920
+ value: oauthValueSchema
51862
51921
  }).strict();
51863
51922
  var httpAuthSchema = external_exports.object({
51864
51923
  targetId: external_exports.uuid(),
@@ -51881,7 +51940,13 @@ var httpCredentialResourceSchema = external_exports.object({
51881
51940
  id: external_exports.uuid(),
51882
51941
  targetId: external_exports.uuid(),
51883
51942
  name,
51884
- header: external_exports.enum(["Authorization", "X-Api-Key"]),
51943
+ header: httpCredentialHeaderSchema,
51944
+ kind: external_exports.enum(["header", "oauth2"]),
51945
+ // Non-secret token settings and the last refresh outcome, for oauth2.
51946
+ oauth: oauthSettingsSchema.extend({
51947
+ lastRefreshAt: external_exports.number().int().nonnegative().nullable(),
51948
+ lastError: external_exports.string().max(200).nullable()
51949
+ }).strict().optional(),
51885
51950
  revision: external_exports.number().int().positive(),
51886
51951
  enabled: external_exports.boolean(),
51887
51952
  hasCredential: external_exports.boolean()
@@ -51897,12 +51962,9 @@ var httpTargetChallengeResponseSchema = external_exports.object({
51897
51962
  }).strict();
51898
51963
  var httpExecutionCredentialSchema = httpAuthSchema.extend({
51899
51964
  origin: httpTargetOriginSchema,
51900
- headers: external_exports.object({
51901
- Authorization: httpCredentialValueSchema.optional(),
51902
- "X-Api-Key": httpCredentialValueSchema.optional()
51903
- }).strict().refine(
51904
- (value2) => Object.keys(value2).length === 1 && Object.values(value2).every((value3) => typeof value3 === "string"),
51905
- "Use exactly one supported credential header"
51965
+ headers: external_exports.record(httpCredentialHeaderSchema, httpCredentialValueSchema).refine(
51966
+ (value2) => Object.keys(value2).length === 1,
51967
+ "Use exactly one credential header"
51906
51968
  )
51907
51969
  }).strict();
51908
51970
 
@@ -52274,6 +52336,11 @@ var VISUAL_POLICY = Object.freeze({
52274
52336
  reviewLogPerHead: 200,
52275
52337
  reviewLogGlobal: 1e4,
52276
52338
  historyDays: 30,
52339
+ // A visual check's run evidence (capture, diff, report) is kept for the
52340
+ // latest passing run and the latest failed runs of each head; older ones
52341
+ // expire at once instead of after the plan's evidence days.
52342
+ passedEvidencePerHead: 1,
52343
+ failedEvidencePerHead: 10,
52277
52344
  pageSize: 50
52278
52345
  });
52279
52346
  var SCRIPT_SCREENSHOT_FILE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,150}\.png$/;
@@ -52638,21 +52705,21 @@ function validateAiVariables(input2) {
52638
52705
  return invalid();
52639
52706
  return value2;
52640
52707
  }
52641
- function renderText(text3, variables) {
52708
+ function renderText(text4, variables) {
52642
52709
  let cursor = 0, result2 = "";
52643
52710
  for (; ; ) {
52644
- const open19 = text3.indexOf("{{", cursor), close = text3.indexOf("}}", cursor);
52711
+ const open19 = text4.indexOf("{{", cursor), close = text4.indexOf("}}", cursor);
52645
52712
  if (close >= 0 && (open19 < 0 || close < open19)) return invalid();
52646
52713
  if (open19 < 0) {
52647
- result2 += text3.slice(cursor);
52714
+ result2 += text4.slice(cursor);
52648
52715
  break;
52649
52716
  }
52650
- const end = text3.indexOf("}}", open19 + 2);
52717
+ const end = text4.indexOf("}}", open19 + 2);
52651
52718
  if (end < 0) return invalid();
52652
- const key = text3.slice(open19 + 2, end);
52719
+ const key = text4.slice(open19 + 2, end);
52653
52720
  if (!name2.test(key)) return invalid();
52654
52721
  if (!Object.hasOwn(variables, key)) throw new AiTemplateError(key);
52655
- result2 += text3.slice(cursor, open19) + variables[key];
52722
+ result2 += text4.slice(cursor, open19) + variables[key];
52656
52723
  if (result2.length > AI_TEMPLATE_LIMITS.fixtureBytes) return invalid();
52657
52724
  cursor = end + 2;
52658
52725
  }
@@ -53134,6 +53201,117 @@ var heartbeatEventSchema = external_exports.object({
53134
53201
  sentAt: external_exports.number().int().positive()
53135
53202
  }).strict();
53136
53203
 
53204
+ // ../../src/contracts/mcp.ts
53205
+ var MCP_LIMITS = {
53206
+ expectTools: 50,
53207
+ toolNameLength: 128,
53208
+ argumentsBytes: 8 * 1024,
53209
+ assertions: 20,
53210
+ responseBytes: 256 * 1024,
53211
+ responseDepth: 64,
53212
+ responseNodes: 32768,
53213
+ listPages: 5,
53214
+ tools: 500,
53215
+ // Tool names the report keeps so a user can pick expectTools.
53216
+ reportedNames: 100,
53217
+ maxTimeoutSeconds: 30
53218
+ };
53219
+ var MCP_CLIENT_PROTOCOL = "2025-11-25";
53220
+ var MCP_PROTOCOL_VERSIONS = [
53221
+ "2025-11-25",
53222
+ "2025-06-18",
53223
+ "2025-03-26",
53224
+ "2024-11-05"
53225
+ ];
53226
+ var toolName = external_exports.string().min(1).max(MCP_LIMITS.toolNameLength).regex(
53227
+ /^[A-Za-z0-9_.\/-]+$/,
53228
+ "Use a tool name of letters, digits, _ . / or -"
53229
+ );
53230
+ var mcpToolCallSchema = external_exports.object({
53231
+ name: toolName,
53232
+ arguments: external_exports.record(external_exports.string(), external_exports.unknown()).default({}).refine(
53233
+ (value2) => isBoundedJson(value2, {
53234
+ bytes: MCP_LIMITS.argumentsBytes,
53235
+ depth: 16,
53236
+ nodes: 4096
53237
+ }),
53238
+ `Use a JSON object of arguments up to ${MCP_LIMITS.argumentsBytes / 1024} KiB`
53239
+ ),
53240
+ assertions: external_exports.array(aiEndpointAssertionSchema).max(MCP_LIMITS.assertions).default([])
53241
+ }).strict();
53242
+ var mcpConfigSchema = external_exports.object({
53243
+ expectTools: external_exports.array(toolName).max(MCP_LIMITS.expectTools).default([]).refine(
53244
+ (names) => new Set(names).size === names.length,
53245
+ "List each expected tool once"
53246
+ ),
53247
+ toolCall: mcpToolCallSchema.optional()
53248
+ }).strict();
53249
+ var reason = external_exports.enum([
53250
+ "INVALID_CONFIGURATION",
53251
+ "INVALID_TARGET",
53252
+ "TRANSPORT_ERROR",
53253
+ "TIMEOUT",
53254
+ "REDIRECT_REFUSED",
53255
+ "RESPONSE_TOO_LARGE",
53256
+ "MALFORMED_RESPONSE",
53257
+ "HTTP_ERROR",
53258
+ "AUTH_REJECTED",
53259
+ "JSONRPC_ERROR",
53260
+ "UNSUPPORTED_PROTOCOL",
53261
+ "NO_TOOLS_CAPABILITY",
53262
+ "MALFORMED_TOOLS",
53263
+ "MISSING_TOOLS",
53264
+ "TOOL_NOT_LISTED",
53265
+ "TOOL_ERROR",
53266
+ "ASSERTION_FAILED"
53267
+ ]);
53268
+ var label = external_exports.string().max(128).nullable();
53269
+ var mcpReportSchema = external_exports.object({
53270
+ schemaVersion: external_exports.literal(1),
53271
+ kind: external_exports.literal("mcp"),
53272
+ status: external_exports.enum(["passed", "failed", "error"]),
53273
+ reason: reason.nullable(),
53274
+ server: external_exports.object({
53275
+ name: label,
53276
+ version: label,
53277
+ protocolVersion: label,
53278
+ session: external_exports.boolean()
53279
+ }).strict(),
53280
+ steps: external_exports.array(
53281
+ external_exports.object({
53282
+ method: external_exports.enum([
53283
+ "initialize",
53284
+ "notifications/initialized",
53285
+ "tools/list",
53286
+ "tools/call"
53287
+ ]),
53288
+ httpStatus: external_exports.number().int().nullable(),
53289
+ durationMs: external_exports.number().int().nonnegative(),
53290
+ ok: external_exports.boolean(),
53291
+ jsonRpcCode: external_exports.number().int().nullable()
53292
+ }).strict()
53293
+ ).max(MCP_LIMITS.listPages + 3),
53294
+ tools: external_exports.object({
53295
+ count: external_exports.number().int().nonnegative().nullable(),
53296
+ truncated: external_exports.boolean(),
53297
+ expected: external_exports.number().int().nonnegative(),
53298
+ missing: external_exports.array(external_exports.string().max(MCP_LIMITS.toolNameLength)),
53299
+ names: external_exports.array(external_exports.string().max(MCP_LIMITS.toolNameLength)).max(MCP_LIMITS.reportedNames)
53300
+ }).strict(),
53301
+ toolCall: external_exports.object({
53302
+ name: external_exports.string().max(MCP_LIMITS.toolNameLength),
53303
+ isError: external_exports.boolean().nullable(),
53304
+ assertions: external_exports.array(
53305
+ external_exports.object({
53306
+ path: external_exports.string().max(260),
53307
+ operator: external_exports.string().max(32),
53308
+ passed: external_exports.boolean(),
53309
+ reason: external_exports.enum(["MISSING_PATH", "TYPE_MISMATCH", "VALUE_MISMATCH"]).nullable()
53310
+ }).strict()
53311
+ )
53312
+ }).strict().nullable()
53313
+ }).strict();
53314
+
53137
53315
  // ../../src/contracts/browser-identities.ts
53138
53316
  var BROWSER_IDENTITY_LIMITS = {
53139
53317
  ownerIdentities: 10,
@@ -53326,7 +53504,8 @@ var monitorSchema = external_exports.object({
53326
53504
  "certificate",
53327
53505
  "visual",
53328
53506
  "heartbeat",
53329
- "ai"
53507
+ "ai",
53508
+ "mcp"
53330
53509
  ]),
53331
53510
  target: external_exports.string().trim().min(1).max(2e3),
53332
53511
  interval: external_exports.number().int().min(60).max(86400).default(300),
@@ -53338,6 +53517,7 @@ var monitorSchema = external_exports.object({
53338
53517
  ai: modelGrantSchema.optional(),
53339
53518
  heartbeat: heartbeatConfigSchema.optional(),
53340
53519
  aiEndpoint: aiEndpointConfigSchema.optional(),
53520
+ mcp: mcpConfigSchema.optional(),
53341
53521
  httpAuth: httpAuthSchema.optional(),
53342
53522
  protectedRequests: productRequestsPolicySchema.optional(),
53343
53523
  browserIdentity: browserIdentityBindingSchema.optional(),
@@ -53357,9 +53537,9 @@ var monitorSchema = external_exports.object({
53357
53537
  }).prefault({})
53358
53538
  }).superRefine((m, ctx) => {
53359
53539
  const issue3 = (message, path2) => ctx.addIssue({ code: "custom", message, path: [path2] });
53360
- if (m.requestBudget && !(m.type === "ai" || m.httpAuth || m.protectedRequests))
53540
+ if (m.requestBudget && !(m.type === "ai" || m.type === "mcp" || m.httpAuth || m.protectedRequests))
53361
53541
  issue3(
53362
- "Daily invocation budgets require an AI endpoint, authenticated HTTP check or protected request script",
53542
+ "Daily invocation budgets require an AI endpoint, MCP, authenticated HTTP check or protected request script",
53363
53543
  "requestBudget"
53364
53544
  );
53365
53545
  if (m.protectedRequests) {
@@ -53385,9 +53565,9 @@ var monitorSchema = external_exports.object({
53385
53565
  }
53386
53566
  }
53387
53567
  if (m.httpAuth) {
53388
- if (!["http", "ai"].includes(m.type) || m.script || m.ai || m.demo || m.settings.envNames.length || Object.keys(m.settings.headers).length)
53568
+ if (!["http", "ai", "mcp"].includes(m.type) || m.script || m.ai || m.demo || m.settings.envNames.length || Object.keys(m.settings.headers).length)
53389
53569
  issue3(
53390
- "HTTP credentials require a live fixed HTTP or AI endpoint check without scripts or custom headers",
53570
+ "HTTP credentials require a live fixed HTTP, AI endpoint or MCP check without scripts or custom headers",
53391
53571
  "httpAuth"
53392
53572
  );
53393
53573
  if (!["GET", "HEAD", "POST"].includes(m.settings.method) || new TextEncoder().encode(m.settings.body).byteLength > 16384)
@@ -53452,6 +53632,31 @@ var monitorSchema = external_exports.object({
53452
53632
  "settings"
53453
53633
  );
53454
53634
  }
53635
+ if (m.type !== "mcp" && m.mcp !== void 0)
53636
+ issue3("MCP settings require an MCP monitor", "mcp");
53637
+ if (m.type === "mcp") {
53638
+ if (!m.mcp) issue3("MCP settings are required", "mcp");
53639
+ if (m.timeout > MCP_LIMITS.maxTimeoutSeconds)
53640
+ issue3(
53641
+ `MCP checks have a maximum timeout of ${MCP_LIMITS.maxTimeoutSeconds} seconds`,
53642
+ "timeout"
53643
+ );
53644
+ try {
53645
+ const target = new URL(m.target);
53646
+ if (target.protocol !== "https:" || target.port && target.port !== "443" || target.username || target.password || target.hash)
53647
+ issue3(
53648
+ "Use a public HTTPS MCP endpoint on port 443 without credentials or a fragment",
53649
+ "target"
53650
+ );
53651
+ } catch {
53652
+ issue3("Use a public HTTPS MCP endpoint", "target");
53653
+ }
53654
+ if (m.demo || m.script || m.ai || m.visual || m.heartbeat || m.aiEndpoint || Object.keys(m.settings.headers).length || m.settings.body || m.settings.envNames.length || m.settings.method !== "GET" || m.settings.contains || m.settings.jsonPath || m.settings.jsonValue || m.settings.maxLatency || m.settings.expectedStatus !== 200 || m.settings.certificateMinDays !== void 0)
53655
+ issue3(
53656
+ "MCP monitors use expected tools and an optional tool call; scripts, custom headers and HTTP assertions are not supported",
53657
+ "settings"
53658
+ );
53659
+ }
53455
53660
  if (m.type !== "heartbeat" && m.heartbeat !== void 0)
53456
53661
  issue3("Heartbeat settings require a heartbeat monitor", "heartbeat");
53457
53662
  if (m.type === "heartbeat") {
@@ -53943,7 +54148,7 @@ async function boundedText(response, maxBytes = 8 * 1024 * 1024) {
53943
54148
  const reader = response.body?.getReader();
53944
54149
  if (!reader) return "";
53945
54150
  const decoder = new TextDecoder();
53946
- let total = 0, text3 = "";
54151
+ let total = 0, text4 = "";
53947
54152
  try {
53948
54153
  while (true) {
53949
54154
  const part2 = await reader.read();
@@ -53951,9 +54156,9 @@ async function boundedText(response, maxBytes = 8 * 1024 * 1024) {
53951
54156
  total += part2.value.byteLength;
53952
54157
  if (total > maxBytes)
53953
54158
  throw new Error("Response exceeds the 8 MiB text limit");
53954
- text3 += decoder.decode(part2.value, { stream: true });
54159
+ text4 += decoder.decode(part2.value, { stream: true });
53955
54160
  }
53956
- return text3 + decoder.decode();
54161
+ return text4 + decoder.decode();
53957
54162
  } finally {
53958
54163
  await reader.cancel().catch(() => {
53959
54164
  });
@@ -54093,7 +54298,7 @@ async function request(server, path2, {
54093
54298
  const message = typeof (detail.message ?? data.error) === "string" ? (detail.message ?? data.error).replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, " ").slice(0, 1e3) : `HTTP ${response.status}`;
54094
54299
  const safe = [cookie, cookie?.split("=")[1], accessToken, ...secrets].filter(
54095
54300
  (value2) => typeof value2 === "string" && value2.length > 0
54096
- ).reduce((text3, secret) => text3.replaceAll(secret, "[redacted]"), message);
54301
+ ).reduce((text4, secret) => text4.replaceAll(secret, "[redacted]"), message);
54097
54302
  const failure3 = new ServiceError(
54098
54303
  safe,
54099
54304
  errorCode ?? (response.status === 401 ? "AUTH_REQUIRED" : response.status === 429 ? "RATE_LIMITED" : "SERVICE_ERROR"),
@@ -54103,7 +54308,7 @@ async function request(server, path2, {
54103
54308
  const redacted = [cookie, cookie?.split("=")[1], accessToken, ...secrets].filter(
54104
54309
  (value2) => typeof value2 === "string" && value2.length > 0
54105
54310
  ).reduce(
54106
- (text3, secret) => text3.replaceAll(secret, "[redacted]"),
54311
+ (text4, secret) => text4.replaceAll(secret, "[redacted]"),
54107
54312
  JSON.stringify(detail.fields)
54108
54313
  );
54109
54314
  try {
@@ -55047,6 +55252,17 @@ var aiEndpointExample = {
55047
55252
  invocationBudget: 1
55048
55253
  }
55049
55254
  };
55255
+ var mcpExample = {
55256
+ schemaVersion: 1,
55257
+ name: "MCP server",
55258
+ type: "mcp",
55259
+ target: "https://example.com/mcp",
55260
+ enabled: false,
55261
+ interval: 1800,
55262
+ timeout: 15,
55263
+ failureThreshold: 2,
55264
+ mcp: { expectTools: ["search"] }
55265
+ };
55050
55266
  var visualExample = {
55051
55267
  schemaVersion: 1,
55052
55268
  name: "Production / homepage appearance",
@@ -55072,10 +55288,10 @@ var visualExample = {
55072
55288
  }
55073
55289
  }
55074
55290
  };
55075
- async function writeText(path2, text3) {
55291
+ async function writeText(path2, text4) {
55076
55292
  const file2 = await open4(path2, "wx", 384);
55077
55293
  try {
55078
- await file2.writeFile(text3);
55294
+ await file2.writeFile(text4);
55079
55295
  } finally {
55080
55296
  await file2.close();
55081
55297
  }
@@ -55084,11 +55300,11 @@ var writeJson = (path2, data) => writeText(path2, JSON.stringify(data, null, 2)
55084
55300
  async function readManifest(path2, { enable = false } = {}) {
55085
55301
  if (!path2) throw new Error("Provide --file PATH to a monitor JSON file.");
55086
55302
  let value2;
55087
- const text3 = await readFile(path2, "utf8");
55088
- if (Buffer.byteLength(text3) > 96e3)
55303
+ const text4 = await readFile(path2, "utf8");
55304
+ if (Buffer.byteLength(text4) > 96e3)
55089
55305
  throw new Error("Monitor configuration exceeds 96 KB.");
55090
55306
  try {
55091
- value2 = JSON.parse(text3);
55307
+ value2 = JSON.parse(text4);
55092
55308
  } catch {
55093
55309
  throw new Error("Monitor configuration must be valid JSON.");
55094
55310
  }
@@ -55104,6 +55320,10 @@ async function readManifest(path2, { enable = false } = {}) {
55104
55320
  throw new Error(
55105
55321
  "AI endpoint monitors do not accept scriptFile; use fixture and assertions."
55106
55322
  );
55323
+ if (definition.type === "mcp")
55324
+ throw new Error(
55325
+ "MCP monitors do not accept scriptFile; use expectTools and toolCall."
55326
+ );
55107
55327
  if (definition.type === "visual")
55108
55328
  throw new Error(
55109
55329
  "Visual monitors do not accept scriptFile; use capture settings."
@@ -55794,8 +56014,8 @@ async function targetConfiguration(file2) {
55794
56014
  await handle.close();
55795
56015
  }
55796
56016
  }
55797
- function httpSecretInput(text3) {
55798
- const value2 = text3.replace(/[\r\n]+$/, "");
56017
+ function httpSecretInput(text4) {
56018
+ const value2 = text4.replace(/[\r\n]+$/, "");
55799
56019
  if (!httpCredentialRotateSchema.shape.value.safeParse(value2).success)
55800
56020
  throw new ServiceError(
55801
56021
  "Use a single-line ASCII HTTP credential value of at most 4096 characters.",
@@ -55893,7 +56113,7 @@ async function targetChallengeToFile(path2, server, issue3) {
55893
56113
  // src/http-local.ts
55894
56114
  var entrySchema = httpAuthSchema.extend({
55895
56115
  origin: external_exports.string().url(),
55896
- header: external_exports.enum(["Authorization", "X-Api-Key"]),
56116
+ header: httpCredentialHeaderSchema,
55897
56117
  credentialFile: external_exports.string().min(1).max(2e3)
55898
56118
  }).strict();
55899
56119
  var mapSchema = external_exports.object({
@@ -56702,13 +56922,13 @@ async function localProductRequestBroker(input2, options = {}) {
56702
56922
  resourceId
56703
56923
  };
56704
56924
  const snapshot = () => {
56705
- const unknown2 = calls.filter((c) => c.state === "unknown").length, pendingCall = calls.some((c) => c.state === "pending"), reason = failure3 ?? (input2.signal.aborted || now() >= input2.deadlineAt ? "PRODUCT_REQUEST_NOT_AUTHORIZED" : pendingCall || unknown2 ? "PRODUCT_REQUEST_UNKNOWN" : null);
56925
+ const unknown2 = calls.filter((c) => c.state === "unknown").length, pendingCall = calls.some((c) => c.state === "pending"), reason2 = failure3 ?? (input2.signal.aborted || now() >= input2.deadlineAt ? "PRODUCT_REQUEST_NOT_AUTHORIZED" : pendingCall || unknown2 ? "PRODUCT_REQUEST_UNKNOWN" : null);
56706
56926
  return {
56707
56927
  provenance: "local",
56708
56928
  resourceId,
56709
56929
  outcome: {
56710
- ok: reason === null,
56711
- reason,
56930
+ ok: reason2 === null,
56931
+ reason: reason2,
56712
56932
  calls: calls.filter((c) => c.state !== "released").length,
56713
56933
  unknown: unknown2
56714
56934
  },
@@ -56793,7 +57013,7 @@ async function localScenarioRuntimeSource() {
56793
57013
  // src/local.ts
56794
57014
  import { createRequire } from "node:module";
56795
57015
  import { randomUUID as randomUUID4, createHash as createHash8 } from "node:crypto";
56796
- import { performance as performance5 } from "node:perf_hooks";
57016
+ import { performance as performance6 } from "node:perf_hooks";
56797
57017
  import {
56798
57018
  mkdir as mkdir4,
56799
57019
  lstat as lstat7,
@@ -56963,7 +57183,7 @@ HTTP ${response.status}
56963
57183
  Cloudflare challenge blocked the probe. No challenge was bypassed.`
56964
57184
  };
56965
57185
  }
56966
- let text3 = "", bytes2 = 0;
57186
+ let text4 = "", bytes2 = 0;
56967
57187
  if (response.body) {
56968
57188
  const reader = response.body.getReader();
56969
57189
  const decoder = new TextDecoder();
@@ -56974,9 +57194,9 @@ Cloudflare challenge blocked the probe. No challenge was bypassed.`
56974
57194
  bytes2 += value2.byteLength;
56975
57195
  if (bytes2 > 256e3)
56976
57196
  throw new Error("Response exceeds the 256 KB check limit");
56977
- text3 += decoder.decode(value2, { stream: true });
57197
+ text4 += decoder.decode(value2, { stream: true });
56978
57198
  }
56979
- text3 += decoder.decode();
57199
+ text4 += decoder.decode();
56980
57200
  } finally {
56981
57201
  await reader.cancel().catch(() => {
56982
57202
  });
@@ -56989,9 +57209,9 @@ Cloudflare challenge blocked the probe. No challenge was bypassed.`
56989
57209
  bytes: bytes2,
56990
57210
  excerpt: omitted ? null : hidden.reduce(
56991
57211
  (value2, secret) => value2.replaceAll(secret, "[redacted]"),
56992
- text3.slice(0, RUN_TRACE_LIMITS.bodyExcerpt)
57212
+ text4.slice(0, RUN_TRACE_LIMITS.bodyExcerpt)
56993
57213
  ),
56994
- truncated: !omitted && text3.length > RUN_TRACE_LIMITS.bodyExcerpt,
57214
+ truncated: !omitted && text4.length > RUN_TRACE_LIMITS.bodyExcerpt,
56995
57215
  omitted
56996
57216
  };
56997
57217
  const latency = Math.round(performance2.now() - start);
@@ -57000,11 +57220,11 @@ Cloudflare challenge blocked the probe. No challenge was bypassed.`
57000
57220
  failures.push(
57001
57221
  `Expected HTTP ${m.settings.expectedStatus}, received ${response.status}`
57002
57222
  );
57003
- if (m.settings.contains && !text3.includes(m.settings.contains))
57223
+ if (m.settings.contains && !text4.includes(m.settings.contains))
57004
57224
  failures.push("Expected text missing from response");
57005
57225
  if (m.settings.jsonPath) {
57006
57226
  try {
57007
- let value2 = JSON.parse(text3);
57227
+ let value2 = JSON.parse(text4);
57008
57228
  for (const part2 of m.settings.jsonPath.split("."))
57009
57229
  value2 = value2?.[part2];
57010
57230
  let expected;
@@ -57079,9 +57299,9 @@ function semanticGradingIdentity(rubric, judge) {
57079
57299
  }
57080
57300
  async function semanticGrade(input2) {
57081
57301
  const report = semanticGradingIdentity(input2.rubric, input2.judge);
57082
- const fail2 = (reason) => ({
57302
+ const fail2 = (reason2) => ({
57083
57303
  ...report,
57084
- reason
57304
+ reason: reason2
57085
57305
  });
57086
57306
  if (input2.signal.aborted) return fail2("CANCELLED");
57087
57307
  if (!input2.selected.found) return fail2("MISSING_OUTPUT");
@@ -57233,6 +57453,57 @@ function matchesSchema(value2, schema) {
57233
57453
  return false;
57234
57454
  return true;
57235
57455
  }
57456
+ function evaluateAssertion(data, assertion, secrets = []) {
57457
+ const found = pointer3(data, assertion.path);
57458
+ let passed = false;
57459
+ if (found.found) {
57460
+ switch (assertion.operator) {
57461
+ case "exists":
57462
+ passed = true;
57463
+ break;
57464
+ case "equals":
57465
+ passed = equals(found.value, assertion.value);
57466
+ break;
57467
+ case "type":
57468
+ passed = matchesType(found.value, assertion.value);
57469
+ break;
57470
+ default: {
57471
+ const text4 = found.value;
57472
+ if (typeof text4 === "string") {
57473
+ switch (assertion.operator) {
57474
+ case "contains":
57475
+ passed = text4.includes(assertion.value);
57476
+ break;
57477
+ case "not-contains":
57478
+ passed = !text4.includes(assertion.value);
57479
+ break;
57480
+ case "contains-any":
57481
+ passed = assertion.value.some(
57482
+ (value2) => text4.includes(value2)
57483
+ );
57484
+ break;
57485
+ case "contains-all":
57486
+ passed = assertion.value.every(
57487
+ (value2) => text4.includes(value2)
57488
+ );
57489
+ break;
57490
+ }
57491
+ }
57492
+ }
57493
+ }
57494
+ }
57495
+ return {
57496
+ path: secrets.some((secret) => assertion.path.includes(secret)) ? "/[redacted]" : assertion.path,
57497
+ operator: assertion.operator,
57498
+ passed,
57499
+ reason: passed ? null : !found.found ? "MISSING_PATH" : assertion.operator === "type" || [
57500
+ "contains",
57501
+ "not-contains",
57502
+ "contains-any",
57503
+ "contains-all"
57504
+ ].includes(assertion.operator) && typeof found.value !== "string" ? "TYPE_MISMATCH" : "VALUE_MISMATCH"
57505
+ };
57506
+ }
57236
57507
  function initialReport(config2) {
57237
57508
  return {
57238
57509
  schemaVersion: 1,
@@ -57298,9 +57569,9 @@ async function singleCheck(monitor, parentSignal, options = {}) {
57298
57569
  const config2 = parsed.data, report = initialReport(config2), deadline = AbortSignal.timeout(
57299
57570
  Math.max(1, Math.ceil(monitor.timeout * 1e3))
57300
57571
  ), signal = parentSignal ? AbortSignal.any([parentSignal, deadline]) : deadline;
57301
- const fail2 = (reason) => {
57572
+ const fail2 = (reason2) => {
57302
57573
  report.transport.status = "error";
57303
- report.transport.reason = reason;
57574
+ report.transport.reason = reason2;
57304
57575
  return result(
57305
57576
  report,
57306
57577
  "error",
@@ -57396,57 +57667,9 @@ async function singleCheck(monitor, parentSignal, options = {}) {
57396
57667
  options.onResponse?.(data);
57397
57668
  report.transport.status = "passed";
57398
57669
  metadata(report, data, secrets);
57399
- report.assertions = config2.assertions.map((assertion) => {
57400
- const found = pointer3(data, assertion.path);
57401
- let passed2 = false;
57402
- if (found.found) {
57403
- switch (assertion.operator) {
57404
- case "exists":
57405
- passed2 = true;
57406
- break;
57407
- case "equals":
57408
- passed2 = equals(found.value, assertion.value);
57409
- break;
57410
- case "type":
57411
- passed2 = matchesType(found.value, assertion.value);
57412
- break;
57413
- default: {
57414
- const text3 = found.value;
57415
- if (typeof text3 === "string") {
57416
- switch (assertion.operator) {
57417
- case "contains":
57418
- passed2 = text3.includes(assertion.value);
57419
- break;
57420
- case "not-contains":
57421
- passed2 = !text3.includes(assertion.value);
57422
- break;
57423
- case "contains-any":
57424
- passed2 = assertion.value.some(
57425
- (value2) => text3.includes(value2)
57426
- );
57427
- break;
57428
- case "contains-all":
57429
- passed2 = assertion.value.every(
57430
- (value2) => text3.includes(value2)
57431
- );
57432
- break;
57433
- }
57434
- }
57435
- }
57436
- }
57437
- }
57438
- return {
57439
- path: secrets.some((secret) => assertion.path.includes(secret)) ? "/[redacted]" : assertion.path,
57440
- operator: assertion.operator,
57441
- passed: passed2,
57442
- reason: passed2 ? null : !found.found ? "MISSING_PATH" : assertion.operator === "type" || [
57443
- "contains",
57444
- "not-contains",
57445
- "contains-any",
57446
- "contains-all"
57447
- ].includes(assertion.operator) && typeof found.value !== "string" ? "TYPE_MISMATCH" : "VALUE_MISMATCH"
57448
- };
57449
- });
57670
+ report.assertions = config2.assertions.map(
57671
+ (assertion) => evaluateAssertion(data, assertion, secrets)
57672
+ );
57450
57673
  if (config2.responseSchema)
57451
57674
  report.responseSchema.passed = matchesSchema(data, config2.responseSchema);
57452
57675
  const passed = report.assertions.every((check2) => check2.passed) && report.responseSchema.passed !== false;
@@ -57810,11 +58033,397 @@ async function certificateCheck(monitor, parentSignal, io = transport, sink = {}
57810
58033
  }
57811
58034
  }
57812
58035
 
58036
+ // ../../src/checks/mcp.ts
58037
+ import { performance as performance4 } from "node:perf_hooks";
58038
+
58039
+ // package.json
58040
+ var package_default = {
58041
+ name: "@waitcher/cli",
58042
+ version: "0.2.25",
58043
+ description: "Synthetic monitoring from your repository: deploy HTTP, certificate, heartbeat, API, browser and visual monitors from waitcher.json.",
58044
+ license: "SEE LICENSE IN LICENSE.txt",
58045
+ author: "S\u0142awomir Radzymi\u0144ski",
58046
+ homepage: "https://waitcher.dev/docs/",
58047
+ repository: {
58048
+ type: "git",
58049
+ url: "git+https://github.com/slawekradzyminski/synthetic-watch.git",
58050
+ directory: "packages/cli"
58051
+ },
58052
+ keywords: [
58053
+ "monitoring",
58054
+ "synthetic-monitoring",
58055
+ "uptime",
58056
+ "e2e",
58057
+ "ci",
58058
+ "cli"
58059
+ ],
58060
+ type: "module",
58061
+ bin: {
58062
+ waitcher: "dist/cli.mjs"
58063
+ },
58064
+ files: [
58065
+ "dist/cli.mjs",
58066
+ "dist/model-client.mjs",
58067
+ "dist/scenario-runtime.mjs",
58068
+ "dist/request-runtime.mjs",
58069
+ "dist/MODEL_CLIENT_NOTICES.txt",
58070
+ "README.md",
58071
+ "THIRD_PARTY_NOTICES.txt",
58072
+ "LICENSE.txt"
58073
+ ],
58074
+ engines: {
58075
+ node: ">=24.15.0"
58076
+ },
58077
+ publishConfig: {
58078
+ access: "public"
58079
+ },
58080
+ scripts: {
58081
+ build: "node build.mjs",
58082
+ prepack: "npm run build"
58083
+ }
58084
+ };
58085
+
58086
+ // ../../src/checks/mcp.ts
58087
+ var COVERAGE = /* @__PURE__ */ new Set([
58088
+ "INVALID_CONFIGURATION",
58089
+ "INVALID_TARGET",
58090
+ "TRANSPORT_ERROR",
58091
+ "TIMEOUT",
58092
+ "REDIRECT_REFUSED",
58093
+ "RESPONSE_TOO_LARGE"
58094
+ ]);
58095
+ var Stop = class extends Error {
58096
+ constructor(reason2, hint = "") {
58097
+ super(reason2);
58098
+ this.reason = reason2;
58099
+ this.hint = hint;
58100
+ }
58101
+ reason;
58102
+ hint;
58103
+ };
58104
+ function authHint(response, hasCredential) {
58105
+ if (response.status !== 401) return "";
58106
+ const challenge = response.headers.get("www-authenticate") ?? "";
58107
+ if (/resource_metadata\s*=/i.test(challenge))
58108
+ return "; the server advertises MCP OAuth, whose interactive flow Waitcher cannot run; if it accepts a token you can obtain without a browser, store it as an HTTP target credential (a static header, or an OAuth 2 token credential)";
58109
+ return hasCredential ? "; check that the stored credential is still valid" : "; add an HTTP target credential for this origin and bind it as httpAuth";
58110
+ }
58111
+ var MESSAGES = {
58112
+ INVALID_CONFIGURATION: "MCP check configuration is invalid",
58113
+ INVALID_TARGET: "Use a public HTTPS MCP endpoint on port 443",
58114
+ TRANSPORT_ERROR: "The MCP server could not be reached",
58115
+ TIMEOUT: "The MCP check did not finish within its timeout",
58116
+ REDIRECT_REFUSED: "The MCP endpoint redirected; use the final URL",
58117
+ RESPONSE_TOO_LARGE: "An MCP response exceeded 256 KiB",
58118
+ MALFORMED_RESPONSE: "The MCP server did not answer with JSON-RPC",
58119
+ HTTP_ERROR: "The MCP server answered with an HTTP error",
58120
+ AUTH_REJECTED: "The MCP server rejected the request as unauthorized",
58121
+ JSONRPC_ERROR: "The MCP server answered with a JSON-RPC error",
58122
+ UNSUPPORTED_PROTOCOL: "The MCP server negotiated an unknown protocol version",
58123
+ NO_TOOLS_CAPABILITY: "The MCP server does not advertise tools",
58124
+ MALFORMED_TOOLS: "The MCP server listed a tool without a name or input schema",
58125
+ MISSING_TOOLS: "Expected MCP tools are missing",
58126
+ TOOL_NOT_LISTED: "The tool to call is not listed by the server",
58127
+ TOOL_ERROR: "The MCP tool call returned an error",
58128
+ ASSERTION_FAILED: "The MCP tool result did not satisfy the checks"
58129
+ };
58130
+ var isObject2 = (value2) => value2 !== null && typeof value2 === "object" && !Array.isArray(value2);
58131
+ var text3 = (value2, secrets) => typeof value2 === "string" && value2.length <= 128 && /^[\x20-\x7e]*$/.test(value2) && !secrets.some((secret) => value2.includes(secret)) ? value2 : null;
58132
+ async function readLimited(response, signal, onChunk) {
58133
+ const length = response.headers.get("content-length");
58134
+ if (length && /^\d+$/.test(length) && Number(length) > MCP_LIMITS.responseBytes) {
58135
+ await response.body?.cancel();
58136
+ throw new Stop("RESPONSE_TOO_LARGE");
58137
+ }
58138
+ const reader = response.body?.getReader();
58139
+ if (!reader) return "";
58140
+ const decoder = new TextDecoder("utf-8", { fatal: true });
58141
+ const abort = () => void reader.cancel().catch(() => {
58142
+ });
58143
+ signal.addEventListener("abort", abort, { once: true });
58144
+ let size = 0, out = "";
58145
+ try {
58146
+ for (; ; ) {
58147
+ signal.throwIfAborted();
58148
+ const { done, value: value2 } = await reader.read();
58149
+ signal.throwIfAborted();
58150
+ if (done) break;
58151
+ size += value2.length;
58152
+ if (size > MCP_LIMITS.responseBytes) throw new Stop("RESPONSE_TOO_LARGE");
58153
+ try {
58154
+ out += decoder.decode(value2, { stream: true });
58155
+ } catch {
58156
+ throw new Stop("MALFORMED_RESPONSE");
58157
+ }
58158
+ if (onChunk?.(out)) break;
58159
+ }
58160
+ return out;
58161
+ } finally {
58162
+ signal.removeEventListener("abort", abort);
58163
+ await reader.cancel().catch(() => {
58164
+ });
58165
+ reader.releaseLock();
58166
+ }
58167
+ }
58168
+ function parseJson(raw) {
58169
+ let data;
58170
+ try {
58171
+ data = JSON.parse(raw);
58172
+ } catch {
58173
+ throw new Stop("MALFORMED_RESPONSE");
58174
+ }
58175
+ if (!isBoundedJson(data, {
58176
+ bytes: MCP_LIMITS.responseBytes,
58177
+ depth: MCP_LIMITS.responseDepth,
58178
+ nodes: MCP_LIMITS.responseNodes
58179
+ }))
58180
+ throw new Stop("MALFORMED_RESPONSE");
58181
+ return data;
58182
+ }
58183
+ function fromEvents(raw, id4, final) {
58184
+ const blocks = raw.split(/\r?\n\r?\n/);
58185
+ if (!final) blocks.pop();
58186
+ for (const block of blocks) {
58187
+ const data = block.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(line.startsWith("data: ") ? 6 : 5)).join("\n");
58188
+ if (!data) continue;
58189
+ const message = parseJson(data);
58190
+ if (isObject2(message) && message.id === id4) return message;
58191
+ }
58192
+ return null;
58193
+ }
58194
+ async function mcpCheck(monitor, parentSignal, options = {}) {
58195
+ const report = {
58196
+ schemaVersion: 1,
58197
+ kind: "mcp",
58198
+ status: "error",
58199
+ reason: null,
58200
+ server: { name: null, version: null, protocolVersion: null, session: false },
58201
+ steps: [],
58202
+ tools: { count: null, truncated: false, expected: 0, missing: [], names: [] },
58203
+ toolCall: null
58204
+ };
58205
+ const finish = (status2, reason2, message) => {
58206
+ report.status = status2;
58207
+ report.reason = reason2;
58208
+ return {
58209
+ status: status2,
58210
+ message,
58211
+ logs: JSON.stringify(report),
58212
+ ...status2 === "error" && reason2 ? { resourceReason: `MCP_${reason2}` } : {}
58213
+ };
58214
+ };
58215
+ const parsed = mcpConfigSchema.safeParse(monitor.mcp);
58216
+ if (!parsed.success || !Number.isFinite(monitor.timeout) || monitor.timeout <= 0 || monitor.timeout > MCP_LIMITS.maxTimeoutSeconds)
58217
+ return finish("error", "INVALID_CONFIGURATION", MESSAGES.INVALID_CONFIGURATION);
58218
+ const config2 = parsed.data;
58219
+ report.tools.expected = config2.expectTools.length;
58220
+ if (!options.fetch) {
58221
+ try {
58222
+ publicTarget(monitor.target);
58223
+ } catch {
58224
+ return finish("error", "INVALID_TARGET", MESSAGES.INVALID_TARGET);
58225
+ }
58226
+ }
58227
+ const deadline = AbortSignal.timeout(Math.ceil(monitor.timeout * 1e3));
58228
+ const signal = parentSignal ? AbortSignal.any([parentSignal, deadline]) : deadline;
58229
+ const secrets = httpCredentialRedactions(options.httpCredential);
58230
+ const fetcher = options.fetch ?? ((url3, init) => publicFetch(url3, init));
58231
+ let session = null, protocol = null, nextId = 1;
58232
+ async function send(method, params, notification = false) {
58233
+ const id4 = nextId++;
58234
+ const step = {
58235
+ method,
58236
+ httpStatus: null,
58237
+ durationMs: 0,
58238
+ ok: false,
58239
+ jsonRpcCode: null
58240
+ };
58241
+ report.steps.push(step);
58242
+ const started = performance4.now();
58243
+ try {
58244
+ const headers = {
58245
+ "content-type": "application/json",
58246
+ accept: "application/json, text/event-stream",
58247
+ "user-agent": `waitcher-mcp-check/${package_default.version}`,
58248
+ ...httpCredentialHeaders(monitor, options.httpCredential)
58249
+ };
58250
+ if (session) headers["mcp-session-id"] = session;
58251
+ if (protocol) headers["mcp-protocol-version"] = protocol;
58252
+ let response;
58253
+ try {
58254
+ response = await fetcher(monitor.target, {
58255
+ method: "POST",
58256
+ redirect: "manual",
58257
+ headers,
58258
+ body: JSON.stringify({
58259
+ jsonrpc: "2.0",
58260
+ ...notification ? {} : { id: id4 },
58261
+ method,
58262
+ ...params ? { params } : {}
58263
+ }),
58264
+ signal
58265
+ });
58266
+ } catch (cause) {
58267
+ if (cause instanceof Stop) throw cause;
58268
+ throw new Stop(deadline.aborted ? "TIMEOUT" : "TRANSPORT_ERROR");
58269
+ }
58270
+ step.httpStatus = response.status;
58271
+ if (response.status >= 300 && response.status < 400) {
58272
+ await response.body?.cancel();
58273
+ throw new Stop("REDIRECT_REFUSED");
58274
+ }
58275
+ if (response.status === 401 || response.status === 403) {
58276
+ await response.body?.cancel();
58277
+ throw new Stop("AUTH_REJECTED", authHint(response, Boolean(monitor.httpAuth)));
58278
+ }
58279
+ if (response.status < 200 || response.status >= 300) {
58280
+ await response.body?.cancel();
58281
+ throw new Stop("HTTP_ERROR");
58282
+ }
58283
+ if (method === "initialize") {
58284
+ const value2 = response.headers.get("mcp-session-id");
58285
+ if (value2 && /^[\x21-\x7e]{1,1024}$/.test(value2)) session = value2;
58286
+ }
58287
+ if (notification) {
58288
+ await response.body?.cancel();
58289
+ step.ok = true;
58290
+ return void 0;
58291
+ }
58292
+ const type = (response.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
58293
+ let message;
58294
+ if (type === "text/event-stream") {
58295
+ let found = null;
58296
+ const raw = await readLimited(response, signal, (sofar) => {
58297
+ found = fromEvents(sofar, id4, false);
58298
+ return found !== null;
58299
+ });
58300
+ message = found ?? fromEvents(raw, id4, true);
58301
+ } else if (type === "application/json") {
58302
+ const data = parseJson(await readLimited(response, signal));
58303
+ message = Array.isArray(data) ? data.find((item) => isObject2(item) && item.id === id4) ?? null : data;
58304
+ } else {
58305
+ await response.body?.cancel();
58306
+ throw new Stop("MALFORMED_RESPONSE");
58307
+ }
58308
+ if (!isObject2(message) || message.jsonrpc !== "2.0" || message.id !== id4)
58309
+ throw new Stop("MALFORMED_RESPONSE");
58310
+ if (isObject2(message.error)) {
58311
+ const code = message.error.code;
58312
+ step.jsonRpcCode = Number.isSafeInteger(code) ? code : null;
58313
+ throw new Stop("JSONRPC_ERROR");
58314
+ }
58315
+ if (!isObject2(message.result)) throw new Stop("MALFORMED_RESPONSE");
58316
+ step.ok = true;
58317
+ return message.result;
58318
+ } catch (cause) {
58319
+ if (cause instanceof Stop) throw cause;
58320
+ throw new Stop(
58321
+ deadline.aborted ? "TIMEOUT" : cause instanceof Error && cause.name === "AbortError" ? "TIMEOUT" : "TRANSPORT_ERROR"
58322
+ );
58323
+ } finally {
58324
+ step.durationMs = Math.max(0, Math.round(performance4.now() - started));
58325
+ }
58326
+ }
58327
+ try {
58328
+ const init = await send("initialize", {
58329
+ protocolVersion: MCP_CLIENT_PROTOCOL,
58330
+ capabilities: {},
58331
+ clientInfo: { name: "waitcher", version: package_default.version }
58332
+ });
58333
+ if (!isObject2(init)) throw new Stop("MALFORMED_RESPONSE");
58334
+ const version2 = init.protocolVersion;
58335
+ report.server.protocolVersion = text3(version2, secrets);
58336
+ report.server.session = Boolean(session);
58337
+ if (isObject2(init.serverInfo)) {
58338
+ report.server.name = text3(init.serverInfo.name, secrets);
58339
+ report.server.version = text3(init.serverInfo.version, secrets);
58340
+ }
58341
+ if (typeof version2 !== "string" || !MCP_PROTOCOL_VERSIONS.includes(version2))
58342
+ throw new Stop("UNSUPPORTED_PROTOCOL");
58343
+ protocol = version2;
58344
+ if (!isObject2(init.capabilities) || !isObject2(init.capabilities.tools))
58345
+ throw new Stop("NO_TOOLS_CAPABILITY");
58346
+ await send("notifications/initialized", void 0, true);
58347
+ const listed = /* @__PURE__ */ new Set();
58348
+ let cursor;
58349
+ for (let page = 0; page < MCP_LIMITS.listPages; page++) {
58350
+ const result2 = await send("tools/list", cursor ? { cursor } : void 0);
58351
+ if (!isObject2(result2) || !Array.isArray(result2.tools))
58352
+ throw new Stop("MALFORMED_TOOLS");
58353
+ for (const tool of result2.tools) {
58354
+ if (!isObject2(tool) || typeof tool.name !== "string" || !tool.name || !isObject2(tool.inputSchema))
58355
+ throw new Stop("MALFORMED_TOOLS");
58356
+ if (listed.size < MCP_LIMITS.tools) listed.add(tool.name);
58357
+ else report.tools.truncated = true;
58358
+ }
58359
+ cursor = typeof result2.nextCursor === "string" && result2.nextCursor ? result2.nextCursor : void 0;
58360
+ if (!cursor) break;
58361
+ if (page === MCP_LIMITS.listPages - 1) report.tools.truncated = true;
58362
+ }
58363
+ report.tools.count = listed.size;
58364
+ for (const name5 of listed) {
58365
+ if (report.tools.names.length === MCP_LIMITS.reportedNames) break;
58366
+ const safe = text3(name5, secrets);
58367
+ if (safe) report.tools.names.push(safe);
58368
+ }
58369
+ report.tools.missing = config2.expectTools.filter((name5) => !listed.has(name5));
58370
+ if (report.tools.missing.length) throw new Stop("MISSING_TOOLS");
58371
+ const call = config2.toolCall;
58372
+ if (call) {
58373
+ report.toolCall = { name: call.name, isError: null, assertions: [] };
58374
+ if (!listed.has(call.name) && !report.tools.truncated)
58375
+ throw new Stop("TOOL_NOT_LISTED");
58376
+ options.onInvocation?.();
58377
+ const result2 = await send("tools/call", {
58378
+ name: call.name,
58379
+ arguments: call.arguments
58380
+ });
58381
+ if (!isObject2(result2)) throw new Stop("MALFORMED_RESPONSE");
58382
+ options.onToolResult?.(result2);
58383
+ report.toolCall.isError = result2.isError === true;
58384
+ if (result2.isError === true) throw new Stop("TOOL_ERROR");
58385
+ report.toolCall.assertions = call.assertions.map(
58386
+ (assertion) => evaluateAssertion(result2, assertion, secrets)
58387
+ );
58388
+ if (report.toolCall.assertions.some((check2) => !check2.passed))
58389
+ throw new Stop("ASSERTION_FAILED");
58390
+ }
58391
+ const listing = `MCP server listed ${listed.size} tool${listed.size === 1 ? "" : "s"}`;
58392
+ return finish(
58393
+ "passed",
58394
+ null,
58395
+ call ? `${listing}; ${call.name} answered as expected` : listing
58396
+ );
58397
+ } catch (cause) {
58398
+ const reason2 = cause instanceof Stop ? cause.reason : "TRANSPORT_ERROR";
58399
+ let message = MESSAGES[reason2] + (cause instanceof Stop ? cause.hint : "");
58400
+ if (reason2 === "MISSING_TOOLS")
58401
+ message += `: ${report.tools.missing.join(", ")}`.slice(0, 400);
58402
+ return finish(COVERAGE.has(reason2) ? "error" : "failed", reason2, message);
58403
+ } finally {
58404
+ if (session && !signal.aborted) {
58405
+ const headers = { "mcp-session-id": session };
58406
+ if (protocol) headers["mcp-protocol-version"] = protocol;
58407
+ try {
58408
+ Object.assign(headers, httpCredentialHeaders(monitor, options.httpCredential));
58409
+ const response = await fetcher(monitor.target, {
58410
+ method: "DELETE",
58411
+ redirect: "manual",
58412
+ headers,
58413
+ signal: AbortSignal.any([signal, AbortSignal.timeout(2e3)])
58414
+ });
58415
+ await response.body?.cancel();
58416
+ } catch {
58417
+ }
58418
+ }
58419
+ }
58420
+ }
58421
+
57813
58422
  // ../../src/runner.ts
57814
58423
  init_limits();
57815
58424
  import { mkdir as mkdir3, writeFile as writeFile3 } from "node:fs/promises";
57816
58425
  import { join as join6 } from "node:path";
57817
- import { performance as performance4 } from "node:perf_hooks";
58426
+ import { performance as performance5 } from "node:perf_hooks";
57818
58427
 
57819
58428
  // ../../src/checks/product-evidence.ts
57820
58429
  import { constants as constants8 } from "node:fs";
@@ -58193,9 +58802,9 @@ async function collectArtifacts(dir, base2 = dir, tokens2 = [], excluded = /* @_
58193
58802
  "AI evidence exceeds its byte limit"
58194
58803
  );
58195
58804
  const original = await handle.readFile("utf8");
58196
- const redactText = (text3) => tokens2.reduce(
58805
+ const redactText = (text4) => tokens2.reduce(
58197
58806
  (value2, token) => value2.replaceAll(token, "[redacted attempt credential]"),
58198
- text3
58807
+ text4
58199
58808
  );
58200
58809
  let clean = redactText(original);
58201
58810
  if (entry2.name.endsWith(".json")) {
@@ -58559,7 +59168,7 @@ try {
58559
59168
  const requestCoverageError = requestEvidence.summary.technicalError;
58560
59169
  const passed = !requestCoverageError && !dataCoverageError && !dataFailed && !scenarioCoverageError && !scenarioFailed && p.code === 0 && run2?.status === "passed" && results.length > 0 && results.every((r) => r.status === "passed");
58561
59170
  const redact = (value2) => redactions.reduce(
58562
- (text3, token) => text3.replaceAll(token, "[redacted attempt credential]"),
59171
+ (text4, token) => text4.replaceAll(token, "[redacted attempt credential]"),
58563
59172
  value2
58564
59173
  );
58565
59174
  const artifacts = await collectArtifacts(
@@ -58679,9 +59288,10 @@ async function execute(monitor, runDir, {
58679
59288
  httpFetch,
58680
59289
  httpCredential,
58681
59290
  browserIdentity,
58682
- snapshots
59291
+ snapshots,
59292
+ onMcpToolResult
58683
59293
  } = {}) {
58684
- const start = performance4.now();
59294
+ const start = performance5.now();
58685
59295
  let result2;
58686
59296
  const exchanges = [];
58687
59297
  const certificate = {};
@@ -58691,7 +59301,7 @@ async function execute(monitor, runDir, {
58691
59301
  throw Error("Unexpected or missing browser identity authority");
58692
59302
  if (httpCredential && !monitor.httpAuth)
58693
59303
  throw Error("Unexpected HTTP credential authority");
58694
- if (monitor.httpAuth && (!["http", "ai"].includes(monitor.type) || monitor.script || monitor.ai || monitor.settings.envNames.length || Object.keys(monitor.settings.headers).length || !["GET", "HEAD", "POST"].includes(monitor.settings.method) || new TextEncoder().encode(monitor.settings.body).byteLength > 16384 || ["GET", "HEAD"].includes(monitor.settings.method) && monitor.settings.body))
59304
+ if (monitor.httpAuth && (!["http", "ai", "mcp"].includes(monitor.type) || monitor.script || monitor.ai || monitor.settings.envNames.length || Object.keys(monitor.settings.headers).length || !["GET", "HEAD", "POST"].includes(monitor.settings.method) || new TextEncoder().encode(monitor.settings.body).byteLength > 16384 || ["GET", "HEAD"].includes(monitor.settings.method) && monitor.settings.body))
58695
59305
  throw Error("Invalid authenticated HTTP execution configuration");
58696
59306
  if (monitor.ai && (!["api", "browser"].includes(monitor.type) || !model))
58697
59307
  throw Error(
@@ -58704,6 +59314,12 @@ async function execute(monitor, runDir, {
58704
59314
  judgeComplete,
58705
59315
  httpCredential
58706
59316
  });
59317
+ else if (monitor.type === "mcp")
59318
+ result2 = await mcpCheck(monitor, signal, {
59319
+ fetch: httpFetch,
59320
+ httpCredential,
59321
+ onToolResult: onMcpToolResult
59322
+ });
58707
59323
  else if (monitor.type === "heartbeat")
58708
59324
  throw Error(
58709
59325
  "Heartbeats receive external events and cannot execute a script"
@@ -58757,7 +59373,7 @@ async function execute(monitor, runDir, {
58757
59373
  ...monitor.ai && !(cause instanceof StorageError) ? { resourceReason: "AI_EXECUTION_ERROR" } : {}
58758
59374
  };
58759
59375
  }
58760
- if (monitor.httpAuth && monitor.type !== "ai") {
59376
+ if (monitor.httpAuth && !["ai", "mcp"].includes(monitor.type)) {
58761
59377
  for (const secret of httpCredentialRedactions(httpCredential)) {
58762
59378
  result2.logs = result2.logs.replaceAll(
58763
59379
  secret,
@@ -58775,14 +59391,14 @@ async function execute(monitor, runDir, {
58775
59391
  certificate: certificate.trace
58776
59392
  } : null;
58777
59393
  if (trace) result2 = await withTrace(result2, runDir, trace);
58778
- return { ...result2, duration: Math.round(performance4.now() - start) };
59394
+ return { ...result2, duration: Math.round(performance5.now() - start) };
58779
59395
  }
58780
59396
  async function withTrace(result2, runDir, trace) {
58781
59397
  try {
58782
- const text3 = JSON.stringify(runTraceFileSchema.parse(trace));
58783
- if (Buffer.byteLength(text3) > RUN_TRACE_LIMITS.fileBytes) return result2;
59398
+ const text4 = JSON.stringify(runTraceFileSchema.parse(trace));
59399
+ if (Buffer.byteLength(text4) > RUN_TRACE_LIMITS.fileBytes) return result2;
58784
59400
  await mkdir3(join6(runDir, ".e2e"), { recursive: true, mode: 448 });
58785
- await writeFile3(join6(runDir, RUN_TRACE_PATH), text3, { mode: 384 });
59401
+ await writeFile3(join6(runDir, RUN_TRACE_PATH), text4, { mode: 384 });
58786
59402
  return {
58787
59403
  ...result2,
58788
59404
  artifacts: [...result2.artifacts ?? [], RUN_TRACE_PATH]
@@ -58831,7 +59447,7 @@ var entries = {
58831
59447
  TYPE_NOT_SUPPORTED: {
58832
59448
  title: "Monitor type cannot be deployed",
58833
59449
  meaning: "AI monitors are not part of waitcher.json yet.",
58834
- fix: "Deploys accept http, certificate, heartbeat, api, browser and visual monitors. Keep AI checks on monitor apply for now."
59450
+ fix: "Deploys accept http, certificate, heartbeat, api, browser, visual and mcp monitors. Keep AI checks on monitor apply for now."
58835
59451
  },
58836
59452
  ENTRY_REQUIRED: {
58837
59453
  title: "Script monitor without a test file",
@@ -58878,6 +59494,21 @@ var entries = {
58878
59494
  meaning: "A script lists a CHECK_* name in settings.envNames that has no value in the environment.",
58879
59495
  fix: "Set it once per environment: waitcher secret set --env NAME --name CHECK_NAME --value-stdin. Values are write-only and never part of waitcher.json."
58880
59496
  },
59497
+ HTTP_CREDENTIAL_REFERENCE: {
59498
+ title: "Malformed credential reference",
59499
+ meaning: "httpAuth.credential is not a credential name, or a name per environment that includes this environment.",
59500
+ fix: 'Write httpAuth as {"credential": "Product key"} or {"credential": {"production": "Prod key", "staging": "Staging key"}}.'
59501
+ },
59502
+ HTTP_CREDENTIAL_NOT_FOUND: {
59503
+ title: "No credential with this name",
59504
+ meaning: "The account has no HTTP target credential with the name httpAuth.credential gives.",
59505
+ fix: "Create it first: waitcher target credential create --file credential.json --credential-file ./private/key (the name is in its JSON), or fix the name."
59506
+ },
59507
+ HTTP_CREDENTIAL_AMBIGUOUS: {
59508
+ title: "Credential name is not unique",
59509
+ meaning: "Two HTTP target credentials share the name, so the reference cannot choose one.",
59510
+ fix: "Give each credential a distinct name, or use the target, credential and revision IDs in httpAuth."
59511
+ },
58881
59512
  ADOPTION_CANDIDATE: {
58882
59513
  title: "An existing monitor looks like this entry",
58883
59514
  meaning: "Applying would create a second monitor next to an unmanaged one with the same name or target.",
@@ -59142,7 +59773,8 @@ var DEPLOY_TYPES = [
59142
59773
  "certificate",
59143
59774
  "heartbeat",
59144
59775
  ...SCRIPT_TYPES,
59145
- "visual"
59776
+ "visual",
59777
+ "mcp"
59146
59778
  ];
59147
59779
  var isScriptType = (type) => SCRIPT_TYPES.includes(type);
59148
59780
  var MONITOR_KEY = /^[a-z0-9][a-z0-9-]{0,62}$/;
@@ -59176,10 +59808,15 @@ var projectConfigSchema = external_exports.object({
59176
59808
  monitors: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).max(CONFIG_LIMITS.monitors)
59177
59809
  }).strict();
59178
59810
  var pathOf = (parts) => parts.reduce(
59179
- (text3, part2) => typeof part2 === "number" ? `${text3}[${part2}]` : `${text3}${text3 ? "." : ""}${String(part2)}`,
59811
+ (text4, part2) => typeof part2 === "number" ? `${text4}[${part2}]` : `${text4}${text4 ? "." : ""}${String(part2)}`,
59180
59812
  ""
59181
59813
  );
59182
- function resolveProjectConfig(input2, environment, scripts) {
59814
+ var PLACEHOLDER_HTTP_AUTH = {
59815
+ targetId: "00000000-0000-4000-8000-000000000000",
59816
+ credentialId: "00000000-0000-4000-8000-000000000000",
59817
+ credentialRevision: 1
59818
+ };
59819
+ function resolveProjectConfig(input2, environment, scripts, httpAuth) {
59183
59820
  const result2 = {
59184
59821
  environments: [],
59185
59822
  declared: [],
@@ -59282,6 +59919,32 @@ function resolveProjectConfig(input2, environment, scripts) {
59282
59919
  `${at}.entry`,
59283
59920
  key
59284
59921
  );
59922
+ const ref = rest.httpAuth;
59923
+ if (ref && typeof ref === "object" && !Array.isArray(ref) && Object.hasOwn(ref, "credential")) {
59924
+ const named = ref.credential;
59925
+ const name5 = typeof named === "string" ? named : named && typeof named === "object" && !Array.isArray(named) ? Object.entries(named).find(
59926
+ ([k]) => lookup3(k) === env
59927
+ )?.[1] : void 0;
59928
+ if (Object.keys(ref).length !== 1 || typeof name5 !== "string" || !name5)
59929
+ return fail2(
59930
+ "HTTP_CREDENTIAL_REFERENCE",
59931
+ `httpAuth.credential is a credential name, or a name per environment including "${env}"`,
59932
+ `${at}.httpAuth`,
59933
+ key
59934
+ );
59935
+ if (!httpAuth) rest.httpAuth = PLACEHOLDER_HTTP_AUTH;
59936
+ else {
59937
+ const bound = httpAuth(name5);
59938
+ if (bound === "missing" || bound === "ambiguous")
59939
+ return fail2(
59940
+ bound === "missing" ? "HTTP_CREDENTIAL_NOT_FOUND" : "HTTP_CREDENTIAL_AMBIGUOUS",
59941
+ bound === "missing" ? `No HTTP credential is named "${name5}"` : `More than one HTTP credential is named "${name5}"; rename one`,
59942
+ `${at}.httpAuth`,
59943
+ key
59944
+ );
59945
+ rest.httpAuth = bound;
59946
+ }
59947
+ }
59285
59948
  let target = rest.target;
59286
59949
  if (path2 !== void 0) {
59287
59950
  if (target !== void 0)
@@ -59385,6 +60048,25 @@ function projectConfigJsonSchema() {
59385
60048
  const { $schema: _, ...config2 } = external_exports.toJSONSchema(projectConfigSchema, io);
59386
60049
  const monitor = external_exports.toJSONSchema(monitorDefinitionSchema, io);
59387
60050
  const properties = { ...monitor.properties };
60051
+ properties.httpAuth = {
60052
+ description: "Stored header credential: account IDs, or a credential name (one per environment as an object)",
60053
+ anyOf: [
60054
+ properties.httpAuth,
60055
+ {
60056
+ type: "object",
60057
+ additionalProperties: false,
60058
+ required: ["credential"],
60059
+ properties: {
60060
+ credential: {
60061
+ anyOf: [
60062
+ { type: "string", minLength: 1 },
60063
+ { type: "object", additionalProperties: { type: "string", minLength: 1 } }
60064
+ ]
60065
+ }
60066
+ }
60067
+ }
60068
+ ]
60069
+ };
59388
60070
  for (const field of ["demo", "enabled", "script", "schemaVersion", "context", "ai", "aiEndpoint"])
59389
60071
  delete properties[field];
59390
60072
  Object.assign(properties, {
@@ -59461,8 +60143,8 @@ async function readConnectionConfiguration(file2) {
59461
60143
  2
59462
60144
  );
59463
60145
  }
59464
- function providerCredential(text3) {
59465
- const parsed = connectionSecretSchema.safeParse(text3.trim());
60146
+ function providerCredential(text4) {
60147
+ const parsed = connectionSecretSchema.safeParse(text4.trim());
59466
60148
  if (!parsed.success)
59467
60149
  throw new ServiceError(
59468
60150
  "Provide a private provider key through --credential-file or --credential-stdin.",
@@ -59629,8 +60311,8 @@ function modelAllowance(body2, models, maxOutput) {
59629
60311
  return { outputTokens, reservedTokens };
59630
60312
  }
59631
60313
  function modelOutcome(input2) {
59632
- const reason = !input2.authorized ? "AI_NOT_AUTHORIZED" : input2.failure ?? (input2.pending || input2.lastState && input2.lastState !== "known" ? "AI_USAGE_UNKNOWN" : null);
59633
- return { ok: reason === null, reason };
60314
+ const reason2 = !input2.authorized ? "AI_NOT_AUTHORIZED" : input2.failure ?? (input2.pending || input2.lastState && input2.lastState !== "known" ? "AI_USAGE_UNKNOWN" : null);
60315
+ return { ok: reason2 === null, reason: reason2 };
59634
60316
  }
59635
60317
  function modelTransport(authority, options = {}) {
59636
60318
  const providerFetch = options.fetchImpl ?? fetch, now = options.now ?? Date.now, requestMs = options.requestMs ?? MODEL_LIMITS.requestMs;
@@ -59720,8 +60402,8 @@ function modelTransport(authority, options = {}) {
59720
60402
  "Model provider did not accept the request"
59721
60403
  );
59722
60404
  }
59723
- const text3 = await boundedText(response2, MODEL_LIMITS.responseBytes);
59724
- if (text3.includes(call.secret) || text3.includes(JSON.stringify(call.secret).slice(1, -1)))
60405
+ const text4 = await boundedText(response2, MODEL_LIMITS.responseBytes);
60406
+ if (text4.includes(call.secret) || text4.includes(JSON.stringify(call.secret).slice(1, -1)))
59725
60407
  throw new AppError(
59726
60408
  502,
59727
60409
  "AI_RESPONSE_REJECTED",
@@ -59729,7 +60411,7 @@ function modelTransport(authority, options = {}) {
59729
60411
  );
59730
60412
  let result2;
59731
60413
  try {
59732
- result2 = modelResponseSchema.safeParse(JSON.parse(text3));
60414
+ result2 = modelResponseSchema.safeParse(JSON.parse(text4));
59733
60415
  } catch {
59734
60416
  }
59735
60417
  if (!result2?.success || result2.data.model !== body2.model)
@@ -60083,7 +60765,7 @@ async function runLocalRequest(definition, options, project) {
60083
60765
  const info = await lstat7(parent);
60084
60766
  if (!info.isDirectory() || info.isSymbolicLink())
60085
60767
  invalid2("Output must be a regular directory, not a symbolic link.");
60086
- const runId = randomUUID4(), directory = join8(parent, runId), startedAt = Date.now(), start = performance5.now();
60768
+ const runId = randomUUID4(), directory = join8(parent, runId), startedAt = Date.now(), start = performance6.now();
60087
60769
  await mkdir4(directory, { mode: 448 });
60088
60770
  const timeout = options.timeout ?? definition.timeout;
60089
60771
  const signal = AbortSignal.any([
@@ -60093,6 +60775,7 @@ async function runLocalRequest(definition, options, project) {
60093
60775
  let broker;
60094
60776
  let modelUsage;
60095
60777
  let check2;
60778
+ let mcpToolResult;
60096
60779
  try {
60097
60780
  if (binding && connection) {
60098
60781
  broker = await localModelBroker(
@@ -60111,6 +60794,7 @@ async function runLocalRequest(definition, options, project) {
60111
60794
  aiEndpointFetch: options.aiEndpointFetch,
60112
60795
  httpFetch: options.httpFetch,
60113
60796
  httpCredential: credential,
60797
+ onMcpToolResult: (result3) => mcpToolResult = result3,
60114
60798
  ...broker ? {
60115
60799
  judgeComplete: async (body2, signal2) => {
60116
60800
  const response = await broker.complete(
@@ -60145,9 +60829,9 @@ async function runLocalRequest(definition, options, project) {
60145
60829
  }
60146
60830
  const report = join8(
60147
60831
  directory,
60148
- definition.type === "ai" ? "ai-endpoint-report.json" : "http-report.json"
60832
+ definition.type === "ai" ? "ai-endpoint-report.json" : definition.type === "mcp" ? "mcp-report.json" : "http-report.json"
60149
60833
  ), log = join8(directory, "execution.log");
60150
- const reportText = definition.type === "ai" ? check2.logs : JSON.stringify({
60834
+ const reportText = ["ai", "mcp"].includes(definition.type) ? check2.logs : JSON.stringify({
60151
60835
  schemaVersion: 1,
60152
60836
  kind: "http",
60153
60837
  status: check2.status,
@@ -60156,6 +60840,12 @@ async function runLocalRequest(definition, options, project) {
60156
60840
  });
60157
60841
  await writeFile4(report, reportText + "\n", { mode: 384, flag: "wx" });
60158
60842
  await writeFile4(log, check2.logs + "\n", { mode: 384, flag: "wx" });
60843
+ if (mcpToolResult !== void 0)
60844
+ await writeFile4(
60845
+ join8(directory, "mcp-tool-result.json"),
60846
+ JSON.stringify(mcpToolResult, null, 2) + "\n",
60847
+ { mode: 384, flag: "wx" }
60848
+ );
60159
60849
  await writeLocalFrozenDefinition(directory, definition);
60160
60850
  const result2 = {
60161
60851
  schemaVersion: 1,
@@ -60165,7 +60855,7 @@ async function runLocalRequest(definition, options, project) {
60165
60855
  status: check2.status,
60166
60856
  message: check2.message,
60167
60857
  startedAt,
60168
- duration: Math.round(performance5.now() - start),
60858
+ duration: Math.round(performance6.now() - start),
60169
60859
  directory,
60170
60860
  report,
60171
60861
  summary: null,
@@ -60201,14 +60891,14 @@ async function runLocal(options) {
60201
60891
  "--browser-identities-file applies only to a bound browser manifest."
60202
60892
  );
60203
60893
  const browserIdentity = definition ? await localBrowserIdentity(options.browserIdentitiesFile, definition) : void 0;
60204
- if (definition && ["ai", "http"].includes(definition.type)) {
60205
- if (definition.type === "ai" && options.timeout !== void 0 && (!Number.isSafeInteger(options.timeout) || options.timeout < 3 || options.timeout > AI_ENDPOINT_LIMITS.maxTimeoutSeconds))
60894
+ if (definition && ["ai", "http", "mcp"].includes(definition.type)) {
60895
+ if (["ai", "mcp"].includes(definition.type) && options.timeout !== void 0 && (!Number.isSafeInteger(options.timeout) || options.timeout < 3 || options.timeout > AI_ENDPOINT_LIMITS.maxTimeoutSeconds))
60206
60896
  invalid2(
60207
- `AI endpoint timeout must be an integer from 3 to ${AI_ENDPOINT_LIMITS.maxTimeoutSeconds} seconds.`
60897
+ `AI endpoint and MCP timeouts must be an integer from 3 to ${AI_ENDPOINT_LIMITS.maxTimeoutSeconds} seconds.`
60208
60898
  );
60209
60899
  if (options.runtime || options.video)
60210
60900
  invalid2(
60211
- "HTTP/AI endpoint fixtures need no E2E runtime or video; omit those options."
60901
+ "HTTP, AI endpoint and MCP checks need no E2E runtime or video; omit those options."
60212
60902
  );
60213
60903
  if (options.connectionsFile && !endpointJudgeBinding(definition.aiEndpoint))
60214
60904
  invalid2(
@@ -60285,7 +60975,7 @@ async function runLocal(options) {
60285
60975
  }
60286
60976
  const runId = randomUUID4(), directory = join8(parent, runId);
60287
60977
  await mkdir4(directory, { mode: 448 });
60288
- const startedAt = Date.now(), start = performance5.now();
60978
+ const startedAt = Date.now(), start = performance6.now();
60289
60979
  const timeout = options.timeout ?? definition?.timeout ?? 60;
60290
60980
  const evidence = definition ? ".e2e" : "evidence";
60291
60981
  let status2 = "error", logs = "", message = "Local execution did not finish";
@@ -60473,7 +61163,7 @@ async function runLocal(options) {
60473
61163
  status: finalStatus,
60474
61164
  message,
60475
61165
  startedAt,
60476
- duration: Math.round(performance5.now() - start),
61166
+ duration: Math.round(performance6.now() - start),
60477
61167
  directory,
60478
61168
  report: files.some((f) => f.path === `${evidence}/report.json`) ? join8(directory, evidence, "report.json") : null,
60479
61169
  summary: files.some((f) => f.path === `${evidence}/summary.md`) ? join8(directory, evidence, "summary.md") : null,
@@ -61132,9 +61822,9 @@ function pinPackageJson(existing, project) {
61132
61822
  }
61133
61823
  return { json: json3, changes };
61134
61824
  }
61135
- var missingIgnores = (text3) => {
61825
+ var missingIgnores = (text4) => {
61136
61826
  const lines = new Set(
61137
- text3.split(/\r?\n/).map((l) => l.trim().replace(/^\//, ""))
61827
+ text4.split(/\r?\n/).map((l) => l.trim().replace(/^\//, ""))
61138
61828
  );
61139
61829
  return RUNTIME_IGNORES.filter(
61140
61830
  (entry2) => !lines.has(entry2) && !lines.has(entry2.slice(0, -1))
@@ -61164,11 +61854,11 @@ function run(command, args, cwd, signal) {
61164
61854
  async function installRuntime(options) {
61165
61855
  const { project, browser, yes, signal } = options;
61166
61856
  const manifestPath = join11(project, "package.json");
61167
- const text3 = await readFile6(manifestPath, "utf8").catch(() => null);
61857
+ const text4 = await readFile6(manifestPath, "utf8").catch(() => null);
61168
61858
  let existing = null;
61169
- if (text3 !== null)
61859
+ if (text4 !== null)
61170
61860
  try {
61171
- existing = JSON.parse(text3);
61861
+ existing = JSON.parse(text4);
61172
61862
  } catch (cause) {
61173
61863
  throw new ServiceError(
61174
61864
  `${manifestPath} is not valid JSON: ${cause.message}`,
@@ -61421,9 +62111,9 @@ async function verifyLocally(options) {
61421
62111
  var configPath = (file2) => resolve13(file2 ?? CONFIG_FILE);
61422
62112
  async function readProjectConfig(file2) {
61423
62113
  const path2 = configPath(file2);
61424
- let text3;
62114
+ let text4;
61425
62115
  try {
61426
- text3 = await readFile7(path2, "utf8");
62116
+ text4 = await readFile7(path2, "utf8");
61427
62117
  } catch {
61428
62118
  throw new ServiceError(
61429
62119
  `${path2} was not found. Run waitcher config init or pass --file.`,
@@ -61431,14 +62121,14 @@ async function readProjectConfig(file2) {
61431
62121
  2
61432
62122
  );
61433
62123
  }
61434
- if (Buffer.byteLength(text3) > CONFIG_LIMITS.bytes)
62124
+ if (Buffer.byteLength(text4) > CONFIG_LIMITS.bytes)
61435
62125
  throw new ServiceError(
61436
62126
  `waitcher.json exceeds ${CONFIG_LIMITS.bytes} bytes.`,
61437
62127
  "VALIDATION_ERROR",
61438
62128
  2
61439
62129
  );
61440
62130
  try {
61441
- return { path: path2, config: JSON.parse(text3) };
62131
+ return { path: path2, config: JSON.parse(text4) };
61442
62132
  } catch (cause) {
61443
62133
  throw new ServiceError(
61444
62134
  `waitcher.json is not valid JSON: ${cause.message}`,
@@ -61513,13 +62203,13 @@ function deployNextSteps(result2, {
61513
62203
  }
61514
62204
 
61515
62205
  // ../../skills/waitcher/SKILL.md
61516
- var SKILL_default = "---\nname: waitcher\ndescription: Set up and maintain Waitcher monitoring from a repository with the waitcher CLI. Use to turn a product's critical journeys into HTTP, certificate, heartbeat, API, browser or visual monitors in waitcher.json, verify them locally, deploy them through a reviewed plan, and diagnose failures from real evidence.\n---\n\n# Waitcher\n\nYou operate the waitcher CLI for the user. The repository is the source of truth: `waitcher.json` declares the monitors of one project per environment, test files hold the scripts, and `waitcher deploy` reconciles one environment at a time. Commands print JSON on stdout (`run diagnose` and `run scenarios` need `--json` for it); failures print `{error:{code,message}}` on stderr. Read the exit code, every `issues` entry and every `next` step.\n\nThis skill says what to do and in which order. For exact syntax use the installed CLI, never memory: `waitcher help TOPIC` (for example `help deploy`, `help secret`, `help run`) prints only that part of the help for this CLI version, and `waitcher explain CODE` explains an issue or error code. The user guide at https://waitcher.dev/docs/ explains the same product for people; link the user to a page (CLI install and updates, alerts, access tokens, account) instead of retelling it.\n\n## Rules\n\n- Never put secrets in files, arguments or output. Pipe values to `--value-stdin`.\n- Keep new monitors paused. Pass `--activate-new`, `--prune`, `--adopt` or `--smoke` only when the user agreed to that effect.\n- Show the user the plan's `changes` before `deploy apply`, and apply with `--based-on` from that plan.\n- A local pass is not hosted permission. If capabilities or limits refuse something, report it; never switch accounts, raise limits or remove assertions to get a green result.\n- An agent's own success claim is not evidence. Verify outcomes through the product's state or real run evidence.\n- Do not turn a whole regression suite into monitors. Pick two to five journeys whose failure the user would act on.\n\n## Workflow\n\n1. **Check the setup.** Run `waitcher doctor` in the repository. Fix `error` checks first; its `next` lists exact commands. Without a session, ask the user to run `waitcher auth login` (CI uses a token).\n2. **Understand the product.** Read the repository: base URLs per environment, existing E2E tests, critical journeys, test accounts and jobs. Ask the user which failures should alert them.\n3. **Start the file.** `waitcher config init --project-name NAME --target https://BASE` when there is no `waitcher.json`. Give each monitor a stable lowercase `key`; changing a key later replaces the monitor and its history.\n4. **Choose types.** `http` for status and content, `certificate` for TLS expiry, `heartbeat` for jobs that report in, `api` for a multi-request invariant, `browser` for a user journey. `waitcher monitor init --type TYPE --file x.json` prints a complete example of any type. Script monitors name their test with `entry`; read [authoring](references/authoring.md) before writing one. They need the pinned runtime next to `waitcher.json`: run `waitcher runtime install`, show the user the steps it lists (npm install runs package install scripts; browser projects download Chromium), and after they agree rerun it with `--yes`. It writes exact pins into `package.json`, updates `.gitignore` and is safe to repeat. The same command upgrades the project after a CLI update (`RUNTIME_VERSION_OUTDATED`).\n5. **Validate offline.** `waitcher config validate` resolves every environment and builds every entry. Fix each issue at its `path`. Add `--env NAME --verify` (optionally `--key KEY`) to run the api/browser entries locally without an account; read the run directory it names when one fails.\n6. **Plan.** `waitcher deploy plan --env NAME --verify` runs script monitors locally against that environment, then asks the server. Resolve errors (`SECRET_MISSING`: ask the user for the value and run `waitcher secret set`; `ADOPTION_CANDIDATE`: ask whether the existing monitor is the same check).\n7. **Apply.** After the user accepts the plan: `waitcher deploy apply --env NAME --based-on BASED_ON`, where BASED_ON is the plan's `basedOn` or `none` when it is null (first deploy); the plan's `next` prints the exact command. Add `--smoke` for one hosted run per changed monitor. New monitors stay paused.\n8. **Report.** Give the user the monitor IDs, what each checks, local and hosted results, evidence paths and anything still pending (paused schedules, heartbeat credentials, secrets for other environments). If `waitcher alert policy list` shows no routing, failures will alert nobody: point the user to https://waitcher.dev/docs/alerts.\n\nFor CI, `waitcher ci init` writes a workflow that plans on pull requests and applies on the main branch. Details of secrets, adoption, rollback and CI are in [deploy](references/deploy.md).\n\n## When something fails\n\n- `waitcher --help` prints a short overview of topics; `waitcher help TOPIC` (or `waitcher GROUP --help`) prints one part with the exit codes; `waitcher help all` is long, avoid it.\n- Exit 2: fix the file or input; exit 3: sign in; exit 4: a check failed (inspect evidence); exit 6: quota, rate or queue limit; exit 7: not permitted; exit 8: conflict or managed by `waitcher.json`; exit 9: not found; exit 10: service unavailable.\n- For a failed run, read [diagnosis](references/diagnosis.md): `waitcher run diagnose --id RUN_ID`, then reproduce locally before changing the test.\n- Never retry a write automatically after an uncertain result; read the current state first.\n\n## References\n\n- [authoring](references/authoring.md): choosing a type, writing API and browser tests, local runs and evidence, single-monitor apply.\n- [deploy](references/deploy.md): waitcher.json details, secrets, adoption, rollback, CI.\n- [diagnosis](references/diagnosis.md): run diagnosis and reproduction.\n- [optional capabilities](references/optional-capabilities.md): visual baselines, browser identities, verified HTTP credentials, invocation budgets, agent checks, public status pages.\n- [AI and agents](references/ai-and-agents.md): agent outcome checks, scenario evidence, AI endpoints and suites, calibration, AI steps in scripts, protected requests.\n- Read the last two only when `waitcher system capabilities` reports the feature and the user needs it.\n";
62206
+ var SKILL_default = "---\nname: waitcher\ndescription: Set up and maintain Waitcher monitoring from a repository with the waitcher CLI. Use to turn a product's critical journeys into HTTP, certificate, heartbeat, API, browser, visual or MCP monitors in waitcher.json, verify them locally, deploy them through a reviewed plan, and diagnose failures from real evidence.\n---\n\n# Waitcher\n\nYou operate the waitcher CLI for the user. The repository is the source of truth: `waitcher.json` declares the monitors of one project per environment, test files hold the scripts, and `waitcher deploy` reconciles one environment at a time. Commands print JSON on stdout (`run diagnose` and `run scenarios` need `--json` for it); failures print `{error:{code,message}}` on stderr. Read the exit code, every `issues` entry and every `next` step.\n\nThis skill says what to do and in which order. For exact syntax use the installed CLI, never memory: `waitcher help TOPIC` (for example `help deploy`, `help secret`, `help run`) prints only that part of the help for this CLI version, and `waitcher explain CODE` explains an issue or error code. The user guide at https://waitcher.dev/docs/ explains the same product for people; link the user to a page (CLI install and updates, alerts, access tokens, account) instead of retelling it.\n\n## Rules\n\n- Never put secrets in files, arguments or output. Pipe values to `--value-stdin`.\n- Keep new monitors paused. Pass `--activate-new`, `--prune`, `--adopt` or `--smoke` only when the user agreed to that effect.\n- Show the user the plan's `changes` before `deploy apply`, and apply with `--based-on` from that plan.\n- A local pass is not hosted permission. If capabilities or limits refuse something, report it; never switch accounts, raise limits or remove assertions to get a green result.\n- An agent's own success claim is not evidence. Verify outcomes through the product's state or real run evidence.\n- Do not turn a whole regression suite into monitors. Pick two to five journeys whose failure the user would act on.\n\n## Workflow\n\n1. **Check the setup.** Run `waitcher doctor` in the repository. Fix `error` checks first; its `next` lists exact commands. Without a session, ask the user to run `waitcher auth login` (CI uses a token).\n2. **Understand the product.** Read the repository: base URLs per environment, existing E2E tests, critical journeys, test accounts and jobs. Ask the user which failures should alert them.\n3. **Start the file.** `waitcher config init --project-name NAME --target https://BASE` when there is no `waitcher.json`. Give each monitor a stable lowercase `key`; changing a key later replaces the monitor and its history.\n4. **Choose types.** `http` for status and content, `certificate` for TLS expiry, `heartbeat` for jobs that report in, `api` for a multi-request invariant, `browser` for a user journey, `mcp` when the product ships a remote MCP server. `waitcher monitor init --type TYPE --file x.json` prints a complete example of any type. Script monitors name their test with `entry`; read [authoring](references/authoring.md) before writing one. They need the pinned runtime next to `waitcher.json`: run `waitcher runtime install`, show the user the steps it lists (npm install runs package install scripts; browser projects download Chromium), and after they agree rerun it with `--yes`. It writes exact pins into `package.json`, updates `.gitignore` and is safe to repeat. The same command upgrades the project after a CLI update (`RUNTIME_VERSION_OUTDATED`).\n5. **Validate offline.** `waitcher config validate` resolves every environment and builds every entry. Fix each issue at its `path`. Add `--env NAME --verify` (optionally `--key KEY`) to run the api/browser entries locally without an account; read the run directory it names when one fails.\n6. **Plan.** `waitcher deploy plan --env NAME --verify` runs script monitors locally against that environment, then asks the server. Resolve errors (`SECRET_MISSING`: ask the user for the value and run `waitcher secret set`; `ADOPTION_CANDIDATE`: ask whether the existing monitor is the same check).\n7. **Apply.** After the user accepts the plan: `waitcher deploy apply --env NAME --based-on BASED_ON`, where BASED_ON is the plan's `basedOn` or `none` when it is null (first deploy); the plan's `next` prints the exact command. Add `--smoke` for one hosted run per changed monitor. New monitors stay paused.\n8. **Report.** Give the user the monitor IDs, what each checks, local and hosted results, evidence paths and anything still pending (paused schedules, heartbeat credentials, secrets for other environments). If `waitcher alert policy list` shows no routing, failures will alert nobody: point the user to https://waitcher.dev/docs/alerts.\n\nFor CI, `waitcher ci init` writes a workflow that plans on pull requests and applies on the main branch. Details of secrets, adoption, rollback and CI are in [deploy](references/deploy.md).\n\n## When something fails\n\n- `waitcher --help` prints a short overview of topics; `waitcher help TOPIC` (or `waitcher GROUP --help`) prints one part with the exit codes; `waitcher help all` is long, avoid it.\n- Exit 2: fix the file or input; exit 3: sign in; exit 4: a check failed (inspect evidence); exit 6: quota, rate or queue limit; exit 7: not permitted; exit 8: conflict or managed by `waitcher.json`; exit 9: not found; exit 10: service unavailable.\n- For a failed run, read [diagnosis](references/diagnosis.md): `waitcher run diagnose --id RUN_ID`, then reproduce locally before changing the test.\n- Never retry a write automatically after an uncertain result; read the current state first.\n\n## References\n\n- [authoring](references/authoring.md): choosing a type, writing API and browser tests, local runs and evidence, single-monitor apply.\n- [deploy](references/deploy.md): waitcher.json details, secrets, adoption, rollback, CI.\n- [diagnosis](references/diagnosis.md): run diagnosis and reproduction.\n- [optional capabilities](references/optional-capabilities.md): visual baselines, browser identities, verified HTTP credentials, invocation budgets, agent checks, public status pages.\n- [AI and agents](references/ai-and-agents.md): agent outcome checks, scenario evidence, AI endpoints and suites, calibration, AI steps in scripts, protected requests.\n- Read the last two only when `waitcher system capabilities` reports the feature and the user needs it.\n";
61517
62207
 
61518
62208
  // ../../skills/waitcher/references/authoring.md
61519
- var authoring_default = '# Authoring and running monitors\n\nRead when writing or changing a test, choosing a monitor type, or running it locally. For exact syntax run `waitcher help monitor` or `waitcher help run`. AI endpoints, agent outcome checks and model steps are in [ai-and-agents](ai-and-agents.md).\n\n## Choose the type\n\n- `http`: status, body text, a JSON value or latency of one request. No script.\n- `certificate`: TLS expiry and chain. No script.\n- `heartbeat`: a job reports start and success; Waitcher alerts when it does not.\n- `api`: a script with several requests and an invariant between them.\n- `browser`: a script that walks a user journey in Chromium.\n- `visual`: a screenshot of one public page or element compared with a baseline the user approved. No script; see [optional capabilities](optional-capabilities.md#optional-visual-checks).\n\n`waitcher monitor init --type TYPE --file x.json` writes a paused example of every type; `api` and `browser` also write `x.e2e.ts`. Keep scripts focused on the requested behavior and use controlled test identities for actions that change state.\n\n## Scripts in waitcher.json\n\nIn a repository, a script monitor is an entry with `entry` pointing at its test file; one test serves every environment because it reads the base URL at run time.\n\n```json\n{ "key": "checkout", "type": "browser", "entry": "monitoring/checkout.e2e.ts", "timeout": 45 }\n```\n\nRun the entries of one environment locally, without an account:\n\n```sh\nwaitcher config validate --env production --verify\nwaitcher config validate --env production --verify --key checkout\n```\n\nExit 4 with `VERIFY_FAILED` names the failing assertion and the run directory to read. `run local --file` takes a single monitor manifest, not `waitcher.json`.\n\n## Browser journey\n\n```ts\nimport { test } from "@e2e-dev/web";\nimport { expect } from "e2e";\n\ntest("visitor can start a game", async ({ app, browser, screen }) => {\n await app.open("/games/klondike/");\n await expect(browser.locator("main h1")).toContainText("Solitaire");\n await expect(screen.getByRole("button", "New game")).toBeVisible();\n await app.screenshot("game");\n});\n```\n\n- `app.open(path)` resolves against the environment\'s base URL. Browser base URLs have no query or fragment; navigate to those URLs inside the script.\n- Find elements the way a visitor does with the `screen` fixture: `screen.getByRole("button", "New game")`, `screen.getByLabel("Email")`, `screen.getByText("Welcome")`, `screen.getByPlaceholder(...)`, `screen.getByTestId(...)`. Prefer these over CSS selectors.\n- The `browser` fixture navigates and offers CSS `browser.locator("main h1")` plus `expect(browser).toHaveURL(...)`; it has no `getBy*` methods.\n- Assertions come from `e2e`: `toBeVisible()`, `toContainText(...)`, `toHaveText(...)`.\n\n## API script\n\n```ts\nimport { test, expect } from "e2e";\n\ntest("orders API keeps totals consistent", async () => {\n const target = new URL(process.env.TARGET_URL!);\n const response = await fetch(new URL("/api/orders?limit=1", target));\n expect(response.status).toBe(200);\n});\n```\n\nAPI scripts import `test, expect` from `e2e` and read `process.env.TARGET_URL`. Secrets reach them only as `CHECK_*` names listed in `settings.envNames` (see [deploy](deploy.md)). The test runs as trusted local code, not in a sandbox.\n\n## Standalone manifest\n\nWithout `waitcher.json`, a monitor is one JSON file. `monitor init --type browser --file monitor.json` writes it with `scriptFile` next to the test:\n\n```json\n{\n "schemaVersion": 1,\n "name": "Product / key journey",\n "type": "browser",\n "target": "https://example.com/",\n "enabled": false,\n "interval": 1800,\n "timeout": 30,\n "scriptFile": "journey.e2e.ts"\n}\n```\n\n`scriptFile` resolves relative to the manifest; `monitor validate --file monitor.json` checks the actual contract. The platform receives one script per monitor, not the project directory. When the test imports shared helpers, run `monitor build --file monitors/checkout.json --project . --output build/checkout`: it needs installed `esbuild@0.28.2`, bundles code and JSON helpers, keeps only supported framework and Node imports, and writes `monitor.js`, `monitor.json` and `build.json` into a new directory. Unsupported dependencies and module-relative file access fail the build. Verify and apply the built `monitor.json`. The script limit is 50,000 characters and hosted dependencies are fixed.\n\n## Run locally and inspect evidence\n\nThe runtime project needs `e2e@0.21.1` and, for browser tests, `@e2e-dev/web@0.15.1` and Chromium. `waitcher runtime install --file DIR/waitcher.json [--browser]` lists the npm install and Chromium download; run it with `--yes` once the user agrees. Chromium goes to the Playwright browser cache (`PLAYWRIGHT_BROWSERS_PATH` when set), not the runtime directory.\n\n```sh\nwaitcher run local --file monitor.json --runtime /path/to/runtime\nwaitcher run local --file monitor.json --runtime /path/to/runtime --video\nwaitcher run local --project /path/to/e2e-project --timeout 60\n```\n\n- `--project` runs an existing E2E project with its own config and imports; its `--output` must stay inside that project.\n- Runs are serial, never retried or replayed, and get a fresh directory under `.waitcher/runs/` (`--output DIR` chooses the parent). Traces are always requested; video is opt-in, and tests can override recording, so inspect the returned files.\n- On failure read `.e2e/summary.md` and `.e2e/results/*/trace.md` in the run directory first, then `execution.log` and `report.json`. The `waitcher-*.mjs` files there are runtime support, not your test. Traces are Markdown, not Playwright ZIPs; there is no HAR option, and app logs hold selected console and request failures only.\n- Exit codes: 0 passed, 4 failed or error, 130 interrupted. After an interruption, inspect partial evidence before repeating a possibly completed action.\n- Fix test mistakes while preserving the user\'s assertions; never weaken an assertion just to get green.\n- Evidence can contain private content: keep `.waitcher/`, `.e2e/`, keys and reports out of Git. Local results are not uploaded and are not hosted health evidence.\n\n## Apply one monitor through the API\n\nWhen hosted scripts are allowed and applying configuration is in scope:\n\n```sh\nwaitcher monitor apply --file monitor.json --dry-run\nwaitcher monitor apply --file monitor.json\nwaitcher monitor get --id MONITOR_ID\n```\n\nKeep the monitor paused unless the user requested scheduled execution; applying does not run it. For an authorized single hosted run use `run start --id MONITOR_ID --wait`, then `run status`, `run trace --id RUN_ID` (steps, failed assertion, screenshots, fetch calls) and `artifact get` for evidence. Hosted scripts run under the server\'s execution policy and can differ from a local run.\n\nEdits are complete replacements: `monitor export`, change the file, then `monitor apply --file FILE --id ID --expected-revision N` with the revision from get or export. Use a stable `--request-key` to recover one uncertain create or run; never change the payload under that key or repeat a possibly executed action. Report the exact monitor and run IDs, local evidence path, observed outcome and any difference between local and hosted results.\n';
62209
+ var authoring_default = '# Authoring and running monitors\n\nRead when writing or changing a test, choosing a monitor type, or running it locally. For exact syntax run `waitcher help monitor` or `waitcher help run`. AI endpoints, agent outcome checks and model steps are in [ai-and-agents](ai-and-agents.md).\n\n## Choose the type\n\n- `http`: status, body text, a JSON value or latency of one request. No script.\n- `certificate`: TLS expiry and chain. No script.\n- `heartbeat`: a job reports start and success; Waitcher alerts when it does not.\n- `mcp`: a remote MCP server (Streamable HTTP). Lists tools and checks `mcp.expectTools`; an optional `mcp.toolCall` calls one side-effect-free tool with fixed arguments and JSON-pointer `assertions` on its result. No script. `run local --file mcp.json` runs it without an account; its `mcp-report.json` lists the tool names and `mcp-tool-result.json` holds the called tool\'s answer, so read both before writing `expectTools` and assertions. Personal tool calls need verified `httpAuth` and a 30-minute interval; listing tools needs neither. Never pick a tool that writes data. Details: https://waitcher.dev/docs/mcp.md.\n- `api`: a script with several requests and an invariant between them.\n- `browser`: a script that walks a user journey in Chromium.\n- `visual`: a screenshot of one public page or element compared with a baseline the user approved. No script; see [optional capabilities](optional-capabilities.md#optional-visual-checks).\n\n`waitcher monitor init --type TYPE --file x.json` writes a paused example of every type; `api` and `browser` also write `x.e2e.ts`. Keep scripts focused on the requested behavior and use controlled test identities for actions that change state.\n\n## Scripts in waitcher.json\n\nIn a repository, a script monitor is an entry with `entry` pointing at its test file; one test serves every environment because it reads the base URL at run time.\n\n```json\n{ "key": "checkout", "type": "browser", "entry": "monitoring/checkout.e2e.ts", "timeout": 45 }\n```\n\nRun the entries of one environment locally, without an account:\n\n```sh\nwaitcher config validate --env production --verify\nwaitcher config validate --env production --verify --key checkout\n```\n\nExit 4 with `VERIFY_FAILED` names the failing assertion and the run directory to read. `run local --file` takes a single monitor manifest, not `waitcher.json`.\n\n## Browser journey\n\n```ts\nimport { test } from "@e2e-dev/web";\nimport { expect } from "e2e";\n\ntest("visitor can start a game", async ({ app, browser, screen }) => {\n await app.open("/games/klondike/");\n await expect(browser.locator("main h1")).toContainText("Solitaire");\n await expect(screen.getByRole("button", "New game")).toBeVisible();\n await app.screenshot("game");\n});\n```\n\n- `app.open(path)` resolves against the environment\'s base URL. Browser base URLs have no query or fragment; navigate to those URLs inside the script.\n- Find elements the way a visitor does with the `screen` fixture: `screen.getByRole("button", "New game")`, `screen.getByLabel("Email")`, `screen.getByText("Welcome")`, `screen.getByPlaceholder(...)`, `screen.getByTestId(...)`. Prefer these over CSS selectors.\n- The `browser` fixture navigates and offers CSS `browser.locator("main h1")` plus `expect(browser).toHaveURL(...)`; it has no `getBy*` methods.\n- Assertions come from `e2e`: `toBeVisible()`, `toContainText(...)`, `toHaveText(...)`.\n\n## API script\n\n```ts\nimport { test, expect } from "e2e";\n\ntest("orders API keeps totals consistent", async () => {\n const target = new URL(process.env.TARGET_URL!);\n const response = await fetch(new URL("/api/orders?limit=1", target));\n expect(response.status).toBe(200);\n});\n```\n\nAPI scripts import `test, expect` from `e2e` and read `process.env.TARGET_URL`. Secrets reach them only as `CHECK_*` names listed in `settings.envNames` (see [deploy](deploy.md)). The test runs as trusted local code, not in a sandbox.\n\n## Standalone manifest\n\nWithout `waitcher.json`, a monitor is one JSON file. `monitor init --type browser --file monitor.json` writes it with `scriptFile` next to the test:\n\n```json\n{\n "schemaVersion": 1,\n "name": "Product / key journey",\n "type": "browser",\n "target": "https://example.com/",\n "enabled": false,\n "interval": 1800,\n "timeout": 30,\n "scriptFile": "journey.e2e.ts"\n}\n```\n\n`scriptFile` resolves relative to the manifest; `monitor validate --file monitor.json` checks the actual contract. The platform receives one script per monitor, not the project directory. When the test imports shared helpers, run `monitor build --file monitors/checkout.json --project . --output build/checkout`: it needs installed `esbuild@0.28.2`, bundles code and JSON helpers, keeps only supported framework and Node imports, and writes `monitor.js`, `monitor.json` and `build.json` into a new directory. Unsupported dependencies and module-relative file access fail the build. Verify and apply the built `monitor.json`. The script limit is 50,000 characters and hosted dependencies are fixed.\n\n## Run locally and inspect evidence\n\nThe runtime project needs `e2e@0.21.1` and, for browser tests, `@e2e-dev/web@0.15.1` and Chromium. `waitcher runtime install --file DIR/waitcher.json [--browser]` lists the npm install and Chromium download; run it with `--yes` once the user agrees. Chromium goes to the Playwright browser cache (`PLAYWRIGHT_BROWSERS_PATH` when set), not the runtime directory.\n\n```sh\nwaitcher run local --file monitor.json --runtime /path/to/runtime\nwaitcher run local --file monitor.json --runtime /path/to/runtime --video\nwaitcher run local --project /path/to/e2e-project --timeout 60\n```\n\n- `--project` runs an existing E2E project with its own config and imports; its `--output` must stay inside that project.\n- Runs are serial, never retried or replayed, and get a fresh directory under `.waitcher/runs/` (`--output DIR` chooses the parent). Traces are always requested; video is opt-in, and tests can override recording, so inspect the returned files.\n- On failure read `.e2e/summary.md` and `.e2e/results/*/trace.md` in the run directory first, then `execution.log` and `report.json`. The `waitcher-*.mjs` files there are runtime support, not your test. Traces are Markdown, not Playwright ZIPs; there is no HAR option, and app logs hold selected console and request failures only.\n- Exit codes: 0 passed, 4 failed or error, 130 interrupted. After an interruption, inspect partial evidence before repeating a possibly completed action.\n- Fix test mistakes while preserving the user\'s assertions; never weaken an assertion just to get green.\n- Evidence can contain private content: keep `.waitcher/`, `.e2e/`, keys and reports out of Git. Local results are not uploaded and are not hosted health evidence.\n\n## Apply one monitor through the API\n\nWhen hosted scripts are allowed and applying configuration is in scope:\n\n```sh\nwaitcher monitor apply --file monitor.json --dry-run\nwaitcher monitor apply --file monitor.json\nwaitcher monitor get --id MONITOR_ID\n```\n\nKeep the monitor paused unless the user requested scheduled execution; applying does not run it. For an authorized single hosted run use `run start --id MONITOR_ID --wait`, then `run status`, `run trace --id RUN_ID` (steps, failed assertion, screenshots, fetch calls) and `artifact get` for evidence. Hosted scripts run under the server\'s execution policy and can differ from a local run.\n\nEdits are complete replacements: `monitor export`, change the file, then `monitor apply --file FILE --id ID --expected-revision N` with the revision from get or export. Use a stable `--request-key` to recover one uncertain create or run; never change the payload under that key or repeat a possibly executed action. Report the exact monitor and run IDs, local evidence path, observed outcome and any difference between local and hosted results.\n';
61520
62210
 
61521
62211
  // ../../skills/waitcher/references/ai-and-agents.md
61522
- var ai_and_agents_default = "# AI endpoints, agent outcomes and model steps\n\nRead only when `waitcher system capabilities` reports the feature and the user needs it. Deterministic HTTP, API and browser monitors need none of this; see [authoring](authoring.md).\n\n## Agent outcome checks\n\nFor hosted scripts using `#waitcher/scenario`, first confirm `features.scenarioEvidence` through `system capabilities`, alongside script admission. Older servers may not provide this helper. Do not silently remove required scenario checks to make an unsupported run pass. Capability discovery is separate from native security, capacity and production release acceptance.\n\nFor an agent that changes application state, start with `monitor init --template agent-outcome --file outcome.json --target https://product.example/api/`. It creates a paused ordinary API script, with no model binding or paid-provider requirement. Adapt its fixed `agent/tasks` submission and `notes/{runId}` resource paths, disposable test namespace and exact expected fields. It submits one action, ignores claims of success and response-provided URLs, then independently reads the known resource at most three times. A fresh per-run random `id` and `correlationId` must both match, alongside the expected result. Action transport errors are never automatically retried. Cleanup runs in `finally` only after an independent read proves the resource belongs to this run; cleanup failures fail the test. If ownership or the action result is uncertain, it records cleanup as unverified and leaves state untouched. Reconcile possible late actions before repeating a mutating test. This pattern verifies the chosen outcome, not the agent's overall quality or the correctness of its explanation.\n\nThe starter uses the optional `#waitcher/scenario` helper with required submit/action, observe, verify and cleanup phases. `createScenario({id, phases})` returns `phase(id, callback)`, `assert(boolean)` and `incomplete(reason)`. Call signals only inside an active phase. Every scenario needs a required verify phase, and an executed verify phase must call `scenario.assert` at least once; an empty verification cannot establish pass. `assert(false)` records a business failure even if caught; ordinary callback exceptions and `incomplete(\"CLEANUP_UNVERIFIED\")` record coverage errors. Inspect `.e2e/waitcher-scenarios.json` in the private evidence: required phases that never ran or remain in flight also prevent a pass. Coverage error takes precedence while retaining failed verification facts. A false agent claim can therefore produce a failed verify phase and an overall error when cleanup remains uncertain. The helper does not automatically classify arbitrary E2E assertions or infer agent/tool traces. Use stable non-secret scenario/phase IDs, avoid raw response values in assertions, and do not use report labels as secret storage.\n\nUse the unchanged file with `monitor validate`, account-free `run local --file outcome.json --runtime YOUR_PINNED_RUNTIME`, and the existing API-script editor or `monitor apply --file outcome.json --dry-run`. Keep it paused after applying. Project authors can extract the script into `scriptFile`, keep helper imports and use `monitor build` to create one portable script; `#waitcher/scenario` stays external and is supplied by the manifest runner. The complete CLI includes `scenario-runtime.mjs`; keep package companions together. Standalone `--project` needs its own helper integration. The starter's default is credential-free. Optional local/trusted-administrator bearer tokens use `CHECK_AGENT_ACTION_TOKEN`, `CHECK_RESOURCE_READ_TOKEN` and `CHECK_RESOURCE_CLEANUP_TOKEN`, explicitly listed in `settings.envNames` and supplied outside the manifest. Hosted personal scripts receive `CHECK_*` values only from their project environment's secrets (`waitcher secret set`), never from the server's environment; do not work around that boundary. Do not log credentials or response bodies, and do not promise complete trace masking for arbitrary custom environment values. Local success does not establish hosted admission or isolation.\n\n## Scenario evidence\n\nInspect readable scenario evidence with `waitcher run scenarios --id RUN_ID`, or use `waitcher run scenarios --directory PRIVATE_RUN_DIR` for account-free local inspection without a server/runtime. Add `--json` for the exact shared report DTO. Do not combine selectors or pass `--server` for local inspection. Inspection of failed/error runs succeeds; execution exit codes remain unchanged. Keep authoritative run status separate from evidence availability: empty valid reports verify no business outcome, and pending/not-recorded/expired/invalid reports cannot establish a pass. Local evidence is checked against its recorded inventory and checksum; never edit it to manufacture a successful outcome.\n\n## AI product endpoints\n\nFor a single AI product endpoint, prefer a declarative `type: \"ai\"` fixture over an E2E script. Run `monitor init --type ai --target https://product.example/ai --file ai.json`, replace the sample request and response checks with the product contract, then `monitor validate --file ai.json`. JSON-pointer assertions support exact equality, type, existence and literal case-sensitive contains/not-contains/contains-any/contains-all checks; an optional bounded response schema checks structure. `run local --file ai.json` uses the same one-POST adapter without an account, model connection, provider key or E2E runtime. It only reaches public HTTPS endpoints and supports optional verified `httpAuth` references as described below; arbitrary custom headers and account-session inheritance are forbidden. Inspect the structured per-assertion report and distinguish transport coverage errors from product assertion failures. Applying the same file to hosted monitoring requires `features.aiEndpoints`; personal admission also requires a currently verified `httpAuth` binding; keep it paused unless scheduling is authorized. This verifies a chosen fixture, not general agent quality or a calibrated semantic judge.\n\nFor a small set of representative prompts against the same endpoint, use `aiEndpoint.adapter: \"json-http-suite-v1\"` and `cases` with 1\u20135 objects containing a stable unique `id`, readable `name`, positive `revision` (default 1), literal JSON-object `fixture`, and assertions and/or response schema. The suite `invocationBudget` equals its case count and is filled in when omitted. Validate offline and run the unchanged manifest locally before applying it; hosted capability `features.aiEndpointSuites` must be available. Cases run serially under one total monitor timeout. Assertion failures permit later cases; a transport/deadline error stops them as `not-run`. Inspect every case and coverage summary, not only the overall status. The controller reserves the full case count before any hosted request, and partial/uncertain runs retain that conservative allowance. Reported attempted requests can therefore be fewer than charged units. Deterministic suites do not provide semantic grading; do not describe text matching as semantic correctness. Single fixtures and each suite case can opt into literal variables with variables:{name:\"string\"} and exact {{name}} placeholders inside fixture string values. Without variables, braces remain literal. Use at most 16 names, ASCII letter followed by letters/digits/underscores (64 characters); prototype-related names are refused. Each value fits 4 KiB UTF-8, maps and rendered fixtures 16 KiB and complete configurations 64 KiB. No expressions, environment lookup, key/URL/assertion/rubric interpolation, matrix expansion or recursive replacement is supported. Missing/malformed placeholders reject before requests. Use non-secret data. Validate locally and preview before applying: exports keep authored maps while enqueue freezes rendered literal requests. Release comparisons use effective rendered bodies, so a changed variable value can be a changed policy even with the same case revision.\n\nFor optional semantic endpoint grading, use `json-http-graded-suite-v1`, portable schemaVersion 2 and explicit context (even the default project/environment). Set the top-level `judge` connectionId/configurationRevision/model/budget and add a rubric to each selected case: stable id/revision, criteria, outputPath, threshold and optional reference examples. Keep target credentials separate from judge keys. Hosted use requires `features.endpointJudges`; local use accepts the same private `--connections-file` map without an account, UI or E2E runtime. Only the selected output and rubric criteria/examples reach the judge. Known echoed managed product keys are refused before grading. Inspect score, verdict, rubric hash and private model-usage.json: malformed/unavailable/unknown/over-budget grading is inconclusive coverage and cannot pass or recover a product incident. There are no retries or fallback models. Every report currently marks calibration unverified; labelled reference examples do not prove accuracy. Keep calibration, pricing and release acceptance distinct from a controlled protocol pass.\n\nTo measure a rubric against labelled examples, use `monitor calibrate --id ID --file REQUEST_JSON` for a saved hosted monitor, then `monitor calibrations --id ID` or `monitor calibration --id ID --calibration-id ID` to inspect retained measurements. The request contains `caseId`, `dataset` and optional `repeats`. For account-free local measurement, use `run calibrate --file MONITOR --case-id CASE --dataset DATASET --connections-file PRIVATE_MAP`; `--dataset` is the dataset object alone. Use 2\u20134 fictional labelled outputs and 1\u20133 repeats, within the saved judge call/token budget and a total 30-second ceiling. Calibration calls only the judge, not the product endpoint, and creates no health runs, incidents or recovery. Keep known keys out of dataset/rubric identifiers, object keys and content as well as prompts. Inspect agreement over valid evaluated decisions, disagreement, repeat instability and technical coverage errors separately. A valid expected inconclusive can agree; a provider error cannot. Inspect private model usage for actual reservations. Exit 4 means disagreement, instability or coverage failure; never erase those results to obtain a green check. A small successful sample applies only to its exact dataset/rubric/model identity and does not establish general accuracy or automatically change the monitor\u2019s unverified calibration label.\n\nFor release regressions, use `project compare --id PROJECT_ID --deployment-id DEPLOYMENT_ID` and follow the opaque `next` cursor with `--before`. AI rows include case-level comparisons from frozen queued definitions and retained structured reports. Inspect each case classification and compatibility reasons. A different fixture, assertion, rubric, judge model or policy identity cannot establish a product regression; do not compare numeric scores across changed policies. Missing/invalid reports and unexecuted cases are coverage gaps. Follow the owned run references for evidence. Last passing and first failure are useful only for the matching case policy; a pass from another case or rubric is not a reproduction baseline. Display-name changes and JSON object key order do not change the evaluation policy. Comparison is read-only and never schedules another paid request.\n\n## AI steps in browser and API scripts\n\nFor personal AI-assisted browser journeys, require both `features.ai` and `features.isolatedAi` alongside script admission. Keep the `ai` model connection binding optional; deterministic scripts need no model or provider key. Hosted personal runs always use server-owned isolated policy and an explicitly model-capable isolated worker. An older worker, withdrawn capability or missing connection is a coverage failure, never a reason to switch accounts or execute through a trusted lane. Use the same version-2 manifest locally with a private connection map before applying it paused. Only attempt-scoped broker authority enters the disposable runtime; upstream keys stay controller-side. Screenshots, page content and prompts used by AI steps reach the selected provider. Inspect native assertions plus authoritative model usage/error evidence; catching an SDK error does not make a run healthy. No browser login-state import or stored application credentials are supported by this capability. API scripts have no built-in screen observation engine: do not call screen-based agent.assert/waitFor/extract on API data. In manifest mode, import {assertGrade, grade} from \"#waitcher/ai\" and pass {data: selectedJsonOrText, rubric: criteria, threshold: 0.8}. The optional judgeModel grades the selected data, otherwise model is used. Keep expected facts in versioned fixtures; send no credentials or unnecessary response fields. Selected JSON is limited to 8 KiB and rubric to 2 KiB. grade returns {verdict,score}; assertGrade throws on non-pass. Any failure, valid inconclusive or technical grading error remains authoritative even when caught or ignored. Inspect private waitcher-data-grades.json alongside model usage and the native report. No retries/fallbacks occur. The alias survives monitor build and is supplied by run local --file and hosted script execution; standalone --project needs its own integration. Deterministic scripts need no binding; fixed endpoint fixtures can use the declarative graded adapter instead.\n\nFor an existing project's custom model setup, use `--project`. A schemaVersion 2 manifest with an `ai` binding can also run unchanged locally using `--connections-file /private/connections.json`, without login. The private map has schemaVersion 1 and a connections array; each record contains id, configurationRevision, provider openrouter (the only provider for AI scripts; anthropic connections serve hosted agent checks only), projectId, environmentId, allowed models and credentialFile. Credential paths resolve relative to the map. IDs/revisions/models and explicit manifest scope must match. Keep both map and key files private (chmod 600); inline keys, provider URLs and symlinks are refused. The selected runtime also needs ai@7.0.107. The complete CLI package ships model-client.mjs and notices; copying only cli.mjs is insufficient for bound AI execution.\n\nThe local manifest runner keeps the provider key in its parent and passes a temporary loopback grant to the test. It uses the hosted transport and per-run budget/outcome rules, but no hosted account/day ledger. Read model-usage.json as well as the native report: caught provider/budget failures may leave a native passed test while Waitcher correctly records error. Unknown usage stays reserved, SDK retries count separately, and local success does not verify hosted enablement or key freshness. Provider keys are not forwarded to the child, and literal temporary broker tokens are redacted from normal text evidence; trusted local code can read its filesystem and is not a sandbox. Traces default on, video stays opt-in.\n\nIn the project's `e2e.config.ts`, construct the chosen provider's AI SDK model under `agents.default.model`, following the installed framework's types. The provider reads its local key; a key alone does not configure a model. Never copy a user's provider key into a monitor manifest or use an operator's account key.\n\nMix exact assertions with selected `agent.act`, `agent.assert`, `agent.waitFor` and schema-bound `agent.extract` calls. AI operations may transmit screen content to the provider and incur cost; preserve the user's provider/call authorization. Step-level `maxModelCalls` is not a whole-run spending limit. Hosted connection/broker/budget support is separate and must be discovered from actual capabilities rather than assumed from a local run.\n\n## Protected product requests\n\nFor protected product operations, use monitor init --template protected-agent-outcome --request-policy-file POLICY.json --project-id UUID --environment-id UUID --file monitor.json. The public policy contains connections with id, canonical HTTPS origin and httpAuth references (targetId, credentialId, credentialRevision); operations with id, connection, method, path, optional static body, responsePointers and maxCalls; and budget.calls. Paths are fixed absolute paths with at most one whole {resourceId} UUID segment. Static JSON bodies may use only exact string leaves {{resourceId}}. Callers cannot choose URLs, methods, headers, bodies, query parameters or UUIDs. GET permits at most three calls, POST and DELETE one; DELETE requires the UUID path and POST must use the run identity. Limits are four connections, eight operations and eight total calls.\n\nThe protected starter requires submit POST, observe GET (three reads), cleanup DELETE, a five-call budget and response pointers /id, /correlationId, /title, /completed. Configure the static submission body to create a note with the parent-generated UUID in both id and correlationId, title Waitcher outcome check, and completed true. The optional #waitcher/requests SDK exposes requestOperation and requestResourceId. Responses contain status and a data map keyed by configured JSON pointers. The script never trusts the agent reply as proof of resulting state, never retries the action, and only cleans up independently proven run-owned state.\n\nLocal execution uses the existing --http-credentials-file private map: schemaVersion 1 and credentials entries with targetId, credentialId, credentialRevision, origin, header and credentialFile. Header is Authorization or X-Api-Key; its raw value stays in a separate private regular file. Map and key files require mode600 and exact reference/revision/origin matches. Keys stay in the CLI parent, never script, manifest, CLI arguments or custom environment. No account, app or AI provider is required locally. Keep request-runtime.mjs with the complete CLI package. For source projects use scriptFile, monitor build, then run local --file; standalone project mode does not inject the protected helper. Hosted use requires explicit capability and isolated execution even for administrators. Combined AI or browser-state bindings need their independent authority. Inspect request-usage.json, scenario and native reports. Caught budget errors, uncertain dispatch and unfinished calls cannot establish a healthy result; never replay mutations automatically.\n\nScenario request associations are optional recorded evidence. The request helper automatically records each issued request UUID on its originating phase. In a verify phase, call `scenario.referenceRequest(response.requestId)` for a request from an earlier completed observe phase in the same scenario; use the validated response envelope UUID, never an ID from response data. The protected starter references its last independent observation before asserting the business state. Read associations with `run scenarios`; `run diagnose` joins them to this run's request records and labels each ID `matched`, `not-found` or `unavailable`. These are script-reported phase associations. A matching controller row proves accounting correspondence, not the correctness of a phase or business outcome. Local matches remain local helper reports. Older evidence without association fields is not recorded, rather than an empty verified list. UNKNOWN requests remain charged and incomplete; no association authorizes mutation replay.\n";
62212
+ var ai_and_agents_default = "# AI endpoints, agent outcomes and model steps\n\nRead only when `waitcher system capabilities` reports the feature and the user needs it. Deterministic HTTP, API and browser monitors need none of this; see [authoring](authoring.md).\n\n## Agent outcome checks\n\nFor hosted scripts using `#waitcher/scenario`, first confirm `features.scenarioEvidence` through `system capabilities`, alongside script admission. Older servers may not provide this helper. Do not silently remove required scenario checks to make an unsupported run pass. Capability discovery is separate from native security, capacity and production release acceptance.\n\nFor an agent that changes application state, start with `monitor init --template agent-outcome --file outcome.json --target https://product.example/api/`. It creates a paused ordinary API script, with no model binding or paid-provider requirement. Adapt its fixed `agent/tasks` submission and `notes/{runId}` resource paths, disposable test namespace and exact expected fields. It submits one action, ignores claims of success and response-provided URLs, then independently reads the known resource at most three times. A fresh per-run random `id` and `correlationId` must both match, alongside the expected result. Action transport errors are never automatically retried. Cleanup runs in `finally` only after an independent read proves the resource belongs to this run; cleanup failures fail the test. If ownership or the action result is uncertain, it records cleanup as unverified and leaves state untouched. Reconcile possible late actions before repeating a mutating test. This pattern verifies the chosen outcome, not the agent's overall quality or the correctness of its explanation.\n\nThe starter uses the optional `#waitcher/scenario` helper with required submit/action, observe, verify and cleanup phases. `createScenario({id, phases})` returns `phase(id, callback)`, `assert(boolean)` and `incomplete(reason)`. Call signals only inside an active phase. Every scenario needs a required verify phase, and an executed verify phase must call `scenario.assert` at least once; an empty verification cannot establish pass. `assert(false)` records a business failure even if caught; ordinary callback exceptions and `incomplete(\"CLEANUP_UNVERIFIED\")` record coverage errors. Inspect `.e2e/waitcher-scenarios.json` in the private evidence: required phases that never ran or remain in flight also prevent a pass. Coverage error takes precedence while retaining failed verification facts. A false agent claim can therefore produce a failed verify phase and an overall error when cleanup remains uncertain. The helper does not automatically classify arbitrary E2E assertions or infer agent/tool traces. Use stable non-secret scenario/phase IDs, avoid raw response values in assertions, and do not use report labels as secret storage.\n\nUse the unchanged file with `monitor validate`, account-free `run local --file outcome.json --runtime YOUR_PINNED_RUNTIME`, and the existing API-script editor or `monitor apply --file outcome.json --dry-run`. Keep it paused after applying. Project authors can extract the script into `scriptFile`, keep helper imports and use `monitor build` to create one portable script; `#waitcher/scenario` stays external and is supplied by the manifest runner. The complete CLI includes `scenario-runtime.mjs`; keep package companions together. Standalone `--project` needs its own helper integration. The starter's default is credential-free. Optional local/trusted-administrator bearer tokens use `CHECK_AGENT_ACTION_TOKEN`, `CHECK_RESOURCE_READ_TOKEN` and `CHECK_RESOURCE_CLEANUP_TOKEN`, explicitly listed in `settings.envNames` and supplied outside the manifest. Hosted personal scripts receive `CHECK_*` values only from their project environment's secrets (`waitcher secret set`), never from the server's environment; do not work around that boundary. Do not log credentials or response bodies, and do not promise complete trace masking for arbitrary custom environment values. Local success does not establish hosted admission or isolation.\n\n## Scenario evidence\n\nInspect readable scenario evidence with `waitcher run scenarios --id RUN_ID`, or use `waitcher run scenarios --directory PRIVATE_RUN_DIR` for account-free local inspection without a server/runtime. Add `--json` for the exact shared report DTO. Do not combine selectors or pass `--server` for local inspection. Inspection of failed/error runs succeeds; execution exit codes remain unchanged. Keep authoritative run status separate from evidence availability: empty valid reports verify no business outcome, and pending/not-recorded/expired/invalid reports cannot establish a pass. Local evidence is checked against its recorded inventory and checksum; never edit it to manufacture a successful outcome.\n\n## AI product endpoints\n\nFor a single AI product endpoint, prefer a declarative `type: \"ai\"` fixture over an E2E script. Run `monitor init --type ai --target https://product.example/ai --file ai.json`, replace the sample request and response checks with the product contract, then `monitor validate --file ai.json`. JSON-pointer assertions support exact equality, type, existence and literal case-sensitive contains/not-contains/contains-any/contains-all checks; an optional bounded response schema checks structure. `run local --file ai.json` uses the same one-POST adapter without an account, model connection, provider key or E2E runtime. It only reaches public HTTPS endpoints and supports optional verified `httpAuth` references as described below; arbitrary custom headers and account-session inheritance are forbidden. Inspect the structured per-assertion report and distinguish transport coverage errors from product assertion failures. Applying the same file to hosted monitoring requires `features.aiEndpoints`; personal admission also requires a currently verified `httpAuth` binding; keep it paused unless scheduling is authorized. This verifies a chosen fixture, not general agent quality or a calibrated semantic judge.\n\nFor a small set of representative prompts against the same endpoint, use `aiEndpoint.adapter: \"json-http-suite-v1\"` and `cases` with 1\u20135 objects containing a stable unique `id`, readable `name`, positive `revision` (default 1), literal JSON-object `fixture`, and assertions and/or response schema. The suite `invocationBudget` equals its case count and is filled in when omitted. Validate offline and run the unchanged manifest locally before applying it; hosted capability `features.aiEndpointSuites` must be available. Cases run serially under one total monitor timeout. Assertion failures permit later cases; a transport/deadline error stops them as `not-run`. Inspect every case and coverage summary, not only the overall status. The controller reserves the full case count before any hosted request, and partial/uncertain runs retain that conservative allowance. Reported attempted requests can therefore be fewer than charged units. Deterministic suites do not provide semantic grading; do not describe text matching as semantic correctness. Single fixtures and each suite case can opt into literal variables with variables:{name:\"string\"} and exact {{name}} placeholders inside fixture string values. Without variables, braces remain literal. Use at most 16 names, ASCII letter followed by letters/digits/underscores (64 characters); prototype-related names are refused. Each value fits 4 KiB UTF-8, maps and rendered fixtures 16 KiB and complete configurations 64 KiB. No expressions, environment lookup, key/URL/assertion/rubric interpolation, matrix expansion or recursive replacement is supported. Missing/malformed placeholders reject before requests. Use non-secret data. Validate locally and preview before applying: exports keep authored maps while enqueue freezes rendered literal requests. Release comparisons use effective rendered bodies, so a changed variable value can be a changed policy even with the same case revision.\n\nFor optional semantic endpoint grading, use `json-http-graded-suite-v1`, portable schemaVersion 2 and explicit context (even the default project/environment). Set the top-level `judge` connectionId/configurationRevision/model/budget and add a rubric to each selected case: stable id/revision, criteria, outputPath, threshold and optional reference examples. Keep target credentials separate from judge keys. Hosted use requires `features.endpointJudges`; local use accepts the same private `--connections-file` map without an account, UI or E2E runtime. Only the selected output and rubric criteria/examples reach the judge. Known echoed managed product keys are refused before grading. Inspect score, verdict, rubric hash and private model-usage.json: malformed/unavailable/unknown/over-budget grading is inconclusive coverage and cannot pass or recover a product incident. There are no retries or fallback models. Every report currently marks calibration unverified; labelled reference examples do not prove accuracy. Keep calibration, pricing and release acceptance distinct from a controlled protocol pass.\n\nTo measure a rubric against labelled examples, use `monitor calibrate --id ID --file REQUEST_JSON` for a saved hosted monitor, then `monitor calibrations --id ID` or `monitor calibration --id ID --calibration-id ID` to inspect retained measurements. The request contains `caseId`, `dataset` and optional `repeats`. For account-free local measurement, use `run calibrate --file MONITOR --case-id CASE --dataset DATASET --connections-file PRIVATE_MAP`; `--dataset` is the dataset object alone. Use 2\u20134 fictional labelled outputs and 1\u20133 repeats, within the saved judge call/token budget and a total 30-second ceiling. Calibration calls only the judge, not the product endpoint, and creates no health runs, incidents or recovery. Keep known keys out of dataset/rubric identifiers, object keys and content as well as prompts. Inspect agreement over valid evaluated decisions, disagreement, repeat instability and technical coverage errors separately. A valid expected inconclusive can agree; a provider error cannot. Inspect private model usage for actual reservations. Exit 4 means disagreement, instability or coverage failure; never erase those results to obtain a green check. A small successful sample applies only to its exact dataset/rubric/model identity and does not establish general accuracy or automatically change the monitor\u2019s unverified calibration label.\n\nFor release regressions, use `project compare --id PROJECT_ID --deployment-id DEPLOYMENT_ID` and follow the opaque `next` cursor with `--before`. AI rows include case-level comparisons from frozen queued definitions and retained structured reports. Inspect each case classification and compatibility reasons. A different fixture, assertion, rubric, judge model or policy identity cannot establish a product regression; do not compare numeric scores across changed policies. Missing/invalid reports and unexecuted cases are coverage gaps. Follow the owned run references for evidence. Last passing and first failure are useful only for the matching case policy; a pass from another case or rubric is not a reproduction baseline. Display-name changes and JSON object key order do not change the evaluation policy. Comparison is read-only and never schedules another paid request.\n\n## AI steps in browser and API scripts\n\nFor personal AI-assisted browser journeys, require both `features.ai` and `features.isolatedAi` alongside script admission. Keep the `ai` model connection binding optional; deterministic scripts need no model or provider key. Hosted personal runs always use server-owned isolated policy and an explicitly model-capable isolated worker. An older worker, withdrawn capability or missing connection is a coverage failure, never a reason to switch accounts or execute through a trusted lane. Use the same version-2 manifest locally with a private connection map before applying it paused. Only attempt-scoped broker authority enters the disposable runtime; upstream keys stay controller-side. Screenshots, page content and prompts used by AI steps reach the selected provider. Inspect native assertions plus authoritative model usage/error evidence; catching an SDK error does not make a run healthy. No browser login-state import or stored application credentials are supported by this capability. API scripts have no built-in screen observation engine: do not call screen-based agent.assert/waitFor/extract on API data. In manifest mode, import {assertGrade, grade} from \"#waitcher/ai\" and pass {data: selectedJsonOrText, rubric: criteria, threshold: 0.8}. The optional judgeModel grades the selected data, otherwise model is used. Keep expected facts in versioned fixtures; send no credentials or unnecessary response fields. Selected JSON is limited to 8 KiB and rubric to 2 KiB. grade returns {verdict,score}; assertGrade throws on non-pass. Any failure, valid inconclusive or technical grading error remains authoritative even when caught or ignored. Inspect private waitcher-data-grades.json alongside model usage and the native report. No retries/fallbacks occur. The alias survives monitor build and is supplied by run local --file and hosted script execution; standalone --project needs its own integration. Deterministic scripts need no binding; fixed endpoint fixtures can use the declarative graded adapter instead.\n\nFor an existing project's custom model setup, use `--project`. A schemaVersion 2 manifest with an `ai` binding can also run unchanged locally using `--connections-file /private/connections.json`, without login. The private map has schemaVersion 1 and a connections array; each record contains id, configurationRevision, provider openrouter (the only provider for AI scripts; anthropic connections serve hosted agent checks only), projectId, environmentId, allowed models and credentialFile. Credential paths resolve relative to the map. IDs/revisions/models and explicit manifest scope must match. Keep both map and key files private (chmod 600); inline keys, provider URLs and symlinks are refused. The selected runtime also needs ai@7.0.107. The complete CLI package ships model-client.mjs and notices; copying only cli.mjs is insufficient for bound AI execution.\n\nThe local manifest runner keeps the provider key in its parent and passes a temporary loopback grant to the test. It uses the hosted transport and per-run budget/outcome rules, but no hosted account/day ledger. Read model-usage.json as well as the native report: caught provider/budget failures may leave a native passed test while Waitcher correctly records error. Unknown usage stays reserved, SDK retries count separately, and local success does not verify hosted enablement or key freshness. Provider keys are not forwarded to the child, and literal temporary broker tokens are redacted from normal text evidence; trusted local code can read its filesystem and is not a sandbox. Traces default on, video stays opt-in.\n\nIn the project's `e2e.config.ts`, construct the chosen provider's AI SDK model under `agents.default.model`, following the installed framework's types. The provider reads its local key; a key alone does not configure a model. Never copy a user's provider key into a monitor manifest or use an operator's account key.\n\nMix exact assertions with selected `agent.act`, `agent.assert`, `agent.waitFor` and schema-bound `agent.extract` calls. AI operations may transmit screen content to the provider and incur cost; preserve the user's provider/call authorization. Step-level `maxModelCalls` is not a whole-run spending limit. Hosted connection/broker/budget support is separate and must be discovered from actual capabilities rather than assumed from a local run.\n\n## Protected product requests\n\nFor protected product operations, use monitor init --template protected-agent-outcome --request-policy-file POLICY.json --project-id UUID --environment-id UUID --file monitor.json. The public policy contains connections with id, canonical HTTPS origin and httpAuth references (targetId, credentialId, credentialRevision); operations with id, connection, method, path, optional static body, responsePointers and maxCalls; and budget.calls. Paths are fixed absolute paths with at most one whole {resourceId} UUID segment. Static JSON bodies may use only exact string leaves {{resourceId}}. Callers cannot choose URLs, methods, headers, bodies, query parameters or UUIDs. GET permits at most three calls, POST and DELETE one; DELETE requires the UUID path and POST must use the run identity. Limits are four connections, eight operations and eight total calls.\n\nThe protected starter requires submit POST, observe GET (three reads), cleanup DELETE, a five-call budget and response pointers /id, /correlationId, /title, /completed. Configure the static submission body to create a note with the parent-generated UUID in both id and correlationId, title Waitcher outcome check, and completed true. The optional #waitcher/requests SDK exposes requestOperation and requestResourceId. Responses contain status and a data map keyed by configured JSON pointers. The script never trusts the agent reply as proof of resulting state, never retries the action, and only cleans up independently proven run-owned state.\n\nLocal execution uses the existing --http-credentials-file private map: schemaVersion 1 and credentials entries with targetId, credentialId, credentialRevision, origin, header and credentialFile. Header is the credential header name (for example Authorization or X-Api-Key); its raw value stays in a separate private regular file. Map and key files require mode600 and exact reference/revision/origin matches. Keys stay in the CLI parent, never script, manifest, CLI arguments or custom environment. No account, app or AI provider is required locally. Keep request-runtime.mjs with the complete CLI package. For source projects use scriptFile, monitor build, then run local --file; standalone project mode does not inject the protected helper. Hosted use requires explicit capability and isolated execution even for administrators. Combined AI or browser-state bindings need their independent authority. Inspect request-usage.json, scenario and native reports. Caught budget errors, uncertain dispatch and unfinished calls cannot establish a healthy result; never replay mutations automatically.\n\nScenario request associations are optional recorded evidence. The request helper automatically records each issued request UUID on its originating phase. In a verify phase, call `scenario.referenceRequest(response.requestId)` for a request from an earlier completed observe phase in the same scenario; use the validated response envelope UUID, never an ID from response data. The protected starter references its last independent observation before asserting the business state. Read associations with `run scenarios`; `run diagnose` joins them to this run's request records and labels each ID `matched`, `not-found` or `unavailable`. These are script-reported phase associations. A matching controller row proves accounting correspondence, not the correctness of a phase or business outcome. Local matches remain local helper reports. Older evidence without association fields is not recorded, rather than an empty verified list. UNKNOWN requests remain charged and incomplete; no association authorizes mutation replay.\n";
61523
62213
 
61524
62214
  // ../../skills/waitcher/references/deploy.md
61525
62215
  var deploy_default = '# Repository deploys\n\nRead when the user keeps monitors in a repository with `waitcher.json`. The core workflow is in SKILL.md; this file holds the details. `waitcher doctor` confirms that the server supports deploys.\n\n## The file\n\n```json\n{\n "schemaVersion": 1,\n "project": "Shop",\n "environments": {\n "production": { "baseUrl": "https://shop.example" },\n "staging": { "baseUrl": "https://staging.shop.example" }\n },\n "defaults": { "interval": 1800, "timeout": 15 },\n "monitors": [\n { "key": "home", "type": "http", "path": "/", "settings": { "contains": "Shop" } },\n { "key": "tls", "type": "certificate" },\n { "key": "checkout", "type": "browser", "entry": "monitoring/checkout.e2e.ts", "timeout": 45 },\n { "key": "orders-api", "type": "api", "entry": "monitoring/orders.e2e.ts",\n "settings": { "envNames": ["CHECK_ORDERS_TOKEN"] } },\n { "key": "nightly-export", "type": "heartbeat", "environments": ["production"],\n "heartbeat": { "graceSeconds": 300, "completionSeconds": 900 } }\n ]\n}\n```\n\n- `config init` starts with two example monitors (`home`: HTTP 200 on `/`; `tls`: certificate expiry). Keep, change or remove them.\n- Environment names match case-insensitively: `production` in the file is the project\'s default `Production` environment.\n- HTTP `settings`: `method`, `expectedStatus`, `contains`, `jsonPath` with `jsonValue`, `maxLatency` (ms), `headers`, `body`; certificates: `certificateMinDays` (default 14). `waitcher monitor init --type TYPE --file x.json` writes a complete example of any type.\n- A 30-minute interval suits HTTP, certificate and browser checks alike; certificates rarely need more often. Personal accounts follow their plan: checks every 30 minutes on starter, 5 on pro and 1 on business at the shortest; script monitors have a count, a shortest interval and runs a day that the running schedules must fit together (starter: one, every 2 hours or slower). Read `limits.minInterval` and `limits.isolatedScripts` in `system capabilities` before planning.\n- Entries are ordinary monitor definitions plus `key`, optional `environments` and optional `path` (resolved against `baseUrl`). Script and certificate targets default to `baseUrl`; heartbeats use the key as their label.\n- Never set `enabled`, `script`, `scriptFile`, `schemaVersion`, `context` or `demo` in entries.\n- Script tests read `process.env.TARGET_URL` (API) or call `app.open("/")` (browser), so one test serves every environment.\n- The directory holding `waitcher.json` must have `e2e@0.21.1`, `@e2e-dev/web@0.15.1` (browser) and `esbuild@0.28.2` installed exactly; `waitcher runtime install` sets them up and later upgrades them (ask before `--yes`). Do not let dependency bots move these three packages. Tests may import project files and JSON; other packages fail with `BUILD_FAILED` naming the import. Replace them with project code, `fetch` or JSON data; do not vendor a dependency to get past the limit. A built script must fit 50,000 characters.\n\n## Plan and apply\n\n- `config validate --env NAME --verify [--key KEY]` runs that environment\'s script entries locally without an account. `deploy plan --env NAME [--verify]` changes nothing. `changes` lists `create`, `adopt`, `update` (with `fields`), `unchanged`, `delete`, `orphaned` and `invalid` per key.\n- `deploy apply --env NAME --based-on BASED_ON` applies the whole environment or nothing. `ok:false` exits 2 and writes nothing. A stale `--based-on` is `CONFLICT`: plan again and show the new plan.\n- The repository owns definitions; the server owns pause and resume. Managed monitors refuse edits through `monitor apply` or the web (`MANAGED_BY_CONFIG`); change the file instead.\n- Undeclared monitors stay as `orphaned` warnings. `--prune` deletes them and their history; use it only with the user\'s consent.\n- Deploy versions come from the Git commit (`-dirty` when `waitcher.json` has uncommitted changes). A configuration deploy is not a product release: runs show `context.deployment` only for markers recorded with `waitcher deployment record`.\n- `--smoke` runs each created, adopted or updated monitor once on the server after apply. A failed smoke leaves the deploy applied and exits 4; follow `next` to `run diagnose`. On a personal account only the first monitor\'s smoke starts (one manual run per 10 minutes); the rest are `skipped`, which is not a failure.\n\n## Secrets\n\nScripts list `CHECK_*` names in `settings.envNames`. Values live per project environment on the server:\n\n```sh\nprintf %s "$VALUE" | waitcher secret set --env staging --name CHECK_ORDERS_TOKEN --value-stdin\nwaitcher secret list --env staging\n```\n\nAsk the user for each value, or tell them the command to run themselves. Never echo, log or commit it. A plan reports `SECRET_MISSING` with the missing names. `--verify` runs with your local environment, so export the same `CHECK_*` variables locally (never in files) or skip `--verify` for that monitor and rely on `--smoke`.\n\nListed values of at least 6 characters appear as `<secret:CHECK_NAME>` in reports, traces and logs; screenshots, video and transformed values are not masked. For a password or token typed into a page, prefer `fill(secrets.get("CHECK_NAME"))` (`import { secrets } from "e2e"`) over `process.env`: the value stays out of the test code and the run refuses `app.screenshot()` after that fill, so take screenshots before it or drop them. Read `process.env.CHECK_NAME` for values the script sends itself, such as API headers. Never log a value or assert on it.\n\n## Adopting existing monitors\n\nWhen a plan warns `ADOPTION_CANDIDATE`, an existing unmanaged monitor looks like the entry. Show it to the user (`waitcher monitor get --id ID`). If it is the same check, plan and apply with `--adopt KEY=MONITOR_ID`: it keeps its ID, history and pause state and takes the file\'s definition. Otherwise ignore the warning; apply creates a separate monitor.\n\n## Rollback\n\n`waitcher deploy list --project-id ID` shows deploys; `restorable:true` marks the latest 10 per environment. `waitcher deploy rollback --id DEPLOY_ID --dry-run` shows the plan, then run it with `--based-on`. Secrets are not rolled back. Tell the user to revert the repository too, or the next apply reintroduces the change.\n\n## CI\n\n`waitcher ci init [--env production] [--file waitcher.json]` writes `.github/workflows/waitcher.yml`: plan on pull requests, apply on pushes to the main branch. It installs the CLI from the server with a checksum and signs in with the `WAITCHER_TOKEN` repository secret. Create that token with read and write permissions (add run for `--smoke`) and `"projectId"` set to the project\'s ID (from `deploy plan`\'s `project.id`) using `waitcher token create`, so CI cannot touch other projects, and let the user store it with `gh secret set WAITCHER_TOKEN`. Signed in with a project token, read `authorization.projectName` from `waitcher auth status` and use it as `waitcher.json`\'s `project` (`config init --project-name NAME`); such a token changes monitors only through `deploy apply`, so do not try `monitor apply`. Set the `WAITCHER_SERVER` repository variable for a non-default server.\n';
@@ -61528,7 +62218,7 @@ var deploy_default = '# Repository deploys\n\nRead when the user keeps monitors
61528
62218
  var diagnosis_default = "# Diagnosing failures\n\nRead when a local, smoke or scheduled run failed or errored.\n\n## Diagnose and reproduce a retained run\n\nConfirm `features.runDiagnosis` for hosted support. Use `run diagnose --id RUN_ID` for a readable hosted packet, or add `--json` for the shared structured report. Use `run diagnose --directory PRIVATE_RUN_DIRECTORY` without an account to inspect indexed local evidence. Hosted request states come from the controller ledger; local helper observations are explicitly local and do not attest hosted accounting. A known response does not prove task success, and an unknown action may have taken effect. Do not automatically repeat a mutation because its result is unknown.\n\nA historical pass is useful only when the frozen verification policy matches. Changed scripts, targets, deadlines or protected-operation policies cannot supply a matching reference. History searches are bounded; unavailable or truncated history is not proof that the product never passed. Stored artifact checksums are metadata; inspect the actual artifact when needed. Scenario evidence is checked against its recorded checksum before display.\n\nFor a completed supported hosted script, `run reproduce --id RUN_ID --output NEW_DIRECTORY` prepares its frozen configuration in a new private folder. It never executes the test or retrieves the current edited monitor. Inspect `monitor.json` and `provenance.json`, then deliberately run `run local --file NEW_DIRECTORY/monitor.json --output FRESH_RUN_DIRECTORY` with the matching installed runtime, optionally `--runtime PROJECT`. Reproduction is a fresh run with separate provenance and does not replace the original evidence.\n\nManaged product credentials, AI keys and browser sessions are not exported. Supply existing private local mappings with `--http-credentials-file`, `--connections-file` and `--browser-identities-file` where required. Authored scripts and literal configuration can themselves be sensitive, so keep the reproduction private. Operator-injected headers, bodies or environment state make this initial portable preparation unavailable rather than silently changing the test. Older local runs without an indexed frozen manifest remain inspectable but cannot establish a captured reproduction policy.\n";
61529
62219
 
61530
62220
  // ../../skills/waitcher/references/optional-capabilities.md
61531
- var optional_capabilities_default = '# Optional capabilities\n\nRead only when capabilities report the feature and the user needs it: visual baselines, signed-in browser identities, verified HTTP credentials and invocation budgets. AI endpoints, agent outcome checks, model steps and protected requests are in [ai-and-agents](ai-and-agents.md).\n\n## Optional visual checks\n\nDiscover `features.visual` for authoring and `features.visualReview` for baseline inspection; `features.isolatedVisual` says personal captures run in the hosted runner. A visual monitor counts as one of the plan\'s script monitors and each capture as a script run; `limits.visual.minInterval` is the shortest interval (2 hours on the free plan, 30 minutes otherwise). In a repository, add a `waitcher.json` entry such as `{ "key": "home-look", "type": "visual", "path": "/" }` with an optional `visual` block (page/element checkpoint, viewport, readiness, masks, thresholds) and deploy it like any other monitor; with `--smoke` the first capture is reported as `baseline_review` with the commands that show and approve it. For one monitor outside a repository, start with `monitor init --type visual --target https://product.example --file visual.json`, then `monitor validate --file visual.json` and `monitor apply --file visual.json --dry-run`. Apply paused; an authorized `run start --id ID --wait` is a separate action. User guide: https://waitcher.dev/docs/visual.md.\n\nFor a screen behind a sign-in or a few clicks, assert it inside a `browser` test instead: `await expect(screen).toHaveScreenshot(\'dashboard.png\')` (options `threshold`, `maxDiffPixels`, `maxDiffPixelRatio`, `mask`). Do not commit snapshot PNGs or pass `--update-snapshots`: Waitcher keeps the baselines. The first hosted run of each screenshot ends as `error` "First capture of NAME: approve it as the baseline"; inspect it with `visual list --monitor-id ID` and `visual image`, then `visual approve --id COMPARISON_ID --expected-revision 0`, one screenshot per run. Later runs fail with a comparison when a screenshot differs. Local runs (`run local`, `--verify`) compare against a capture from the same run, so a local pass says nothing about the look. Visual monitors accept no script, model binding, session identity or custom request credential. Fixed visual baseline execution is not supported by `run local`; local API/browser script evidence does not establish a visual baseline.\n\nA scheduled run never creates a baseline. Set the first one, or accept an intended change, with one run: `run start --id MONITOR_ID --update-baselines --wait` captures and approves it (write access); then inspect it with `visual list` and `visual image`. The alternative is to run normally and approve the capture. Until a baseline exists a run ends as `error` "First capture of NAME"; that is missing coverage, not a product failure. Every later run of a visual monitor keeps its comparison, passing runs included. Inspect `visual list`, `visual get --id COMPARISON_ID`, `visual heads --id MONITOR_ID`, `visual artifacts --id COMPARISON_ID` and `visual image --id COMPARISON_ID --role candidate|original|diff --file NEW_PRIVATE_PATH`. Review actual images and metrics before an authorized `visual approve --id COMPARISON_ID --expected-revision SELECTED_REVISION`; an initial selection uses 0. Restore only a reviewed retained baseline with `visual restore --id HEAD_ID --baseline-id BASELINE_ID --expected-revision CURRENT_HEAD_REVISION`. Stale decisions conflict: reload instead of retrying or changing revisions blindly. Approval preserves the historical result. Changed capture fingerprints need their own baseline. Foreign-owner/read-only refusals are boundaries, not reasons to switch credentials. Screenshots are private evidence; masks cover selected pixels only. Use actual `visual` and `run` help for current flags and capabilities.\n\n## Optional browser test-account identity\n\nFor a signed-in browser journey, discover hosted `features.browserIdentities` before configuring `identity create/rotate/enable/disable/delete`. Supply bounded cookies/localStorage through a private `--state-file`; metadata is scoped to one verified exact origin, project/environment and explicit expiry. State is write-only and cannot be exported. New identities default disabled; enable explicitly and bind the resulting current `{identityId, revision}` under `browserIdentity` in a version-2 browser manifest with explicit context. Rename, state replacement and enable/disable advance revisions; inspect current metadata and deliberately rebind rather than silently upgrading. After an uncertain write inspect metadata before retrying. No running Chrome profile is imported.\n\nRun the same manifest account-free with `run local --file MONITOR --runtime RUNTIME --browser-identities-file PRIVATE_MAP`. The map is `{schemaVersion:1,identities:[{identityId,revision,projectId,environmentId,origin,expiresAt,stateFile}]}`; state paths resolve relative to the map. Both map/state are private regular JSON files (chmod 600), no symlinks/hard links or inline state. Exact IDs/revision/scope/origin and bounded future expiry must match. Local mappings do not attest hosted target verification or revocation. The optional model map remains separate. Hosted identity-backed runs use the isolated lane for all owners; local code remains trusted. The selected script receives its own session and signed-in page content can reach private evidence or optional AI providers. Never promise pixel/encoded-secret masking. Use dedicated test accounts and inspect coverage errors after expiry/revocation before repeating a possibly completed action.\n\n## Verified HTTP credentials\n\nFor an authenticated HTTP or AI endpoint, use the user\'s owned verified HTTPS origin and an `httpAuth` reference (`targetId`, `credentialId`, `credentialRevision`). Check `features.httpTargets` before hosted configuration. Create/renew a target challenge with `target create` or `target challenge`, writing it to a new private `--output`; never print the token. The user publishes the supplied proof at `/.well-known/waitcher-verification.txt`, then `target verify` checks it without credentials. Verification expires after 24 hours and must be renewed. An origin excludes paths, query and fragments and is immutable.\n\nUse `target credential create/rotate` with non-secret metadata JSON plus `--credential-file` (mode 600) or `--credential-stdin`. Headers are limited to `Authorization` or `X-Api-Key`; values are complete single-line ASCII header values up to 4096 bytes. For Bearer auth, include the `Bearer ` prefix in the private value. Keys are write-only and encrypted on the server. The monitor and export retain references only. Rotation advances the credential revision; update the monitor binding explicitly. Disabled, expired, foreign or stale bindings fail without forwarding a request. Authenticated redirects are never followed.\n\nFor local execution without the app or account, pass `run local --file monitor.json --http-credentials-file private/http-map.json`. The private map is `{schemaVersion:1,credentials:[{targetId,credentialId,credentialRevision,origin,header,credentialFile}]}` and the referenced private file contains the raw header value. Paths resolve relative to the map. Never inline a key or reuse the CLI\'s own account cookie/token as a target credential. The local resolver requires exactly matching IDs, revision and canonical origin, and the shared runner enforces the single supported header and redirect policy. Local mapping does not prove that the hosted target is still verified or its key current. Keep the same manifest as the hosted monitor; only local key resolution differs. HTTP local checks need no E2E runtime. Use explicit user authorization for POST fixtures that change state.\n\n## Hosted endpoint invocation budgets\n\nBefore running dedicated AI endpoints or HTTP checks with `httpAuth`, read `account invocations` for the account/monitor UTC-day counters and limits. The manifest accepts `requestBudget: {dailyInvocations: N}` (default 50, maximum 1,000). Configure the owner cap with `account budget --daily-invocations N --expected-revision CURRENT_REVISION` only when authorized; personal accounts cap at 200, administrators at 5,000, and the controller also has a global 5,000 cap. Validate/apply/export do not charge calls.\n\n`INVOCATION_BUDGET_EXHAUSTED` is a coverage error: no request was dispatched and no product incident is created. Do not automatically retry or raise a limit to bypass it. Completed and uncertain dispatched calls consume budget, independent of product success or worker-reported usage. Local execution needs no account, preserves the setting and makes at most one endpoint call per fixture case, but does not enforce or consume the hosted daily ledger. After backup restore, `window.restoreHeld` blocks these checks until the next UTC reset because snapshot counters may be stale; do not bypass the hold by raising caps. These are request counts, separate from model-broker token/call caps and downstream provider spending. Inspect `account invocations` and the current `account` help for the hosted accounting contract.\n\n## Agent checks\n\nWhen `features.agentChecks` is true, an `api` entry may carry an `agent` block: Claude Code works on `task` in a sandbox, then the entry\'s script verifies the product\'s state ([guide](https://waitcher.dev/docs/agent-checks.md)). It needs an Anthropic connection in the entry\'s project environment (`connection create` with `"provider":"anthropic"`, the user\'s own Anthropic API key from a private file; models `haiku`, `sonnet`, `opus` or `fable` follow the latest model of that family, resolved at each run, or exact IDs like `claude-sonnet-5-5` stay fixed); an OpenRouter connection is refused for agent checks and serves only AI scripts and AI checks and fields `connectionId`, `configurationRevision`, `model`, `task`, optionally `seconds`, `turns`, `tokens`, `hosts` and `envNames` (a subset of `settings.envNames`). Read `limits.agentChecks` for the plan\'s count and bounds; the interval is at least 6 hours. Write the task as a user would say it and never put a secret in it. The verifier must reset the test account it checks; a project token lets it list that project\'s monitors, and monitors it finds there that a deploy created are removed by a deploy with `--prune`, not `monitor delete`. Read a run with `run diagnose --id RUN_ID`, which leads with the agent\'s outcome, model, pages read, failed steps, gateway refusals and final message, apart from the verifier\'s verdict. Ask before creating a connection: it stores the user\'s key and every run is billed to it.\n\n## Status pages\n\nWhen `features.statusPages` is true, the account can publish public pages at `https://waitcher.dev/status/SLUG` ([guide](https://waitcher.dev/docs/status-pages.md)); `limits.statusPages` is the plan\'s count. `waitcher status-page save --file page.json` takes `slug`, `title` and `components` (`monitorId`, a public `name`, optional `group`); `waitcher help status` has the full shape. A page is private until `"published": true` and asks search engines not to index it unless `"indexable": true`. Write public names the user\'s customers would recognise, never a target URL or an internal monitor name; ask before publishing, because the address is public. During an incident, `waitcher incident update --id INCIDENT_ID --kind identified --message TEXT` posts a note to every page that shows it. People can also open an incident no monitor has seen (`incident open --page-id ID --title TEXT --message TEXT [--impact down|degraded|none] [--services "A,B"]`), and change any incident with `incident edit` (title, impact, open or resolved, hidden; `--expected-revision` from `status-page incidents --id PAGE_ID`). On a monitor\'s incident those values win over the monitor until reset (`--state auto`). A page with `"automaticIncidents": false` shows only incidents people open. Visitors can subscribe to email updates unless `"subscriptions": false`; opening, updating, resolving or reopening an incident emails them, so treat every such command as a message to the user\'s customers. Everything on these pages is public: only post, open, resolve or hide what the user wrote or approved.\n';
62221
+ var optional_capabilities_default = '# Optional capabilities\n\nRead only when capabilities report the feature and the user needs it: visual baselines, signed-in browser identities, verified HTTP credentials and invocation budgets. AI endpoints, agent outcome checks, model steps and protected requests are in [ai-and-agents](ai-and-agents.md).\n\n## Optional visual checks\n\nDiscover `features.visual` for authoring and `features.visualReview` for baseline inspection; `features.isolatedVisual` says personal captures run in the hosted runner. A visual monitor counts as one of the plan\'s script monitors and each capture as a script run; `limits.visual.minInterval` is the shortest interval (2 hours on the free plan, 30 minutes otherwise). In a repository, add a `waitcher.json` entry such as `{ "key": "home-look", "type": "visual", "path": "/" }` with an optional `visual` block (page/element checkpoint, viewport, readiness, masks, thresholds) and deploy it like any other monitor; with `--smoke` the first capture is reported as `baseline_review` with the commands that show and approve it. For one monitor outside a repository, start with `monitor init --type visual --target https://product.example --file visual.json`, then `monitor validate --file visual.json` and `monitor apply --file visual.json --dry-run`. Apply paused; an authorized `run start --id ID --wait` is a separate action. User guide: https://waitcher.dev/docs/visual.md.\n\nFor a screen behind a sign-in or a few clicks, assert it inside a `browser` test instead: `await expect(screen).toHaveScreenshot(\'dashboard.png\')` (options `threshold`, `maxDiffPixels`, `maxDiffPixelRatio`, `mask`). Do not commit snapshot PNGs or pass `--update-snapshots`: Waitcher keeps the baselines. The first hosted run of each screenshot ends as `error` "First capture of NAME: approve it as the baseline"; inspect it with `visual list --monitor-id ID` and `visual image`, then `visual approve --id COMPARISON_ID --expected-revision 0`, one screenshot per run. Later runs fail with a comparison when a screenshot differs. Local runs (`run local`, `--verify`) compare against a capture from the same run, so a local pass says nothing about the look. Visual monitors accept no script, model binding, session identity or custom request credential. Fixed visual baseline execution is not supported by `run local`; local API/browser script evidence does not establish a visual baseline.\n\nA scheduled run never creates a baseline. Set the first one, or accept an intended change, with one run: `run start --id MONITOR_ID --update-baselines --wait` captures and approves it (write access); then inspect it with `visual list` and `visual image`. The alternative is to run normally and approve the capture. Until a baseline exists a run ends as `error` "First capture of NAME"; that is missing coverage, not a product failure. Every later run of a visual monitor keeps its comparison, passing runs included. Inspect `visual list`, `visual get --id COMPARISON_ID`, `visual heads --id MONITOR_ID`, `visual artifacts --id COMPARISON_ID` and `visual image --id COMPARISON_ID --role candidate|original|diff --file NEW_PRIVATE_PATH`. Review actual images and metrics before an authorized `visual approve --id COMPARISON_ID --expected-revision SELECTED_REVISION`; an initial selection uses 0. Restore only a reviewed retained baseline with `visual restore --id HEAD_ID --baseline-id BASELINE_ID --expected-revision CURRENT_HEAD_REVISION`. Stale decisions conflict: reload instead of retrying or changing revisions blindly. Approval preserves the historical result. Changed capture fingerprints need their own baseline. Foreign-owner/read-only refusals are boundaries, not reasons to switch credentials. Screenshots are private evidence; masks cover selected pixels only. Use actual `visual` and `run` help for current flags and capabilities.\n\n## Optional browser test-account identity\n\nFor a signed-in browser journey, discover hosted `features.browserIdentities` before configuring `identity create/rotate/enable/disable/delete`. Supply bounded cookies/localStorage through a private `--state-file`; metadata is scoped to one verified exact origin, project/environment and explicit expiry. State is write-only and cannot be exported. New identities default disabled; enable explicitly and bind the resulting current `{identityId, revision}` under `browserIdentity` in a version-2 browser manifest with explicit context. Rename, state replacement and enable/disable advance revisions; inspect current metadata and deliberately rebind rather than silently upgrading. After an uncertain write inspect metadata before retrying. No running Chrome profile is imported.\n\nRun the same manifest account-free with `run local --file MONITOR --runtime RUNTIME --browser-identities-file PRIVATE_MAP`. The map is `{schemaVersion:1,identities:[{identityId,revision,projectId,environmentId,origin,expiresAt,stateFile}]}`; state paths resolve relative to the map. Both map/state are private regular JSON files (chmod 600), no symlinks/hard links or inline state. Exact IDs/revision/scope/origin and bounded future expiry must match. Local mappings do not attest hosted target verification or revocation. The optional model map remains separate. Hosted identity-backed runs use the isolated lane for all owners; local code remains trusted. The selected script receives its own session and signed-in page content can reach private evidence or optional AI providers. Never promise pixel/encoded-secret masking. Use dedicated test accounts and inspect coverage errors after expiry/revocation before repeating a possibly completed action.\n\n## Verified HTTP credentials\n\nFor an authenticated HTTP or AI endpoint, use the user\'s owned verified HTTPS origin and an `httpAuth` reference (`targetId`, `credentialId`, `credentialRevision`; in `waitcher.json` write `{"credential": "NAME"}` or `{"credential": {"production": "NAME", "staging": "NAME"}}` and the deploy binds it). Check `features.httpTargets` before hosted configuration. Create/renew a target challenge with `target create` or `target challenge`, writing it to a new private `--output`; never print the token. The user publishes the supplied proof at `/.well-known/waitcher-verification.txt`, then `target verify` checks it without credentials. Verification expires after 24 hours and must be renewed. An origin excludes paths, query and fragments and is immutable.\n\nUse `target credential create/rotate` with non-secret metadata JSON plus `--credential-file` (mode 600) or `--credential-stdin`. The header is any valid name (not Host, Cookie or transport headers); basic auth is `Authorization` with `Basic ` plus base64(user:password); values are complete single-line ASCII header values up to 4096 bytes. For Bearer auth, include the `Bearer ` prefix in the private value. For OAuth 2 (a token endpoint, client credentials or a refresh token) create the credential with `"kind":"oauth2"` and an `oauth` block (`grant`, `tokenUrl`, `clientId`, optional `scope`, `clientAuth`); the private value is the client secret, or for `refresh_token` one JSON line `{"refreshToken":"...","clientSecret":"..."}`. Waitcher mints, caches and refreshes the Bearer token; `run local` cannot use it. Keys are write-only and encrypted on the server. The monitor and export retain references only. Rotation advances the credential revision; update the monitor binding explicitly. Disabled, expired, foreign or stale bindings fail without forwarding a request. Authenticated redirects are never followed.\n\nFor local execution without the app or account, pass `run local --file monitor.json --http-credentials-file private/http-map.json`. The private map is `{schemaVersion:1,credentials:[{targetId,credentialId,credentialRevision,origin,header,credentialFile}]}` and the referenced private file contains the raw header value. Paths resolve relative to the map. Never inline a key or reuse the CLI\'s own account cookie/token as a target credential. The local resolver requires exactly matching IDs, revision and canonical origin, and the shared runner enforces the single supported header and redirect policy. Local mapping does not prove that the hosted target is still verified or its key current. Keep the same manifest as the hosted monitor; only local key resolution differs. HTTP local checks need no E2E runtime. Use explicit user authorization for POST fixtures that change state.\n\n## Hosted endpoint invocation budgets\n\nBefore running dedicated AI endpoints or HTTP checks with `httpAuth`, read `account invocations` for the account/monitor UTC-day counters and limits. The manifest accepts `requestBudget: {dailyInvocations: N}` (default 50, maximum 1,000). Configure the owner cap with `account budget --daily-invocations N --expected-revision CURRENT_REVISION` only when authorized; personal accounts cap at 200, administrators at 5,000, and the controller also has a global 5,000 cap. Validate/apply/export do not charge calls.\n\n`INVOCATION_BUDGET_EXHAUSTED` is a coverage error: no request was dispatched and no product incident is created. Do not automatically retry or raise a limit to bypass it. Completed and uncertain dispatched calls consume budget, independent of product success or worker-reported usage. Local execution needs no account, preserves the setting and makes at most one endpoint call per fixture case, but does not enforce or consume the hosted daily ledger. After backup restore, `window.restoreHeld` blocks these checks until the next UTC reset because snapshot counters may be stale; do not bypass the hold by raising caps. These are request counts, separate from model-broker token/call caps and downstream provider spending. Inspect `account invocations` and the current `account` help for the hosted accounting contract.\n\n## Agent checks\n\nWhen `features.agentChecks` is true, an `api` entry may carry an `agent` block: Claude Code works on `task` in a sandbox, then the entry\'s script verifies the product\'s state ([guide](https://waitcher.dev/docs/agent-checks.md)). It needs an Anthropic connection in the entry\'s project environment (`connection create` with `"provider":"anthropic"`, the user\'s own Anthropic API key from a private file; models `haiku`, `sonnet`, `opus` or `fable` follow the latest model of that family, resolved at each run, or exact IDs like `claude-sonnet-5-5` stay fixed); an OpenRouter connection is refused for agent checks and serves only AI scripts and AI checks and fields `connectionId`, `configurationRevision`, `model`, `task`, optionally `seconds`, `turns`, `tokens`, `hosts` and `envNames` (a subset of `settings.envNames`). Read `limits.agentChecks` for the plan\'s count and bounds; the interval is at least 6 hours. Write the task as a user would say it and never put a secret in it. The verifier must reset the test account it checks; a project token lets it list that project\'s monitors, and monitors it finds there that a deploy created are removed by a deploy with `--prune`, not `monitor delete`. Read a run with `run diagnose --id RUN_ID`, which leads with the agent\'s outcome, model, pages read, failed steps, gateway refusals and final message, apart from the verifier\'s verdict. Ask before creating a connection: it stores the user\'s key and every run is billed to it.\n\n## Status pages\n\nWhen `features.statusPages` is true, the account can publish public pages at `https://waitcher.dev/status/SLUG` ([guide](https://waitcher.dev/docs/status-pages.md)); `limits.statusPages` is the plan\'s count. `waitcher status-page save --file page.json` takes `slug`, `title` and `components` (`monitorId`, a public `name`, optional `group`); `waitcher help status` has the full shape. A page is private until `"published": true` and asks search engines not to index it unless `"indexable": true`. Write public names the user\'s customers would recognise, never a target URL or an internal monitor name; ask before publishing, because the address is public. During an incident, `waitcher incident update --id INCIDENT_ID --kind identified --message TEXT` posts a note to every page that shows it. People can also open an incident no monitor has seen (`incident open --page-id ID --title TEXT --message TEXT [--impact down|degraded|none] [--services "A,B"]`), and change any incident with `incident edit` (title, impact, open or resolved, hidden; `--expected-revision` from `status-page incidents --id PAGE_ID`). On a monitor\'s incident those values win over the monitor until reset (`--state auto`). A page with `"automaticIncidents": false` shows only incidents people open. Visitors can subscribe to email updates unless `"subscriptions": false`; opening, updating, resolving or reopening an incident emails them, so treat every such command as a message to the user\'s customers. Everything on these pages is public: only post, open, resolve or hide what the user wrote or approved.\n';
61532
62222
 
61533
62223
  // ../../skills/waitcher/agents/openai.yaml
61534
62224
  var openai_default = 'interface:\n display_name: "Waitcher"\n short_description: "Deploy monitoring from a repository and inspect evidence"\n default_prompt: "Use $waitcher to set up monitoring for this repository: pick the critical journeys, verify them locally and deploy them paused through a reviewed plan."\n';
@@ -61568,8 +62258,8 @@ async function installSkill(options) {
61568
62258
  await mkdir8(join13(directory, "references"), { recursive: true });
61569
62259
  await mkdir8(join13(directory, "agents"), { recursive: true });
61570
62260
  await writeFile9(join13(directory, "SKILL.md"), SKILL_default);
61571
- for (const [name5, text3] of Object.entries(references))
61572
- await writeFile9(join13(directory, "references", name5), text3);
62261
+ for (const [name5, text4] of Object.entries(references))
62262
+ await writeFile9(join13(directory, "references", name5), text4);
61573
62263
  await writeFile9(join13(directory, "agents/openai.yaml"), openai_default);
61574
62264
  await writeFile9(
61575
62265
  join13(directory, MARKER),
@@ -61693,7 +62383,7 @@ async function doctor(options) {
61693
62383
  for (const home of skillHomes) {
61694
62384
  if (!await exists(join14(home, "SKILL.md"))) continue;
61695
62385
  installed.push(home);
61696
- const marker2 = await readFile9(join14(home, ".waitcher-skill.json"), "utf8").then((text3) => JSON.parse(text3)).catch(() => null);
62386
+ const marker2 = await readFile9(join14(home, ".waitcher-skill.json"), "utf8").then((text4) => JSON.parse(text4)).catch(() => null);
61697
62387
  if (marker2 && marker2.version !== options.version) stale.push(home);
61698
62388
  }
61699
62389
  const install = root === process.cwd() ? "waitcher skill install" : `waitcher skill install --path ${join14(root, ".claude", "skills")}`;
@@ -62114,8 +62804,8 @@ var incidentEditSchema = external_exports.object({
62114
62804
  // src/access.ts
62115
62805
  import { lstat as lstat10, open as open16, unlink as unlink3 } from "node:fs/promises";
62116
62806
  import { dirname as dirname15, resolve as resolve16 } from "node:path";
62117
- function accessTokenInput(text3) {
62118
- let token = text3.trim();
62807
+ function accessTokenInput(text4) {
62808
+ let token = text4.trim();
62119
62809
  if (token.startsWith("{")) {
62120
62810
  try {
62121
62811
  token = JSON.parse(token).token;
@@ -62221,10 +62911,10 @@ async function readPrivate(path2) {
62221
62911
  }
62222
62912
  async function loadSession(server) {
62223
62913
  const path2 = sessionPath(server);
62224
- let text3;
62914
+ let text4;
62225
62915
  try {
62226
62916
  await privatePath(dirname16(path2), true);
62227
- text3 = await readPrivate(path2);
62917
+ text4 = await readPrivate(path2);
62228
62918
  } catch (cause) {
62229
62919
  const error62 = asError(cause);
62230
62920
  if (error62.code === "ENOENT")
@@ -62235,7 +62925,7 @@ async function loadSession(server) {
62235
62925
  }
62236
62926
  let session;
62237
62927
  try {
62238
- session = JSON.parse(text3);
62928
+ session = JSON.parse(text4);
62239
62929
  } catch {
62240
62930
  throw new Error("Saved session is unreadable. Run auth login again.");
62241
62931
  }
@@ -62692,14 +63382,14 @@ Repository deploys (waitcher.json)
62692
63382
  Keys identify monitors; renaming a key replaces the monitor and its history.
62693
63383
  The repository owns definitions; the server owns pause and resume. New monitors start
62694
63384
  paused unless --activate-new. Undeclared monitors are reported and deleted only with --prune.
62695
- Deploys accept http, certificate, heartbeat, api, browser and visual (first --smoke
63385
+ Deploys accept http, certificate, heartbeat, api, browser, visual and mcp (first --smoke
62696
63386
  capture: baseline_review, see help visual). Script monitors name an
62697
63387
  entry file; the CLI builds it like monitor build (project needs e2e@${RUNTIME_PINS.e2e},
62698
63388
  @e2e-dev/web@${RUNTIME_PINS["@e2e-dev/web"]} for browser, esbuild@${RUNTIME_PINS.esbuild}). Plans and results list issues with
62699
63389
  code, path, monitor key and hint; ok:false exits 2. --based-on refuses a stale plan.
62700
63390
 
62701
63391
  Monitor configuration
62702
- monitor init --file PATH [--type http|certificate|api|browser|visual|heartbeat|ai] [--target URL]
63392
+ monitor init --file PATH [--type http|certificate|api|browser|visual|heartbeat|ai|mcp] [--target URL]
62703
63393
  Write a paused example; never overwrite
62704
63394
  api and browser also write PATH.e2e.ts next to it
62705
63395
  monitor init --template agent-outcome --file PATH [--target API_BASE]
@@ -62807,17 +63497,35 @@ Verified HTTP targets and write-only request credentials (features.httpTargets)
62807
63497
  target credential disable --id ID --expected-revision N
62808
63498
  target credential delete --id ID --expected-revision N --yes
62809
63499
  Target JSON: {"name":"Product","origin":"https://product.example"}.
62810
- Credential JSON: {"targetId":"UUID","name":"API key","header":"X-Api-Key"}.
63500
+ Credential JSON: {"targetId":"UUID","name":"API key","header":"X-Api-Key"}; header is any name your API reads (X-Api-Key, Authorization, X-Auth-Token, ...), not Host, Cookie or transport headers.
63501
+ Basic auth: header Authorization, private value "Basic " + base64(user:password).
63502
+ OAuth 2: {"targetId":"UUID","name":"Product OAuth","kind":"oauth2","oauth":{"grant":"client_credentials","tokenUrl":"https://auth.example.com/oauth/token","clientId":"ID","scope":"read","clientAuth":"post"}}.
63503
+ The private value is the client secret; for grant refresh_token it is one JSON line {"refreshToken":"...","clientSecret":"..."} (clientSecret optional).
63504
+ Waitcher fetches and caches the access token and sends Authorization: Bearer; a rotated refresh token is kept. Hosted runs only; run local needs a static header.
62811
63505
  Challenge output requires a new file in a private directory (700); token never printed.
62812
63506
  Publish its proof at /.well-known/waitcher-verification.txt, then verify explicitly.
62813
63507
  Proof expires after 15 minutes; verification lasts 24 hours. Redirects are refused.
62814
63508
  Keys are single-line ASCII values up to 4096 characters, private file (600) or stdin.
62815
63509
  Monitor httpAuth contains reference IDs/revision only; keys never appear in export.
62816
- run local --file HTTP_OR_AI.json --http-credentials-file PRIVATE_MAP
63510
+ run local --file HTTP_AI_OR_MCP.json --http-credentials-file PRIVATE_MAP
62817
63511
  Local map resolves reference IDs/revision/origin/header to private credentialFile.
62818
63512
  Map schemaVersion 1, credentials:[{targetId,credentialId,credentialRevision,
62819
63513
  origin,header,credentialFile}]. Paths resolve relative to map; no inline keys.
62820
63514
 
63515
+ MCP server monitoring (remote Streamable HTTP servers)
63516
+ monitor init --type mcp --target https://product.example/mcp --file mcp.json
63517
+ Locally without an account: waitcher run local --file mcp.json [--timeout 3..30]
63518
+ Each run: initialize, tools/list, optional tools/call, then the session is closed.
63519
+ monitor apply --file mcp.json Save paused; then monitor resume --id ID
63520
+ "mcp": {"expectTools":["search"],"toolCall":{"name":"search","arguments":{},
63521
+ "assertions":[{"path":"/content/0/type","operator":"equals","value":"text"}]}}
63522
+ Missing tools, JSON-RPC errors, isError results and failed assertions fail the check.
63523
+ Personal accounts: listing tools needs nothing extra; a toolCall needs verified
63524
+ httpAuth, an interval of at least 30 minutes and counts one daily invocation.
63525
+ Reports record steps, server name/version and tool names, never arguments or tool output.
63526
+ stdio servers, OAuth flows, resources and prompts are not checked
63527
+ (https://waitcher.dev/docs/mcp.md).
63528
+
62821
63529
  AI product endpoint monitoring (administrator pilot; requires features.aiEndpoints)
62822
63530
  monitor init --type ai --target https://product.example/ai --file ai.json
62823
63531
  monitor validate --file ai.json Offline JSON fixture/assertion/schema validation
@@ -63091,55 +63799,8 @@ ${exitCodes}
63091
63799
  `;
63092
63800
  }
63093
63801
 
63094
- // package.json
63095
- var package_default = {
63096
- name: "@waitcher/cli",
63097
- version: "0.2.24",
63098
- description: "Synthetic monitoring from your repository: deploy HTTP, certificate, heartbeat, API, browser and visual monitors from waitcher.json.",
63099
- license: "SEE LICENSE IN LICENSE.txt",
63100
- author: "S\u0142awomir Radzymi\u0144ski",
63101
- homepage: "https://waitcher.dev/docs/",
63102
- repository: {
63103
- type: "git",
63104
- url: "git+https://github.com/slawekradzyminski/synthetic-watch.git",
63105
- directory: "packages/cli"
63106
- },
63107
- keywords: [
63108
- "monitoring",
63109
- "synthetic-monitoring",
63110
- "uptime",
63111
- "e2e",
63112
- "ci",
63113
- "cli"
63114
- ],
63115
- type: "module",
63116
- bin: {
63117
- waitcher: "dist/cli.mjs"
63118
- },
63119
- files: [
63120
- "dist/cli.mjs",
63121
- "dist/model-client.mjs",
63122
- "dist/scenario-runtime.mjs",
63123
- "dist/request-runtime.mjs",
63124
- "dist/MODEL_CLIENT_NOTICES.txt",
63125
- "README.md",
63126
- "THIRD_PARTY_NOTICES.txt",
63127
- "LICENSE.txt"
63128
- ],
63129
- engines: {
63130
- node: ">=24.15.0"
63131
- },
63132
- publishConfig: {
63133
- access: "public"
63134
- },
63135
- scripts: {
63136
- build: "node build.mjs",
63137
- prepack: "npm run build"
63138
- }
63139
- };
63140
-
63141
63802
  // src/main.ts
63142
- var list = (text3) => (text3 ?? "").split(",").map((x) => x.trim()).filter(Boolean);
63803
+ var list = (text4) => (text4 ?? "").split(",").map((x) => x.trim()).filter(Boolean);
63143
63804
  var issues = (all) => all.map((i) => `${i.path.join(".")}: ${i.message}`).join("\n");
63144
63805
  var controller = new AbortController();
63145
63806
  process.once("SIGINT", () => controller.abort());
@@ -63152,9 +63813,9 @@ function id3(value2) {
63152
63813
  usage2("Provide --id with the exact monitor or execution ID.");
63153
63814
  return encodeURIComponent(value2);
63154
63815
  }
63155
- function integer2(value2, label, min, max) {
63816
+ function integer2(value2, label2, min, max) {
63156
63817
  if (!/^\d+$/.test(value2 ?? "") || !Number.isSafeInteger(Number(value2)) || Number(value2) < min || Number(value2) > max)
63157
- usage2(`${label} must be an integer from ${min} to ${max}.`);
63818
+ usage2(`${label2} must be an integer from ${min} to ${max}.`);
63158
63819
  return Number(value2);
63159
63820
  }
63160
63821
  function summary(m) {
@@ -63210,16 +63871,16 @@ async function passwordFromStdin(maxBytes = 2048) {
63210
63871
  usage2(
63211
63872
  "Pipe the password to stdin, or use --password-file PATH. Passwords are not accepted as command arguments."
63212
63873
  );
63213
- let text3 = "";
63874
+ let text4 = "";
63214
63875
  const cancel = () => process.stdin.destroy(new Error("Interrupted."));
63215
63876
  controller.signal.addEventListener("abort", cancel, { once: true });
63216
63877
  try {
63217
63878
  for await (const chunk of process.stdin) {
63218
- text3 += chunk;
63219
- if (Buffer.byteLength(text3) > maxBytes)
63879
+ text4 += chunk;
63880
+ if (Buffer.byteLength(text4) > maxBytes)
63220
63881
  usage2("Password input is too long.");
63221
63882
  }
63222
- return text3.replace(/[\r\n]+$/, "");
63883
+ return text4.replace(/[\r\n]+$/, "");
63223
63884
  } finally {
63224
63885
  controller.signal.removeEventListener("abort", cancel);
63225
63886
  }
@@ -63947,10 +64608,11 @@ async function main() {
63947
64608
  "browser",
63948
64609
  "visual",
63949
64610
  "heartbeat",
63950
- "ai"
64611
+ "ai",
64612
+ "mcp"
63951
64613
  ].includes(v.type))
63952
64614
  usage2(
63953
- "monitor init supports --type http, certificate, api, browser, visual, heartbeat or ai."
64615
+ "monitor init supports --type http, certificate, api, browser, visual, heartbeat, ai or mcp."
63954
64616
  );
63955
64617
  let protectedInitial;
63956
64618
  if (v.template === "protected-agent-outcome") {
@@ -63974,7 +64636,7 @@ async function main() {
63974
64636
  usage2(
63975
64637
  "These request policy/context options require --template protected-agent-outcome."
63976
64638
  );
63977
- const initial = protectedInitial ?? (v.template === "agent-outcome" ? agentOutcomeExample : v.type === "ai" ? aiEndpointExample : v.type === "heartbeat" ? {
64639
+ const initial = protectedInitial ?? (v.template === "agent-outcome" ? agentOutcomeExample : v.type === "ai" ? aiEndpointExample : v.type === "mcp" ? mcpExample : v.type === "heartbeat" ? {
63978
64640
  schemaVersion: 1,
63979
64641
  name: "Scheduled job",
63980
64642
  type: "heartbeat",
@@ -64329,7 +64991,7 @@ async function main() {
64329
64991
  });
64330
64992
  if (!parsed2.success)
64331
64993
  usage2(
64332
- "Credential JSON must contain targetId, name and header Authorization or X-Api-Key."
64994
+ "Credential JSON must contain targetId, name and either a valid header name or kind oauth2 with an oauth block (grant, tokenUrl, clientId). See: waitcher help target."
64333
64995
  );
64334
64996
  result2 = await api("http-targets/credentials", {
64335
64997
  method: "POST",
@@ -64971,12 +65633,12 @@ async function main() {
64971
65633
  usage2(
64972
65634
  "Provide --file PATH with the complete configuration and expectedRevision for edits."
64973
65635
  );
64974
- const text3 = await readFile11(v.file, "utf8");
64975
- if (Buffer.byteLength(text3) > 16e3)
65636
+ const text4 = await readFile11(v.file, "utf8");
65637
+ if (Buffer.byteLength(text4) > 16e3)
64976
65638
  usage2("Project configuration exceeds 16 KB");
64977
65639
  let body2;
64978
65640
  try {
64979
- body2 = JSON.parse(text3);
65641
+ body2 = JSON.parse(text4);
64980
65642
  } catch {
64981
65643
  usage2("Configuration must be JSON");
64982
65644
  }
@@ -65221,10 +65883,10 @@ async function main() {
65221
65883
  if (!v.file) usage2("Provide --file PATH for the configuration.");
65222
65884
  let input2;
65223
65885
  try {
65224
- const text3 = await readFile11(v.file, "utf8");
65225
- if (Buffer.byteLength(text3) > 96e3)
65886
+ const text4 = await readFile11(v.file, "utf8");
65887
+ if (Buffer.byteLength(text4) > 96e3)
65226
65888
  usage2("Configuration exceeds 96 KB.");
65227
- input2 = JSON.parse(text3);
65889
+ input2 = JSON.parse(text4);
65228
65890
  } catch {
65229
65891
  usage2("Could not read valid JSON configuration.");
65230
65892
  }
@@ -65676,10 +66338,10 @@ async function main() {
65676
66338
  if (!v.file) usage2("Provide --file PATH for the status page.");
65677
66339
  let input2;
65678
66340
  try {
65679
- const text3 = await readFile11(v.file, "utf8");
65680
- if (Buffer.byteLength(text3) > 96e3)
66341
+ const text4 = await readFile11(v.file, "utf8");
66342
+ if (Buffer.byteLength(text4) > 96e3)
65681
66343
  usage2("Configuration exceeds 96 KB.");
65682
- input2 = JSON.parse(text3);
66344
+ input2 = JSON.parse(text4);
65683
66345
  } catch {
65684
66346
  usage2("Could not read valid JSON configuration.");
65685
66347
  }