@waitcher/cli 0.2.25 → 0.2.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.mjs +976 -115
  3. package/package.json +1 -1
package/dist/cli.mjs CHANGED
@@ -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: performance7 } = __require("node:perf_hooks");
4299
+ var { performance: performance8 } = __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(performance7.now(), crossOriginIsolatedCapability);
4457
+ return coarsenTime(performance8.now(), crossOriginIsolatedCapability);
4458
4458
  }
4459
4459
  function createOpaqueTimingInfo(timingInfo) {
4460
4460
  return {
@@ -18153,14 +18153,14 @@ var require_mock_utils = __commonJS({
18153
18153
  mockDispatch.call(this, opts, handler);
18154
18154
  } catch (error62) {
18155
18155
  if (error62.code === "UND_MOCK_ERR_MOCK_NOT_MATCHED") {
18156
- const netConnect = agent[kGetNetConnect]();
18156
+ const netConnect2 = agent[kGetNetConnect]();
18157
18157
  const totalInterceptsCount = this[kDispatches][kTotalDispatchCount] || this[kDispatches].length;
18158
18158
  const pendingInterceptsCount = this[kDispatches].filter(({ consumed }) => !consumed).length;
18159
18159
  const interceptsMessage = `, ${pendingInterceptsCount} interceptor(s) remaining out of ${totalInterceptsCount} defined`;
18160
- if (netConnect === false) {
18160
+ if (netConnect2 === false) {
18161
18161
  throw new MockNotMatchedError(`${error62.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)${interceptsMessage}`);
18162
18162
  }
18163
- if (checkNetConnect(netConnect, origin)) {
18163
+ if (checkNetConnect(netConnect2, origin)) {
18164
18164
  originalDispatch.call(this, "__mockAgentBodyForDispatch" in opts ? { ...opts, body: opts.__mockAgentBodyForDispatch } : opts, handler);
18165
18165
  } else {
18166
18166
  throw new MockNotMatchedError(`${error62.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)${interceptsMessage}`);
@@ -18174,11 +18174,11 @@ var require_mock_utils = __commonJS({
18174
18174
  }
18175
18175
  };
18176
18176
  }
18177
- function checkNetConnect(netConnect, origin) {
18177
+ function checkNetConnect(netConnect2, origin) {
18178
18178
  const url3 = new URL(origin);
18179
- if (netConnect === true) {
18179
+ if (netConnect2 === true) {
18180
18180
  return true;
18181
- } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url3.host))) {
18181
+ } else if (Array.isArray(netConnect2) && netConnect2.some((matcher) => matchValue(matcher, url3.host))) {
18182
18182
  return true;
18183
18183
  }
18184
18184
  return false;
@@ -20296,7 +20296,7 @@ var require_dump = __commonJS({
20296
20296
  var require_dns = __commonJS({
20297
20297
  "../../node_modules/undici/lib/interceptor/dns.js"(exports, module) {
20298
20298
  "use strict";
20299
- var { isIP: isIP2 } = __require("node:net");
20299
+ var { isIP: isIP3 } = __require("node:net");
20300
20300
  var { lookup: lookup3 } = __require("node:dns");
20301
20301
  var DecoratorHandler = require_decorator_handler();
20302
20302
  var { InvalidArgumentError, InformationalError } = require_errors();
@@ -20713,7 +20713,7 @@ var require_dns = __commonJS({
20713
20713
  return dispatch(origDispatchOpts, handler);
20714
20714
  }
20715
20715
  const origin = origDispatchOpts.origin.constructor === URL ? origDispatchOpts.origin : new URL(origDispatchOpts.origin);
20716
- if (isIP2(origin.hostname) !== 0) {
20716
+ if (isIP3(origin.hostname) !== 0) {
20717
20717
  return dispatch(origDispatchOpts, handler);
20718
20718
  }
20719
20719
  instance.runLookup(origin, origDispatchOpts, (err, newOrigin) => {
@@ -24574,17 +24574,17 @@ var require_sqlite_cache_store = __commonJS({
24574
24574
  if (now >= value2.deleteAt && !canBeExpired) {
24575
24575
  continue;
24576
24576
  }
24577
- let matches = true;
24577
+ let matches2 = true;
24578
24578
  if (value2.vary) {
24579
24579
  const vary = JSON.parse(value2.vary);
24580
24580
  for (const header in vary) {
24581
24581
  if (!headerValueEquals(headers[header], vary[header])) {
24582
- matches = false;
24582
+ matches2 = false;
24583
24583
  break;
24584
24584
  }
24585
24585
  }
24586
24586
  }
24587
- if (matches) {
24587
+ if (matches2) {
24588
24588
  return value2;
24589
24589
  }
24590
24590
  }
@@ -35903,16 +35903,16 @@ var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
35903
35903
  };
35904
35904
  });
35905
35905
  function handleExclusiveUnionResults(results, final, inst, ctx) {
35906
- const matches = [];
35906
+ const matches2 = [];
35907
35907
  for (let i = 0; i < results.length; i++) {
35908
35908
  if (results[i].issues.length === 0)
35909
- matches.push(i);
35909
+ matches2.push(i);
35910
35910
  }
35911
- if (matches.length === 1) {
35912
- final.value = results[matches[0]].value;
35911
+ if (matches2.length === 1) {
35912
+ final.value = results[matches2[0]].value;
35913
35913
  return final;
35914
35914
  }
35915
- if (matches.length === 0) {
35915
+ if (matches2.length === 0) {
35916
35916
  final.issues.push({
35917
35917
  code: "invalid_union",
35918
35918
  input: final.value,
@@ -35926,7 +35926,7 @@ function handleExclusiveUnionResults(results, final, inst, ctx) {
35926
35926
  inst,
35927
35927
  errors: [],
35928
35928
  inclusive: false,
35929
- matches
35929
+ matches: matches2
35930
35930
  });
35931
35931
  }
35932
35932
  return final;
@@ -51135,20 +51135,20 @@ function checkArrayGuards(arraySchema, guards) {
51135
51135
  if (guards.containsSchema) {
51136
51136
  const minContains = guards.minContains ?? 1;
51137
51137
  const ceiling = guards.maxContains !== void 0 ? guards.maxContains + 1 : Number.POSITIVE_INFINITY;
51138
- let matches = 0;
51138
+ let matches2 = 0;
51139
51139
  for (const item of items) {
51140
- if (guards.containsSchema.safeParse(item).success && ++matches >= ceiling)
51140
+ if (guards.containsSchema.safeParse(item).success && ++matches2 >= ceiling)
51141
51141
  break;
51142
51142
  }
51143
- if (matches < minContains) {
51143
+ if (matches2 < minContains) {
51144
51144
  payload.issues.push({
51145
51145
  code: "custom",
51146
- message: `Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches}`,
51146
+ message: `Array must contain at least ${minContains} matching ${plural(minContains)}; found ${matches2}`,
51147
51147
  input: items,
51148
51148
  continue: true
51149
51149
  });
51150
51150
  }
51151
- if (guards.maxContains !== void 0 && matches > guards.maxContains) {
51151
+ if (guards.maxContains !== void 0 && matches2 > guards.maxContains) {
51152
51152
  payload.issues.push({
51153
51153
  code: "custom",
51154
51154
  message: `Array must contain at most ${guards.maxContains} matching ${plural(guards.maxContains)}`,
@@ -53484,6 +53484,62 @@ var agentKeySchema = external_exports.object({
53484
53484
  model: modelNameSchema
53485
53485
  }).strict();
53486
53486
 
53487
+ // ../../src/contracts/network.ts
53488
+ var NETWORK_LIMITS = Object.freeze({
53489
+ maxTimeoutSeconds: 15,
53490
+ bannerChars: 200,
53491
+ bannerBytes: 1024,
53492
+ expectedValues: 20,
53493
+ valueChars: 255,
53494
+ answers: 32
53495
+ });
53496
+ var DNS_RECORD_TYPES = ["A", "AAAA", "CNAME", "MX", "TXT"];
53497
+ var tcpConfigSchema = external_exports.object({
53498
+ // Text the server must send first, such as "SSH-2.0" or "220 ". Empty
53499
+ // means a completed connection passes.
53500
+ banner: external_exports.string().max(NETWORK_LIMITS.bannerChars).default("")
53501
+ }).strict();
53502
+ var dnsConfigSchema = external_exports.object({
53503
+ recordType: external_exports.enum(DNS_RECORD_TYPES),
53504
+ // Values the answer must hold. Empty means any answer passes.
53505
+ expected: external_exports.array(external_exports.string().trim().min(1).max(NETWORK_LIMITS.valueChars)).max(NETWORK_LIMITS.expectedValues).default([]),
53506
+ // includes: every expected value is in the answer; exact: the answer is
53507
+ // exactly the expected set.
53508
+ match: external_exports.enum(["includes", "exact"]).default("includes")
53509
+ }).strict();
53510
+ var RESERVED = /(^|\.)(localhost|local|internal|test|invalid|example|home\.arpa|lan|corp)\.?$/i;
53511
+ var LABELS = /^(?=.{1,253}$)(?:[A-Za-z0-9_](?:[A-Za-z0-9_-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z][A-Za-z0-9-]{0,61}[A-Za-z0-9]\.?$/;
53512
+ var IPV4 = /^(?:25[0-5]|2[0-4]\d|1?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;
53513
+ function publicDnsName(name5) {
53514
+ return LABELS.test(name5) && !RESERVED.test(name5);
53515
+ }
53516
+ function parseTcpTarget(target) {
53517
+ const match = /^\[([0-9A-Fa-f:.]{2,45})\]:(\d{1,5})$/.exec(target) ?? /^([A-Za-z0-9._-]{1,253}):(\d{1,5})$/.exec(target);
53518
+ if (!match) return null;
53519
+ const host = match[1], port = Number(match[2]);
53520
+ if (port < 1 || port > 65535) return null;
53521
+ if (target.startsWith("[") || IPV4.test(host)) return { host, port };
53522
+ return publicDnsName(host) ? { host: host.replace(/\.$/, ""), port } : null;
53523
+ }
53524
+ var networkTraceSchema = external_exports.object({
53525
+ protocol: external_exports.enum(["tcp", "dns"]),
53526
+ host: external_exports.string().max(253),
53527
+ port: external_exports.number().int().min(1).max(65535).nullable(),
53528
+ recordType: external_exports.enum(DNS_RECORD_TYPES).nullable(),
53529
+ // The resolver a DNS check asked; TCP uses the host's resolver.
53530
+ resolver: external_exports.string().max(100).nullable(),
53531
+ // The address a TCP check connected to.
53532
+ address: external_exports.string().max(64).nullable(),
53533
+ answers: external_exports.array(external_exports.string().max(300)).max(NETWORK_LIMITS.answers),
53534
+ banner: external_exports.string().max(300).nullable(),
53535
+ timings: external_exports.object({
53536
+ dns: external_exports.number().int().min(0).nullable(),
53537
+ connect: external_exports.number().int().min(0).nullable(),
53538
+ banner: external_exports.number().int().min(0).nullable()
53539
+ }).strict(),
53540
+ error: external_exports.string().max(300).nullable()
53541
+ }).strict();
53542
+
53487
53543
  // ../../src/contracts/monitor.ts
53488
53544
  var url2 = external_exports.string().max(2e3).url().refine((value2) => {
53489
53545
  try {
@@ -53505,7 +53561,9 @@ var monitorSchema = external_exports.object({
53505
53561
  "visual",
53506
53562
  "heartbeat",
53507
53563
  "ai",
53508
- "mcp"
53564
+ "mcp",
53565
+ "tcp",
53566
+ "dns"
53509
53567
  ]),
53510
53568
  target: external_exports.string().trim().min(1).max(2e3),
53511
53569
  interval: external_exports.number().int().min(60).max(86400).default(300),
@@ -53518,11 +53576,16 @@ var monitorSchema = external_exports.object({
53518
53576
  heartbeat: heartbeatConfigSchema.optional(),
53519
53577
  aiEndpoint: aiEndpointConfigSchema.optional(),
53520
53578
  mcp: mcpConfigSchema.optional(),
53579
+ tcp: tcpConfigSchema.optional(),
53580
+ dns: dnsConfigSchema.optional(),
53521
53581
  httpAuth: httpAuthSchema.optional(),
53522
53582
  protectedRequests: productRequestsPolicySchema.optional(),
53523
53583
  browserIdentity: browserIdentityBindingSchema.optional(),
53524
53584
  agent: agentBindingSchema.optional(),
53525
53585
  requestBudget: requestBudgetSchema.optional(),
53586
+ // false opts an HTTP or certificate check out of second-region
53587
+ // confirmation (docs/design/second-region.md); absent means on.
53588
+ secondRegion: external_exports.boolean().optional(),
53526
53589
  settings: external_exports.object({
53527
53590
  certificateMinDays: external_exports.number().int().min(1).max(90).optional(),
53528
53591
  method: external_exports.enum(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"]).default("GET"),
@@ -53598,6 +53661,11 @@ var monitorSchema = external_exports.object({
53598
53661
  issue3("Use a public HTTPS endpoint", "target");
53599
53662
  }
53600
53663
  }
53664
+ if (m.secondRegion !== void 0 && !["http", "certificate"].includes(m.type))
53665
+ issue3(
53666
+ "Second-region confirmation applies to HTTP and certificate checks",
53667
+ "secondRegion"
53668
+ );
53601
53669
  if (m.type !== "ai" && m.aiEndpoint !== void 0)
53602
53670
  issue3(
53603
53671
  "AI endpoint settings require an AI endpoint monitor",
@@ -53657,6 +53725,34 @@ var monitorSchema = external_exports.object({
53657
53725
  "settings"
53658
53726
  );
53659
53727
  }
53728
+ if (m.type !== "tcp" && m.tcp !== void 0)
53729
+ issue3("TCP settings require a TCP monitor", "tcp");
53730
+ if (m.type !== "dns" && m.dns !== void 0)
53731
+ issue3("DNS settings require a DNS monitor", "dns");
53732
+ if (m.type === "tcp" || m.type === "dns") {
53733
+ if (m.type === "dns" && !m.dns)
53734
+ issue3("Choose a DNS record type", "dns");
53735
+ if (m.type === "tcp" && !parseTcpTarget(m.target))
53736
+ issue3(
53737
+ "Enter HOST:PORT with a public hostname or IP address, such as db.example.com:5432",
53738
+ "target"
53739
+ );
53740
+ if (m.type === "dns" && !publicDnsName(m.target))
53741
+ issue3(
53742
+ "Enter a public DNS name such as example.com, without a scheme or path",
53743
+ "target"
53744
+ );
53745
+ if (m.timeout > NETWORK_LIMITS.maxTimeoutSeconds)
53746
+ issue3(
53747
+ `TCP and DNS checks have a maximum timeout of ${NETWORK_LIMITS.maxTimeoutSeconds} seconds`,
53748
+ "timeout"
53749
+ );
53750
+ if (m.demo || m.script || m.ai || m.visual || m.heartbeat || m.aiEndpoint || m.mcp || m.httpAuth || m.requestBudget || 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)
53751
+ issue3(
53752
+ m.type === "tcp" ? "TCP checks accept a host, port and optional banner only; scripts and HTTP assertions are not supported" : "DNS checks accept a name, record type and expected values only; scripts and HTTP assertions are not supported",
53753
+ "settings"
53754
+ );
53755
+ }
53660
53756
  if (m.type !== "heartbeat" && m.heartbeat !== void 0)
53661
53757
  issue3("Heartbeat settings require a heartbeat monitor", "heartbeat");
53662
53758
  if (m.type === "heartbeat") {
@@ -53721,7 +53817,7 @@ var monitorSchema = external_exports.object({
53721
53817
  "Enter a hostname or IP address, without a URL or flags",
53722
53818
  "target"
53723
53819
  );
53724
- } else if (m.type !== "heartbeat") {
53820
+ } else if (!["heartbeat", "tcp", "dns"].includes(m.type)) {
53725
53821
  if (!url2.safeParse(m.target).success)
53726
53822
  issue3("Enter an HTTP(S) URL without embedded credentials", "target");
53727
53823
  if (m.type === "browser") {
@@ -54215,6 +54311,10 @@ function asError(value2) {
54215
54311
  }
54216
54312
 
54217
54313
  // src/client.ts
54314
+ var defaultWorkspace;
54315
+ function useWorkspace(id4) {
54316
+ defaultWorkspace = id4;
54317
+ }
54218
54318
  var ServiceError = class extends Error {
54219
54319
  idempotencyKey;
54220
54320
  code;
@@ -54236,7 +54336,8 @@ async function request(server, path2, {
54236
54336
  body: body2,
54237
54337
  signal,
54238
54338
  secrets = [],
54239
- version: version2 = "v1"
54339
+ version: version2 = "v1",
54340
+ workspace = defaultWorkspace
54240
54341
  } = {}) {
54241
54342
  if (idempotencyKey !== void 0 && (!requestKeyPattern.test(idempotencyKey) || !keyedOperation(path2, method)))
54242
54343
  throw new ServiceError(
@@ -54266,7 +54367,8 @@ async function request(server, path2, {
54266
54367
  "Content-Type": "application/json",
54267
54368
  ...key ? { "Idempotency-Key": key } : {},
54268
54369
  ...cookie ? { Cookie: cookie } : {},
54269
- ...accessToken ? { Authorization: `Bearer ${accessToken}` } : {}
54370
+ ...accessToken ? { Authorization: `Bearer ${accessToken}` } : {},
54371
+ ...workspace ? { "Waitcher-Workspace": workspace } : {}
54270
54372
  },
54271
54373
  ...body2 !== void 0 ? { body: JSON.stringify(body2) } : {},
54272
54374
  signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15e3)]) : AbortSignal.timeout(15e3)
@@ -54523,6 +54625,136 @@ function formatScenarioReport(input2) {
54523
54625
  return lines.join("\n") + "\n";
54524
54626
  }
54525
54627
 
54628
+ // ../../src/contracts/evidence.ts
54629
+ var safeEvidencePath = (path2) => path2.length <= 512 && !path2.includes("\\") && path2.split("/").every(
54630
+ (p) => p !== "" && p !== "." && p !== ".." && !/[\x00-\x1f\x7f]/.test(p)
54631
+ );
54632
+
54633
+ // ../../src/cloud/contract.ts
54634
+ var cloudAttemptSchema = external_exports.object({
54635
+ attemptId: external_exports.uuid(),
54636
+ deadlineAt: external_exports.number().int().positive(),
54637
+ monitor: monitorDefinitionSchema,
54638
+ environment: external_exports.record(external_exports.string().regex(/^CHECK_[A-Z0-9_]+$/), external_exports.string().max(16e3)).default({}),
54639
+ // Approved baselines of the test's toHaveScreenshot calls, base64 by the
54640
+ // file name the framework looks for.
54641
+ snapshots: external_exports.record(
54642
+ external_exports.string().regex(SCRIPT_SCREENSHOT_FILE),
54643
+ external_exports.string().max(Math.ceil(SCRIPT_SCREENSHOT_LIMITS.totalBytes / 3) * 4)
54644
+ ).refine(
54645
+ (files) => Object.keys(files).length <= SCRIPT_SCREENSHOT_LIMITS.files && Object.values(files).reduce((n, data) => n + data.length, 0) <= Math.ceil(SCRIPT_SCREENSHOT_LIMITS.totalBytes / 3) * 4,
54646
+ "Stored screenshots exceed their budget"
54647
+ ).optional()
54648
+ }).strict().superRefine((value2, ctx) => {
54649
+ const m = value2.monitor, target = new URL(m.target);
54650
+ if (!["api", "browser", "visual"].includes(m.type) || value2.snapshots && m.type === "api" || (m.type === "visual" ? !m.visual || Boolean(m.script) || Object.keys(value2.environment).length > 0 : !m.script?.trim()) || m.ai || m.httpAuth || m.protectedRequests || m.browserIdentity || m.demo || target.protocol !== "https:" || target.port && target.port !== "443" || Object.keys(value2.environment).some(
54651
+ (name5) => !m.settings.envNames.includes(name5)
54652
+ ))
54653
+ ctx.addIssue({
54654
+ code: "custom",
54655
+ message: "Cloud attempts accept deterministic public HTTPS API/browser scripts, visual checks and only listed CHECK_* values"
54656
+ });
54657
+ });
54658
+ var cloudAgentSchema = external_exports.object({
54659
+ attemptId: external_exports.uuid(),
54660
+ deadlineAt: external_exports.number().int().positive(),
54661
+ agent: external_exports.object({
54662
+ runner: external_exports.literal("claude-code"),
54663
+ task: external_exports.string().min(1).max(8e3),
54664
+ model: external_exports.string().min(1).max(120),
54665
+ turns: external_exports.number().int().min(1).max(100),
54666
+ placeholder: external_exports.string().regex(/^wa_[a-f0-9]{48}$/)
54667
+ }).strict(),
54668
+ environment: external_exports.record(external_exports.string().regex(/^CHECK_[A-Z0-9_]+$/), external_exports.string().max(16e3)).default({})
54669
+ }).strict();
54670
+ function egressAllowed(url3) {
54671
+ const host = url3.hostname.replace(/^\[|\]$/g, "").toLowerCase();
54672
+ return url3.protocol === "https:" && (url3.port === "" || url3.port === "443") && !url3.username && !url3.password && !/^[\d.]+$/.test(host) && !host.includes(":") && host.includes(".") && !/(^|\.)(localhost|local|internal|home|lan|arpa)$/.test(host);
54673
+ }
54674
+ var CLOUD_EVIDENCE = Object.freeze({
54675
+ files: 32,
54676
+ fileBytes: 8 * 1024 * 1024,
54677
+ totalBytes: 16 * 1024 * 1024
54678
+ });
54679
+
54680
+ // ../../src/contracts/second-region.ts
54681
+ var SECOND_REGIONS = [
54682
+ "enam",
54683
+ "wnam",
54684
+ "apac",
54685
+ "apac-ne",
54686
+ "apac-se",
54687
+ "oc"
54688
+ ];
54689
+ var PRIMARY_REGION = "Europe";
54690
+ var SECOND_REGION_LIMITS = Object.freeze({
54691
+ redirects: 3,
54692
+ bodyBytes: 256e3,
54693
+ // Added to an eligible attempt's absolute deadline, beyond its timeout.
54694
+ allowanceSeconds: 10,
54695
+ // Seconds beyond the monitor timeout the control plane waits for the Worker.
54696
+ requestSlackSeconds: 5,
54697
+ message: 300
54698
+ });
54699
+ var recheckRequestSchema = external_exports.object({
54700
+ schemaVersion: external_exports.literal(1),
54701
+ region: external_exports.enum(SECOND_REGIONS),
54702
+ // "http": the monitor's own assertions; "tls": any HTTP answer means the
54703
+ // TLS handshake verified from there.
54704
+ kind: external_exports.enum(["http", "tls"]),
54705
+ method: external_exports.enum(["GET", "HEAD"]),
54706
+ url: external_exports.string().max(2e3).refine((value2) => {
54707
+ try {
54708
+ return egressAllowed(new URL(value2));
54709
+ } catch {
54710
+ return false;
54711
+ }
54712
+ }, "Public HTTPS names on port 443 only"),
54713
+ expectedStatus: external_exports.number().int().min(100).max(599),
54714
+ contains: external_exports.string().max(2e3).default(""),
54715
+ jsonPath: external_exports.string().max(200).default(""),
54716
+ jsonValue: external_exports.string().max(2e3).default(""),
54717
+ timeoutMs: external_exports.number().int().min(1e3).max(18e4)
54718
+ }).strict();
54719
+ var ms = external_exports.number().int().min(0).max(6e5);
54720
+ var recheckResponseSchema = external_exports.object({
54721
+ schemaVersion: external_exports.literal(1),
54722
+ region: external_exports.enum(SECOND_REGIONS),
54723
+ // IATA code of the data center the object ran in, null if unknown.
54724
+ colo: external_exports.string().regex(/^[A-Z]{3}$/).nullable(),
54725
+ verdict: external_exports.enum(["passed", "failed", "error"]),
54726
+ status: external_exports.number().int().min(100).max(599).nullable(),
54727
+ message: external_exports.string().max(SECOND_REGION_LIMITS.message),
54728
+ durationMs: ms,
54729
+ hops: external_exports.array(
54730
+ external_exports.object({
54731
+ url: external_exports.string().max(2048),
54732
+ status: external_exports.number().int().min(100).max(599).nullable(),
54733
+ firstByteMs: ms.nullable(),
54734
+ totalMs: ms.nullable(),
54735
+ error: external_exports.string().max(SECOND_REGION_LIMITS.message).nullable()
54736
+ }).strict()
54737
+ ).max(SECOND_REGION_LIMITS.redirects + 1)
54738
+ }).strict();
54739
+ var confirmationOutcomes = [
54740
+ "confirmed",
54741
+ "not_confirmed",
54742
+ "recheck_error",
54743
+ "skipped"
54744
+ ];
54745
+ var runConfirmationSchema = external_exports.object({
54746
+ outcome: external_exports.enum(confirmationOutcomes),
54747
+ primary: external_exports.literal(PRIMARY_REGION),
54748
+ region: external_exports.enum(SECOND_REGIONS).nullable(),
54749
+ colo: external_exports.string().max(8).nullable(),
54750
+ status: external_exports.number().int().min(100).max(599).nullable(),
54751
+ durationMs: ms.nullable(),
54752
+ message: external_exports.string().max(SECOND_REGION_LIMITS.message),
54753
+ hops: recheckResponseSchema.shape.hops,
54754
+ at: external_exports.number().int().min(0),
54755
+ incidentId: external_exports.string().max(64).nullable()
54756
+ }).strict();
54757
+
54526
54758
  // ../../src/contracts/run-trace.ts
54527
54759
  var RUN_TRACE_PATH = ".e2e/waitcher-trace.json";
54528
54760
  var FETCH_TRACE_PATH = ".e2e/waitcher-fetch.json";
@@ -54541,8 +54773,8 @@ var RUN_TRACE_LIMITS = Object.freeze({
54541
54773
  fileBytes: 65536
54542
54774
  });
54543
54775
  var text = (max = RUN_TRACE_LIMITS.text) => external_exports.string().max(max);
54544
- var ms = external_exports.number().int().min(0).max(864e5);
54545
- var nullableMs = ms.nullable();
54776
+ var ms2 = external_exports.number().int().min(0).max(864e5);
54777
+ var nullableMs = ms2.nullable();
54546
54778
  var TRACE_HEADERS = [
54547
54779
  "content-type",
54548
54780
  "content-length",
@@ -54617,13 +54849,18 @@ var runTraceFileSchema = external_exports.discriminatedUnion("kind", [
54617
54849
  schemaVersion: external_exports.literal(1),
54618
54850
  kind: external_exports.literal("certificate"),
54619
54851
  certificate: certificateTraceSchema
54852
+ }).strict(),
54853
+ external_exports.object({
54854
+ schemaVersion: external_exports.literal(1),
54855
+ kind: external_exports.literal("network"),
54856
+ network: networkTraceSchema
54620
54857
  }).strict()
54621
54858
  ]);
54622
54859
  var fetchRecordSchema = external_exports.object({
54623
54860
  method: external_exports.string().min(1).max(16),
54624
54861
  url: text(2048),
54625
54862
  status: external_exports.number().int().min(0).max(599).nullable(),
54626
- durationMs: ms,
54863
+ durationMs: ms2,
54627
54864
  error: text().nullable()
54628
54865
  }).strict();
54629
54866
  var fetchTraceFileSchema = external_exports.object({
@@ -54663,7 +54900,7 @@ var traceTestSchema = external_exports.object({
54663
54900
  api: text(64),
54664
54901
  label: text(),
54665
54902
  status: stepStatus,
54666
- durationMs: ms,
54903
+ durationMs: ms2,
54667
54904
  line: external_exports.number().int().min(1).nullable(),
54668
54905
  error: text(RUN_TRACE_LIMITS.message).nullable()
54669
54906
  }).strict()
@@ -54697,11 +54934,15 @@ var runTraceSchema = external_exports.object({
54697
54934
  exchanges: external_exports.array(httpExchangeSchema).max(RUN_TRACE_LIMITS.exchanges)
54698
54935
  }).strict().nullable(),
54699
54936
  certificate: certificateTraceSchema.nullable(),
54937
+ // TCP and DNS checks; absent for other types, so older CLIs still parse.
54938
+ network: networkTraceSchema.optional(),
54700
54939
  tests: external_exports.array(traceTestSchema).max(RUN_TRACE_LIMITS.tests).nullable(),
54701
54940
  requests: external_exports.object({
54702
54941
  items: external_exports.array(fetchRecordSchema).max(RUN_TRACE_LIMITS.requests),
54703
54942
  dropped: external_exports.number().int().min(0)
54704
54943
  }).strict().nullable(),
54944
+ // The second-region recheck before an incident (docs/design/second-region.md).
54945
+ secondRegion: runConfirmationSchema.nullable().optional(),
54705
54946
  // A finished run's captured test output; empty means the runner printed nothing.
54706
54947
  output: external_exports.object({ bytes: external_exports.number().int().min(0), empty: external_exports.boolean() }).strict()
54707
54948
  }).strict();
@@ -54893,11 +55134,6 @@ import { createHash as createHash3 } from "node:crypto";
54893
55134
  import { mkdir, lstat as lstat2, rm } from "node:fs/promises";
54894
55135
  import { dirname as dirname2, join as join2, resolve as resolve3 } from "node:path";
54895
55136
 
54896
- // ../../src/contracts/evidence.ts
54897
- var safeEvidencePath = (path2) => path2.length <= 512 && !path2.includes("\\") && path2.split("/").every(
54898
- (p) => p !== "" && p !== "." && p !== ".." && !/[\x00-\x1f\x7f]/.test(p)
54899
- );
54900
-
54901
55137
  // ../../src/contracts/run-diagnosis.ts
54902
55138
  var DIAGNOSIS_LIMITS = {
54903
55139
  history: 200,
@@ -55263,6 +55499,28 @@ var mcpExample = {
55263
55499
  failureThreshold: 2,
55264
55500
  mcp: { expectTools: ["search"] }
55265
55501
  };
55502
+ var tcpExample = {
55503
+ schemaVersion: 1,
55504
+ name: "Database port",
55505
+ type: "tcp",
55506
+ target: "db.example.com:5432",
55507
+ enabled: false,
55508
+ interval: 1800,
55509
+ timeout: 10,
55510
+ failureThreshold: 2,
55511
+ tcp: { banner: "" }
55512
+ };
55513
+ var dnsExample = {
55514
+ schemaVersion: 1,
55515
+ name: "Mail records",
55516
+ type: "dns",
55517
+ target: "example.com",
55518
+ enabled: false,
55519
+ interval: 1800,
55520
+ timeout: 10,
55521
+ failureThreshold: 2,
55522
+ dns: { recordType: "MX", expected: ["mail.example.com"], match: "includes" }
55523
+ };
55266
55524
  var visualExample = {
55267
55525
  schemaVersion: 1,
55268
55526
  name: "Production / homepage appearance",
@@ -55324,6 +55582,10 @@ async function readManifest(path2, { enable = false } = {}) {
55324
55582
  throw new Error(
55325
55583
  "MCP monitors do not accept scriptFile; use expectTools and toolCall."
55326
55584
  );
55585
+ if (definition.type === "tcp" || definition.type === "dns")
55586
+ throw new Error(
55587
+ "TCP and DNS monitors do not accept scriptFile; use tcp or dns settings."
55588
+ );
55327
55589
  if (definition.type === "visual")
55328
55590
  throw new Error(
55329
55591
  "Visual monitors do not accept scriptFile; use capture settings."
@@ -56175,11 +56437,11 @@ async function localHttpCredential(file2, definition) {
56175
56437
  "VALIDATION_ERROR",
56176
56438
  2
56177
56439
  );
56178
- const matches = parsed.data.credentials.filter(
56440
+ const matches2 = parsed.data.credentials.filter(
56179
56441
  (entry2) => entry2.targetId === definition.httpAuth.targetId && entry2.credentialId === definition.httpAuth.credentialId
56180
56442
  );
56181
- const value2 = matches[0], origin = new URL(definition.target).origin;
56182
- if (matches.length !== 1 || !value2 || value2.credentialRevision !== definition.httpAuth.credentialRevision || value2.origin !== origin || new URL(value2.origin).origin !== value2.origin)
56443
+ const value2 = matches2[0], origin = new URL(definition.target).origin;
56444
+ if (matches2.length !== 1 || !value2 || value2.credentialRevision !== definition.httpAuth.credentialRevision || value2.origin !== origin || new URL(value2.origin).origin !== value2.origin)
56183
56445
  throw new ServiceError(
56184
56446
  "Local HTTP credential ID, revision and canonical origin must match the monitor exactly.",
56185
56447
  "VALIDATION_ERROR",
@@ -56278,8 +56540,10 @@ var import_ipaddr2 = __toESM(require_ipaddr(), 1);
56278
56540
  // ../../src/contracts/plans.ts
56279
56541
  var ACCOUNT_PLANS = Object.freeze({
56280
56542
  starter: Object.freeze({
56281
- monitors: 5,
56282
- // HTTP, certificate and heartbeat checks.
56543
+ // HTTP, certificate and heartbeat checks run on the host and cost close
56544
+ // to nothing; scripts, which cost runner time, stay at one (PRICING.md).
56545
+ monitors: 10,
56546
+ // HTTP, certificate, heartbeat, MCP, TCP and DNS checks.
56283
56547
  checkMinInterval: 1800,
56284
56548
  scriptMonitors: 1,
56285
56549
  scriptMinInterval: 7200,
@@ -56290,7 +56554,10 @@ var ACCOUNT_PLANS = Object.freeze({
56290
56554
  statusPages: 1,
56291
56555
  // Days evidence files and run history are kept (docs/STORAGE.md).
56292
56556
  artifactDays: 7,
56293
- historyDays: 14
56557
+ historyDays: 14,
56558
+ // People in a team workspace on this plan (docs/design/teams.md); a
56559
+ // personal workspace always has one.
56560
+ members: 3
56294
56561
  }),
56295
56562
  // Design partners, assigned by the administrator: the pro limits, unpaid.
56296
56563
  pilot: Object.freeze({
@@ -56302,7 +56569,8 @@ var ACCOUNT_PLANS = Object.freeze({
56302
56569
  agentChecks: 1,
56303
56570
  statusPages: 3,
56304
56571
  artifactDays: 30,
56305
- historyDays: 30
56572
+ historyDays: 30,
56573
+ members: 5
56306
56574
  }),
56307
56575
  // Paid plan (docs/PRICING.md): more monitors checked every 5 minutes and a
56308
56576
  // month of evidence. Scripts may run every 5 minutes; what bounds our cost
@@ -56317,7 +56585,8 @@ var ACCOUNT_PLANS = Object.freeze({
56317
56585
  agentChecks: 1,
56318
56586
  statusPages: 3,
56319
56587
  artifactDays: 30,
56320
- historyDays: 30
56588
+ historyDays: 30,
56589
+ members: 5
56321
56590
  }),
56322
56591
  // Volume for one account (docs/PRICING.md): 1 minute checks and 2,500
56323
56592
  // script runs a day, about 18 USD of runner cost a month when fully used.
@@ -56330,7 +56599,23 @@ var ACCOUNT_PLANS = Object.freeze({
56330
56599
  agentChecks: 5,
56331
56600
  statusPages: 10,
56332
56601
  artifactDays: 30,
56333
- historyDays: 30
56602
+ historyDays: 30,
56603
+ members: 10
56604
+ }),
56605
+ // Team workspaces (docs/design/teams.md): business volume shared by up to
56606
+ // 25 people. Sold only to team workspaces, priced per workspace
56607
+ // (docs/PRICING.md).
56608
+ team: Object.freeze({
56609
+ monitors: 100,
56610
+ checkMinInterval: 60,
56611
+ scriptMonitors: 25,
56612
+ scriptMinInterval: 120,
56613
+ scriptDailyRuns: 2500,
56614
+ agentChecks: 5,
56615
+ statusPages: 10,
56616
+ artifactDays: 30,
56617
+ historyDays: 30,
56618
+ members: 25
56334
56619
  })
56335
56620
  });
56336
56621
  var SCRIPT_MIN_INTERVAL = Math.min(
@@ -56338,7 +56623,8 @@ var SCRIPT_MIN_INTERVAL = Math.min(
56338
56623
  );
56339
56624
  var PRO_PRICES_USD = Object.freeze({ month: 12, year: 120 });
56340
56625
  var BUSINESS_PRICES_USD = Object.freeze({ month: 49, year: 490 });
56341
- var PAID_PLANS = ["pro", "business"];
56626
+ var TEAM_PRICES_USD = Object.freeze({ month: 79, year: 790 });
56627
+ var PAID_PLANS = ["pro", "business", "team"];
56342
56628
  var billingCheckoutSchema = external_exports.object({
56343
56629
  // Checkout defaults to monthly; a running subscription keeps its own
56344
56630
  // interval unless one is given.
@@ -56350,7 +56636,10 @@ var accountPlanSchema = external_exports.enum(
56350
56636
  Object.keys(ACCOUNT_PLANS)
56351
56637
  );
56352
56638
  var accountPlanWriteSchema = external_exports.object({ plan: accountPlanSchema }).strict();
56353
- var accountOwnerSchema = external_exports.string().regex(/^clerk:user_[A-Za-z0-9]{8,64}$/, "Use an owner like clerk:user_ID");
56639
+ var accountOwnerSchema = external_exports.string().regex(
56640
+ /^(clerk:user_[A-Za-z0-9]{8,64}|team:[a-f0-9]{24})$/,
56641
+ "Use an owner like clerk:user_ID or team:ID"
56642
+ );
56354
56643
  var accountSuspensionWriteSchema = external_exports.object({ reason: external_exports.string().trim().min(3).max(200) }).strict();
56355
56644
 
56356
56645
  // ../../src/public-http.ts
@@ -57013,7 +57302,7 @@ async function localScenarioRuntimeSource() {
57013
57302
  // src/local.ts
57014
57303
  import { createRequire } from "node:module";
57015
57304
  import { randomUUID as randomUUID4, createHash as createHash8 } from "node:crypto";
57016
- import { performance as performance6 } from "node:perf_hooks";
57305
+ import { performance as performance7 } from "node:perf_hooks";
57017
57306
  import {
57018
57307
  mkdir as mkdir4,
57019
57308
  lstat as lstat7,
@@ -57566,9 +57855,9 @@ async function singleCheck(monitor, parentSignal, options = {}) {
57566
57855
  "AI_ENDPOINT_CONFIGURATION_ERROR"
57567
57856
  );
57568
57857
  }
57569
- const config2 = parsed.data, report = initialReport(config2), deadline = AbortSignal.timeout(
57858
+ const config2 = parsed.data, report = initialReport(config2), deadline2 = AbortSignal.timeout(
57570
57859
  Math.max(1, Math.ceil(monitor.timeout * 1e3))
57571
- ), signal = parentSignal ? AbortSignal.any([parentSignal, deadline]) : deadline;
57860
+ ), signal = parentSignal ? AbortSignal.any([parentSignal, deadline2]) : deadline2;
57572
57861
  const fail2 = (reason2) => {
57573
57862
  report.transport.status = "error";
57574
57863
  report.transport.reason = reason2;
@@ -57682,7 +57971,7 @@ async function singleCheck(monitor, parentSignal, options = {}) {
57682
57971
  await response?.body?.cancel().catch(() => {
57683
57972
  });
57684
57973
  return fail2(
57685
- parentSignal?.aborted ? "CANCELLED" : deadline.aborted ? "TIMEOUT" : "REQUEST_FAILED"
57974
+ parentSignal?.aborted ? "CANCELLED" : deadline2.aborted ? "TIMEOUT" : "REQUEST_FAILED"
57686
57975
  );
57687
57976
  }
57688
57977
  }
@@ -57700,10 +57989,10 @@ async function aiEndpointCheck(monitor, parentSignal, options = {}) {
57700
57989
  }
57701
57990
  async function suiteCheck(monitor, config2, parentSignal, options) {
57702
57991
  const end = performance.now() + monitor.timeout * 1e3;
57703
- const deadline = AbortSignal.timeout(
57992
+ const deadline2 = AbortSignal.timeout(
57704
57993
  Math.max(1, Math.ceil(monitor.timeout * 1e3))
57705
57994
  );
57706
- const signal = parentSignal ? AbortSignal.any([parentSignal, deadline]) : deadline;
57995
+ const signal = parentSignal ? AbortSignal.any([parentSignal, deadline2]) : deadline2;
57707
57996
  const secrets = httpCredentialRedactions(options.httpCredential);
57708
57997
  const graded = config2.adapter === "json-http-graded-suite-v1";
57709
57998
  const report = {
@@ -57778,7 +58067,7 @@ async function suiteCheck(monitor, config2, parentSignal, options) {
57778
58067
  diagnostic.transport.status = "error";
57779
58068
  diagnostic.transport.reason = parentSignal?.aborted ? "CANCELLED" : "TIMEOUT";
57780
58069
  }
57781
- if (outcome.status === "error" && !parentSignal?.aborted && deadline.aborted && diagnostic.transport.reason === "CANCELLED")
58070
+ if (outcome.status === "error" && !parentSignal?.aborted && deadline2.aborted && diagnostic.transport.reason === "CANCELLED")
57782
58071
  diagnostic.transport.reason = "TIMEOUT";
57783
58072
  if (graded && "rubric" in item && item.rubric) {
57784
58073
  const grading = outcome.status === "failed" ? {
@@ -58039,7 +58328,7 @@ import { performance as performance4 } from "node:perf_hooks";
58039
58328
  // package.json
58040
58329
  var package_default = {
58041
58330
  name: "@waitcher/cli",
58042
- version: "0.2.25",
58331
+ version: "0.2.27",
58043
58332
  description: "Synthetic monitoring from your repository: deploy HTTP, certificate, heartbeat, API, browser and visual monitors from waitcher.json.",
58044
58333
  license: "SEE LICENSE IN LICENSE.txt",
58045
58334
  author: "S\u0142awomir Radzymi\u0144ski",
@@ -58224,8 +58513,8 @@ async function mcpCheck(monitor, parentSignal, options = {}) {
58224
58513
  return finish("error", "INVALID_TARGET", MESSAGES.INVALID_TARGET);
58225
58514
  }
58226
58515
  }
58227
- const deadline = AbortSignal.timeout(Math.ceil(monitor.timeout * 1e3));
58228
- const signal = parentSignal ? AbortSignal.any([parentSignal, deadline]) : deadline;
58516
+ const deadline2 = AbortSignal.timeout(Math.ceil(monitor.timeout * 1e3));
58517
+ const signal = parentSignal ? AbortSignal.any([parentSignal, deadline2]) : deadline2;
58229
58518
  const secrets = httpCredentialRedactions(options.httpCredential);
58230
58519
  const fetcher = options.fetch ?? ((url3, init) => publicFetch(url3, init));
58231
58520
  let session = null, protocol = null, nextId = 1;
@@ -58265,7 +58554,7 @@ async function mcpCheck(monitor, parentSignal, options = {}) {
58265
58554
  });
58266
58555
  } catch (cause) {
58267
58556
  if (cause instanceof Stop) throw cause;
58268
- throw new Stop(deadline.aborted ? "TIMEOUT" : "TRANSPORT_ERROR");
58557
+ throw new Stop(deadline2.aborted ? "TIMEOUT" : "TRANSPORT_ERROR");
58269
58558
  }
58270
58559
  step.httpStatus = response.status;
58271
58560
  if (response.status >= 300 && response.status < 400) {
@@ -58318,7 +58607,7 @@ async function mcpCheck(monitor, parentSignal, options = {}) {
58318
58607
  } catch (cause) {
58319
58608
  if (cause instanceof Stop) throw cause;
58320
58609
  throw new Stop(
58321
- deadline.aborted ? "TIMEOUT" : cause instanceof Error && cause.name === "AbortError" ? "TIMEOUT" : "TRANSPORT_ERROR"
58610
+ deadline2.aborted ? "TIMEOUT" : cause instanceof Error && cause.name === "AbortError" ? "TIMEOUT" : "TRANSPORT_ERROR"
58322
58611
  );
58323
58612
  } finally {
58324
58613
  step.durationMs = Math.max(0, Math.round(performance4.now() - started));
@@ -58419,11 +58708,270 @@ async function mcpCheck(monitor, parentSignal, options = {}) {
58419
58708
  }
58420
58709
  }
58421
58710
 
58711
+ // ../../src/checks/network.ts
58712
+ import { lookup as systemLookup } from "node:dns/promises";
58713
+ import { Resolver } from "node:dns/promises";
58714
+ import { connect as netConnect, isIP as isIP2 } from "node:net";
58715
+ import { performance as performance5 } from "node:perf_hooks";
58716
+ var configuredResolvers = () => (process.env.WAITCHER_DNS_SERVERS ?? "1.1.1.1,8.8.8.8").split(",").map((s) => s.trim()).filter(Boolean);
58717
+ var tcpTransport = {
58718
+ lookup: (host, options) => systemLookup(host, options),
58719
+ connect: (options) => netConnect(options)
58720
+ };
58721
+ var publicDns = (servers = configuredResolvers()) => ({
58722
+ servers,
58723
+ async resolve(name5, type, signal) {
58724
+ const resolver = new Resolver({ timeout: 4e3, tries: 2 });
58725
+ resolver.setServers(servers);
58726
+ const cancel = () => resolver.cancel();
58727
+ signal.addEventListener("abort", cancel, { once: true });
58728
+ try {
58729
+ if (type === "MX")
58730
+ return (await resolver.resolveMx(name5)).map(
58731
+ (r) => `${r.priority} ${r.exchange}`
58732
+ );
58733
+ if (type === "TXT")
58734
+ return (await resolver.resolveTxt(name5)).map((chunks) => chunks.join(""));
58735
+ if (type === "CNAME") return await resolver.resolveCname(name5);
58736
+ if (type === "AAAA") return await resolver.resolve6(name5);
58737
+ return await resolver.resolve4(name5);
58738
+ } finally {
58739
+ signal.removeEventListener("abort", cancel);
58740
+ }
58741
+ }
58742
+ });
58743
+ var short = (value2, max = 300) => value2.replace(/[\x00-\x08\x0b-\x1f\x7f]/g, "\xB7").slice(0, max);
58744
+ var deadline = (monitor, parent) => AbortSignal.any([
58745
+ AbortSignal.timeout(
58746
+ Math.min(monitor.timeout, NETWORK_LIMITS.maxTimeoutSeconds) * 1e3
58747
+ ),
58748
+ ...parent ? [parent] : []
58749
+ ]);
58750
+ function race(work, signal, message) {
58751
+ return new Promise((resolve18, reject) => {
58752
+ const abort = () => reject(new Error(message));
58753
+ if (signal.aborted) return abort();
58754
+ signal.addEventListener("abort", abort, { once: true });
58755
+ work.then(resolve18, reject).finally(
58756
+ () => signal.removeEventListener("abort", abort)
58757
+ );
58758
+ });
58759
+ }
58760
+ async function tcpCheck(monitor, parent, io = tcpTransport, sink = {}) {
58761
+ const signal = deadline(monitor, parent);
58762
+ const target = parseTcpTarget(monitor.target);
58763
+ const expected = monitor.tcp?.banner ?? "";
58764
+ const trace = {
58765
+ protocol: "tcp",
58766
+ host: short(target?.host ?? monitor.target, 253),
58767
+ port: target?.port ?? null,
58768
+ recordType: null,
58769
+ resolver: null,
58770
+ address: null,
58771
+ answers: [],
58772
+ banner: null,
58773
+ timings: { dns: null, connect: null, banner: null },
58774
+ error: null
58775
+ };
58776
+ sink.trace = trace;
58777
+ const fail2 = (status2, message, logs) => {
58778
+ trace.error = short(message);
58779
+ return { status: status2, message, logs };
58780
+ };
58781
+ if (!target)
58782
+ return fail2("error", "TCP target is invalid", "Use HOST:PORT.");
58783
+ let addresses;
58784
+ const started = performance5.now();
58785
+ if (isIP2(target.host)) addresses = [{ address: target.host, family: isIP2(target.host) }];
58786
+ else {
58787
+ try {
58788
+ addresses = await race(
58789
+ io.lookup(target.host, { all: true, verbatim: true }),
58790
+ signal,
58791
+ "TCP check cancelled or timed out"
58792
+ );
58793
+ } catch (cause) {
58794
+ const code = cause.code;
58795
+ return fail2(
58796
+ signal.aborted ? "error" : "failed",
58797
+ signal.aborted ? "TCP check timed out while resolving the host" : `Host ${target.host} did not resolve${code ? ` (${code})` : ""}`,
58798
+ "No connection was attempted."
58799
+ );
58800
+ }
58801
+ trace.timings.dns = Math.round(performance5.now() - started);
58802
+ }
58803
+ trace.answers = addresses.slice(0, NETWORK_LIMITS.answers).map((a) => a.address);
58804
+ if (!addresses.length || addresses.length > NETWORK_LIMITS.answers || addresses.some((a) => !isPublicAddress(a.address)))
58805
+ return fail2(
58806
+ "error",
58807
+ "TCP destination is blocked",
58808
+ "All resolved addresses must be public; private, loopback, link-local and reserved destinations are blocked."
58809
+ );
58810
+ const address = addresses[0].address;
58811
+ trace.address = address;
58812
+ const connectStarted = performance5.now();
58813
+ return await new Promise((resolve18) => {
58814
+ let done = false;
58815
+ const chunks = [];
58816
+ let bytes2 = 0;
58817
+ let connectedAt = 0;
58818
+ const socket = io.connect({ host: address, port: target.port });
58819
+ const finish = (result2) => {
58820
+ if (done) return;
58821
+ done = true;
58822
+ signal.removeEventListener("abort", abort);
58823
+ socket.destroy();
58824
+ if (bytes2)
58825
+ trace.banner = short(Buffer.concat(chunks).toString("utf8").trim());
58826
+ resolve18(result2);
58827
+ };
58828
+ const abort = () => finish(
58829
+ connectedAt ? fail2(
58830
+ "failed",
58831
+ `Connected, but the server did not send "${short(expected, 80)}" in time`,
58832
+ `Connected to ${address}:${target.port}; ${bytes2} bytes received before the deadline.`
58833
+ ) : fail2(
58834
+ "failed",
58835
+ `Connection to ${target.host}:${target.port} timed out`,
58836
+ `No TCP handshake with ${address}:${target.port} before the deadline.`
58837
+ )
58838
+ );
58839
+ if (signal.aborted) return abort();
58840
+ signal.addEventListener("abort", abort, { once: true });
58841
+ socket.once("connect", () => {
58842
+ connectedAt = performance5.now();
58843
+ trace.timings.connect = Math.round(connectedAt - connectStarted);
58844
+ if (!expected)
58845
+ finish({
58846
+ status: "passed",
58847
+ message: `Connected to ${target.host}:${target.port}`,
58848
+ logs: `TCP handshake with ${address}:${target.port} in ${trace.timings.connect} ms. No data was sent.`
58849
+ });
58850
+ });
58851
+ socket.on("data", (chunk) => {
58852
+ chunks.push(chunk);
58853
+ bytes2 += chunk.length;
58854
+ const text4 = Buffer.concat(chunks).toString("utf8");
58855
+ if (text4.includes(expected)) {
58856
+ trace.timings.banner = Math.round(performance5.now() - connectedAt);
58857
+ finish({
58858
+ status: "passed",
58859
+ message: `Connected to ${target.host}:${target.port}; banner matched`,
58860
+ logs: `TCP handshake with ${address}:${target.port}; the server sent the expected banner. No data was sent.`
58861
+ });
58862
+ } else if (bytes2 >= NETWORK_LIMITS.bannerBytes)
58863
+ finish(
58864
+ fail2(
58865
+ "failed",
58866
+ `Banner does not contain "${short(expected, 80)}"`,
58867
+ `Read ${bytes2} bytes from ${address}:${target.port} without the expected text.`
58868
+ )
58869
+ );
58870
+ });
58871
+ socket.once(
58872
+ "end",
58873
+ () => finish(
58874
+ fail2(
58875
+ "failed",
58876
+ `Server closed the connection without sending "${short(expected, 80)}"`,
58877
+ `Connected to ${address}:${target.port}; ${bytes2} bytes received before close.`
58878
+ )
58879
+ )
58880
+ );
58881
+ socket.once(
58882
+ "error",
58883
+ (error62) => finish(
58884
+ fail2(
58885
+ "failed",
58886
+ error62.code === "ECONNREFUSED" ? `Connection to ${target.host}:${target.port} was refused` : `Connection to ${target.host}:${target.port} failed${error62.code ? ` (${error62.code})` : ""}`,
58887
+ `TCP connect to ${address}:${target.port} failed.`
58888
+ )
58889
+ )
58890
+ );
58891
+ });
58892
+ }
58893
+ var normal = (type, value2) => {
58894
+ const v = value2.trim();
58895
+ if (type === "TXT") return v;
58896
+ if (type === "AAAA" && isIP2(v) === 6)
58897
+ return v.toLowerCase().replace(/(^|:)0+(?=[0-9a-f])/g, "$1");
58898
+ return v.toLowerCase().replace(/\.$/, "").replace(/\s+/g, " ");
58899
+ };
58900
+ var matches = (type, answer, expected) => answer === expected || type === "MX" && answer.split(" ").slice(1).join(" ") === expected;
58901
+ async function dnsCheck(monitor, parent, io = publicDns(), sink = {}) {
58902
+ const signal = deadline(monitor, parent);
58903
+ const config2 = monitor.dns;
58904
+ const name5 = monitor.target.replace(/\.$/, "");
58905
+ const type = config2?.recordType ?? "A";
58906
+ const trace = {
58907
+ protocol: "dns",
58908
+ host: short(name5, 253),
58909
+ port: null,
58910
+ recordType: type,
58911
+ resolver: short(io.servers.join(", "), 100) || null,
58912
+ address: null,
58913
+ answers: [],
58914
+ banner: null,
58915
+ timings: { dns: null, connect: null, banner: null },
58916
+ error: null
58917
+ };
58918
+ sink.trace = trace;
58919
+ const result2 = (status2, message, logs2) => {
58920
+ if (status2 !== "passed") trace.error = short(message);
58921
+ return { status: status2, message, logs: logs2 };
58922
+ };
58923
+ if (!config2 || !publicDnsName(name5))
58924
+ return result2("error", "DNS target is invalid", "Use a public DNS name.");
58925
+ const started = performance5.now();
58926
+ let answers;
58927
+ try {
58928
+ answers = await race(
58929
+ io.resolve(name5, type, signal),
58930
+ signal,
58931
+ "DNS check cancelled or timed out"
58932
+ );
58933
+ } catch (cause) {
58934
+ trace.timings.dns = Math.round(performance5.now() - started);
58935
+ const code = cause.code ?? "";
58936
+ if (code === "ENOTFOUND" || code === "ENODATA")
58937
+ return result2(
58938
+ "failed",
58939
+ code === "ENOTFOUND" ? `${name5} does not exist (NXDOMAIN)` : `${name5} has no ${type} record`,
58940
+ `Asked ${trace.resolver} for ${type} ${name5}.`
58941
+ );
58942
+ return result2(
58943
+ "error",
58944
+ signal.aborted ? "DNS check cancelled or timed out" : `DNS resolution failed${code ? ` (${code})` : ""}`,
58945
+ `Asked ${trace.resolver} for ${type} ${name5}; no answer was evaluated.`
58946
+ );
58947
+ }
58948
+ trace.timings.dns = Math.round(performance5.now() - started);
58949
+ const got = answers.map((a) => normal(type, a));
58950
+ trace.answers = answers.slice(0, NETWORK_LIMITS.answers).map((a) => short(a));
58951
+ const want = config2.expected.map((e) => normal(type, e));
58952
+ const logs = `Asked ${trace.resolver} for ${type} ${name5}.
58953
+ Answer: ${trace.answers.join(" | ") || "(none)"}`;
58954
+ if (!got.length) return result2("failed", `${name5} has no ${type} record`, logs);
58955
+ const missing = want.filter((w) => !got.some((g) => matches(type, g, w)));
58956
+ const extra = config2.match === "exact" ? got.filter((g) => !want.some((w) => matches(type, g, w))) : [];
58957
+ if (missing.length || extra.length)
58958
+ return result2(
58959
+ "failed",
58960
+ missing.length ? `${type} ${name5} is missing ${missing.map((m) => short(m, 80)).join(", ")}` : `${type} ${name5} has unexpected ${extra.map((m) => short(m, 80)).join(", ")}`,
58961
+ logs
58962
+ );
58963
+ return result2(
58964
+ "passed",
58965
+ want.length ? `${type} ${name5} holds the expected value${want.length === 1 ? "" : "s"}` : `${type} ${name5} resolved to ${answers.length} record${answers.length === 1 ? "" : "s"}`,
58966
+ logs
58967
+ );
58968
+ }
58969
+
58422
58970
  // ../../src/runner.ts
58423
58971
  init_limits();
58424
58972
  import { mkdir as mkdir3, writeFile as writeFile3 } from "node:fs/promises";
58425
58973
  import { join as join6 } from "node:path";
58426
- import { performance as performance5 } from "node:perf_hooks";
58974
+ import { performance as performance6 } from "node:perf_hooks";
58427
58975
 
58428
58976
  // ../../src/checks/product-evidence.ts
58429
58977
  import { constants as constants8 } from "node:fs";
@@ -59243,13 +59791,13 @@ async function scriptCheck(m, dir, signal, options = {}) {
59243
59791
  mode: 384,
59244
59792
  flag: "wx"
59245
59793
  });
59246
- const deadline = Math.min(
59794
+ const deadline2 = Math.min(
59247
59795
  identity.expiresAt,
59248
59796
  ...identity.storageState.cookies.filter((cookie) => cookie.expires > 0).map((cookie) => cookie.expires * 1e3)
59249
59797
  );
59250
59798
  const identitySignal = AbortSignal.any([
59251
59799
  ...signal ? [signal] : [],
59252
- AbortSignal.timeout(Math.max(1, Math.ceil(deadline - Date.now())))
59800
+ AbortSignal.timeout(Math.max(1, Math.ceil(deadline2 - Date.now())))
59253
59801
  ]);
59254
59802
  const result2 = await scriptCheckInternal(m, dir, identitySignal, {
59255
59803
  ...options,
@@ -59291,10 +59839,11 @@ async function execute(monitor, runDir, {
59291
59839
  snapshots,
59292
59840
  onMcpToolResult
59293
59841
  } = {}) {
59294
- const start = performance5.now();
59842
+ const start = performance6.now();
59295
59843
  let result2;
59296
59844
  const exchanges = [];
59297
59845
  const certificate = {};
59846
+ const network = {};
59298
59847
  try {
59299
59848
  signal?.throwIfAborted();
59300
59849
  if (Boolean(monitor.browserIdentity) !== Boolean(browserIdentity) || browserIdentity && monitor.type !== "browser")
@@ -59332,6 +59881,10 @@ async function execute(monitor, runDir, {
59332
59881
  });
59333
59882
  else if (monitor.type === "certificate")
59334
59883
  result2 = await certificateCheck(monitor, signal, void 0, certificate);
59884
+ else if (monitor.type === "tcp")
59885
+ result2 = await tcpCheck(monitor, signal, void 0, network);
59886
+ else if (monitor.type === "dns")
59887
+ result2 = await dnsCheck(monitor, signal, void 0, network);
59335
59888
  else if (monitor.type === "ping") {
59336
59889
  const p = await child(
59337
59890
  "ping",
@@ -59389,9 +59942,9 @@ async function execute(monitor, runDir, {
59389
59942
  schemaVersion: 1,
59390
59943
  kind: "certificate",
59391
59944
  certificate: certificate.trace
59392
- } : null;
59945
+ } : network.trace ? { schemaVersion: 1, kind: "network", network: network.trace } : null;
59393
59946
  if (trace) result2 = await withTrace(result2, runDir, trace);
59394
- return { ...result2, duration: Math.round(performance5.now() - start) };
59947
+ return { ...result2, duration: Math.round(performance6.now() - start) };
59395
59948
  }
59396
59949
  async function withTrace(result2, runDir, trace) {
59397
59950
  try {
@@ -59447,7 +60000,7 @@ var entries = {
59447
60000
  TYPE_NOT_SUPPORTED: {
59448
60001
  title: "Monitor type cannot be deployed",
59449
60002
  meaning: "AI monitors are not part of waitcher.json yet.",
59450
- fix: "Deploys accept http, certificate, heartbeat, api, browser, visual and mcp monitors. Keep AI checks on monitor apply for now."
60003
+ fix: "Deploys accept http, certificate, heartbeat, api, browser, visual, mcp, tcp and dns monitors. Keep AI checks on monitor apply for now."
59451
60004
  },
59452
60005
  ENTRY_REQUIRED: {
59453
60006
  title: "Script monitor without a test file",
@@ -59774,7 +60327,9 @@ var DEPLOY_TYPES = [
59774
60327
  "heartbeat",
59775
60328
  ...SCRIPT_TYPES,
59776
60329
  "visual",
59777
- "mcp"
60330
+ "mcp",
60331
+ "tcp",
60332
+ "dns"
59778
60333
  ];
59779
60334
  var isScriptType = (type) => SCRIPT_TYPES.includes(type);
59780
60335
  var MONITOR_KEY = /^[a-z0-9][a-z0-9-]{0,62}$/;
@@ -59962,6 +60517,7 @@ function resolveProjectConfig(input2, environment, scripts, httpAuth) {
59962
60517
  if (rest.type === "heartbeat") target = key;
59963
60518
  else if (rest.type === "certificate" && baseUrl)
59964
60519
  target = `${new URL(baseUrl).origin}/`;
60520
+ else if (rest.type === "dns" && baseUrl) target = new URL(baseUrl).hostname;
59965
60521
  else if ((script || rest.type === "visual") && baseUrl) target = baseUrl;
59966
60522
  else
59967
60523
  return fail2("TARGET_REQUIRED", "A target is required", `${at}.target`, key);
@@ -60765,7 +61321,7 @@ async function runLocalRequest(definition, options, project) {
60765
61321
  const info = await lstat7(parent);
60766
61322
  if (!info.isDirectory() || info.isSymbolicLink())
60767
61323
  invalid2("Output must be a regular directory, not a symbolic link.");
60768
- const runId = randomUUID4(), directory = join8(parent, runId), startedAt = Date.now(), start = performance6.now();
61324
+ const runId = randomUUID4(), directory = join8(parent, runId), startedAt = Date.now(), start = performance7.now();
60769
61325
  await mkdir4(directory, { mode: 448 });
60770
61326
  const timeout = options.timeout ?? definition.timeout;
60771
61327
  const signal = AbortSignal.any([
@@ -60829,11 +61385,11 @@ async function runLocalRequest(definition, options, project) {
60829
61385
  }
60830
61386
  const report = join8(
60831
61387
  directory,
60832
- definition.type === "ai" ? "ai-endpoint-report.json" : definition.type === "mcp" ? "mcp-report.json" : "http-report.json"
61388
+ definition.type === "ai" ? "ai-endpoint-report.json" : definition.type === "mcp" ? "mcp-report.json" : ["tcp", "dns"].includes(definition.type) ? "network-report.json" : "http-report.json"
60833
61389
  ), log = join8(directory, "execution.log");
60834
61390
  const reportText = ["ai", "mcp"].includes(definition.type) ? check2.logs : JSON.stringify({
60835
61391
  schemaVersion: 1,
60836
- kind: "http",
61392
+ kind: ["tcp", "dns"].includes(definition.type) ? definition.type : "http",
60837
61393
  status: check2.status,
60838
61394
  message: check2.message,
60839
61395
  duration: check2.duration
@@ -60855,7 +61411,7 @@ async function runLocalRequest(definition, options, project) {
60855
61411
  status: check2.status,
60856
61412
  message: check2.message,
60857
61413
  startedAt,
60858
- duration: Math.round(performance6.now() - start),
61414
+ duration: Math.round(performance7.now() - start),
60859
61415
  directory,
60860
61416
  report,
60861
61417
  summary: null,
@@ -60891,14 +61447,14 @@ async function runLocal(options) {
60891
61447
  "--browser-identities-file applies only to a bound browser manifest."
60892
61448
  );
60893
61449
  const browserIdentity = definition ? await localBrowserIdentity(options.browserIdentitiesFile, definition) : void 0;
60894
- if (definition && ["ai", "http", "mcp"].includes(definition.type)) {
61450
+ if (definition && ["ai", "http", "mcp", "tcp", "dns"].includes(definition.type)) {
60895
61451
  if (["ai", "mcp"].includes(definition.type) && options.timeout !== void 0 && (!Number.isSafeInteger(options.timeout) || options.timeout < 3 || options.timeout > AI_ENDPOINT_LIMITS.maxTimeoutSeconds))
60896
61452
  invalid2(
60897
61453
  `AI endpoint and MCP timeouts must be an integer from 3 to ${AI_ENDPOINT_LIMITS.maxTimeoutSeconds} seconds.`
60898
61454
  );
60899
61455
  if (options.runtime || options.video)
60900
61456
  invalid2(
60901
- "HTTP, AI endpoint and MCP checks need no E2E runtime or video; omit those options."
61457
+ "HTTP, AI endpoint, MCP, TCP and DNS checks need no E2E runtime or video; omit those options."
60902
61458
  );
60903
61459
  if (options.connectionsFile && !endpointJudgeBinding(definition.aiEndpoint))
60904
61460
  invalid2(
@@ -60975,7 +61531,7 @@ async function runLocal(options) {
60975
61531
  }
60976
61532
  const runId = randomUUID4(), directory = join8(parent, runId);
60977
61533
  await mkdir4(directory, { mode: 448 });
60978
- const startedAt = Date.now(), start = performance6.now();
61534
+ const startedAt = Date.now(), start = performance7.now();
60979
61535
  const timeout = options.timeout ?? definition?.timeout ?? 60;
60980
61536
  const evidence = definition ? ".e2e" : "evidence";
60981
61537
  let status2 = "error", logs = "", message = "Local execution did not finish";
@@ -61163,7 +61719,7 @@ async function runLocal(options) {
61163
61719
  status: finalStatus,
61164
61720
  message,
61165
61721
  startedAt,
61166
- duration: Math.round(performance6.now() - start),
61722
+ duration: Math.round(performance7.now() - start),
61167
61723
  directory,
61168
61724
  report: files.some((f) => f.path === `${evidence}/report.json`) ? join8(directory, evidence, "report.json") : null,
61169
61725
  summary: files.some((f) => f.path === `${evidence}/summary.md`) ? join8(directory, evidence, "summary.md") : null,
@@ -62203,10 +62759,10 @@ function deployNextSteps(result2, {
62203
62759
  }
62204
62760
 
62205
62761
  // ../../skills/waitcher/SKILL.md
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";
62762
+ 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, TCP, DNS, 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 or workspaces, raise limits or remove assertions to get a green result.\n- Work in the workspace the user chose. `waitcher auth status` names the active one (personal or a team) and your role; ask before `workspace use`, `--workspace` or any `member` command.\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, `tcp` for a database, mail or SSH port, `dns` for records that must keep their values, `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, team workspaces.\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";
62207
62763
 
62208
62764
  // ../../skills/waitcher/references/authoring.md
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';
62765
+ 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- `tcp`: a public `HOST:PORT` accepts connections (database, mail, SSH); optional `tcp.banner` the server must send first. No script.\n- `dns`: a name\'s `A`, `AAAA`, `CNAME`, `MX` or `TXT` records hold `dns.expected` (`match`: `includes` or `exact`), asked of public resolvers. In `waitcher.json` a `dns` entry without `target` checks the `baseUrl` host. Details: https://waitcher.dev/docs/network.md.\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';
62210
62766
 
62211
62767
  // ../../skills/waitcher/references/ai-and-agents.md
62212
62768
  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";
@@ -62215,10 +62771,10 @@ var ai_and_agents_default = "# AI endpoints, agent outcomes and model steps\n\nR
62215
62771
  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';
62216
62772
 
62217
62773
  // ../../skills/waitcher/references/diagnosis.md
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";
62774
+ var diagnosis_default = '# Diagnosing failures\n\nRead when a local, smoke or scheduled run failed or errored.\n\nFor "since when" or "how often" questions, `waitcher monitor history --id ID` gives 13 months of daily runs, failures, availability and p50/p95 for one monitor, and `waitcher report history` sums the account by month and monitor; individual runs and evidence only go back as far as the plan keeps them.\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';
62219
62775
 
62220
62776
  // ../../skills/waitcher/references/optional-capabilities.md
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';
62777
+ 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## Second-region confirmation\n\nWhen `features.secondRegion` is true, a failing HTTP or certificate check that would open an incident is first repeated once from a Cloudflare region outside Europe ([guide](https://waitcher.dev/docs/results.md#second-region)). A pass there marks the run "Not confirmed" and opens no incident; a failure there marks the incident "Confirmed from 2 regions"; a recheck that cannot answer alerts as usual. `run trace`, `run status` and `incident list` carry it as `secondRegion` (outcome, region, data center, status, time, hops). Checks with `httpAuth`, custom headers, a body or a method other than GET or HEAD are never repeated, and the trace says so; do not remove credentials or headers just to get a recheck. `"secondRegion": false` on a definition or `waitcher.json` entry opts a monitor out; suggest it only when the user wants alerts from the first region alone. A "Not confirmed" run is still a real failure from Europe: mention it when diagnosing, but it is not an outage of the site.\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\n## Team workspaces\n\nWhen `features.teams` is true, the user may belong to team workspaces ([guide](https://waitcher.dev/docs/teams.md)). Monitors, projects, alerts, status pages, tokens, plan, export and deletion belong to the active workspace; `waitcher auth status` shows it (`workspace.id`, `workspace.role`). `waitcher workspace list` lists the user\'s workspaces and invitations; `workspace use --id team:ID` switches for later commands and `--workspace team:ID|personal` acts once. Deploy a repository into the workspace the user names, and never move work between workspaces to get around a limit. A member can change monitors, projects, deploys, alert routing and status pages; a `FORBIDDEN` refusal for credentials, settings, export, billing or members means an owner or admin must do it, so report it. A project token is bound to the team it was created in. `member invite`, `member remove`, `member role`, `workspace leave` and account deletion with a team active affect other people: run them only when the user asked for that exact change.\n';
62222
62778
 
62223
62779
  // ../../skills/waitcher/agents/openai.yaml
62224
62780
  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';
@@ -62645,12 +63201,31 @@ var accountActivityQuerySchema = external_exports.object({
62645
63201
  }).strict();
62646
63202
 
62647
63203
  // ../../src/contracts/alerts.ts
63204
+ var channelKinds = [
63205
+ "account-email",
63206
+ "slack",
63207
+ "webhook",
63208
+ "email",
63209
+ "pagerduty",
63210
+ "discord",
63211
+ "teams",
63212
+ "telegram",
63213
+ "ntfy"
63214
+ ];
63215
+ var regionalKinds = ["pagerduty"];
63216
+ var TELEGRAM_CHAT_ID = /^(-?\d{1,20}|@[A-Za-z][A-Za-z0-9_]{4,31})$/;
62648
63217
  var channelSchema = external_exports.object({
62649
63218
  name: external_exports.string().trim().min(1).max(100),
62650
- kind: external_exports.enum(["account-email", "slack", "webhook", "email"]),
63219
+ kind: external_exports.enum(channelKinds),
62651
63220
  credential: external_exports.string().trim().min(1).max(8192).optional(),
62652
63221
  from: external_exports.string().trim().max(254).default(""),
62653
63222
  to: external_exports.string().trim().max(254).default(""),
63223
+ region: external_exports.enum(["us", "eu"]).optional(),
63224
+ // Telegram only: where the bot posts.
63225
+ chatId: external_exports.string().trim().max(40).optional(),
63226
+ // ntfy only, write-only like the credential: a bearer access token
63227
+ // (tk_...) for a protected topic.
63228
+ accessToken: external_exports.string().trim().min(1).max(200).optional(),
62654
63229
  enabled: external_exports.boolean().default(false),
62655
63230
  expectedRevision: external_exports.number().int().positive().optional()
62656
63231
  }).strict().superRefine((value2, ctx) => {
@@ -62669,6 +63244,39 @@ var channelSchema = external_exports.object({
62669
63244
  path: ["kind"],
62670
63245
  message: value2.kind === "account-email" ? "Account email always goes to your verified sign-in address" : "Email addresses apply only to email channels"
62671
63246
  });
63247
+ if (value2.region && !regionalKinds.includes(value2.kind))
63248
+ ctx.addIssue({
63249
+ code: "custom",
63250
+ path: ["region"],
63251
+ message: "A region applies only to PagerDuty channels"
63252
+ });
63253
+ if (value2.kind === "telegram") {
63254
+ if (value2.chatId !== void 0 && !TELEGRAM_CHAT_ID.test(value2.chatId))
63255
+ ctx.addIssue({
63256
+ code: "custom",
63257
+ path: ["chatId"],
63258
+ message: "Use a numeric chat id such as -1001234567890 or a public channel such as @team_alerts"
63259
+ });
63260
+ } else if (value2.chatId !== void 0)
63261
+ ctx.addIssue({
63262
+ code: "custom",
63263
+ path: ["chatId"],
63264
+ message: "A chat id applies only to Telegram channels"
63265
+ });
63266
+ if (value2.accessToken !== void 0) {
63267
+ if (value2.kind !== "ntfy")
63268
+ ctx.addIssue({
63269
+ code: "custom",
63270
+ path: ["accessToken"],
63271
+ message: "An access token applies only to ntfy channels"
63272
+ });
63273
+ else if (!/^tk_[A-Za-z0-9]{20,64}$/.test(value2.accessToken))
63274
+ ctx.addIssue({
63275
+ code: "custom",
63276
+ path: ["accessToken"],
63277
+ message: "Use an ntfy access token (tk_...)"
63278
+ });
63279
+ }
62672
63280
  if (value2.kind === "account-email" && value2.credential)
62673
63281
  ctx.addIssue({
62674
63282
  code: "custom",
@@ -63012,6 +63620,41 @@ async function forgetSession(server) {
63012
63620
  if (error62.code !== "ENOENT") throw error62;
63013
63621
  }
63014
63622
  }
63623
+ var workspacePath = (server) => sessionPath(server).replace(/\.json$/, ".workspace.json");
63624
+ async function loadWorkspace(server) {
63625
+ try {
63626
+ const value2 = JSON.parse(await readPrivate(workspacePath(server)));
63627
+ return value2?.server === server && typeof value2.workspace === "string" && /^team:[a-f0-9]{24}$/.test(value2.workspace) ? value2.workspace : null;
63628
+ } catch {
63629
+ return null;
63630
+ }
63631
+ }
63632
+ async function saveWorkspace(server, workspace) {
63633
+ const path2 = workspacePath(server);
63634
+ if (!workspace) {
63635
+ await unlink4(path2).catch((error62) => {
63636
+ if (error62.code !== "ENOENT") throw error62;
63637
+ });
63638
+ return;
63639
+ }
63640
+ const directory = dirname16(path2);
63641
+ await mkdir10(directory, { recursive: true, mode: 448 });
63642
+ await privatePath(directory, true);
63643
+ const temp = join15(directory, `.workspace-${randomUUID7()}.tmp`);
63644
+ try {
63645
+ const file2 = await open17(temp, "wx", 384);
63646
+ try {
63647
+ await file2.writeFile(JSON.stringify({ server, workspace }));
63648
+ } finally {
63649
+ await file2.close();
63650
+ }
63651
+ await rename(temp, path2);
63652
+ } finally {
63653
+ await unlink4(temp).catch((error62) => {
63654
+ if (error62.code !== "ENOENT") throw error62;
63655
+ });
63656
+ }
63657
+ }
63015
63658
 
63016
63659
  // src/oauth.ts
63017
63660
  var fail = (message) => new ServiceError(message, "AUTH_REQUIRED", 3);
@@ -63264,13 +63907,35 @@ Authentication
63264
63907
 
63265
63908
  Plans and billing
63266
63909
  account billing Plan, limits and subscription status
63267
- account upgrade [--plan pro|business] [--yearly] [--trial]
63268
- Stripe Checkout URL for a paid plan (default pro; --trial: pro,
63269
- 14 days, once, no card); a subscribed account moves in place
63910
+ account upgrade [--plan pro|business|team] [--yearly] [--trial]
63911
+ Stripe Checkout URL for a paid plan (default pro, or team in a
63912
+ team workspace; --trial: pro, 14 days, once, no card); a
63913
+ subscribed account moves in place
63270
63914
  account billing-portal Stripe portal URL to change payment or cancel
63271
63915
  The plan changes only when Stripe confirms the payment, never on the return page.
63272
63916
  Billing appears when the server reports features.billing.
63273
63917
 
63918
+ Teams (when the server reports features.teams)
63919
+ workspace list Your personal workspace, your teams with your role, and
63920
+ invitations to your verified email
63921
+ workspace create --name NAME Create a team you own (at most 3); it starts on starter
63922
+ workspace use --id TEAM_ID|personal Act in that team from now on, on this server
63923
+ workspace join --id INVITE_ID Accept an invitation (signed in with the invited email)
63924
+ workspace decline --id INVITE_ID Decline an invitation
63925
+ workspace rename --name NAME --expected-revision N
63926
+ workspace leave --yes Leave the active team; the last owner cannot
63927
+ member list Members, roles and pending invitations of the active team
63928
+ member invite --email ADDRESS [--role member|admin|owner]
63929
+ Owners and admins; the email expires in 7 days
63930
+ member cancel-invite --id INVITE_ID
63931
+ member role --member MEMBER_ID --role owner|admin|member Owners only
63932
+ member remove --member MEMBER_ID --yes Revokes the tokens they created in the team
63933
+ --workspace TEAM_ID|personal on any command acts there once. Monitors, projects,
63934
+ alerts, status pages, tokens, plan, export and deletion all follow the active
63935
+ workspace; account deletion with a team active deletes the team (owners only).
63936
+ Members cannot change credentials, settings, billing or members. A token is bound
63937
+ to the workspace it was created in and stops when its creator leaves.
63938
+
63274
63939
  Account data
63275
63940
  account deletion Review current deletion revision and impact
63276
63941
  account deletion-prepare --expected-revision N --output NEW_PRIVATE_RECEIPT
@@ -63310,10 +63975,10 @@ Capabilities
63310
63975
  system capabilities Show account features, limits and contract versions
63311
63976
  system diagnostics Operator resource, queue and storage diagnostics
63312
63977
  system plans Administrator: plan profiles and accounts not on starter
63313
- system plan --owner clerk:USER_ID --plan starter|pilot
63978
+ system plan --owner clerk:USER_ID|team:ID --plan starter|pilot|pro|business|team
63314
63979
  Administrator: assign a plan; takes effect immediately
63315
63980
  system suspensions Administrator: accounts whose checks are suspended
63316
- system suspend --owner clerk:USER_ID --reason TEXT
63981
+ system suspend --owner clerk:USER_ID|team:ID --reason TEXT
63317
63982
  Administrator: stop every check of one account; data stays
63318
63983
  system unsuspend --owner clerk:USER_ID Administrator: lift a suspension
63319
63984
 
@@ -63382,14 +64047,14 @@ Repository deploys (waitcher.json)
63382
64047
  Keys identify monitors; renaming a key replaces the monitor and its history.
63383
64048
  The repository owns definitions; the server owns pause and resume. New monitors start
63384
64049
  paused unless --activate-new. Undeclared monitors are reported and deleted only with --prune.
63385
- Deploys accept http, certificate, heartbeat, api, browser, visual and mcp (first --smoke
64050
+ Deploys accept http, certificate, heartbeat, api, browser, visual, mcp, tcp and dns (first --smoke
63386
64051
  capture: baseline_review, see help visual). Script monitors name an
63387
64052
  entry file; the CLI builds it like monitor build (project needs e2e@${RUNTIME_PINS.e2e},
63388
64053
  @e2e-dev/web@${RUNTIME_PINS["@e2e-dev/web"]} for browser, esbuild@${RUNTIME_PINS.esbuild}). Plans and results list issues with
63389
64054
  code, path, monitor key and hint; ok:false exits 2. --based-on refuses a stale plan.
63390
64055
 
63391
64056
  Monitor configuration
63392
- monitor init --file PATH [--type http|certificate|api|browser|visual|heartbeat|ai|mcp] [--target URL]
64057
+ monitor init --file PATH [--type http|certificate|api|browser|visual|heartbeat|ai|mcp|tcp|dns] [--target URL]
63393
64058
  Write a paused example; never overwrite
63394
64059
  api and browser also write PATH.e2e.ts next to it
63395
64060
  monitor init --template agent-outcome --file PATH [--target API_BASE]
@@ -63416,6 +64081,11 @@ Monitor configuration
63416
64081
  monitor pause --id ID Disable scheduled executions
63417
64082
  monitor resume --id ID Enable scheduled executions
63418
64083
  monitor delete --id ID --yes Permanently remove monitor and history
64084
+ Second region (features.secondRegion): before a failing HTTP or certificate check
64085
+ opens an incident, Waitcher repeats it once from North America or Asia-Pacific; a pass
64086
+ there means no incident. "secondRegion": false in a definition or waitcher.json entry
64087
+ opts a monitor out. Checks with httpAuth, custom headers, a body or a write method are
64088
+ not repeated (https://waitcher.dev/docs/results.md#second-region).
63419
64089
 
63420
64090
  Executions and reports
63421
64091
  run scenarios --id RUN_ID [--json]
@@ -63427,8 +64097,7 @@ Executions and reports
63427
64097
  [--connections-file PRIVATE_JSON] Scoped local AI keys; no login
63428
64098
  run local --project E2E_PROJECT [--output DIR] [--video] [--timeout 60]
63429
64099
  Run trusted local tests without login or API access
63430
- JSON/report/logs/traces; video opt-in, fresh output per run
63431
- Project output must stay inside the E2E project
64100
+ Fresh output per run inside the project; video opt-in
63432
64101
  run start --id MONITOR_ID [--wait [--brief]] [--timeout 60] [--update-baselines]
63433
64102
  A finished run prints status, duration, message and a
63434
64103
  report link (SERVER/app#run/RUN_ID) first;
@@ -63439,11 +64108,14 @@ Executions and reports
63439
64108
  artifact get --id RUN_ID --path PATH --file OUTPUT
63440
64109
  Download checksum-verified evidence; no overwrite
63441
64110
  run status --id RUN_ID
63442
- run trace --id RUN_ID What the run did: HTTP hops and timings,
63443
- certificate chain, e2e steps, app log,
63444
- screenshots and the test's fetch requests
64111
+ run trace --id RUN_ID What the run did: HTTP hops, certificate,
64112
+ TCP/DNS, e2e steps, logs, screenshots,
64113
+ fetch calls, secondRegion
63445
64114
  run wait --id RUN_ID [--timeout 60] [--brief] Bounded wait (1 to 900 seconds)
63446
64115
  report get [--days 1|7|14] [--demo]
64116
+ report history [--file PATH] 13 months of daily availability, p50, p95;
64117
+ --file writes a new CSV
64118
+ monitor history --id ID One monitor's 13 months
63447
64119
  incident list [--demo]
63448
64120
 
63449
64121
  Visual checks and baseline review (features.visual, features.visualReview; decisions
@@ -63501,11 +64173,11 @@ Verified HTTP targets and write-only request credentials (features.httpTargets)
63501
64173
  Basic auth: header Authorization, private value "Basic " + base64(user:password).
63502
64174
  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
64175
  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.
63505
- Challenge output requires a new file in a private directory (700); token never printed.
64176
+ Waitcher mints, caches and refreshes the Bearer token. Hosted runs only.
64177
+ Challenge output needs a new file in a private directory (700); token not printed.
63506
64178
  Publish its proof at /.well-known/waitcher-verification.txt, then verify explicitly.
63507
64179
  Proof expires after 15 minutes; verification lasts 24 hours. Redirects are refused.
63508
- Keys are single-line ASCII values up to 4096 characters, private file (600) or stdin.
64180
+ Keys: one ASCII line up to 4096 characters, private file (600) or stdin.
63509
64181
  Monitor httpAuth contains reference IDs/revision only; keys never appear in export.
63510
64182
  run local --file HTTP_AI_OR_MCP.json --http-credentials-file PRIVATE_MAP
63511
64183
  Local map resolves reference IDs/revision/origin/header to private credentialFile.
@@ -63526,6 +64198,21 @@ MCP server monitoring (remote Streamable HTTP servers)
63526
64198
  stdio servers, OAuth flows, resources and prompts are not checked
63527
64199
  (https://waitcher.dev/docs/mcp.md).
63528
64200
 
64201
+ TCP and DNS monitoring (every account, at the plan's HTTP interval)
64202
+ monitor init --type tcp --file db.json Then set "target":"db.example.com:5432"
64203
+ monitor init --type dns --file mx.json Then set "target":"example.com"
64204
+ Locally without an account: waitcher run local --file db.json
64205
+ "tcp": {"banner":"SSH-2.0"} Optional text the server must send first (1 KB read);
64206
+ empty passes once the connection opens. Waitcher sends nothing.
64207
+ "dns": {"recordType":"A|AAAA|CNAME|MX|TXT","expected":["203.0.113.10"],
64208
+ "match":"includes|exact"} No expected values passes on any answer; MX may
64209
+ name the exchange alone or "10 mail.example.com". Asked of public resolvers.
64210
+ Targets must be public: a TCP host resolves once, every address must be public
64211
+ and the connection goes to the checked address. Timeout at most 15 seconds.
64212
+ NXDOMAIN, a missing record, a refused or timed out connection fail; a resolver
64213
+ that does not answer is an error. In waitcher.json a dns entry without a
64214
+ target checks the environment's baseUrl host (https://waitcher.dev/docs/network.md).
64215
+
63529
64216
  AI product endpoint monitoring (administrator pilot; requires features.aiEndpoints)
63530
64217
  monitor init --type ai --target https://product.example/ai --file ai.json
63531
64218
  monitor validate --file ai.json Offline JSON fixture/assertion/schema validation
@@ -63607,10 +64294,14 @@ Alerts
63607
64294
  alert channel list
63608
64295
  alert channel save --file PATH [--id ID]
63609
64296
  [--credential-file PATH | --credential-stdin]
64297
+ [--access-token-file PATH]
63610
64298
  Kinds: account-email (no credential; Waitcher emails your
63611
64299
  verified sign-in address, up to 50 per day; sign in with
63612
- this CLI version first), slack, webhook, email (your own
63613
- Resend key)
64300
+ this CLI version first), slack, discord, teams (a Teams
64301
+ Workflows URL), pagerduty (Events API v2 integration key),
64302
+ telegram (bot token; JSON "chatId"), ntfy (topic URL;
64303
+ --access-token-file for a protected topic), webhook,
64304
+ email (your own Resend key)
63614
64305
  alert channel delete --id ID --yes
63615
64306
  alert channel test --id ID --yes Sends a real notification; no monitor runs
63616
64307
  alert maintenance list
@@ -63621,9 +64312,14 @@ Alerts
63621
64312
  alert policy delete (--id ID | --project-id ID) --yes Use '*' for default routing
63622
64313
  alert deliveries
63623
64314
  alert attempts --id DELIVERY_ID
63624
- Channel JSON: {"name":"Ops","kind":"slack","enabled":true}; email adds "from" and "to".
63625
- enabled defaults to false and test refuses a disabled channel. The Slack/webhook URL or
63626
- Resend key is the credential: private file or stdin, never JSON. Updates add
64315
+ Channel JSON: {"name":"Ops","kind":"slack","enabled":true}; email adds "from" and "to";
64316
+ pagerduty takes "region":"us"|"eu" (default us); telegram needs "chatId"
64317
+ (-100... or @channel).
64318
+ enabled defaults to false and test refuses a disabled channel. The webhook URL,
64319
+ integration key or Resend key is the credential: private file or stdin, never JSON.
64320
+ PagerDuty opens one alert per incident and resolves it on recovery; its test
64321
+ is a change event that pages nobody. Grafana IRM: use a webhook channel
64322
+ (https://waitcher.dev/docs/alerts.md#grafana-irm). Updates add
63627
64323
  "expectedRevision":N (from channel list); omit the credential to keep it.
63628
64324
  Policy JSON: {"monitorId":"*","channelIds":["CHANNEL_ID"],"events":["incident","recovered"],
63629
64325
  "cooldownSeconds":0,"enabled":true,"expectedRevision":0}. Scope: "*" (account default),
@@ -63636,6 +64332,7 @@ Alerts
63636
64332
  Shared options
63637
64333
  --server URL HTTPS origin, or loopback HTTP for development
63638
64334
  Default: WAITCHER_SERVER or https://waitcher.dev
64335
+ --workspace ID Act in a team (team:...) or personal, for this command only
63639
64336
  --request-key KEY Recover a create, run start or channel test (16 to 100 characters)
63640
64337
  Same account, operation and payload; retained for 24 hours
63641
64338
  --json Structured JSON for run diagnose and run scenarios (others default to JSON)
@@ -63761,14 +64458,14 @@ function helpTopic(topic) {
63761
64458
  const needle = topic.toLowerCase();
63762
64459
  if (needle === "all") return help;
63763
64460
  const word = new RegExp(`\\b${needle.replace(/[^a-z0-9-]/g, "")}\\b`);
63764
- const matches = sections.filter((section) => {
64461
+ const matches2 = sections.filter((section) => {
63765
64462
  if (section === exitCodes) return false;
63766
64463
  const [heading, ...lines] = section.split("\n");
63767
64464
  return word.test(heading.toLowerCase()) || lines.some(
63768
64465
  (line) => /^ {2}[a-z]/.test(line) && line.trimStart().startsWith(`${needle} `)
63769
64466
  );
63770
64467
  });
63771
- return matches.length ? [intro, ...matches, exitCodes].join("\n\n") + "\n" : `No help section matches "${topic}".
64468
+ return matches2.length ? [intro, ...matches2, exitCodes].join("\n\n") + "\n" : `No help section matches "${topic}".
63772
64469
 
63773
64470
  ${overview()}`;
63774
64471
  }
@@ -63958,6 +64655,9 @@ async function main() {
63958
64655
  "environment-id": { type: "string" },
63959
64656
  before: { type: "string" },
63960
64657
  server: { type: "string" },
64658
+ workspace: { type: "string" },
64659
+ member: { type: "string" },
64660
+ email: { type: "string" },
63961
64661
  id: { type: "string" },
63962
64662
  file: { type: "string" },
63963
64663
  template: { type: "string" },
@@ -63967,6 +64667,7 @@ async function main() {
63967
64667
  "token-file": { type: "string" },
63968
64668
  "token-stdin": { type: "boolean" },
63969
64669
  "credential-file": { type: "string" },
64670
+ "access-token-file": { type: "string" },
63970
64671
  "connections-file": { type: "string" },
63971
64672
  "credential-stdin": { type: "boolean" },
63972
64673
  enable: { type: "boolean" },
@@ -64029,6 +64730,18 @@ async function main() {
64029
64730
  );
64030
64731
  const command = p.join(" ");
64031
64732
  const commands2 = {
64733
+ "workspace list": [],
64734
+ "workspace use": ["id"],
64735
+ "workspace create": ["name"],
64736
+ "workspace rename": ["name", "expected-revision"],
64737
+ "workspace join": ["id"],
64738
+ "workspace decline": ["id"],
64739
+ "workspace leave": ["yes"],
64740
+ "member list": [],
64741
+ "member invite": ["email", "role"],
64742
+ "member cancel-invite": ["id"],
64743
+ "member role": ["member", "role"],
64744
+ "member remove": ["member", "yes"],
64032
64745
  "identity list": [],
64033
64746
  "identity get": ["id"],
64034
64747
  "identity create": ["file", "state-file"],
@@ -64235,6 +64948,8 @@ async function main() {
64235
64948
  "run trace": ["id"],
64236
64949
  "run wait": ["id", "timeout", "brief"],
64237
64950
  "report get": ["days", "demo"],
64951
+ "report history": ["file"],
64952
+ "monitor history": ["id"],
64238
64953
  "incident list": ["demo"],
64239
64954
  "incident update": ["id", "kind", "message"],
64240
64955
  "incident open": [
@@ -64268,6 +64983,7 @@ async function main() {
64268
64983
  "id",
64269
64984
  "credential-file",
64270
64985
  "credential-stdin",
64986
+ "access-token-file",
64271
64987
  "request-key"
64272
64988
  ],
64273
64989
  "alert channel delete": ["id", "yes"],
@@ -64283,7 +64999,7 @@ async function main() {
64283
64999
  };
64284
65000
  if (!commands2[command]) usage2("Unknown command. Run waitcher --help.");
64285
65001
  for (const option of Object.keys(v))
64286
- if (!["server", "json"].includes(option) && !commands2[command].includes(option))
65002
+ if (!["server", "json", "workspace"].includes(option) && !commands2[command].includes(option))
64287
65003
  usage2(`--${option} does not apply to ${command}.`);
64288
65004
  if (v["request-key"] && (v.id && [
64289
65005
  "monitor apply",
@@ -64609,10 +65325,12 @@ async function main() {
64609
65325
  "visual",
64610
65326
  "heartbeat",
64611
65327
  "ai",
64612
- "mcp"
65328
+ "mcp",
65329
+ "tcp",
65330
+ "dns"
64613
65331
  ].includes(v.type))
64614
65332
  usage2(
64615
- "monitor init supports --type http, certificate, api, browser, visual, heartbeat, ai or mcp."
65333
+ "monitor init supports --type http, certificate, api, browser, visual, heartbeat, ai, mcp, tcp or dns."
64616
65334
  );
64617
65335
  let protectedInitial;
64618
65336
  if (v.template === "protected-agent-outcome") {
@@ -64636,7 +65354,7 @@ async function main() {
64636
65354
  usage2(
64637
65355
  "These request policy/context options require --template protected-agent-outcome."
64638
65356
  );
64639
- const initial = protectedInitial ?? (v.template === "agent-outcome" ? agentOutcomeExample : v.type === "ai" ? aiEndpointExample : v.type === "mcp" ? mcpExample : v.type === "heartbeat" ? {
65357
+ const initial = protectedInitial ?? (v.template === "agent-outcome" ? agentOutcomeExample : v.type === "ai" ? aiEndpointExample : v.type === "mcp" ? mcpExample : v.type === "tcp" ? tcpExample : v.type === "dns" ? dnsExample : v.type === "heartbeat" ? {
64640
65358
  schemaVersion: 1,
64641
65359
  name: "Scheduled job",
64642
65360
  type: "heartbeat",
@@ -64646,7 +65364,7 @@ async function main() {
64646
65364
  failureThreshold: 2,
64647
65365
  heartbeat: { graceSeconds: 60, completionSeconds: 300 }
64648
65366
  } : v.type === "visual" ? visualExample : v.type === "certificate" ? certificateExample : example);
64649
- if (v.target && v.type !== "heartbeat") {
65367
+ if (v.target && !["heartbeat", "tcp", "dns"].includes(v.type ?? "")) {
64650
65368
  try {
64651
65369
  const target = new URL(v.target);
64652
65370
  if (!["https:", "http:"].includes(target.protocol) || target.username || target.password)
@@ -64873,6 +65591,12 @@ async function main() {
64873
65591
  };
64874
65592
  } else {
64875
65593
  const session = await authenticatedSession(server);
65594
+ const teamId = /^team:[a-f0-9]{24}$/;
65595
+ if (v.workspace !== void 0 && v.workspace !== "personal" && !teamId.test(v.workspace))
65596
+ usage2("--workspace takes a team ID (team:...) or personal.");
65597
+ useWorkspace(
65598
+ v.workspace === "personal" ? void 0 : v.workspace ?? (session.kind === "automation" || command === "workspace use" ? void 0 : await loadWorkspace(server) ?? void 0)
65599
+ );
64876
65600
  const api = async (path2, options = {}) => (await request(server, path2, {
64877
65601
  cookie: session.cookie,
64878
65602
  accessToken: session.accessToken,
@@ -64880,7 +65604,120 @@ async function main() {
64880
65604
  ...options,
64881
65605
  ...options.method === "POST" ? { idempotencyKey: v["request-key"] } : {}
64882
65606
  })).data;
64883
- if (command.startsWith("identity ")) {
65607
+ if (command.startsWith("workspace ") || command.startsWith("member ")) {
65608
+ const member = (value2) => {
65609
+ if (typeof value2 !== "string" || !/^(admin|clerk:user_[A-Za-z0-9]{8,64})$/.test(value2))
65610
+ usage2("Provide --member with a member ID from member list.");
65611
+ return encodeURIComponent(value2);
65612
+ };
65613
+ const role = () => {
65614
+ if (v.role !== void 0 && !["owner", "admin", "member"].includes(v.role))
65615
+ usage2("--role must be owner, admin or member.");
65616
+ return v.role;
65617
+ };
65618
+ if (command === "workspace list") {
65619
+ const data = await api("workspaces");
65620
+ const saved = await loadWorkspace(server);
65621
+ result2 = {
65622
+ ...data,
65623
+ selected: saved ?? data.workspaces[0]?.id ?? null
65624
+ };
65625
+ } else if (command === "workspace use") {
65626
+ if (typeof v.id !== "string")
65627
+ usage2("Provide --id with a team ID from workspace list, or personal.");
65628
+ if (v.id === "personal") {
65629
+ await saveWorkspace(server, null);
65630
+ result2 = { event: "workspace_selected", workspace: "personal" };
65631
+ } else {
65632
+ if (!teamId.test(v.id))
65633
+ usage2("Provide --id with a team ID from workspace list, or personal.");
65634
+ if (session.kind === "automation")
65635
+ usage2("An automation token is bound to its own workspace.");
65636
+ const data = await api("workspaces");
65637
+ const found = data.workspaces.find(
65638
+ (w) => w.id === v.id
65639
+ );
65640
+ if (!found)
65641
+ throw new ServiceError(
65642
+ "You are not a member of that workspace.",
65643
+ "WORKSPACE_NOT_FOUND",
65644
+ 4
65645
+ );
65646
+ await saveWorkspace(server, v.id);
65647
+ result2 = { event: "workspace_selected", workspace: found };
65648
+ }
65649
+ } else if (command === "workspace create") {
65650
+ if (!v.name) usage2("Provide --name for the team.");
65651
+ const created = await api("workspaces", {
65652
+ method: "POST",
65653
+ body: { name: v.name }
65654
+ });
65655
+ result2 = {
65656
+ event: "workspace_created",
65657
+ workspace: created,
65658
+ next: [`waitcher workspace use --id ${created.id}`]
65659
+ };
65660
+ } else if (command === "workspace rename") {
65661
+ if (!v.name) usage2("Provide --name for the team.");
65662
+ result2 = await api("workspaces/current", {
65663
+ method: "PUT",
65664
+ body: {
65665
+ name: v.name,
65666
+ expectedRevision: integer2(
65667
+ v["expected-revision"],
65668
+ "expected-revision",
65669
+ 1,
65670
+ Number.MAX_SAFE_INTEGER
65671
+ )
65672
+ }
65673
+ });
65674
+ } else if (command === "workspace join" || command === "workspace decline") {
65675
+ if (typeof v.id !== "string" || !/^[a-f0-9-]{36}$/.test(v.id))
65676
+ usage2("Provide --id with an invitation ID from workspace list.");
65677
+ result2 = await api(
65678
+ `workspaces/invites/${v.id}/${command === "workspace join" ? "accept" : "decline"}`,
65679
+ { method: "POST", body: {} }
65680
+ );
65681
+ if (command === "workspace join")
65682
+ result2 = {
65683
+ event: "workspace_joined",
65684
+ workspace: result2,
65685
+ next: [`waitcher workspace use --id ${result2.id}`]
65686
+ };
65687
+ } else if (command === "workspace leave") {
65688
+ if (!v.yes) usage2("Pass --yes to leave the active team.");
65689
+ const me = (await api("workspaces")).workspaces[0].id;
65690
+ result2 = await api(`workspaces/current/members/${member(me)}`, {
65691
+ method: "DELETE"
65692
+ });
65693
+ await saveWorkspace(server, null);
65694
+ } else if (command === "member list")
65695
+ result2 = await api("workspaces/current/members");
65696
+ else if (command === "member invite") {
65697
+ if (!v.email) usage2("Provide --email of the person to invite.");
65698
+ result2 = await api("workspaces/current/invites", {
65699
+ method: "POST",
65700
+ body: { email: v.email, ...role() ? { role: role() } : {} }
65701
+ });
65702
+ } else if (command === "member cancel-invite") {
65703
+ if (typeof v.id !== "string" || !/^[a-f0-9-]{36}$/.test(v.id))
65704
+ usage2("Provide --id with an invitation ID from member list.");
65705
+ result2 = await api(`workspaces/current/invites/${v.id}`, {
65706
+ method: "DELETE"
65707
+ });
65708
+ } else if (command === "member role") {
65709
+ if (!role()) usage2("Provide --role owner, admin or member.");
65710
+ result2 = await api(`workspaces/current/members/${member(v.member)}`, {
65711
+ method: "PUT",
65712
+ body: { role: role() }
65713
+ });
65714
+ } else {
65715
+ if (!v.yes) usage2("Pass --yes to remove this member.");
65716
+ result2 = await api(`workspaces/current/members/${member(v.member)}`, {
65717
+ method: "DELETE"
65718
+ });
65719
+ }
65720
+ } else if (command.startsWith("identity ")) {
64884
65721
  const action = p[1];
64885
65722
  const revision = () => {
64886
65723
  const n = Number(v["expected-revision"]);
@@ -65901,6 +66738,15 @@ async function main() {
65901
66738
  if (v["credential-file"] && v["credential-stdin"])
65902
66739
  usage2("Choose one credential input method.");
65903
66740
  credential = v["credential-file"] ? (await readPrivate(v["credential-file"])).trim() : v["credential-stdin"] ? (await passwordFromStdin(8192)).trim() : void 0;
66741
+ if (Object.hasOwn(input2, "accessToken"))
66742
+ usage2(
66743
+ "Keep the ntfy access token out of configuration. Use --access-token-file."
66744
+ );
66745
+ if (v["access-token-file"]) {
66746
+ if (input2.kind !== "ntfy")
66747
+ usage2("--access-token-file applies only to ntfy channels.");
66748
+ input2.accessToken = (await readPrivate(v["access-token-file"])).trim();
66749
+ }
65904
66750
  if (input2.kind === "account-email" && credential)
65905
66751
  usage2(
65906
66752
  "Account email needs no credential; Waitcher sends to your verified sign-in address."
@@ -66007,8 +66853,8 @@ async function main() {
66007
66853
  else if (command === "account billing") result2 = await api("billing");
66008
66854
  else if (command === "account upgrade" || command === "account billing-portal") {
66009
66855
  const plan = v.plan === void 0 ? void 0 : String(v.plan);
66010
- if (command === "account upgrade" && plan && !["pro", "business"].includes(plan))
66011
- usage2("--plan must be pro or business");
66856
+ if (command === "account upgrade" && plan && !["pro", "business", "team"].includes(plan))
66857
+ usage2("--plan must be pro, business or team");
66012
66858
  const { url: url3, changed } = await api(
66013
66859
  command === "account upgrade" ? "billing/checkout" : "billing/portal",
66014
66860
  {
@@ -66034,8 +66880,8 @@ async function main() {
66034
66880
  };
66035
66881
  } else if (command === "system plan") {
66036
66882
  const owner = String(v.owner ?? ""), plan = String(v.plan ?? "");
66037
- if (!/^clerk:user_[A-Za-z0-9]{8,64}$/.test(owner))
66038
- usage2("--owner must be an account owner like clerk:user_ID");
66883
+ if (!/^(clerk:user_[A-Za-z0-9]{8,64}|team:[a-f0-9]{24})$/.test(owner))
66884
+ usage2("--owner must be an account owner like clerk:user_ID or team:ID");
66039
66885
  if (!/^[a-z]{1,32}$/.test(plan)) usage2("--plan must be a plan name");
66040
66886
  result2 = await api(`system/plans/${encodeURIComponent(owner)}`, {
66041
66887
  method: "PUT",
@@ -66043,8 +66889,8 @@ async function main() {
66043
66889
  });
66044
66890
  } else if (command === "system suspend" || command === "system unsuspend") {
66045
66891
  const owner = String(v.owner ?? "");
66046
- if (!/^clerk:user_[A-Za-z0-9]{8,64}$/.test(owner))
66047
- usage2("--owner must be an account owner like clerk:user_ID");
66892
+ if (!/^(clerk:user_[A-Za-z0-9]{8,64}|team:[a-f0-9]{24})$/.test(owner))
66893
+ usage2("--owner must be an account owner like clerk:user_ID or team:ID");
66048
66894
  const suspend = command === "system suspend";
66049
66895
  if (suspend && String(v.reason ?? "").trim().length < 3)
66050
66896
  usage2("--reason must say why, in 3 to 200 characters");
@@ -66061,6 +66907,7 @@ async function main() {
66061
66907
  mode: session.kind === "automation" ? "automation" : session.kind === "oauth" ? "oauth" : "admin_password",
66062
66908
  authorization: data.authorization,
66063
66909
  account: data.account,
66910
+ ...data.workspace ? { workspace: data.workspace } : {},
66064
66911
  ...data.owner ? {
66065
66912
  owner: data.owner,
66066
66913
  plan: data.limits?.plan,
@@ -66247,6 +67094,20 @@ async function main() {
66247
67094
  );
66248
67095
  }
66249
67096
  }
67097
+ } else if (command === "monitor history") {
67098
+ result2 = await api(`monitors/${id3(v.id)}/history`);
67099
+ } else if (command === "report history") {
67100
+ if (v.file) {
67101
+ const csv = await api("reports/history.csv", { responseType: "text" });
67102
+ const file2 = await open18(v.file, "wx", 384);
67103
+ try {
67104
+ await file2.writeFile(csv);
67105
+ await file2.sync();
67106
+ } finally {
67107
+ await file2.close();
67108
+ }
67109
+ result2 = { event: "exported", file: v.file };
67110
+ } else result2 = await api("reports/history");
66250
67111
  } else if (command === "report get") {
66251
67112
  const days = integer2(v.days ?? "1", "days", 1, 14);
66252
67113
  if (![1, 7, 14].includes(days)) usage2("days must be 1, 7 or 14.");