@probelabs/visor 0.1.174 → 0.1.175-ee

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 (91) hide show
  1. package/README.md +3 -2
  2. package/dist/cli-main.d.ts.map +1 -1
  3. package/dist/docs/guides/tdd-assistant-workflows.md +519 -0
  4. package/dist/docs/testing/dsl-reference.md +93 -0
  5. package/dist/examples/lifecycle-hooks.tests.yaml +62 -0
  6. package/dist/generated/config-schema.d.ts +28 -7
  7. package/dist/generated/config-schema.d.ts.map +1 -1
  8. package/dist/generated/config-schema.json +31 -7
  9. package/dist/index.js +2169 -47
  10. package/dist/providers/ai-check-provider.d.ts.map +1 -1
  11. package/dist/providers/mcp-custom-sse-server.d.ts +4 -0
  12. package/dist/providers/mcp-custom-sse-server.d.ts.map +1 -1
  13. package/dist/sdk/{check-provider-registry-UPQNHHFF.mjs → check-provider-registry-K34RCO6G.mjs} +3 -3
  14. package/dist/sdk/{check-provider-registry-YVQI4IOR.mjs → check-provider-registry-O36CQEGD.mjs} +3 -3
  15. package/dist/sdk/{chunk-I6GKXMQ5.mjs → chunk-4Z6HTWGJ.mjs} +155 -16
  16. package/dist/sdk/chunk-4Z6HTWGJ.mjs.map +1 -0
  17. package/dist/sdk/{chunk-2PL2YH3B.mjs → chunk-FZPCP444.mjs} +153 -14
  18. package/dist/sdk/chunk-FZPCP444.mjs.map +1 -0
  19. package/dist/sdk/{chunk-W4KCJM6J.mjs → chunk-MLXGCLZJ.mjs} +29 -8
  20. package/dist/sdk/chunk-MLXGCLZJ.mjs.map +1 -0
  21. package/dist/sdk/{config-BVL3KFMB.mjs → config-4JMBJKWS.mjs} +2 -2
  22. package/dist/sdk/{host-KJTXX76P.mjs → host-LRWIKURZ.mjs} +3 -3
  23. package/dist/sdk/knex-store-QCEW4I4R.mjs +527 -0
  24. package/dist/sdk/knex-store-QCEW4I4R.mjs.map +1 -0
  25. package/dist/sdk/loader-Q7K76ZIY.mjs +89 -0
  26. package/dist/sdk/loader-Q7K76ZIY.mjs.map +1 -0
  27. package/dist/sdk/opa-policy-engine-QCSSIMUF.mjs +655 -0
  28. package/dist/sdk/opa-policy-engine-QCSSIMUF.mjs.map +1 -0
  29. package/dist/sdk/{schedule-tool-UMDRCNO5.mjs → schedule-tool-XOXKUW5G.mjs} +3 -3
  30. package/dist/sdk/{schedule-tool-IEY2CFLU.mjs → schedule-tool-XVSYLH4Z.mjs} +3 -3
  31. package/dist/sdk/{schedule-tool-handler-5EPTHBLS.mjs → schedule-tool-handler-3I6AZ4N7.mjs} +3 -3
  32. package/dist/sdk/{schedule-tool-handler-HMEGLYJF.mjs → schedule-tool-handler-CFMFHDUL.mjs} +3 -3
  33. package/dist/sdk/sdk.d.mts +9 -1
  34. package/dist/sdk/sdk.d.ts +9 -1
  35. package/dist/sdk/sdk.js +1827 -293
  36. package/dist/sdk/sdk.js.map +1 -1
  37. package/dist/sdk/sdk.mjs +5 -5
  38. package/dist/sdk/validator-XTZJZZJH.mjs +134 -0
  39. package/dist/sdk/validator-XTZJZZJH.mjs.map +1 -0
  40. package/dist/sdk/{workflow-check-provider-VJ7VIMCQ.mjs → workflow-check-provider-ETM452BO.mjs} +3 -3
  41. package/dist/sdk/{workflow-check-provider-EWMZEEES.mjs → workflow-check-provider-EV6VCG7M.mjs} +3 -3
  42. package/dist/test-runner/conversation-sugar.d.ts.map +1 -1
  43. package/dist/test-runner/index.d.ts +19 -0
  44. package/dist/test-runner/index.d.ts.map +1 -1
  45. package/dist/test-runner/validator.d.ts.map +1 -1
  46. package/dist/types/config.d.ts +9 -1
  47. package/dist/types/config.d.ts.map +1 -1
  48. package/package.json +1 -1
  49. package/dist/output/traces/run-2026-03-09T15-44-30-340Z.ndjson +0 -138
  50. package/dist/output/traces/run-2026-03-09T15-45-10-778Z.ndjson +0 -2280
  51. package/dist/sdk/a2a-frontend-5L6H7ZVF.mjs +0 -1658
  52. package/dist/sdk/a2a-frontend-5L6H7ZVF.mjs.map +0 -1
  53. package/dist/sdk/check-provider-registry-UM762L7S.mjs +0 -30
  54. package/dist/sdk/chunk-2PL2YH3B.mjs.map +0 -1
  55. package/dist/sdk/chunk-EP7PQ4IX.mjs +0 -45016
  56. package/dist/sdk/chunk-EP7PQ4IX.mjs.map +0 -1
  57. package/dist/sdk/chunk-I6GKXMQ5.mjs.map +0 -1
  58. package/dist/sdk/chunk-UTBSBJFV.mjs +0 -739
  59. package/dist/sdk/chunk-UTBSBJFV.mjs.map +0 -1
  60. package/dist/sdk/chunk-W4KCJM6J.mjs.map +0 -1
  61. package/dist/sdk/chunk-YEARBXYT.mjs +0 -1502
  62. package/dist/sdk/chunk-YEARBXYT.mjs.map +0 -1
  63. package/dist/sdk/chunk-ZI3SEHWA.mjs +0 -516
  64. package/dist/sdk/chunk-ZI3SEHWA.mjs.map +0 -1
  65. package/dist/sdk/failure-condition-evaluator-4O6BTC4Q.mjs +0 -18
  66. package/dist/sdk/github-frontend-UXL73NKB.mjs +0 -1386
  67. package/dist/sdk/github-frontend-UXL73NKB.mjs.map +0 -1
  68. package/dist/sdk/routing-AWYB2YX3.mjs +0 -26
  69. package/dist/sdk/schedule-tool-SGCYDSHL.mjs +0 -36
  70. package/dist/sdk/schedule-tool-handler-5EPTHBLS.mjs.map +0 -1
  71. package/dist/sdk/schedule-tool-handler-5QVUZ5EZ.mjs +0 -40
  72. package/dist/sdk/schedule-tool-handler-5QVUZ5EZ.mjs.map +0 -1
  73. package/dist/sdk/schedule-tool-handler-HMEGLYJF.mjs.map +0 -1
  74. package/dist/sdk/trace-helpers-6TEWG7RK.mjs +0 -29
  75. package/dist/sdk/trace-helpers-6TEWG7RK.mjs.map +0 -1
  76. package/dist/sdk/workflow-check-provider-7VNIO6L5.mjs +0 -30
  77. package/dist/sdk/workflow-check-provider-7VNIO6L5.mjs.map +0 -1
  78. package/dist/sdk/workflow-check-provider-EWMZEEES.mjs.map +0 -1
  79. package/dist/sdk/workflow-check-provider-VJ7VIMCQ.mjs.map +0 -1
  80. package/dist/traces/run-2026-03-09T15-44-30-340Z.ndjson +0 -138
  81. package/dist/traces/run-2026-03-09T15-45-10-778Z.ndjson +0 -2280
  82. /package/dist/sdk/{check-provider-registry-UM762L7S.mjs.map → check-provider-registry-K34RCO6G.mjs.map} +0 -0
  83. /package/dist/sdk/{check-provider-registry-UPQNHHFF.mjs.map → check-provider-registry-O36CQEGD.mjs.map} +0 -0
  84. /package/dist/sdk/{check-provider-registry-YVQI4IOR.mjs.map → config-4JMBJKWS.mjs.map} +0 -0
  85. /package/dist/sdk/{host-KJTXX76P.mjs.map → host-LRWIKURZ.mjs.map} +0 -0
  86. /package/dist/sdk/{config-BVL3KFMB.mjs.map → schedule-tool-XOXKUW5G.mjs.map} +0 -0
  87. /package/dist/sdk/{failure-condition-evaluator-4O6BTC4Q.mjs.map → schedule-tool-XVSYLH4Z.mjs.map} +0 -0
  88. /package/dist/sdk/{routing-AWYB2YX3.mjs.map → schedule-tool-handler-3I6AZ4N7.mjs.map} +0 -0
  89. /package/dist/sdk/{schedule-tool-IEY2CFLU.mjs.map → schedule-tool-handler-CFMFHDUL.mjs.map} +0 -0
  90. /package/dist/sdk/{schedule-tool-SGCYDSHL.mjs.map → workflow-check-provider-ETM452BO.mjs.map} +0 -0
  91. /package/dist/sdk/{schedule-tool-UMDRCNO5.mjs.map → workflow-check-provider-EV6VCG7M.mjs.map} +0 -0
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- process.env.VISOR_VERSION = '0.1.174';
2
+ process.env.VISOR_VERSION = '0.1.175';
3
3
  process.env.PROBE_VERSION = '0.6.0-rc291';
4
- process.env.VISOR_COMMIT_SHA = 'e8809d0dd7ef9584a6c687826df911bbc12d7fbd';
5
- process.env.VISOR_COMMIT_SHORT = 'e8809d0d';
4
+ process.env.VISOR_COMMIT_SHA = '5b303b06870720f90057ff3f58f0e72f34bf80cb';
5
+ process.env.VISOR_COMMIT_SHORT = '5b303b0';
6
6
  /******/ (() => { // webpackBootstrap
7
7
  /******/ var __webpack_modules__ = ({
8
8
 
@@ -302951,7 +302951,7 @@ async function handleDumpPolicyInput(checkId, argv) {
302951
302951
  let PolicyInputBuilder;
302952
302952
  try {
302953
302953
  // @ts-ignore — enterprise/ may not exist in OSS builds (caught at runtime)
302954
- const mod = await Promise.resolve().then(() => __importStar(__nccwpck_require__(71370)));
302954
+ const mod = await Promise.resolve().then(() => __importStar(__nccwpck_require__(17117)));
302955
302955
  PolicyInputBuilder = mod.PolicyInputBuilder;
302956
302956
  }
302957
302957
  catch {
@@ -303441,6 +303441,7 @@ async function handleTestCommand(argv) {
303441
303441
  const flagsWithValues = new Set([
303442
303442
  '--config',
303443
303443
  '--only',
303444
+ '--case',
303444
303445
  '--json',
303445
303446
  '--report',
303446
303447
  '--summary',
@@ -303470,7 +303471,7 @@ async function handleTestCommand(argv) {
303470
303471
  break;
303471
303472
  }
303472
303473
  }
303473
- const only = getArg('--only');
303474
+ const only = getArg('--only') || getArg('--case');
303474
303475
  const bail = hasFlag('--bail');
303475
303476
  const noMocks = hasFlag('--no-mocks');
303476
303477
  const noMocksForRaw = getArg('--no-mocks-for');
@@ -311018,6 +311019,1810 @@ class EmailPollingRunner {
311018
311019
  exports.EmailPollingRunner = EmailPollingRunner;
311019
311020
 
311020
311021
 
311022
+ /***/ }),
311023
+
311024
+ /***/ 50069:
311025
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
311026
+
311027
+ "use strict";
311028
+
311029
+ /**
311030
+ * Copyright (c) ProbeLabs. All rights reserved.
311031
+ * Licensed under the Elastic License 2.0; you may not use this file except
311032
+ * in compliance with the Elastic License 2.0.
311033
+ */
311034
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
311035
+ if (k2 === undefined) k2 = k;
311036
+ var desc = Object.getOwnPropertyDescriptor(m, k);
311037
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
311038
+ desc = { enumerable: true, get: function() { return m[k]; } };
311039
+ }
311040
+ Object.defineProperty(o, k2, desc);
311041
+ }) : (function(o, m, k, k2) {
311042
+ if (k2 === undefined) k2 = k;
311043
+ o[k2] = m[k];
311044
+ }));
311045
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
311046
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
311047
+ }) : function(o, v) {
311048
+ o["default"] = v;
311049
+ });
311050
+ var __importStar = (this && this.__importStar) || (function () {
311051
+ var ownKeys = function(o) {
311052
+ ownKeys = Object.getOwnPropertyNames || function (o) {
311053
+ var ar = [];
311054
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
311055
+ return ar;
311056
+ };
311057
+ return ownKeys(o);
311058
+ };
311059
+ return function (mod) {
311060
+ if (mod && mod.__esModule) return mod;
311061
+ var result = {};
311062
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
311063
+ __setModuleDefault(result, mod);
311064
+ return result;
311065
+ };
311066
+ })();
311067
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
311068
+ exports.LicenseValidator = void 0;
311069
+ const crypto = __importStar(__nccwpck_require__(76982));
311070
+ const fs = __importStar(__nccwpck_require__(79896));
311071
+ const path = __importStar(__nccwpck_require__(16928));
311072
+ class LicenseValidator {
311073
+ /** Ed25519 public key for license verification (PEM format). */
311074
+ static PUBLIC_KEY = '-----BEGIN PUBLIC KEY-----\n' +
311075
+ 'MCowBQYDK2VwAyEAI/Zd08EFmgIdrDm/HXd0l3/5GBt7R1PrdvhdmEXhJlU=\n' +
311076
+ '-----END PUBLIC KEY-----\n';
311077
+ cache = null;
311078
+ static CACHE_TTL = 5 * 60 * 1000; // 5 minutes
311079
+ static GRACE_PERIOD = 72 * 3600 * 1000; // 72 hours after expiry
311080
+ /**
311081
+ * Load and validate license from environment or file.
311082
+ *
311083
+ * Resolution order:
311084
+ * 1. VISOR_LICENSE env var (JWT string)
311085
+ * 2. VISOR_LICENSE_FILE env var (path to file)
311086
+ * 3. .visor-license in project root (cwd)
311087
+ * 4. .visor-license in ~/.config/visor/
311088
+ */
311089
+ async loadAndValidate() {
311090
+ // Return cached result if still fresh
311091
+ if (this.cache && Date.now() - this.cache.validatedAt < LicenseValidator.CACHE_TTL) {
311092
+ return this.cache.payload;
311093
+ }
311094
+ const token = this.resolveToken();
311095
+ if (!token)
311096
+ return null;
311097
+ const payload = this.verifyAndDecode(token);
311098
+ if (!payload)
311099
+ return null;
311100
+ this.cache = { payload, validatedAt: Date.now() };
311101
+ return payload;
311102
+ }
311103
+ /** Check if a specific feature is licensed */
311104
+ hasFeature(feature) {
311105
+ if (!this.cache)
311106
+ return false;
311107
+ return this.cache.payload.features.includes(feature);
311108
+ }
311109
+ /** Check if license is valid (with grace period) */
311110
+ isValid() {
311111
+ if (!this.cache)
311112
+ return false;
311113
+ const now = Date.now();
311114
+ const expiryMs = this.cache.payload.exp * 1000;
311115
+ return now < expiryMs + LicenseValidator.GRACE_PERIOD;
311116
+ }
311117
+ /** Check if the license is within its grace period (expired but still valid) */
311118
+ isInGracePeriod() {
311119
+ if (!this.cache)
311120
+ return false;
311121
+ const now = Date.now();
311122
+ const expiryMs = this.cache.payload.exp * 1000;
311123
+ return now >= expiryMs && now < expiryMs + LicenseValidator.GRACE_PERIOD;
311124
+ }
311125
+ resolveToken() {
311126
+ // 1. Direct env var
311127
+ if (process.env.VISOR_LICENSE) {
311128
+ return process.env.VISOR_LICENSE.trim();
311129
+ }
311130
+ // 2. File path from env (validate against path traversal)
311131
+ if (process.env.VISOR_LICENSE_FILE) {
311132
+ // path.resolve() produces an absolute path with all '..' segments resolved,
311133
+ // so a separate resolved.includes('..') check is unnecessary.
311134
+ const resolved = path.resolve(process.env.VISOR_LICENSE_FILE);
311135
+ const home = process.env.HOME || process.env.USERPROFILE || '';
311136
+ const allowedPrefixes = [path.normalize(process.cwd())];
311137
+ if (home)
311138
+ allowedPrefixes.push(path.normalize(path.join(home, '.config', 'visor')));
311139
+ // Resolve symlinks so an attacker cannot create a symlink inside an
311140
+ // allowed prefix that points to an arbitrary file outside it.
311141
+ let realPath;
311142
+ try {
311143
+ realPath = fs.realpathSync(resolved);
311144
+ }
311145
+ catch {
311146
+ return null; // File doesn't exist or isn't accessible
311147
+ }
311148
+ const isSafe = allowedPrefixes.some(prefix => realPath === prefix || realPath.startsWith(prefix + path.sep));
311149
+ if (!isSafe)
311150
+ return null;
311151
+ return this.readFile(realPath);
311152
+ }
311153
+ // 3. .visor-license in cwd
311154
+ const cwdPath = path.join(process.cwd(), '.visor-license');
311155
+ const cwdToken = this.readFile(cwdPath);
311156
+ if (cwdToken)
311157
+ return cwdToken;
311158
+ // 4. ~/.config/visor/.visor-license
311159
+ const home = process.env.HOME || process.env.USERPROFILE || '';
311160
+ if (home) {
311161
+ const configPath = path.join(home, '.config', 'visor', '.visor-license');
311162
+ const configToken = this.readFile(configPath);
311163
+ if (configToken)
311164
+ return configToken;
311165
+ }
311166
+ return null;
311167
+ }
311168
+ readFile(filePath) {
311169
+ try {
311170
+ return fs.readFileSync(filePath, 'utf-8').trim();
311171
+ }
311172
+ catch {
311173
+ return null;
311174
+ }
311175
+ }
311176
+ verifyAndDecode(token) {
311177
+ try {
311178
+ const parts = token.split('.');
311179
+ if (parts.length !== 3)
311180
+ return null;
311181
+ const [headerB64, payloadB64, signatureB64] = parts;
311182
+ // Decode header to verify algorithm
311183
+ const header = JSON.parse(Buffer.from(headerB64, 'base64url').toString());
311184
+ if (header.alg !== 'EdDSA')
311185
+ return null;
311186
+ // Verify signature
311187
+ const data = `${headerB64}.${payloadB64}`;
311188
+ const signature = Buffer.from(signatureB64, 'base64url');
311189
+ const publicKey = crypto.createPublicKey(LicenseValidator.PUBLIC_KEY);
311190
+ // Validate that the loaded public key is actually Ed25519 (OID 1.3.101.112).
311191
+ // This prevents algorithm-confusion attacks if the embedded key were ever
311192
+ // swapped to a different type.
311193
+ if (publicKey.asymmetricKeyType !== 'ed25519') {
311194
+ return null;
311195
+ }
311196
+ // Ed25519 verification: algorithm must be null because EdDSA performs its
311197
+ // own internal hashing (SHA-512) — passing a digest algorithm here would
311198
+ // cause Node.js to throw. The key type is validated above.
311199
+ const isValid = crypto.verify(null, Buffer.from(data), publicKey, signature);
311200
+ if (!isValid)
311201
+ return null;
311202
+ // Decode payload
311203
+ const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString());
311204
+ // Validate required fields
311205
+ if (!payload.org ||
311206
+ !Array.isArray(payload.features) ||
311207
+ typeof payload.exp !== 'number' ||
311208
+ typeof payload.iat !== 'number' ||
311209
+ !payload.sub) {
311210
+ return null;
311211
+ }
311212
+ // Check expiry (with grace period)
311213
+ const now = Date.now();
311214
+ const expiryMs = payload.exp * 1000;
311215
+ if (now >= expiryMs + LicenseValidator.GRACE_PERIOD) {
311216
+ return null;
311217
+ }
311218
+ return payload;
311219
+ }
311220
+ catch {
311221
+ return null;
311222
+ }
311223
+ }
311224
+ }
311225
+ exports.LicenseValidator = LicenseValidator;
311226
+
311227
+
311228
+ /***/ }),
311229
+
311230
+ /***/ 87068:
311231
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
311232
+
311233
+ "use strict";
311234
+
311235
+ /**
311236
+ * Copyright (c) ProbeLabs. All rights reserved.
311237
+ * Licensed under the Elastic License 2.0; you may not use this file except
311238
+ * in compliance with the Elastic License 2.0.
311239
+ */
311240
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
311241
+ if (k2 === undefined) k2 = k;
311242
+ var desc = Object.getOwnPropertyDescriptor(m, k);
311243
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
311244
+ desc = { enumerable: true, get: function() { return m[k]; } };
311245
+ }
311246
+ Object.defineProperty(o, k2, desc);
311247
+ }) : (function(o, m, k, k2) {
311248
+ if (k2 === undefined) k2 = k;
311249
+ o[k2] = m[k];
311250
+ }));
311251
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
311252
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
311253
+ }) : function(o, v) {
311254
+ o["default"] = v;
311255
+ });
311256
+ var __importStar = (this && this.__importStar) || (function () {
311257
+ var ownKeys = function(o) {
311258
+ ownKeys = Object.getOwnPropertyNames || function (o) {
311259
+ var ar = [];
311260
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
311261
+ return ar;
311262
+ };
311263
+ return ownKeys(o);
311264
+ };
311265
+ return function (mod) {
311266
+ if (mod && mod.__esModule) return mod;
311267
+ var result = {};
311268
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
311269
+ __setModuleDefault(result, mod);
311270
+ return result;
311271
+ };
311272
+ })();
311273
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
311274
+ exports.loadEnterprisePolicyEngine = loadEnterprisePolicyEngine;
311275
+ exports.loadEnterpriseStoreBackend = loadEnterpriseStoreBackend;
311276
+ const default_engine_1 = __nccwpck_require__(93866);
311277
+ /**
311278
+ * Load the enterprise policy engine if licensed, otherwise return the default no-op engine.
311279
+ *
311280
+ * This is the sole import boundary between OSS and enterprise code. Core code
311281
+ * must only import from this module (via dynamic `await import()`), never from
311282
+ * individual enterprise submodules.
311283
+ */
311284
+ async function loadEnterprisePolicyEngine(config) {
311285
+ try {
311286
+ const { LicenseValidator } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(50069)));
311287
+ const validator = new LicenseValidator();
311288
+ const license = await validator.loadAndValidate();
311289
+ if (!license || !validator.hasFeature('policy')) {
311290
+ return new default_engine_1.DefaultPolicyEngine();
311291
+ }
311292
+ if (validator.isInGracePeriod()) {
311293
+ // eslint-disable-next-line no-console
311294
+ console.warn('[visor:enterprise] License has expired but is within the 72-hour grace period. ' +
311295
+ 'Please renew your license.');
311296
+ }
311297
+ const { OpaPolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(39530)));
311298
+ const engine = new OpaPolicyEngine(config);
311299
+ await engine.initialize(config);
311300
+ return engine;
311301
+ }
311302
+ catch (err) {
311303
+ // Enterprise code not available or initialization failed
311304
+ const msg = err instanceof Error ? err.message : String(err);
311305
+ try {
311306
+ const { logger } = __nccwpck_require__(86999);
311307
+ logger.warn(`[PolicyEngine] Enterprise policy init failed, falling back to default: ${msg}`);
311308
+ }
311309
+ catch {
311310
+ // silent
311311
+ }
311312
+ return new default_engine_1.DefaultPolicyEngine();
311313
+ }
311314
+ }
311315
+ /**
311316
+ * Load the enterprise schedule store backend if licensed.
311317
+ *
311318
+ * @param driver Database driver ('postgresql', 'mysql', or 'mssql')
311319
+ * @param storageConfig Storage configuration with connection details
311320
+ * @param haConfig Optional HA configuration
311321
+ * @throws Error if enterprise license is not available or missing 'scheduler-sql' feature
311322
+ */
311323
+ async function loadEnterpriseStoreBackend(driver, storageConfig, haConfig) {
311324
+ const { LicenseValidator } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(50069)));
311325
+ const validator = new LicenseValidator();
311326
+ const license = await validator.loadAndValidate();
311327
+ if (!license || !validator.hasFeature('scheduler-sql')) {
311328
+ throw new Error(`The ${driver} schedule storage driver requires a Visor Enterprise license ` +
311329
+ `with the 'scheduler-sql' feature. Please upgrade or use driver: 'sqlite' (default).`);
311330
+ }
311331
+ if (validator.isInGracePeriod()) {
311332
+ // eslint-disable-next-line no-console
311333
+ console.warn('[visor:enterprise] License has expired but is within the 72-hour grace period. ' +
311334
+ 'Please renew your license.');
311335
+ }
311336
+ const { KnexStoreBackend } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(63737)));
311337
+ return new KnexStoreBackend(driver, storageConfig, haConfig);
311338
+ }
311339
+
311340
+
311341
+ /***/ }),
311342
+
311343
+ /***/ 628:
311344
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
311345
+
311346
+ "use strict";
311347
+
311348
+ /**
311349
+ * Copyright (c) ProbeLabs. All rights reserved.
311350
+ * Licensed under the Elastic License 2.0; you may not use this file except
311351
+ * in compliance with the Elastic License 2.0.
311352
+ */
311353
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
311354
+ if (k2 === undefined) k2 = k;
311355
+ var desc = Object.getOwnPropertyDescriptor(m, k);
311356
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
311357
+ desc = { enumerable: true, get: function() { return m[k]; } };
311358
+ }
311359
+ Object.defineProperty(o, k2, desc);
311360
+ }) : (function(o, m, k, k2) {
311361
+ if (k2 === undefined) k2 = k;
311362
+ o[k2] = m[k];
311363
+ }));
311364
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
311365
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
311366
+ }) : function(o, v) {
311367
+ o["default"] = v;
311368
+ });
311369
+ var __importStar = (this && this.__importStar) || (function () {
311370
+ var ownKeys = function(o) {
311371
+ ownKeys = Object.getOwnPropertyNames || function (o) {
311372
+ var ar = [];
311373
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
311374
+ return ar;
311375
+ };
311376
+ return ownKeys(o);
311377
+ };
311378
+ return function (mod) {
311379
+ if (mod && mod.__esModule) return mod;
311380
+ var result = {};
311381
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
311382
+ __setModuleDefault(result, mod);
311383
+ return result;
311384
+ };
311385
+ })();
311386
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
311387
+ exports.OpaCompiler = void 0;
311388
+ const fs = __importStar(__nccwpck_require__(79896));
311389
+ const path = __importStar(__nccwpck_require__(16928));
311390
+ const os = __importStar(__nccwpck_require__(70857));
311391
+ const crypto = __importStar(__nccwpck_require__(76982));
311392
+ const child_process_1 = __nccwpck_require__(35317);
311393
+ /**
311394
+ * OPA Rego Compiler - compiles .rego policy files to WASM bundles using the `opa` CLI.
311395
+ *
311396
+ * Handles:
311397
+ * - Resolving input paths to WASM bytes (direct .wasm, directory with policy.wasm, or .rego files)
311398
+ * - Compiling .rego files to WASM via `opa build`
311399
+ * - Caching compiled bundles based on content hashes
311400
+ * - Extracting policy.wasm from OPA tar.gz bundles
311401
+ *
311402
+ * Requires:
311403
+ * - `opa` CLI on PATH (only when auto-compiling .rego files)
311404
+ */
311405
+ class OpaCompiler {
311406
+ static CACHE_DIR = path.join(os.tmpdir(), 'visor-opa-cache');
311407
+ /**
311408
+ * Resolve the input paths to WASM bytes.
311409
+ *
311410
+ * Strategy:
311411
+ * 1. If any path is a .wasm file, read it directly
311412
+ * 2. If a directory contains policy.wasm, read it
311413
+ * 3. Otherwise, collect all .rego files and auto-compile via `opa build`
311414
+ */
311415
+ async resolveWasmBytes(paths) {
311416
+ // Collect .rego files and check for existing .wasm
311417
+ const regoFiles = [];
311418
+ for (const p of paths) {
311419
+ const resolved = path.resolve(p);
311420
+ // Reject paths containing '..' after resolution (path traversal)
311421
+ if (path.normalize(resolved).includes('..')) {
311422
+ throw new Error(`Policy path contains traversal sequences: ${p}`);
311423
+ }
311424
+ // Direct .wasm file
311425
+ if (resolved.endsWith('.wasm') && fs.existsSync(resolved)) {
311426
+ return fs.readFileSync(resolved);
311427
+ }
311428
+ if (!fs.existsSync(resolved))
311429
+ continue;
311430
+ const stat = fs.statSync(resolved);
311431
+ if (stat.isDirectory()) {
311432
+ // Check for pre-compiled policy.wasm in directory
311433
+ const wasmCandidate = path.join(resolved, 'policy.wasm');
311434
+ if (fs.existsSync(wasmCandidate)) {
311435
+ return fs.readFileSync(wasmCandidate);
311436
+ }
311437
+ // Collect all .rego files from directory
311438
+ const files = fs.readdirSync(resolved);
311439
+ for (const f of files) {
311440
+ if (f.endsWith('.rego')) {
311441
+ regoFiles.push(path.join(resolved, f));
311442
+ }
311443
+ }
311444
+ }
311445
+ else if (resolved.endsWith('.rego')) {
311446
+ regoFiles.push(resolved);
311447
+ }
311448
+ }
311449
+ if (regoFiles.length === 0) {
311450
+ throw new Error(`OPA WASM evaluator: no .wasm bundle or .rego files found in: ${paths.join(', ')}`);
311451
+ }
311452
+ // Auto-compile .rego -> .wasm
311453
+ return this.compileRego(regoFiles);
311454
+ }
311455
+ /**
311456
+ * Auto-compile .rego files to a WASM bundle using the `opa` CLI.
311457
+ *
311458
+ * Caches the compiled bundle based on a content hash of all input .rego files
311459
+ * so subsequent runs skip compilation if policies haven't changed.
311460
+ */
311461
+ compileRego(regoFiles) {
311462
+ // Check that `opa` CLI is available
311463
+ try {
311464
+ (0, child_process_1.execFileSync)('opa', ['version'], { stdio: 'pipe' });
311465
+ }
311466
+ catch {
311467
+ throw new Error('OPA CLI (`opa`) not found on PATH. Install it from https://www.openpolicyagent.org/docs/latest/#running-opa\n' +
311468
+ 'Or pre-compile your .rego files: opa build -t wasm -e visor -o bundle.tar.gz ' +
311469
+ regoFiles.join(' '));
311470
+ }
311471
+ // Compute content hash for cache key
311472
+ const hash = crypto.createHash('sha256');
311473
+ for (const f of regoFiles.sort()) {
311474
+ hash.update(fs.readFileSync(f));
311475
+ hash.update(f); // include filename for disambiguation
311476
+ }
311477
+ const cacheKey = hash.digest('hex').slice(0, 16);
311478
+ const cacheDir = OpaCompiler.CACHE_DIR;
311479
+ const cachedWasm = path.join(cacheDir, `${cacheKey}.wasm`);
311480
+ // Return cached bundle if still valid
311481
+ if (fs.existsSync(cachedWasm)) {
311482
+ return fs.readFileSync(cachedWasm);
311483
+ }
311484
+ // Compile to WASM via opa build
311485
+ fs.mkdirSync(cacheDir, { recursive: true });
311486
+ const bundleTar = path.join(cacheDir, `${cacheKey}-bundle.tar.gz`);
311487
+ try {
311488
+ const args = [
311489
+ 'build',
311490
+ '-t',
311491
+ 'wasm',
311492
+ '-e',
311493
+ 'visor', // entrypoint: the visor package tree
311494
+ '-o',
311495
+ bundleTar,
311496
+ ...regoFiles,
311497
+ ];
311498
+ (0, child_process_1.execFileSync)('opa', args, {
311499
+ stdio: 'pipe',
311500
+ timeout: 30000,
311501
+ });
311502
+ }
311503
+ catch (err) {
311504
+ const stderr = err?.stderr?.toString() || '';
311505
+ throw new Error(`Failed to compile .rego files to WASM:\n${stderr}\n` +
311506
+ 'Ensure your .rego files are valid and the `opa` CLI is installed.');
311507
+ }
311508
+ // Extract policy.wasm from the tar.gz bundle
311509
+ // OPA bundles are tar.gz with /policy.wasm inside
311510
+ try {
311511
+ (0, child_process_1.execFileSync)('tar', ['-xzf', bundleTar, '-C', cacheDir, '/policy.wasm'], {
311512
+ stdio: 'pipe',
311513
+ });
311514
+ const extractedWasm = path.join(cacheDir, 'policy.wasm');
311515
+ if (fs.existsSync(extractedWasm)) {
311516
+ // Move to cache-key named file
311517
+ fs.renameSync(extractedWasm, cachedWasm);
311518
+ }
311519
+ }
311520
+ catch {
311521
+ // Some tar implementations don't like leading /
311522
+ try {
311523
+ (0, child_process_1.execFileSync)('tar', ['-xzf', bundleTar, '-C', cacheDir, 'policy.wasm'], {
311524
+ stdio: 'pipe',
311525
+ });
311526
+ const extractedWasm = path.join(cacheDir, 'policy.wasm');
311527
+ if (fs.existsSync(extractedWasm)) {
311528
+ fs.renameSync(extractedWasm, cachedWasm);
311529
+ }
311530
+ }
311531
+ catch (err2) {
311532
+ throw new Error(`Failed to extract policy.wasm from OPA bundle: ${err2?.message || err2}`);
311533
+ }
311534
+ }
311535
+ // Clean up tar
311536
+ try {
311537
+ fs.unlinkSync(bundleTar);
311538
+ }
311539
+ catch { }
311540
+ if (!fs.existsSync(cachedWasm)) {
311541
+ throw new Error('OPA build succeeded but policy.wasm was not found in the bundle');
311542
+ }
311543
+ return fs.readFileSync(cachedWasm);
311544
+ }
311545
+ }
311546
+ exports.OpaCompiler = OpaCompiler;
311547
+
311548
+
311549
+ /***/ }),
311550
+
311551
+ /***/ 44693:
311552
+ /***/ ((__unused_webpack_module, exports) => {
311553
+
311554
+ "use strict";
311555
+
311556
+ /**
311557
+ * Copyright (c) ProbeLabs. All rights reserved.
311558
+ * Licensed under the Elastic License 2.0; you may not use this file except
311559
+ * in compliance with the Elastic License 2.0.
311560
+ */
311561
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
311562
+ exports.OpaHttpEvaluator = void 0;
311563
+ /**
311564
+ * OPA HTTP Evaluator - evaluates policies via an external OPA server's REST API.
311565
+ *
311566
+ * Uses the built-in `fetch` API (Node 18+), so no extra dependencies are needed.
311567
+ */
311568
+ class OpaHttpEvaluator {
311569
+ baseUrl;
311570
+ timeout;
311571
+ constructor(baseUrl, timeout = 5000) {
311572
+ // Validate URL format and protocol
311573
+ let parsed;
311574
+ try {
311575
+ parsed = new URL(baseUrl);
311576
+ }
311577
+ catch {
311578
+ throw new Error(`OPA HTTP evaluator: invalid URL: ${baseUrl}`);
311579
+ }
311580
+ if (!['http:', 'https:'].includes(parsed.protocol)) {
311581
+ throw new Error(`OPA HTTP evaluator: url must use http:// or https:// protocol, got: ${baseUrl}`);
311582
+ }
311583
+ // Block cloud metadata, loopback, link-local, and private network addresses
311584
+ const hostname = parsed.hostname;
311585
+ if (this.isBlockedHostname(hostname)) {
311586
+ throw new Error(`OPA HTTP evaluator: url must not point to internal, loopback, or private network addresses`);
311587
+ }
311588
+ // Normalize: strip trailing slash
311589
+ this.baseUrl = baseUrl.replace(/\/+$/, '');
311590
+ this.timeout = timeout;
311591
+ }
311592
+ /**
311593
+ * Check if a hostname is blocked due to SSRF concerns.
311594
+ *
311595
+ * Blocks:
311596
+ * - Loopback addresses (127.x.x.x, localhost, 0.0.0.0, ::1)
311597
+ * - Link-local addresses (169.254.x.x)
311598
+ * - Private networks (10.x.x.x, 172.16-31.x.x, 192.168.x.x)
311599
+ * - IPv6 unique local addresses (fd00::/8)
311600
+ * - Cloud metadata services (*.internal)
311601
+ */
311602
+ isBlockedHostname(hostname) {
311603
+ if (!hostname)
311604
+ return true; // block empty hostnames
311605
+ // Normalize hostname: lowercase and remove brackets for IPv6
311606
+ const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, '');
311607
+ // Block .internal domains (cloud metadata services)
311608
+ if (normalized === 'metadata.google.internal' || normalized.endsWith('.internal')) {
311609
+ return true;
311610
+ }
311611
+ // Block localhost variants
311612
+ if (normalized === 'localhost' || normalized === 'localhost.localdomain') {
311613
+ return true;
311614
+ }
311615
+ // Block IPv6 loopback
311616
+ if (normalized === '::1' || normalized === '0:0:0:0:0:0:0:1') {
311617
+ return true;
311618
+ }
311619
+ // Check IPv4 patterns
311620
+ const ipv4Pattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
311621
+ const ipv4Match = normalized.match(ipv4Pattern);
311622
+ if (ipv4Match) {
311623
+ const octets = ipv4Match.slice(1, 5).map(Number);
311624
+ // Validate octets are in range [0, 255]
311625
+ if (octets.some(octet => octet > 255)) {
311626
+ return false;
311627
+ }
311628
+ const [a, b] = octets;
311629
+ // Block loopback: 127.0.0.0/8
311630
+ if (a === 127) {
311631
+ return true;
311632
+ }
311633
+ // Block 0.0.0.0/8 (this host)
311634
+ if (a === 0) {
311635
+ return true;
311636
+ }
311637
+ // Block link-local: 169.254.0.0/16
311638
+ if (a === 169 && b === 254) {
311639
+ return true;
311640
+ }
311641
+ // Block private networks
311642
+ // 10.0.0.0/8
311643
+ if (a === 10) {
311644
+ return true;
311645
+ }
311646
+ // 172.16.0.0/12 (172.16.x.x through 172.31.x.x)
311647
+ if (a === 172 && b >= 16 && b <= 31) {
311648
+ return true;
311649
+ }
311650
+ // 192.168.0.0/16
311651
+ if (a === 192 && b === 168) {
311652
+ return true;
311653
+ }
311654
+ }
311655
+ // Check IPv6 patterns
311656
+ // Block unique local addresses: fd00::/8
311657
+ if (normalized.startsWith('fd') || normalized.startsWith('fc')) {
311658
+ return true;
311659
+ }
311660
+ // Block link-local: fe80::/10
311661
+ if (normalized.startsWith('fe80:')) {
311662
+ return true;
311663
+ }
311664
+ return false;
311665
+ }
311666
+ /**
311667
+ * Evaluate a policy rule against an input document via OPA REST API.
311668
+ *
311669
+ * @param input - The input document to evaluate
311670
+ * @param rulePath - OPA rule path (e.g., 'visor/check/execute')
311671
+ * @returns The result object from OPA, or undefined on error
311672
+ */
311673
+ async evaluate(input, rulePath) {
311674
+ // OPA Data API: POST /v1/data/<path>
311675
+ const encodedPath = rulePath
311676
+ .split('/')
311677
+ .map(s => encodeURIComponent(s))
311678
+ .join('/');
311679
+ const url = `${this.baseUrl}/v1/data/${encodedPath}`;
311680
+ const controller = new AbortController();
311681
+ const timer = setTimeout(() => controller.abort(), this.timeout);
311682
+ try {
311683
+ const response = await fetch(url, {
311684
+ method: 'POST',
311685
+ headers: { 'Content-Type': 'application/json' },
311686
+ body: JSON.stringify({ input }),
311687
+ signal: controller.signal,
311688
+ });
311689
+ if (!response.ok) {
311690
+ throw new Error(`OPA HTTP ${response.status}: ${response.statusText}`);
311691
+ }
311692
+ let body;
311693
+ try {
311694
+ body = await response.json();
311695
+ }
311696
+ catch (jsonErr) {
311697
+ throw new Error(`OPA HTTP evaluator: failed to parse JSON response: ${jsonErr instanceof Error ? jsonErr.message : String(jsonErr)}`);
311698
+ }
311699
+ // OPA returns { result: { ... } }
311700
+ return body?.result;
311701
+ }
311702
+ finally {
311703
+ clearTimeout(timer);
311704
+ }
311705
+ }
311706
+ async shutdown() {
311707
+ // No persistent connections to close
311708
+ }
311709
+ }
311710
+ exports.OpaHttpEvaluator = OpaHttpEvaluator;
311711
+
311712
+
311713
+ /***/ }),
311714
+
311715
+ /***/ 39530:
311716
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
311717
+
311718
+ "use strict";
311719
+
311720
+ /**
311721
+ * Copyright (c) ProbeLabs. All rights reserved.
311722
+ * Licensed under the Elastic License 2.0; you may not use this file except
311723
+ * in compliance with the Elastic License 2.0.
311724
+ */
311725
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
311726
+ exports.OpaPolicyEngine = void 0;
311727
+ const opa_wasm_evaluator_1 = __nccwpck_require__(8613);
311728
+ const opa_http_evaluator_1 = __nccwpck_require__(44693);
311729
+ const policy_input_builder_1 = __nccwpck_require__(17117);
311730
+ /**
311731
+ * Enterprise OPA Policy Engine.
311732
+ *
311733
+ * Wraps both WASM (local) and HTTP (remote) OPA evaluators behind the
311734
+ * OSS PolicyEngine interface. All OPA input building and role resolution
311735
+ * is handled internally — the OSS call sites pass only plain types.
311736
+ */
311737
+ class OpaPolicyEngine {
311738
+ evaluator = null;
311739
+ fallback;
311740
+ timeout;
311741
+ config;
311742
+ inputBuilder = null;
311743
+ logger = null;
311744
+ constructor(config) {
311745
+ this.config = config;
311746
+ this.fallback = config.fallback || 'deny';
311747
+ this.timeout = config.timeout || 5000;
311748
+ }
311749
+ async initialize(config) {
311750
+ // Resolve logger once at initialization
311751
+ try {
311752
+ this.logger = (__nccwpck_require__(86999).logger);
311753
+ }
311754
+ catch {
311755
+ // logger not available in this context
311756
+ }
311757
+ // Build actor/repo context from environment (available at engine init time)
311758
+ const actor = {
311759
+ authorAssociation: process.env.VISOR_AUTHOR_ASSOCIATION,
311760
+ login: process.env.VISOR_AUTHOR_LOGIN || process.env.GITHUB_ACTOR,
311761
+ isLocalMode: !process.env.GITHUB_ACTIONS,
311762
+ };
311763
+ const repo = {
311764
+ owner: process.env.GITHUB_REPOSITORY_OWNER,
311765
+ name: process.env.GITHUB_REPOSITORY?.split('/')[1],
311766
+ branch: process.env.GITHUB_HEAD_REF,
311767
+ baseBranch: process.env.GITHUB_BASE_REF,
311768
+ event: process.env.GITHUB_EVENT_NAME,
311769
+ };
311770
+ const prNum = process.env.GITHUB_PR_NUMBER
311771
+ ? parseInt(process.env.GITHUB_PR_NUMBER, 10)
311772
+ : undefined;
311773
+ const pullRequest = {
311774
+ number: prNum !== undefined && Number.isFinite(prNum) ? prNum : undefined,
311775
+ };
311776
+ this.inputBuilder = new policy_input_builder_1.PolicyInputBuilder(config, actor, repo, pullRequest);
311777
+ if (config.engine === 'local') {
311778
+ if (!config.rules) {
311779
+ throw new Error('OPA local mode requires `policy.rules` path to .wasm or .rego files');
311780
+ }
311781
+ const wasm = new opa_wasm_evaluator_1.OpaWasmEvaluator();
311782
+ await wasm.initialize(config.rules);
311783
+ if (config.data) {
311784
+ wasm.loadData(config.data);
311785
+ }
311786
+ this.evaluator = wasm;
311787
+ }
311788
+ else if (config.engine === 'remote') {
311789
+ if (!config.url) {
311790
+ throw new Error('OPA remote mode requires `policy.url` pointing to OPA server');
311791
+ }
311792
+ this.evaluator = new opa_http_evaluator_1.OpaHttpEvaluator(config.url, this.timeout);
311793
+ }
311794
+ else {
311795
+ this.evaluator = null;
311796
+ }
311797
+ }
311798
+ /**
311799
+ * Update actor/repo/PR context (e.g., after PR info becomes available).
311800
+ * Called by the enterprise loader when engine context is enriched.
311801
+ */
311802
+ setActorContext(actor, repo, pullRequest) {
311803
+ this.inputBuilder = new policy_input_builder_1.PolicyInputBuilder(this.config, actor, repo, pullRequest);
311804
+ }
311805
+ async evaluateCheckExecution(checkId, checkConfig) {
311806
+ if (!this.evaluator || !this.inputBuilder)
311807
+ return { allowed: true };
311808
+ const cfg = checkConfig && typeof checkConfig === 'object'
311809
+ ? checkConfig
311810
+ : {};
311811
+ const policyOverride = cfg.policy;
311812
+ const input = this.inputBuilder.forCheckExecution({
311813
+ id: checkId,
311814
+ type: cfg.type || 'ai',
311815
+ group: cfg.group,
311816
+ tags: cfg.tags,
311817
+ criticality: cfg.criticality,
311818
+ sandbox: cfg.sandbox,
311819
+ policy: policyOverride,
311820
+ });
311821
+ return this.doEvaluate(input, this.resolveRulePath('check.execute', policyOverride?.rule));
311822
+ }
311823
+ async evaluateToolInvocation(serverName, methodName, transport) {
311824
+ if (!this.evaluator || !this.inputBuilder)
311825
+ return { allowed: true };
311826
+ const input = this.inputBuilder.forToolInvocation(serverName, methodName, transport);
311827
+ return this.doEvaluate(input, 'visor/tool/invoke');
311828
+ }
311829
+ async evaluateCapabilities(checkId, capabilities) {
311830
+ if (!this.evaluator || !this.inputBuilder)
311831
+ return { allowed: true };
311832
+ const input = this.inputBuilder.forCapabilityResolve(checkId, capabilities);
311833
+ return this.doEvaluate(input, 'visor/capability/resolve');
311834
+ }
311835
+ async shutdown() {
311836
+ if (this.evaluator && 'shutdown' in this.evaluator) {
311837
+ await this.evaluator.shutdown();
311838
+ }
311839
+ this.evaluator = null;
311840
+ this.inputBuilder = null;
311841
+ }
311842
+ resolveRulePath(defaultScope, override) {
311843
+ if (override) {
311844
+ return override.startsWith('visor/') ? override : `visor/${override}`;
311845
+ }
311846
+ return `visor/${defaultScope.replace(/\./g, '/')}`;
311847
+ }
311848
+ async doEvaluate(input, rulePath) {
311849
+ try {
311850
+ this.logger?.debug(`[PolicyEngine] Evaluating ${rulePath}`, JSON.stringify(input));
311851
+ let timer;
311852
+ const timeoutPromise = new Promise((_resolve, reject) => {
311853
+ timer = setTimeout(() => reject(new Error('policy evaluation timeout')), this.timeout);
311854
+ });
311855
+ try {
311856
+ const result = await Promise.race([this.rawEvaluate(input, rulePath), timeoutPromise]);
311857
+ const decision = this.parseDecision(result);
311858
+ // In warn mode, override denied decisions to allowed but flag as warn
311859
+ if (!decision.allowed && this.fallback === 'warn') {
311860
+ decision.allowed = true;
311861
+ decision.warn = true;
311862
+ decision.reason = `audit: ${decision.reason || 'policy denied'}`;
311863
+ }
311864
+ this.logger?.debug(`[PolicyEngine] Decision for ${rulePath}: allowed=${decision.allowed}, warn=${decision.warn || false}, reason=${decision.reason || 'none'}`);
311865
+ return decision;
311866
+ }
311867
+ finally {
311868
+ if (timer)
311869
+ clearTimeout(timer);
311870
+ }
311871
+ }
311872
+ catch (err) {
311873
+ const msg = err instanceof Error ? err.message : String(err);
311874
+ this.logger?.warn(`[PolicyEngine] Evaluation failed for ${rulePath}: ${msg}`);
311875
+ return {
311876
+ allowed: this.fallback === 'allow' || this.fallback === 'warn',
311877
+ warn: this.fallback === 'warn' ? true : undefined,
311878
+ reason: `policy evaluation failed, fallback=${this.fallback}`,
311879
+ };
311880
+ }
311881
+ }
311882
+ async rawEvaluate(input, rulePath) {
311883
+ if (this.evaluator instanceof opa_wasm_evaluator_1.OpaWasmEvaluator) {
311884
+ const result = await this.evaluator.evaluate(input);
311885
+ // WASM compiled with `-e visor` entrypoint returns the full visor package tree.
311886
+ // Navigate to the specific rule subtree using rulePath segments.
311887
+ // e.g., 'visor/check/execute' → result.check.execute
311888
+ return this.navigateWasmResult(result, rulePath);
311889
+ }
311890
+ return this.evaluator.evaluate(input, rulePath);
311891
+ }
311892
+ /**
311893
+ * Navigate nested OPA WASM result tree to reach the specific rule's output.
311894
+ * The WASM entrypoint `-e visor` means the result root IS the visor package,
311895
+ * so we strip the `visor/` prefix and walk the remaining segments.
311896
+ */
311897
+ navigateWasmResult(result, rulePath) {
311898
+ if (!result || typeof result !== 'object')
311899
+ return result;
311900
+ // Strip the 'visor/' prefix (matches our compilation entrypoint)
311901
+ const segments = rulePath.replace(/^visor\//, '').split('/');
311902
+ let current = result;
311903
+ for (const seg of segments) {
311904
+ if (current && typeof current === 'object' && seg in current) {
311905
+ current = current[seg];
311906
+ }
311907
+ else {
311908
+ return undefined; // path not found in result tree
311909
+ }
311910
+ }
311911
+ return current;
311912
+ }
311913
+ parseDecision(result) {
311914
+ if (result === undefined || result === null) {
311915
+ return {
311916
+ allowed: this.fallback === 'allow' || this.fallback === 'warn',
311917
+ warn: this.fallback === 'warn' ? true : undefined,
311918
+ reason: this.fallback === 'warn' ? 'audit: no policy result' : 'no policy result',
311919
+ };
311920
+ }
311921
+ const allowed = result.allowed !== false;
311922
+ const decision = {
311923
+ allowed,
311924
+ reason: result.reason,
311925
+ };
311926
+ if (result.capabilities) {
311927
+ decision.capabilities = result.capabilities;
311928
+ }
311929
+ return decision;
311930
+ }
311931
+ }
311932
+ exports.OpaPolicyEngine = OpaPolicyEngine;
311933
+
311934
+
311935
+ /***/ }),
311936
+
311937
+ /***/ 8613:
311938
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
311939
+
311940
+ "use strict";
311941
+
311942
+ /**
311943
+ * Copyright (c) ProbeLabs. All rights reserved.
311944
+ * Licensed under the Elastic License 2.0; you may not use this file except
311945
+ * in compliance with the Elastic License 2.0.
311946
+ */
311947
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
311948
+ if (k2 === undefined) k2 = k;
311949
+ var desc = Object.getOwnPropertyDescriptor(m, k);
311950
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
311951
+ desc = { enumerable: true, get: function() { return m[k]; } };
311952
+ }
311953
+ Object.defineProperty(o, k2, desc);
311954
+ }) : (function(o, m, k, k2) {
311955
+ if (k2 === undefined) k2 = k;
311956
+ o[k2] = m[k];
311957
+ }));
311958
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
311959
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
311960
+ }) : function(o, v) {
311961
+ o["default"] = v;
311962
+ });
311963
+ var __importStar = (this && this.__importStar) || (function () {
311964
+ var ownKeys = function(o) {
311965
+ ownKeys = Object.getOwnPropertyNames || function (o) {
311966
+ var ar = [];
311967
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
311968
+ return ar;
311969
+ };
311970
+ return ownKeys(o);
311971
+ };
311972
+ return function (mod) {
311973
+ if (mod && mod.__esModule) return mod;
311974
+ var result = {};
311975
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
311976
+ __setModuleDefault(result, mod);
311977
+ return result;
311978
+ };
311979
+ })();
311980
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
311981
+ exports.OpaWasmEvaluator = void 0;
311982
+ const fs = __importStar(__nccwpck_require__(79896));
311983
+ const path = __importStar(__nccwpck_require__(16928));
311984
+ const opa_compiler_1 = __nccwpck_require__(628);
311985
+ /**
311986
+ * OPA WASM Evaluator - loads and evaluates OPA policies locally.
311987
+ *
311988
+ * Supports three input formats:
311989
+ * 1. Pre-compiled `.wasm` bundle — loaded directly (fastest startup)
311990
+ * 2. `.rego` files or directory — auto-compiled to WASM via `opa build` CLI
311991
+ * 3. Directory with `policy.wasm` inside — loaded directly
311992
+ *
311993
+ * Compilation and caching of .rego files is delegated to {@link OpaCompiler}.
311994
+ *
311995
+ * Requires:
311996
+ * - `@open-policy-agent/opa-wasm` npm package (optional dep)
311997
+ * - `opa` CLI on PATH (only when auto-compiling .rego files)
311998
+ */
311999
+ class OpaWasmEvaluator {
312000
+ policy = null;
312001
+ dataDocument = {};
312002
+ compiler = new opa_compiler_1.OpaCompiler();
312003
+ async initialize(rulesPath) {
312004
+ const paths = Array.isArray(rulesPath) ? rulesPath : [rulesPath];
312005
+ const wasmBytes = await this.compiler.resolveWasmBytes(paths);
312006
+ try {
312007
+ // Use createRequire to load the optional dep at runtime without ncc bundling it.
312008
+ // `new Function('id', 'return require(id)')` fails in ncc bundles because
312009
+ // `require` is not in the `new Function` scope. `createRequire` works correctly
312010
+ // because it creates a real Node.js require rooted at the given path.
312011
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
312012
+ const { createRequire } = __nccwpck_require__(73339);
312013
+ const runtimeRequire = createRequire(__filename);
312014
+ const opaWasm = runtimeRequire('@open-policy-agent/opa-wasm');
312015
+ const loadPolicy = opaWasm.loadPolicy || opaWasm.default?.loadPolicy;
312016
+ if (!loadPolicy) {
312017
+ throw new Error('loadPolicy not found in @open-policy-agent/opa-wasm');
312018
+ }
312019
+ this.policy = await loadPolicy(wasmBytes);
312020
+ }
312021
+ catch (err) {
312022
+ if (err?.code === 'MODULE_NOT_FOUND' || err?.code === 'ERR_MODULE_NOT_FOUND') {
312023
+ throw new Error('OPA WASM evaluator requires @open-policy-agent/opa-wasm. ' +
312024
+ 'Install it with: npm install @open-policy-agent/opa-wasm');
312025
+ }
312026
+ throw err;
312027
+ }
312028
+ }
312029
+ /**
312030
+ * Load external data from a JSON file to use as the OPA data document.
312031
+ * The loaded data will be passed to `policy.setData()` during evaluation,
312032
+ * making it available in Rego via `data.<key>`.
312033
+ */
312034
+ loadData(dataPath) {
312035
+ const resolved = path.resolve(dataPath);
312036
+ if (path.normalize(resolved).includes('..')) {
312037
+ throw new Error(`Data path contains traversal sequences: ${dataPath}`);
312038
+ }
312039
+ if (!fs.existsSync(resolved)) {
312040
+ throw new Error(`OPA data file not found: ${resolved}`);
312041
+ }
312042
+ const stat = fs.statSync(resolved);
312043
+ if (stat.size > 10 * 1024 * 1024) {
312044
+ throw new Error(`OPA data file exceeds 10MB limit: ${resolved} (${stat.size} bytes)`);
312045
+ }
312046
+ const raw = fs.readFileSync(resolved, 'utf-8');
312047
+ try {
312048
+ const parsed = JSON.parse(raw);
312049
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
312050
+ throw new Error('OPA data file must contain a JSON object (not an array or primitive)');
312051
+ }
312052
+ this.dataDocument = parsed;
312053
+ }
312054
+ catch (err) {
312055
+ if (err.message.startsWith('OPA data file must')) {
312056
+ throw err;
312057
+ }
312058
+ throw new Error(`Failed to parse OPA data file ${resolved}: ${err.message}`);
312059
+ }
312060
+ }
312061
+ async evaluate(input) {
312062
+ if (!this.policy) {
312063
+ throw new Error('OPA WASM evaluator not initialized');
312064
+ }
312065
+ this.policy.setData(this.dataDocument);
312066
+ const resultSet = this.policy.evaluate(input);
312067
+ if (Array.isArray(resultSet) && resultSet.length > 0) {
312068
+ return resultSet[0].result;
312069
+ }
312070
+ return undefined;
312071
+ }
312072
+ async shutdown() {
312073
+ if (this.policy) {
312074
+ // opa-wasm policy objects may have a close/free method for WASM cleanup
312075
+ if (typeof this.policy.close === 'function') {
312076
+ try {
312077
+ this.policy.close();
312078
+ }
312079
+ catch { }
312080
+ }
312081
+ else if (typeof this.policy.free === 'function') {
312082
+ try {
312083
+ this.policy.free();
312084
+ }
312085
+ catch { }
312086
+ }
312087
+ }
312088
+ this.policy = null;
312089
+ }
312090
+ }
312091
+ exports.OpaWasmEvaluator = OpaWasmEvaluator;
312092
+
312093
+
312094
+ /***/ }),
312095
+
312096
+ /***/ 17117:
312097
+ /***/ ((__unused_webpack_module, exports) => {
312098
+
312099
+ "use strict";
312100
+
312101
+ /**
312102
+ * Copyright (c) ProbeLabs. All rights reserved.
312103
+ * Licensed under the Elastic License 2.0; you may not use this file except
312104
+ * in compliance with the Elastic License 2.0.
312105
+ */
312106
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
312107
+ exports.PolicyInputBuilder = void 0;
312108
+ /**
312109
+ * Builds OPA-compatible input documents from engine context.
312110
+ *
312111
+ * Resolves actor roles from the `policy.roles` config section by matching
312112
+ * the actor's authorAssociation and login against role definitions.
312113
+ */
312114
+ class PolicyInputBuilder {
312115
+ roles;
312116
+ actor;
312117
+ repository;
312118
+ pullRequest;
312119
+ constructor(policyConfig, actor, repository, pullRequest) {
312120
+ this.roles = policyConfig.roles || {};
312121
+ this.actor = actor;
312122
+ this.repository = repository;
312123
+ this.pullRequest = pullRequest;
312124
+ }
312125
+ /** Resolve which roles apply to the current actor. */
312126
+ resolveRoles() {
312127
+ const matched = [];
312128
+ for (const [roleName, roleConfig] of Object.entries(this.roles)) {
312129
+ let identityMatch = false;
312130
+ if (roleConfig.author_association &&
312131
+ this.actor.authorAssociation &&
312132
+ roleConfig.author_association.includes(this.actor.authorAssociation)) {
312133
+ identityMatch = true;
312134
+ }
312135
+ if (!identityMatch &&
312136
+ roleConfig.users &&
312137
+ this.actor.login &&
312138
+ roleConfig.users.includes(this.actor.login)) {
312139
+ identityMatch = true;
312140
+ }
312141
+ // Slack user ID match
312142
+ if (!identityMatch &&
312143
+ roleConfig.slack_users &&
312144
+ this.actor.slack?.userId &&
312145
+ roleConfig.slack_users.includes(this.actor.slack.userId)) {
312146
+ identityMatch = true;
312147
+ }
312148
+ // Email match (case-insensitive)
312149
+ if (!identityMatch && roleConfig.emails && this.actor.slack?.email) {
312150
+ const actorEmail = this.actor.slack.email.toLowerCase();
312151
+ if (roleConfig.emails.some(e => e.toLowerCase() === actorEmail)) {
312152
+ identityMatch = true;
312153
+ }
312154
+ }
312155
+ // Note: teams-based role resolution requires GitHub API access (read:org scope)
312156
+ // and is not yet implemented. If configured, the role will not match via teams.
312157
+ if (!identityMatch)
312158
+ continue;
312159
+ // slack_channels gate: if set, the role only applies when triggered from one of these channels
312160
+ if (roleConfig.slack_channels && roleConfig.slack_channels.length > 0) {
312161
+ if (!this.actor.slack?.channelId ||
312162
+ !roleConfig.slack_channels.includes(this.actor.slack.channelId)) {
312163
+ continue;
312164
+ }
312165
+ }
312166
+ matched.push(roleName);
312167
+ }
312168
+ return matched;
312169
+ }
312170
+ buildActor() {
312171
+ return {
312172
+ authorAssociation: this.actor.authorAssociation,
312173
+ login: this.actor.login,
312174
+ roles: this.resolveRoles(),
312175
+ isLocalMode: this.actor.isLocalMode,
312176
+ ...(this.actor.slack && { slack: this.actor.slack }),
312177
+ };
312178
+ }
312179
+ forCheckExecution(check) {
312180
+ return {
312181
+ scope: 'check.execute',
312182
+ check: {
312183
+ id: check.id,
312184
+ type: check.type,
312185
+ group: check.group,
312186
+ tags: check.tags,
312187
+ criticality: check.criticality,
312188
+ sandbox: check.sandbox,
312189
+ policy: check.policy,
312190
+ },
312191
+ actor: this.buildActor(),
312192
+ repository: this.repository,
312193
+ pullRequest: this.pullRequest,
312194
+ };
312195
+ }
312196
+ forToolInvocation(serverName, methodName, transport) {
312197
+ return {
312198
+ scope: 'tool.invoke',
312199
+ tool: { serverName, methodName, transport },
312200
+ actor: this.buildActor(),
312201
+ repository: this.repository,
312202
+ pullRequest: this.pullRequest,
312203
+ };
312204
+ }
312205
+ forCapabilityResolve(checkId, capabilities) {
312206
+ return {
312207
+ scope: 'capability.resolve',
312208
+ check: { id: checkId, type: 'ai' },
312209
+ capability: capabilities,
312210
+ actor: this.buildActor(),
312211
+ repository: this.repository,
312212
+ pullRequest: this.pullRequest,
312213
+ };
312214
+ }
312215
+ }
312216
+ exports.PolicyInputBuilder = PolicyInputBuilder;
312217
+
312218
+
312219
+ /***/ }),
312220
+
312221
+ /***/ 63737:
312222
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
312223
+
312224
+ "use strict";
312225
+
312226
+ /**
312227
+ * Copyright (c) ProbeLabs. All rights reserved.
312228
+ * Licensed under the Elastic License 2.0; you may not use this file except
312229
+ * in compliance with the Elastic License 2.0.
312230
+ */
312231
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
312232
+ if (k2 === undefined) k2 = k;
312233
+ var desc = Object.getOwnPropertyDescriptor(m, k);
312234
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
312235
+ desc = { enumerable: true, get: function() { return m[k]; } };
312236
+ }
312237
+ Object.defineProperty(o, k2, desc);
312238
+ }) : (function(o, m, k, k2) {
312239
+ if (k2 === undefined) k2 = k;
312240
+ o[k2] = m[k];
312241
+ }));
312242
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
312243
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
312244
+ }) : function(o, v) {
312245
+ o["default"] = v;
312246
+ });
312247
+ var __importStar = (this && this.__importStar) || (function () {
312248
+ var ownKeys = function(o) {
312249
+ ownKeys = Object.getOwnPropertyNames || function (o) {
312250
+ var ar = [];
312251
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
312252
+ return ar;
312253
+ };
312254
+ return ownKeys(o);
312255
+ };
312256
+ return function (mod) {
312257
+ if (mod && mod.__esModule) return mod;
312258
+ var result = {};
312259
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
312260
+ __setModuleDefault(result, mod);
312261
+ return result;
312262
+ };
312263
+ })();
312264
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
312265
+ exports.KnexStoreBackend = void 0;
312266
+ /**
312267
+ * Knex-backed schedule store for PostgreSQL, MySQL, and MSSQL (Enterprise)
312268
+ *
312269
+ * Uses Knex query builder for database-agnostic SQL. Same schema as SQLite backend
312270
+ * but with real distributed locking via row-level claims (claimed_by/claimed_at/lock_token).
312271
+ */
312272
+ const fs = __importStar(__nccwpck_require__(79896));
312273
+ const path = __importStar(__nccwpck_require__(16928));
312274
+ const uuid_1 = __nccwpck_require__(31914);
312275
+ const logger_1 = __nccwpck_require__(86999);
312276
+ function toNum(val) {
312277
+ if (val === null || val === undefined)
312278
+ return undefined;
312279
+ return typeof val === 'string' ? parseInt(val, 10) : val;
312280
+ }
312281
+ function safeJsonParse(value) {
312282
+ if (!value)
312283
+ return undefined;
312284
+ try {
312285
+ return JSON.parse(value);
312286
+ }
312287
+ catch {
312288
+ return undefined;
312289
+ }
312290
+ }
312291
+ function fromTriggerRow(row) {
312292
+ return {
312293
+ id: row.id,
312294
+ creatorId: row.creator_id,
312295
+ creatorContext: row.creator_context ?? undefined,
312296
+ creatorName: row.creator_name ?? undefined,
312297
+ description: row.description ?? undefined,
312298
+ channels: safeJsonParse(row.channels),
312299
+ fromUsers: safeJsonParse(row.from_users),
312300
+ fromBots: row.from_bots === true || row.from_bots === 1,
312301
+ contains: safeJsonParse(row.contains),
312302
+ matchPattern: row.match_pattern ?? undefined,
312303
+ threads: row.threads,
312304
+ workflow: row.workflow,
312305
+ inputs: safeJsonParse(row.inputs),
312306
+ outputContext: safeJsonParse(row.output_context),
312307
+ status: row.status,
312308
+ enabled: row.enabled === true || row.enabled === 1,
312309
+ createdAt: toNum(row.created_at),
312310
+ };
312311
+ }
312312
+ function toTriggerInsertRow(trigger) {
312313
+ return {
312314
+ id: trigger.id,
312315
+ creator_id: trigger.creatorId,
312316
+ creator_context: trigger.creatorContext ?? null,
312317
+ creator_name: trigger.creatorName ?? null,
312318
+ description: trigger.description ?? null,
312319
+ channels: trigger.channels ? JSON.stringify(trigger.channels) : null,
312320
+ from_users: trigger.fromUsers ? JSON.stringify(trigger.fromUsers) : null,
312321
+ from_bots: trigger.fromBots,
312322
+ contains: trigger.contains ? JSON.stringify(trigger.contains) : null,
312323
+ match_pattern: trigger.matchPattern ?? null,
312324
+ threads: trigger.threads,
312325
+ workflow: trigger.workflow,
312326
+ inputs: trigger.inputs ? JSON.stringify(trigger.inputs) : null,
312327
+ output_context: trigger.outputContext ? JSON.stringify(trigger.outputContext) : null,
312328
+ status: trigger.status,
312329
+ enabled: trigger.enabled,
312330
+ created_at: trigger.createdAt,
312331
+ };
312332
+ }
312333
+ function fromDbRow(row) {
312334
+ return {
312335
+ id: row.id,
312336
+ creatorId: row.creator_id,
312337
+ creatorContext: row.creator_context ?? undefined,
312338
+ creatorName: row.creator_name ?? undefined,
312339
+ timezone: row.timezone,
312340
+ schedule: row.schedule_expr,
312341
+ runAt: toNum(row.run_at),
312342
+ isRecurring: row.is_recurring === true || row.is_recurring === 1,
312343
+ originalExpression: row.original_expression,
312344
+ workflow: row.workflow ?? undefined,
312345
+ workflowInputs: safeJsonParse(row.workflow_inputs),
312346
+ outputContext: safeJsonParse(row.output_context),
312347
+ status: row.status,
312348
+ createdAt: toNum(row.created_at),
312349
+ lastRunAt: toNum(row.last_run_at),
312350
+ nextRunAt: toNum(row.next_run_at),
312351
+ runCount: row.run_count,
312352
+ failureCount: row.failure_count,
312353
+ lastError: row.last_error ?? undefined,
312354
+ previousResponse: row.previous_response ?? undefined,
312355
+ };
312356
+ }
312357
+ function toInsertRow(schedule) {
312358
+ return {
312359
+ id: schedule.id,
312360
+ creator_id: schedule.creatorId,
312361
+ creator_context: schedule.creatorContext ?? null,
312362
+ creator_name: schedule.creatorName ?? null,
312363
+ timezone: schedule.timezone,
312364
+ schedule_expr: schedule.schedule,
312365
+ run_at: schedule.runAt ?? null,
312366
+ is_recurring: schedule.isRecurring,
312367
+ original_expression: schedule.originalExpression,
312368
+ workflow: schedule.workflow ?? null,
312369
+ workflow_inputs: schedule.workflowInputs ? JSON.stringify(schedule.workflowInputs) : null,
312370
+ output_context: schedule.outputContext ? JSON.stringify(schedule.outputContext) : null,
312371
+ status: schedule.status,
312372
+ created_at: schedule.createdAt,
312373
+ last_run_at: schedule.lastRunAt ?? null,
312374
+ next_run_at: schedule.nextRunAt ?? null,
312375
+ run_count: schedule.runCount,
312376
+ failure_count: schedule.failureCount,
312377
+ last_error: schedule.lastError ?? null,
312378
+ previous_response: schedule.previousResponse ?? null,
312379
+ };
312380
+ }
312381
+ /**
312382
+ * Enterprise Knex-backed store for PostgreSQL, MySQL, and MSSQL
312383
+ */
312384
+ class KnexStoreBackend {
312385
+ knex = null;
312386
+ driver;
312387
+ connection;
312388
+ constructor(driver, storageConfig, _haConfig) {
312389
+ this.driver = driver;
312390
+ this.connection = (storageConfig.connection || {});
312391
+ }
312392
+ async initialize() {
312393
+ // Load knex dynamically
312394
+ const { createRequire } = __nccwpck_require__(73339);
312395
+ const runtimeRequire = createRequire(__filename);
312396
+ let knexFactory;
312397
+ try {
312398
+ knexFactory = runtimeRequire('knex');
312399
+ }
312400
+ catch (err) {
312401
+ const code = err?.code;
312402
+ if (code === 'MODULE_NOT_FOUND' || code === 'ERR_MODULE_NOT_FOUND') {
312403
+ throw new Error('knex is required for PostgreSQL/MySQL/MSSQL schedule storage. ' +
312404
+ 'Install it with: npm install knex');
312405
+ }
312406
+ throw err;
312407
+ }
312408
+ const clientMap = {
312409
+ postgresql: 'pg',
312410
+ mysql: 'mysql2',
312411
+ mssql: 'tedious',
312412
+ };
312413
+ const client = clientMap[this.driver];
312414
+ // Build connection config
312415
+ let connection;
312416
+ if (this.connection.connection_string) {
312417
+ connection = this.connection.connection_string;
312418
+ }
312419
+ else if (this.driver === 'mssql') {
312420
+ connection = this.buildMssqlConnection();
312421
+ }
312422
+ else {
312423
+ connection = this.buildStandardConnection();
312424
+ }
312425
+ this.knex = knexFactory({
312426
+ client,
312427
+ connection,
312428
+ pool: {
312429
+ min: this.connection.pool?.min ?? 0,
312430
+ max: this.connection.pool?.max ?? 10,
312431
+ },
312432
+ });
312433
+ // Run schema migration
312434
+ await this.migrateSchema();
312435
+ logger_1.logger.info(`[KnexStore] Initialized (${this.driver})`);
312436
+ }
312437
+ buildStandardConnection() {
312438
+ return {
312439
+ host: this.connection.host || 'localhost',
312440
+ port: this.connection.port,
312441
+ database: this.connection.database || 'visor',
312442
+ user: this.connection.user,
312443
+ password: this.connection.password,
312444
+ ssl: this.resolveSslConfig(),
312445
+ };
312446
+ }
312447
+ buildMssqlConnection() {
312448
+ const ssl = this.connection.ssl;
312449
+ const sslEnabled = ssl === true || (typeof ssl === 'object' && ssl.enabled !== false);
312450
+ return {
312451
+ server: this.connection.host || 'localhost',
312452
+ port: this.connection.port,
312453
+ database: this.connection.database || 'visor',
312454
+ user: this.connection.user,
312455
+ password: this.connection.password,
312456
+ options: {
312457
+ encrypt: sslEnabled,
312458
+ trustServerCertificate: typeof ssl === 'object' ? ssl.reject_unauthorized === false : !sslEnabled,
312459
+ },
312460
+ };
312461
+ }
312462
+ resolveSslConfig() {
312463
+ const ssl = this.connection.ssl;
312464
+ if (ssl === false || ssl === undefined)
312465
+ return false;
312466
+ if (ssl === true)
312467
+ return { rejectUnauthorized: true };
312468
+ // Object config
312469
+ if (ssl.enabled === false)
312470
+ return false;
312471
+ const result = {
312472
+ rejectUnauthorized: ssl.reject_unauthorized !== false,
312473
+ };
312474
+ if (ssl.ca) {
312475
+ const caPath = this.validateSslPath(ssl.ca, 'CA certificate');
312476
+ result.ca = fs.readFileSync(caPath, 'utf8');
312477
+ }
312478
+ if (ssl.cert) {
312479
+ const certPath = this.validateSslPath(ssl.cert, 'client certificate');
312480
+ result.cert = fs.readFileSync(certPath, 'utf8');
312481
+ }
312482
+ if (ssl.key) {
312483
+ const keyPath = this.validateSslPath(ssl.key, 'client key');
312484
+ result.key = fs.readFileSync(keyPath, 'utf8');
312485
+ }
312486
+ return result;
312487
+ }
312488
+ validateSslPath(filePath, label) {
312489
+ const resolved = path.resolve(filePath);
312490
+ if (resolved !== path.normalize(resolved)) {
312491
+ throw new Error(`SSL ${label} path contains invalid sequences: ${filePath}`);
312492
+ }
312493
+ if (!fs.existsSync(resolved)) {
312494
+ throw new Error(`SSL ${label} not found: ${filePath}`);
312495
+ }
312496
+ return resolved;
312497
+ }
312498
+ async shutdown() {
312499
+ if (this.knex) {
312500
+ await this.knex.destroy();
312501
+ this.knex = null;
312502
+ }
312503
+ }
312504
+ async migrateSchema() {
312505
+ const knex = this.getKnex();
312506
+ const exists = await knex.schema.hasTable('schedules');
312507
+ if (!exists) {
312508
+ await knex.schema.createTable('schedules', table => {
312509
+ table.string('id', 36).primary();
312510
+ table.string('creator_id', 255).notNullable().index();
312511
+ table.string('creator_context', 255);
312512
+ table.string('creator_name', 255);
312513
+ table.string('timezone', 64).notNullable().defaultTo('UTC');
312514
+ table.string('schedule_expr', 255);
312515
+ table.bigInteger('run_at');
312516
+ table.boolean('is_recurring').notNullable();
312517
+ table.text('original_expression');
312518
+ table.string('workflow', 255);
312519
+ table.text('workflow_inputs');
312520
+ table.text('output_context');
312521
+ table.string('status', 20).notNullable().index();
312522
+ table.bigInteger('created_at').notNullable();
312523
+ table.bigInteger('last_run_at');
312524
+ table.bigInteger('next_run_at');
312525
+ table.integer('run_count').notNullable().defaultTo(0);
312526
+ table.integer('failure_count').notNullable().defaultTo(0);
312527
+ table.text('last_error');
312528
+ table.text('previous_response');
312529
+ table.index(['status', 'next_run_at']);
312530
+ });
312531
+ }
312532
+ // Create message_triggers table
312533
+ const triggersExist = await knex.schema.hasTable('message_triggers');
312534
+ if (!triggersExist) {
312535
+ await knex.schema.createTable('message_triggers', table => {
312536
+ table.string('id', 36).primary();
312537
+ table.string('creator_id', 255).notNullable().index();
312538
+ table.string('creator_context', 255);
312539
+ table.string('creator_name', 255);
312540
+ table.text('description');
312541
+ table.text('channels'); // JSON array
312542
+ table.text('from_users'); // JSON array
312543
+ table.boolean('from_bots').notNullable().defaultTo(false);
312544
+ table.text('contains'); // JSON array
312545
+ table.text('match_pattern');
312546
+ table.string('threads', 20).notNullable().defaultTo('any');
312547
+ table.string('workflow', 255).notNullable();
312548
+ table.text('inputs'); // JSON
312549
+ table.text('output_context'); // JSON
312550
+ table.string('status', 20).notNullable().defaultTo('active').index();
312551
+ table.boolean('enabled').notNullable().defaultTo(true);
312552
+ table.bigInteger('created_at').notNullable();
312553
+ });
312554
+ }
312555
+ // Create scheduler_locks table for distributed locking
312556
+ const locksExist = await knex.schema.hasTable('scheduler_locks');
312557
+ if (!locksExist) {
312558
+ await knex.schema.createTable('scheduler_locks', table => {
312559
+ table.string('lock_id', 255).primary();
312560
+ table.string('node_id', 255).notNullable();
312561
+ table.string('lock_token', 36).notNullable();
312562
+ table.bigInteger('acquired_at').notNullable();
312563
+ table.bigInteger('expires_at').notNullable();
312564
+ });
312565
+ }
312566
+ }
312567
+ getKnex() {
312568
+ if (!this.knex) {
312569
+ throw new Error('[KnexStore] Not initialized. Call initialize() first.');
312570
+ }
312571
+ return this.knex;
312572
+ }
312573
+ // --- CRUD ---
312574
+ async create(schedule) {
312575
+ const knex = this.getKnex();
312576
+ const newSchedule = {
312577
+ ...schedule,
312578
+ id: (0, uuid_1.v4)(),
312579
+ createdAt: Date.now(),
312580
+ runCount: 0,
312581
+ failureCount: 0,
312582
+ status: 'active',
312583
+ };
312584
+ await knex('schedules').insert(toInsertRow(newSchedule));
312585
+ logger_1.logger.info(`[KnexStore] Created schedule ${newSchedule.id} for user ${newSchedule.creatorId}`);
312586
+ return newSchedule;
312587
+ }
312588
+ async importSchedule(schedule) {
312589
+ const knex = this.getKnex();
312590
+ const existing = await knex('schedules').where('id', schedule.id).first();
312591
+ if (existing)
312592
+ return; // Already imported (idempotent)
312593
+ await knex('schedules').insert(toInsertRow(schedule));
312594
+ }
312595
+ async get(id) {
312596
+ const knex = this.getKnex();
312597
+ const row = await knex('schedules').where('id', id).first();
312598
+ return row ? fromDbRow(row) : undefined;
312599
+ }
312600
+ async update(id, patch) {
312601
+ const knex = this.getKnex();
312602
+ const existing = await knex('schedules').where('id', id).first();
312603
+ if (!existing)
312604
+ return undefined;
312605
+ const current = fromDbRow(existing);
312606
+ const updated = { ...current, ...patch, id: current.id };
312607
+ const row = toInsertRow(updated);
312608
+ // Remove id from update (PK cannot change)
312609
+ delete row.id;
312610
+ await knex('schedules').where('id', id).update(row);
312611
+ return updated;
312612
+ }
312613
+ async delete(id) {
312614
+ const knex = this.getKnex();
312615
+ const deleted = await knex('schedules').where('id', id).del();
312616
+ if (deleted > 0) {
312617
+ logger_1.logger.info(`[KnexStore] Deleted schedule ${id}`);
312618
+ return true;
312619
+ }
312620
+ return false;
312621
+ }
312622
+ // --- Queries ---
312623
+ async getByCreator(creatorId) {
312624
+ const knex = this.getKnex();
312625
+ const rows = await knex('schedules').where('creator_id', creatorId);
312626
+ return rows.map((r) => fromDbRow(r));
312627
+ }
312628
+ async getActiveSchedules() {
312629
+ const knex = this.getKnex();
312630
+ const rows = await knex('schedules').where('status', 'active');
312631
+ return rows.map((r) => fromDbRow(r));
312632
+ }
312633
+ async getDueSchedules(now) {
312634
+ const ts = now ?? Date.now();
312635
+ const knex = this.getKnex();
312636
+ // MSSQL uses 1/0 for booleans
312637
+ const bFalse = this.driver === 'mssql' ? 0 : false;
312638
+ const bTrue = this.driver === 'mssql' ? 1 : true;
312639
+ const rows = await knex('schedules')
312640
+ .where('status', 'active')
312641
+ .andWhere(function () {
312642
+ this.where(function () {
312643
+ this.where('is_recurring', bFalse)
312644
+ .whereNotNull('run_at')
312645
+ .where('run_at', '<=', ts);
312646
+ }).orWhere(function () {
312647
+ this.where('is_recurring', bTrue)
312648
+ .whereNotNull('next_run_at')
312649
+ .where('next_run_at', '<=', ts);
312650
+ });
312651
+ });
312652
+ return rows.map((r) => fromDbRow(r));
312653
+ }
312654
+ async findByWorkflow(creatorId, workflowName) {
312655
+ const knex = this.getKnex();
312656
+ const escaped = workflowName.toLowerCase().replace(/[%_\\]/g, '\\$&');
312657
+ const pattern = `%${escaped}%`;
312658
+ const rows = await knex('schedules')
312659
+ .where('creator_id', creatorId)
312660
+ .where('status', 'active')
312661
+ .whereRaw("LOWER(workflow) LIKE ? ESCAPE '\\'", [pattern]);
312662
+ return rows.map((r) => fromDbRow(r));
312663
+ }
312664
+ async getAll() {
312665
+ const knex = this.getKnex();
312666
+ const rows = await knex('schedules');
312667
+ return rows.map((r) => fromDbRow(r));
312668
+ }
312669
+ async getStats() {
312670
+ const knex = this.getKnex();
312671
+ // MSSQL uses 1/0 for booleans; PostgreSQL/MySQL accept both true/1
312672
+ const boolTrue = this.driver === 'mssql' ? '1' : 'true';
312673
+ const boolFalse = this.driver === 'mssql' ? '0' : 'false';
312674
+ const result = await knex('schedules')
312675
+ .select(knex.raw('COUNT(*) as total'), knex.raw("SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active"), knex.raw("SUM(CASE WHEN status = 'paused' THEN 1 ELSE 0 END) as paused"), knex.raw("SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed"), knex.raw("SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed"), knex.raw(`SUM(CASE WHEN is_recurring = ${boolTrue} THEN 1 ELSE 0 END) as recurring`), knex.raw(`SUM(CASE WHEN is_recurring = ${boolFalse} THEN 1 ELSE 0 END) as one_time`))
312676
+ .first();
312677
+ return {
312678
+ total: Number(result.total) || 0,
312679
+ active: Number(result.active) || 0,
312680
+ paused: Number(result.paused) || 0,
312681
+ completed: Number(result.completed) || 0,
312682
+ failed: Number(result.failed) || 0,
312683
+ recurring: Number(result.recurring) || 0,
312684
+ oneTime: Number(result.one_time) || 0,
312685
+ };
312686
+ }
312687
+ async validateLimits(creatorId, isRecurring, limits) {
312688
+ const knex = this.getKnex();
312689
+ if (limits.maxGlobal) {
312690
+ const result = await knex('schedules').count('* as cnt').first();
312691
+ if (Number(result?.cnt) >= limits.maxGlobal) {
312692
+ throw new Error(`Global schedule limit reached (${limits.maxGlobal})`);
312693
+ }
312694
+ }
312695
+ if (limits.maxPerUser) {
312696
+ const result = await knex('schedules')
312697
+ .where('creator_id', creatorId)
312698
+ .count('* as cnt')
312699
+ .first();
312700
+ if (Number(result?.cnt) >= limits.maxPerUser) {
312701
+ throw new Error(`You have reached the maximum number of schedules (${limits.maxPerUser})`);
312702
+ }
312703
+ }
312704
+ if (isRecurring && limits.maxRecurringPerUser) {
312705
+ const bTrue = this.driver === 'mssql' ? 1 : true;
312706
+ const result = await knex('schedules')
312707
+ .where('creator_id', creatorId)
312708
+ .where('is_recurring', bTrue)
312709
+ .count('* as cnt')
312710
+ .first();
312711
+ if (Number(result?.cnt) >= limits.maxRecurringPerUser) {
312712
+ throw new Error(`You have reached the maximum number of recurring schedules (${limits.maxRecurringPerUser})`);
312713
+ }
312714
+ }
312715
+ }
312716
+ // --- HA Distributed Locking (via scheduler_locks table) ---
312717
+ async tryAcquireLock(lockId, nodeId, ttlSeconds) {
312718
+ const knex = this.getKnex();
312719
+ const now = Date.now();
312720
+ const expiresAt = now + ttlSeconds * 1000;
312721
+ const token = (0, uuid_1.v4)();
312722
+ // Step 1: Try to claim an existing expired lock
312723
+ const updated = await knex('scheduler_locks')
312724
+ .where('lock_id', lockId)
312725
+ .where('expires_at', '<', now)
312726
+ .update({
312727
+ node_id: nodeId,
312728
+ lock_token: token,
312729
+ acquired_at: now,
312730
+ expires_at: expiresAt,
312731
+ });
312732
+ if (updated > 0)
312733
+ return token;
312734
+ // Step 2: Try to INSERT a new lock row
312735
+ try {
312736
+ await knex('scheduler_locks').insert({
312737
+ lock_id: lockId,
312738
+ node_id: nodeId,
312739
+ lock_token: token,
312740
+ acquired_at: now,
312741
+ expires_at: expiresAt,
312742
+ });
312743
+ return token;
312744
+ }
312745
+ catch {
312746
+ // Unique constraint violation — another node holds the lock
312747
+ return null;
312748
+ }
312749
+ }
312750
+ async releaseLock(lockId, lockToken) {
312751
+ const knex = this.getKnex();
312752
+ await knex('scheduler_locks').where('lock_id', lockId).where('lock_token', lockToken).del();
312753
+ }
312754
+ async renewLock(lockId, lockToken, ttlSeconds) {
312755
+ const knex = this.getKnex();
312756
+ const now = Date.now();
312757
+ const expiresAt = now + ttlSeconds * 1000;
312758
+ const updated = await knex('scheduler_locks')
312759
+ .where('lock_id', lockId)
312760
+ .where('lock_token', lockToken)
312761
+ .update({ acquired_at: now, expires_at: expiresAt });
312762
+ return updated > 0;
312763
+ }
312764
+ async flush() {
312765
+ // No-op for server-based backends
312766
+ }
312767
+ // --- Message Trigger CRUD ---
312768
+ async createTrigger(trigger) {
312769
+ const knex = this.getKnex();
312770
+ const newTrigger = {
312771
+ ...trigger,
312772
+ id: (0, uuid_1.v4)(),
312773
+ createdAt: Date.now(),
312774
+ };
312775
+ await knex('message_triggers').insert(toTriggerInsertRow(newTrigger));
312776
+ logger_1.logger.info(`[KnexStore] Created trigger ${newTrigger.id} for user ${newTrigger.creatorId}`);
312777
+ return newTrigger;
312778
+ }
312779
+ async getTrigger(id) {
312780
+ const knex = this.getKnex();
312781
+ const row = await knex('message_triggers').where('id', id).first();
312782
+ return row ? fromTriggerRow(row) : undefined;
312783
+ }
312784
+ async updateTrigger(id, patch) {
312785
+ const knex = this.getKnex();
312786
+ const existing = await knex('message_triggers').where('id', id).first();
312787
+ if (!existing)
312788
+ return undefined;
312789
+ const current = fromTriggerRow(existing);
312790
+ const updated = {
312791
+ ...current,
312792
+ ...patch,
312793
+ id: current.id,
312794
+ createdAt: current.createdAt,
312795
+ };
312796
+ const row = toTriggerInsertRow(updated);
312797
+ delete row.id;
312798
+ await knex('message_triggers').where('id', id).update(row);
312799
+ return updated;
312800
+ }
312801
+ async deleteTrigger(id) {
312802
+ const knex = this.getKnex();
312803
+ const deleted = await knex('message_triggers').where('id', id).del();
312804
+ if (deleted > 0) {
312805
+ logger_1.logger.info(`[KnexStore] Deleted trigger ${id}`);
312806
+ return true;
312807
+ }
312808
+ return false;
312809
+ }
312810
+ async getTriggersByCreator(creatorId) {
312811
+ const knex = this.getKnex();
312812
+ const rows = await knex('message_triggers').where('creator_id', creatorId);
312813
+ return rows.map((r) => fromTriggerRow(r));
312814
+ }
312815
+ async getActiveTriggers() {
312816
+ const knex = this.getKnex();
312817
+ const rows = await knex('message_triggers')
312818
+ .where('status', 'active')
312819
+ .where('enabled', this.driver === 'mssql' ? 1 : true);
312820
+ return rows.map((r) => fromTriggerRow(r));
312821
+ }
312822
+ }
312823
+ exports.KnexStoreBackend = KnexStoreBackend;
312824
+
312825
+
311021
312826
  /***/ }),
311022
312827
 
311023
312828
  /***/ 83864:
@@ -314327,7 +316132,7 @@ exports.configSchema = {
314327
316132
  properties: {
314328
316133
  type: {
314329
316134
  type: 'string',
314330
- enum: ['command', 'api', 'workflow'],
316135
+ enum: ['command', 'api', 'workflow', 'http_client'],
314331
316136
  description: "Tool implementation type (defaults to 'command')",
314332
316137
  },
314333
316138
  name: {
@@ -314524,6 +316329,27 @@ exports.configSchema = {
314524
316329
  type: 'number',
314525
316330
  description: 'Alias for requestTimeoutMs (snake_case)',
314526
316331
  },
316332
+ base_url: {
316333
+ type: 'string',
316334
+ description: 'Base URL for HTTP client tools',
316335
+ },
316336
+ auth: {
316337
+ type: 'object',
316338
+ properties: {
316339
+ type: {
316340
+ type: 'string',
316341
+ },
316342
+ token: {
316343
+ type: 'string',
316344
+ },
316345
+ },
316346
+ required: ['type'],
316347
+ additionalProperties: {},
316348
+ description: 'Authentication config for HTTP client tools',
316349
+ patternProperties: {
316350
+ '^x-': {},
316351
+ },
316352
+ },
314527
316353
  workflow: {
314528
316354
  type: 'string',
314529
316355
  description: "Workflow ID (registry lookup) or file path (for type: 'workflow')",
@@ -315063,7 +316889,7 @@ exports.configSchema = {
315063
316889
  description: 'Arguments/inputs for the workflow',
315064
316890
  },
315065
316891
  overrides: {
315066
- $ref: '#/definitions/Record%3Cstring%2CPartial%3Cinterface-src_types_config.ts-14017-28611-src_types_config.ts-0-56833%3E%3E',
316892
+ $ref: '#/definitions/Record%3Cstring%2CPartial%3Cinterface-src_types_config.ts-14017-28611-src_types_config.ts-0-57090%3E%3E',
315067
316893
  description: 'Override specific step configurations in the workflow',
315068
316894
  },
315069
316895
  output_mapping: {
@@ -315079,7 +316905,7 @@ exports.configSchema = {
315079
316905
  description: 'Config file path - alternative to workflow ID (loads a Visor config file as workflow)',
315080
316906
  },
315081
316907
  workflow_overrides: {
315082
- $ref: '#/definitions/Record%3Cstring%2CPartial%3Cinterface-src_types_config.ts-14017-28611-src_types_config.ts-0-56833%3E%3E',
316908
+ $ref: '#/definitions/Record%3Cstring%2CPartial%3Cinterface-src_types_config.ts-14017-28611-src_types_config.ts-0-57090%3E%3E',
315083
316909
  description: 'Alias for overrides - workflow step overrides (backward compatibility)',
315084
316910
  },
315085
316911
  ref: {
@@ -315781,7 +317607,7 @@ exports.configSchema = {
315781
317607
  description: 'Custom output name (defaults to workflow name)',
315782
317608
  },
315783
317609
  overrides: {
315784
- $ref: '#/definitions/Record%3Cstring%2CPartial%3Cinterface-src_types_config.ts-14017-28611-src_types_config.ts-0-56833%3E%3E',
317610
+ $ref: '#/definitions/Record%3Cstring%2CPartial%3Cinterface-src_types_config.ts-14017-28611-src_types_config.ts-0-57090%3E%3E',
315785
317611
  description: 'Step overrides',
315786
317612
  },
315787
317613
  output_mapping: {
@@ -315796,13 +317622,13 @@ exports.configSchema = {
315796
317622
  '^x-': {},
315797
317623
  },
315798
317624
  },
315799
- 'Record<string,Partial<interface-src_types_config.ts-14017-28611-src_types_config.ts-0-56833>>': {
317625
+ 'Record<string,Partial<interface-src_types_config.ts-14017-28611-src_types_config.ts-0-57090>>': {
315800
317626
  type: 'object',
315801
317627
  additionalProperties: {
315802
- $ref: '#/definitions/Partial%3Cinterface-src_types_config.ts-14017-28611-src_types_config.ts-0-56833%3E',
317628
+ $ref: '#/definitions/Partial%3Cinterface-src_types_config.ts-14017-28611-src_types_config.ts-0-57090%3E',
315803
317629
  },
315804
317630
  },
315805
- 'Partial<interface-src_types_config.ts-14017-28611-src_types_config.ts-0-56833>': {
317631
+ 'Partial<interface-src_types_config.ts-14017-28611-src_types_config.ts-0-57090>': {
315806
317632
  type: 'object',
315807
317633
  additionalProperties: false,
315808
317634
  },
@@ -323531,6 +325357,35 @@ class OutputFormatters {
323531
325357
  exports.OutputFormatters = OutputFormatters;
323532
325358
 
323533
325359
 
325360
+ /***/ }),
325361
+
325362
+ /***/ 93866:
325363
+ /***/ ((__unused_webpack_module, exports) => {
325364
+
325365
+ "use strict";
325366
+
325367
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
325368
+ exports.DefaultPolicyEngine = void 0;
325369
+ /**
325370
+ * Default (no-op) policy engine — always allows everything.
325371
+ * Used when no enterprise license is present or policy is disabled.
325372
+ */
325373
+ class DefaultPolicyEngine {
325374
+ async initialize(_config) { }
325375
+ async evaluateCheckExecution(_checkId, _checkConfig) {
325376
+ return { allowed: true };
325377
+ }
325378
+ async evaluateToolInvocation(_serverName, _methodName, _transport) {
325379
+ return { allowed: true };
325380
+ }
325381
+ async evaluateCapabilities(_checkId, _capabilities) {
325382
+ return { allowed: true };
325383
+ }
325384
+ async shutdown() { }
325385
+ }
325386
+ exports.DefaultPolicyEngine = DefaultPolicyEngine;
325387
+
325388
+
323534
325389
  /***/ }),
323535
325390
 
323536
325391
  /***/ 96611:
@@ -325781,12 +327636,14 @@ class AICheckProvider extends check_provider_interface_1.CheckProvider {
325781
327636
  break; // Only support one custom tools server per check
325782
327637
  }
325783
327638
  }
325784
- // Option 4: Extract workflow and tool entries from ai_mcp_servers/ai_mcp_servers_js
327639
+ // Option 4: Extract workflow, tool, and http_client entries from ai_mcp_servers/ai_mcp_servers_js
325785
327640
  // Unified format:
325786
327641
  // { workflow: 'name', inputs: {...} } → workflow tool
325787
327642
  // { tool: 'name' } → custom tool from tools: section or built-in (e.g., 'schedule')
327643
+ // { type: 'http_client', base_url: '...', ... } → HTTP client tool (REST API proxy)
325788
327644
  const workflowEntriesFromMcp = [];
325789
327645
  const toolEntriesFromMcp = [];
327646
+ const httpClientEntriesFromMcp = [];
325790
327647
  const mcpEntriesToRemove = [];
325791
327648
  for (const [serverName, serverConfig] of Object.entries(mcpServers)) {
325792
327649
  const cfg = serverConfig;
@@ -325801,6 +327658,12 @@ class AICheckProvider extends check_provider_interface_1.CheckProvider {
325801
327658
  mcpEntriesToRemove.push(serverName);
325802
327659
  logger_1.logger.debug(`[AICheckProvider] Extracted workflow tool '${serverName}' (workflow=${cfg.workflow}) from ai_mcp_servers`);
325803
327660
  }
327661
+ else if (cfg.type === 'http_client' && (cfg.base_url || cfg.url)) {
327662
+ // HTTP client tool entry — REST API proxy exposed as an MCP tool
327663
+ httpClientEntriesFromMcp.push({ name: serverName, config: cfg });
327664
+ mcpEntriesToRemove.push(serverName);
327665
+ logger_1.logger.debug(`[AICheckProvider] Extracted http_client tool '${serverName}' (base_url=${cfg.base_url || cfg.url}) from ai_mcp_servers`);
327666
+ }
325804
327667
  else if (cfg.tool && typeof cfg.tool === 'string') {
325805
327668
  // Custom tool or built-in tool entry
325806
327669
  toolEntriesFromMcp.push(cfg.tool);
@@ -325859,8 +327722,10 @@ class AICheckProvider extends check_provider_interface_1.CheckProvider {
325859
327722
  }
325860
327723
  // Legacy support: enable_scheduler: true also enables the schedule tool
325861
327724
  const scheduleToolEnabled = scheduleToolRequested || (config.ai?.enable_scheduler === true && !config.ai?.disableTools);
325862
- if ((customToolsToLoad.length > 0 || scheduleToolEnabled) &&
325863
- (customToolsServerName || scheduleToolEnabled) &&
327725
+ if ((customToolsToLoad.length > 0 ||
327726
+ scheduleToolEnabled ||
327727
+ httpClientEntriesFromMcp.length > 0) &&
327728
+ (customToolsServerName || scheduleToolEnabled || httpClientEntriesFromMcp.length > 0) &&
325864
327729
  !config.ai?.disableTools) {
325865
327730
  if (!customToolsServerName) {
325866
327731
  customToolsServerName = '__tools__';
@@ -325896,6 +327761,49 @@ class AICheckProvider extends check_provider_interface_1.CheckProvider {
325896
327761
  customTools.set(scheduleTool.name, scheduleTool);
325897
327762
  logger_1.logger.debug(`[AICheckProvider] Added built-in schedule tool`);
325898
327763
  }
327764
+ // Add http_client tools extracted from ai_mcp_servers
327765
+ for (const entry of httpClientEntriesFromMcp) {
327766
+ const httpTool = {
327767
+ name: entry.name,
327768
+ type: 'http_client',
327769
+ description: entry.config.description ||
327770
+ `Call ${entry.name} HTTP API (base: ${entry.config.base_url || entry.config.url})`,
327771
+ base_url: (entry.config.base_url || entry.config.url),
327772
+ auth: entry.config.auth,
327773
+ headers: entry.config.headers,
327774
+ timeout: entry.config.timeout || 30000,
327775
+ inputSchema: {
327776
+ type: 'object',
327777
+ properties: {
327778
+ path: {
327779
+ type: 'string',
327780
+ description: 'API path (e.g. /jobs, /candidates/{id})',
327781
+ },
327782
+ method: {
327783
+ type: 'string',
327784
+ description: 'HTTP method (default: GET)',
327785
+ enum: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
327786
+ },
327787
+ query: {
327788
+ type: 'object',
327789
+ description: 'Query string parameters',
327790
+ additionalProperties: { type: 'string' },
327791
+ },
327792
+ body: {
327793
+ type: 'object',
327794
+ description: 'Request body for POST/PUT/PATCH',
327795
+ },
327796
+ },
327797
+ required: ['path'],
327798
+ },
327799
+ };
327800
+ customTools.set(entry.name, httpTool);
327801
+ logger_1.logger.debug(`[AICheckProvider] Added http_client tool '${entry.name}' (base_url=${httpTool.base_url})`);
327802
+ }
327803
+ // Ensure SSE server is created when http_client tools are present
327804
+ if (httpClientEntriesFromMcp.length > 0 && !customToolsServerName) {
327805
+ customToolsServerName = '__tools__';
327806
+ }
325899
327807
  if (customTools.size > 0) {
325900
327808
  const sessionId = config.checkName || `ai-check-${Date.now()}`;
325901
327809
  const debug = aiConfig.debug || process.env.VISOR_DEBUG === 'true';
@@ -333737,6 +335645,13 @@ const workflow_registry_1 = __nccwpck_require__(82824);
333737
335645
  const schedule_tool_1 = __nccwpck_require__(13395);
333738
335646
  // Legacy Slack-specific imports for backwards compatibility
333739
335647
  const schedule_tool_handler_1 = __nccwpck_require__(28883);
335648
+ const env_resolver_1 = __nccwpck_require__(58749);
335649
+ /**
335650
+ * Check if a tool definition is an http_client tool
335651
+ */
335652
+ function isHttpClientTool(tool) {
335653
+ return Boolean(tool && tool.type === 'http_client' && (tool.base_url || tool.url));
335654
+ }
333740
335655
  /**
333741
335656
  * SSE-based MCP server that exposes custom tools from YAML configuration
333742
335657
  * Implements the Model Context Protocol over Server-Sent Events
@@ -333775,14 +335690,16 @@ class CustomToolsSSEServer {
333775
335690
  }
333776
335691
  }
333777
335692
  }
333778
- // Second pass: separate workflow tools from regular tools
335693
+ // Second pass: separate workflow and http_client tools from regular tools
333779
335694
  for (const [name, tool] of this.tools.entries()) {
333780
- // Skip workflow tools - they're handled separately
333781
- if (!(0, workflow_tool_executor_1.isWorkflowTool)(tool)) {
333782
- toolsRecord[name] = tool;
335695
+ // Skip workflow and http_client tools - they're handled separately
335696
+ if ((0, workflow_tool_executor_1.isWorkflowTool)(tool) || isHttpClientTool(tool)) {
335697
+ if ((0, workflow_tool_executor_1.isWorkflowTool)(tool)) {
335698
+ workflowToolNames.push(name);
335699
+ }
333783
335700
  }
333784
335701
  else {
333785
- workflowToolNames.push(name);
335702
+ toolsRecord[name] = tool;
333786
335703
  }
333787
335704
  }
333788
335705
  // Warn if workflow tools are present but no context is provided
@@ -334256,7 +336173,14 @@ class CustomToolsSSEServer {
334256
336173
  description: tool.description || `Execute ${tool.name}`,
334257
336174
  inputSchema: normalizeInputSchema(tool.inputSchema),
334258
336175
  }));
334259
- const allTools = [...regularTools, ...workflowTools];
336176
+ const httpClientTools = Array.from(this.tools.values())
336177
+ .filter(isHttpClientTool)
336178
+ .map(tool => ({
336179
+ name: tool.name,
336180
+ description: tool.description || `Call ${tool.name} HTTP API`,
336181
+ inputSchema: normalizeInputSchema(tool.inputSchema),
336182
+ }));
336183
+ const allTools = [...regularTools, ...workflowTools, ...httpClientTools];
334260
336184
  if (this.debug) {
334261
336185
  logger_1.logger.debug(`[CustomToolsSSEServer:${this.sessionId}] Listing ${allTools.length} tools: ${allTools.map(t => t.name).join(', ')}`);
334262
336186
  }
@@ -334378,6 +336302,10 @@ class CustomToolsSSEServer {
334378
336302
  const workflowTool = tool;
334379
336303
  result = await (0, workflow_tool_executor_1.executeWorkflowAsTool)(workflowTool.__workflowId, args, this.workflowContext, workflowTool.__argsOverrides);
334380
336304
  }
336305
+ else if (tool && isHttpClientTool(tool)) {
336306
+ // Execute HTTP client tool — proxy REST API calls
336307
+ result = await this.executeHttpClientTool(tool, args);
336308
+ }
334381
336309
  else {
334382
336310
  // Execute regular custom tool
334383
336311
  result = await this.toolExecutor.execute(toolName, args);
@@ -334442,6 +336370,88 @@ class CustomToolsSSEServer {
334442
336370
  }
334443
336371
  }
334444
336372
  }
336373
+ /**
336374
+ * Execute an http_client tool — proxy REST API calls through the configured base URL.
336375
+ */
336376
+ async executeHttpClientTool(tool, args) {
336377
+ const baseUrl = (tool.base_url || tool.url).replace(/\/+$/, '');
336378
+ const apiPath = args.path || '';
336379
+ const method = (args.method || 'GET').toUpperCase();
336380
+ const queryParams = args.query || {};
336381
+ const body = args.body;
336382
+ const toolHeaders = tool.headers || {};
336383
+ const timeout = tool.timeout || 30000;
336384
+ // Build full URL
336385
+ let url = apiPath.startsWith('http') ? apiPath : `${baseUrl}/${apiPath.replace(/^\/+/, '')}`;
336386
+ // Append query parameters
336387
+ if (Object.keys(queryParams).length > 0) {
336388
+ const qs = new URLSearchParams(queryParams).toString();
336389
+ url += `${url.includes('?') ? '&' : '?'}${qs}`;
336390
+ }
336391
+ // Resolve environment variables in headers
336392
+ const resolvedHeaders = {};
336393
+ for (const [key, value] of Object.entries(toolHeaders)) {
336394
+ resolvedHeaders[key] = String(env_resolver_1.EnvironmentResolver.resolveValue(value));
336395
+ }
336396
+ // Handle auth
336397
+ if (tool.auth) {
336398
+ const authType = tool.auth.type;
336399
+ if (authType === 'bearer' && tool.auth.token) {
336400
+ const token = String(env_resolver_1.EnvironmentResolver.resolveValue(tool.auth.token));
336401
+ resolvedHeaders['Authorization'] = `Bearer ${token}`;
336402
+ }
336403
+ }
336404
+ if (this.debug) {
336405
+ logger_1.logger.debug(`[CustomToolsSSEServer:${this.sessionId}] HTTP client: ${method} ${url}`);
336406
+ }
336407
+ const controller = new AbortController();
336408
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
336409
+ try {
336410
+ const requestOptions = {
336411
+ method,
336412
+ headers: resolvedHeaders,
336413
+ signal: controller.signal,
336414
+ };
336415
+ if (method !== 'GET' && body) {
336416
+ requestOptions.body = typeof body === 'string' ? body : JSON.stringify(body);
336417
+ if (!resolvedHeaders['Content-Type'] && !resolvedHeaders['content-type']) {
336418
+ resolvedHeaders['Content-Type'] = 'application/json';
336419
+ }
336420
+ }
336421
+ const response = await fetch(url, requestOptions);
336422
+ clearTimeout(timeoutId);
336423
+ if (!response.ok) {
336424
+ let errorBody = '';
336425
+ try {
336426
+ errorBody = await response.text();
336427
+ }
336428
+ catch { }
336429
+ throw new Error(`HTTP ${response.status}: ${response.statusText}${errorBody ? ` - ${errorBody.substring(0, 500)}` : ''}`);
336430
+ }
336431
+ // Parse response
336432
+ const contentType = response.headers.get('content-type');
336433
+ if (contentType && contentType.includes('application/json')) {
336434
+ return await response.json();
336435
+ }
336436
+ const text = await response.text();
336437
+ if (text.trim().startsWith('{') || text.trim().startsWith('[')) {
336438
+ try {
336439
+ return JSON.parse(text);
336440
+ }
336441
+ catch {
336442
+ return text;
336443
+ }
336444
+ }
336445
+ return text;
336446
+ }
336447
+ catch (error) {
336448
+ clearTimeout(timeoutId);
336449
+ if (error instanceof Error && error.name === 'AbortError') {
336450
+ throw new Error(`HTTP client request timed out after ${timeout}ms`);
336451
+ }
336452
+ throw error;
336453
+ }
336454
+ }
334445
336455
  /**
334446
336456
  * Convert a type: 'workflow' tool definition into a WorkflowToolDefinition marker.
334447
336457
  *
@@ -346522,7 +348532,7 @@ class StateMachineExecutionEngine {
346522
348532
  try {
346523
348533
  logger_1.logger.debug(`[PolicyEngine] Loading enterprise policy engine (engine=${configWithTagFilter.policy.engine})`);
346524
348534
  // @ts-ignore — enterprise/ may not exist in OSS builds (caught at runtime)
346525
- const { loadEnterprisePolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(7065)));
348535
+ const { loadEnterprisePolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(87068)));
346526
348536
  context.policyEngine = await loadEnterprisePolicyEngine(configWithTagFilter.policy);
346527
348537
  logger_1.logger.debug(`[PolicyEngine] Initialized: ${context.policyEngine?.constructor?.name || 'unknown'}`);
346528
348538
  }
@@ -358261,7 +360271,7 @@ async function initTelemetry(opts = {}) {
358261
360271
  const path = __nccwpck_require__(16928);
358262
360272
  const outDir = opts.file?.dir ||
358263
360273
  process.env.VISOR_TRACE_DIR ||
358264
- __nccwpck_require__.ab + "traces";
360274
+ path.join(process.cwd(), 'output', 'traces');
358265
360275
  fs.mkdirSync(outDir, { recursive: true });
358266
360276
  const ts = new Date().toISOString().replace(/[:.]/g, '-');
358267
360277
  process.env.VISOR_FALLBACK_TRACE_FILE = path.join(outDir, `run-${ts}.ndjson`);
@@ -358511,7 +360521,7 @@ async function shutdownTelemetry() {
358511
360521
  if (process.env.VISOR_TRACE_REPORT === 'true') {
358512
360522
  const fs = __nccwpck_require__(79896);
358513
360523
  const path = __nccwpck_require__(16928);
358514
- const outDir = process.env.VISOR_TRACE_DIR || __nccwpck_require__.ab + "traces";
360524
+ const outDir = process.env.VISOR_TRACE_DIR || path.join(process.cwd(), 'output', 'traces');
358515
360525
  if (!fs.existsSync(outDir))
358516
360526
  fs.mkdirSync(outDir, { recursive: true });
358517
360527
  const ts = new Date().toISOString().replace(/[:.]/g, '-');
@@ -359062,7 +361072,7 @@ function __getOrCreateNdjsonPath() {
359062
361072
  fs.mkdirSync(dir, { recursive: true });
359063
361073
  return __ndjsonPath;
359064
361074
  }
359065
- const outDir = process.env.VISOR_TRACE_DIR || __nccwpck_require__.ab + "traces";
361075
+ const outDir = process.env.VISOR_TRACE_DIR || path.join(process.cwd(), 'output', 'traces');
359066
361076
  if (!fs.existsSync(outDir))
359067
361077
  fs.mkdirSync(outDir, { recursive: true });
359068
361078
  if (!__ndjsonPath) {
@@ -359551,9 +361561,11 @@ function expandConversationToFlow(testCase) {
359551
361561
  flow.push(stage);
359552
361562
  // After this stage, add user message + assumed assistant response to history
359553
361563
  messageHistory.push({ role: 'user', text: turn.text });
359554
- // Look for mock response text to add as assistant message for next turn
361564
+ // Look for mock response text to add as assistant message for next turn.
361565
+ // Record the index so the runner can replace it with the real response in --no-mocks mode.
359555
361566
  const assistantText = extractMockResponseText(turn.mocks);
359556
361567
  if (assistantText) {
361568
+ stage._mockAssistantMsgIndex = messageHistory.length; // index of the assistant msg about to be pushed
359557
361569
  messageHistory.push({ role: 'assistant', text: assistantText });
359558
361570
  }
359559
361571
  }
@@ -361681,6 +363693,31 @@ class VisorTestRunner {
361681
363693
  const pad = Math.max(1, width - title.length - 2);
361682
363694
  return `${char.repeat(2)} ${title} ${char.repeat(pad)}`;
361683
363695
  }
363696
+ /**
363697
+ * Execute a lifecycle hook (shell command). Returns true on success, false on failure.
363698
+ */
363699
+ async runHook(hook, label, cwd) {
363700
+ if (!hook)
363701
+ return { ok: true };
363702
+ const timeoutMs = hook.timeout || 30_000;
363703
+ console.log(this.gray(` ⚙ ${label}: ${hook.exec}`));
363704
+ try {
363705
+ const { execSync } = __nccwpck_require__(35317);
363706
+ execSync(hook.exec, {
363707
+ cwd,
363708
+ stdio: ['ignore', 'pipe', 'pipe'],
363709
+ timeout: timeoutMs,
363710
+ env: { ...process.env },
363711
+ });
363712
+ return { ok: true };
363713
+ }
363714
+ catch (err) {
363715
+ const stderr = err.stderr ? err.stderr.toString().trim() : '';
363716
+ const msg = stderr || err.message || String(err);
363717
+ console.log(this.color(` ✖ ${label} failed: ${msg}`, '31'));
363718
+ return { ok: false, error: `${label} failed: ${msg}` };
363719
+ }
363720
+ }
361684
363721
  // Extracted helper: prepare engine/recorder, prompts/mocks, env, and checksToRun for a single-event case
361685
363722
  setupTestCase(_case, cfg, defaultStrict, defaultPromptCap, ghRec, defaultIncludeTags, defaultExcludeTags, noMocks, noMocksFor) {
361686
363723
  const name = _case.name || '(unnamed)';
@@ -362082,6 +364119,7 @@ class VisorTestRunner {
362082
364119
  extends: doc.extends,
362083
364120
  tests: {
362084
364121
  defaults: tests.defaults || {},
364122
+ hooks: tests.hooks || undefined,
362085
364123
  fixtures: tests.fixtures || [],
362086
364124
  cases: tests.cases,
362087
364125
  },
@@ -362271,6 +364309,18 @@ class VisorTestRunner {
362271
364309
  }
362272
364310
  }
362273
364311
  catch { }
364312
+ // Lifecycle hooks
364313
+ const suiteHooks = suite.tests.hooks || {};
364314
+ const suiteCwd = path_1.default.dirname(testsPath);
364315
+ const beforeAllResult = await this.runHook(suiteHooks.before_all, 'before_all', suiteCwd);
364316
+ if (!beforeAllResult.ok) {
364317
+ // Skip all cases when before_all fails
364318
+ for (const c of selected) {
364319
+ caseResults.push({ name: c.name, passed: false, errors: [beforeAllResult.error] });
364320
+ }
364321
+ clearInterval(__keepAlive);
364322
+ return { failures: selected.length, results: caseResults };
364323
+ }
362274
364324
  const runOne = async (_caseOrig) => {
362275
364325
  // Expand conversation sugar to flow stages before any processing
362276
364326
  const { expandConversationToFlow } = __nccwpck_require__(15921);
@@ -362290,11 +364340,32 @@ class VisorTestRunner {
362290
364340
  caseResults.push({ name: _case.name, passed: true, errors: [] });
362291
364341
  return { name: _case.name, failed: 0 };
362292
364342
  }
364343
+ // Run before_each (suite-level) and before (case-level) hooks
364344
+ const caseHooks = _case.hooks || {};
364345
+ const beforeEachRes = await this.runHook(suiteHooks.before_each, 'before_each', suiteCwd);
364346
+ if (!beforeEachRes.ok) {
364347
+ caseResults.push({ name: _case.name, passed: false, errors: [beforeEachRes.error] });
364348
+ return { name: _case.name, failed: 1 };
364349
+ }
364350
+ const beforeRes = await this.runHook(caseHooks.before, `before (${_case.name})`, suiteCwd);
364351
+ if (!beforeRes.ok) {
364352
+ // after_each still runs even if before fails
364353
+ await this.runHook(suiteHooks.after_each, 'after_each', suiteCwd);
364354
+ caseResults.push({ name: _case.name, passed: false, errors: [beforeRes.error] });
364355
+ return { name: _case.name, failed: 1 };
364356
+ }
362293
364357
  if (Array.isArray(_case.flow) && _case.flow.length > 0) {
362294
- const flowRes = await this.runFlowCase(_case, cfg, defaultStrict, options.bail || false, defaultPromptCap, stageFilter, noMocksMode);
362295
- const failed = flowRes.failures;
362296
- caseResults.push({ name: _case.name, passed: failed === 0, stages: flowRes.stages });
362297
- return { name: _case.name, failed };
364358
+ try {
364359
+ const flowRes = await this.runFlowCase(_case, cfg, defaultStrict, options.bail || false, defaultPromptCap, stageFilter, noMocksMode);
364360
+ const failed = flowRes.failures;
364361
+ caseResults.push({ name: _case.name, passed: failed === 0, stages: flowRes.stages });
364362
+ return { name: _case.name, failed };
364363
+ }
364364
+ finally {
364365
+ // after (case-level) and after_each (suite-level) always run
364366
+ await this.runHook(caseHooks.after, `after (${_case.name})`, suiteCwd);
364367
+ await this.runHook(suiteHooks.after_each, 'after_each', suiteCwd);
364368
+ }
362298
364369
  }
362299
364370
  // Per-case AI override: include code context when requested
362300
364371
  const suiteDefaults = this.suiteDefaults || {};
@@ -362523,6 +364594,9 @@ class VisorTestRunner {
362523
364594
  return { name: _case.name, failed: 1 };
362524
364595
  }
362525
364596
  finally {
364597
+ // after (case-level) and after_each (suite-level) always run
364598
+ await this.runHook(caseHooks.after, `after (${_case.name})`, suiteCwd);
364599
+ await this.runHook(suiteHooks.after_each, 'after_each', suiteCwd);
362526
364600
  try {
362527
364601
  // Restore env for this case using original setup
362528
364602
  setup.restoreEnv();
@@ -362553,6 +364627,8 @@ class VisorTestRunner {
362553
364627
  };
362554
364628
  await Promise.all(Array.from({ length: workers }, runWorker));
362555
364629
  }
364630
+ // after_all always runs (like finally), even if tests failed
364631
+ await this.runHook(suiteHooks.after_all, 'after_all', suiteCwd);
362556
364632
  // Summary (suppressible for embedded runs)
362557
364633
  const failedCases = caseResults.filter(r => !r.passed);
362558
364634
  const passedCases = caseResults.filter(r => r.passed);
@@ -362761,6 +364837,24 @@ class VisorTestRunner {
362761
364837
  const defaultExcludeTags = parseTags(suiteDefaults?.exclude_tags);
362762
364838
  const stageRunner = new flow_stage_1.FlowStage(flowName, engine, recorder, cfg, prompts, promptCap, this.mapEventFromFixtureName.bind(this), this.computeChecksToRun.bind(this), this.printStageHeader.bind(this), this.printSelectedChecks.bind(this), this.warnUnmockedProviders.bind(this), defaultIncludeTags, defaultExcludeTags, (suiteDefaults.frontends || undefined), noMocks, suiteDefaults.llm_judge || undefined, cumulativeOutputHistory);
362763
364839
  const outcome = await stageRunner.run(stage, flowCase, strict);
364840
+ // In conversation sugar + --no-mocks: replace mock assistant text in
364841
+ // subsequent stages' message history with the real AI response.
364842
+ if (noMocks &&
364843
+ flowCase._conversationSugar &&
364844
+ typeof stage._mockAssistantMsgIndex === 'number') {
364845
+ const realText = this.extractLastResponseText(cumulativeOutputHistory);
364846
+ if (realText) {
364847
+ for (let j = i + 1; j < flowCase.flow.length; j++) {
364848
+ const nextMsgs = flowCase.flow[j]?.execution_context?.conversation?.messages;
364849
+ if (Array.isArray(nextMsgs) && nextMsgs[stage._mockAssistantMsgIndex]) {
364850
+ nextMsgs[stage._mockAssistantMsgIndex] = {
364851
+ ...nextMsgs[stage._mockAssistantMsgIndex],
364852
+ text: realText,
364853
+ };
364854
+ }
364855
+ }
364856
+ }
364857
+ }
362764
364858
  const expect = stage.expect || {};
362765
364859
  if (outcome.stats)
362766
364860
  this.printCoverage(outcome.name, outcome.stats, expect);
@@ -362805,6 +364899,21 @@ class VisorTestRunner {
362805
364899
  console.log(`${this.tagFail ? this.tagFail() : '❌ FAIL'} ${flowName} (${failures} stage error${failures > 1 ? 's' : ''})`);
362806
364900
  return { failures, stages: stagesSummary };
362807
364901
  }
364902
+ /**
364903
+ * Extract the last response text from cumulative output history (for conversation sugar).
364904
+ * Looks for 'chat' step outputs with a 'text' field.
364905
+ */
364906
+ extractLastResponseText(history) {
364907
+ // The assistant workflow emits output on the 'chat' step with a 'text' field
364908
+ const chatOutputs = history['chat'];
364909
+ if (!Array.isArray(chatOutputs) || chatOutputs.length === 0)
364910
+ return undefined;
364911
+ const last = chatOutputs[chatOutputs.length - 1];
364912
+ if (last && typeof last === 'object' && typeof last.text === 'string') {
364913
+ return last.text;
364914
+ }
364915
+ return undefined;
364916
+ }
362808
364917
  mapEventFromFixtureName(name) {
362809
364918
  if (!name)
362810
364919
  return 'manual';
@@ -363662,6 +365771,7 @@ const schema = {
363662
365771
  },
363663
365772
  },
363664
365773
  },
365774
+ hooks: { $ref: '#/$defs/suiteHooks' },
363665
365775
  fixtures: { type: 'array' },
363666
365776
  cases: {
363667
365777
  type: 'array',
@@ -363673,6 +365783,33 @@ const schema = {
363673
365783
  },
363674
365784
  required: ['tests'],
363675
365785
  $defs: {
365786
+ hookDef: {
365787
+ type: 'object',
365788
+ additionalProperties: false,
365789
+ properties: {
365790
+ exec: { type: 'string' },
365791
+ timeout: { type: 'number' },
365792
+ },
365793
+ required: ['exec'],
365794
+ },
365795
+ suiteHooks: {
365796
+ type: 'object',
365797
+ additionalProperties: false,
365798
+ properties: {
365799
+ before_all: { $ref: '#/$defs/hookDef' },
365800
+ after_all: { $ref: '#/$defs/hookDef' },
365801
+ before_each: { $ref: '#/$defs/hookDef' },
365802
+ after_each: { $ref: '#/$defs/hookDef' },
365803
+ },
365804
+ },
365805
+ caseHooks: {
365806
+ type: 'object',
365807
+ additionalProperties: false,
365808
+ properties: {
365809
+ before: { $ref: '#/$defs/hookDef' },
365810
+ after: { $ref: '#/$defs/hookDef' },
365811
+ },
365812
+ },
363676
365813
  fixtureRef: {
363677
365814
  oneOf: [
363678
365815
  { type: 'string' },
@@ -363751,6 +365888,7 @@ const schema = {
363751
365888
  },
363752
365889
  // Workflow testing: input values to pass to the workflow
363753
365890
  workflow_input: { type: 'object' },
365891
+ hooks: { $ref: '#/$defs/caseHooks' },
363754
365892
  expect: { $ref: '#/$defs/expectBlock' },
363755
365893
  // Flow cases
363756
365894
  flow: {
@@ -374988,22 +377126,6 @@ class WorkflowRegistry {
374988
377126
  exports.WorkflowRegistry = WorkflowRegistry;
374989
377127
 
374990
377128
 
374991
- /***/ }),
374992
-
374993
- /***/ 7065:
374994
- /***/ ((module) => {
374995
-
374996
- module.exports = eval("require")("./enterprise/loader");
374997
-
374998
-
374999
- /***/ }),
375000
-
375001
- /***/ 71370:
375002
- /***/ ((module) => {
375003
-
375004
- module.exports = eval("require")("./enterprise/policy/policy-input-builder");
375005
-
375006
-
375007
377129
  /***/ }),
375008
377130
 
375009
377131
  /***/ 18327:
@@ -608370,7 +610492,7 @@ module.exports = /*#__PURE__*/JSON.parse('["aaa","aarp","abb","abbott","abbvie",
608370
610492
  /***/ ((module) => {
608371
610493
 
608372
610494
  "use strict";
608373
- module.exports = /*#__PURE__*/JSON.parse('{"name":"@probelabs/visor","version":"0.1.174","main":"dist/index.js","bin":{"visor":"./dist/index.js"},"exports":{".":{"require":"./dist/index.js","import":"./dist/index.js"},"./sdk":{"types":"./dist/sdk/sdk.d.ts","import":"./dist/sdk/sdk.mjs","require":"./dist/sdk/sdk.js"},"./cli":{"require":"./dist/index.js"}},"files":["dist/","defaults/","action.yml","README.md","LICENSE"],"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"scripts":{"build:cli":"ncc build src/index.ts -o dist && cp -r defaults dist/ && cp -r output dist/ && cp -r docs dist/ && cp -r examples dist/ && cp -r src/debug-visualizer/ui dist/debug-visualizer/ && node scripts/inject-version.js && echo \'#!/usr/bin/env node\' | cat - dist/index.js > temp && mv temp dist/index.js && chmod +x dist/index.js","build:sdk":"tsup src/sdk.ts --dts --sourcemap --format esm,cjs --out-dir dist/sdk","build":"./scripts/build-oss.sh","build:ee":"npm run build:cli && npm run build:sdk","test":"jest && npm run test:yaml","test:unit":"jest","prepublishOnly":"npm run build","test:watch":"jest --watch","test:coverage":"jest --coverage","test:ee":"jest --testPathPatterns=\'tests/ee\' --testPathIgnorePatterns=\'/node_modules/\' --no-coverage","test:manual:bash":"RUN_MANUAL_TESTS=true jest tests/manual/bash-config-manual.test.ts","lint":"eslint src tests --ext .ts","lint:fix":"eslint src tests --ext .ts --fix","format":"prettier --write src tests","format:check":"prettier --check src tests","clean":"","clean:traces":"node scripts/clean-traces.js","prebuild":"npm run clean && node scripts/generate-config-schema.js","pretest":"npm run clean:traces && node scripts/generate-config-schema.js && npm run build:cli","pretest:unit":"npm run clean:traces && node scripts/generate-config-schema.js && npm run build:cli","test:with-build":"npm run build:cli && jest","test:yaml":"node dist/index.js test --progress compact","test:yaml:parallel":"node dist/index.js test --progress compact --max-parallel 4","prepare":"husky","pre-commit":"lint-staged","deploy:site":"cd site && npx wrangler pages deploy . --project-name=visor-site --commit-dirty=true","deploy:worker":"npx wrangler deploy","deploy":"npm run deploy:site && npm run deploy:worker","publish:ee":"./scripts/publish-ee.sh","release":"./scripts/release.sh","release:patch":"./scripts/release.sh patch","release:minor":"./scripts/release.sh minor","release:major":"./scripts/release.sh major","release:prerelease":"./scripts/release.sh prerelease","docs:validate":"node scripts/validate-readme-links.js","workshop:setup":"npm install -D reveal-md@6.1.2","workshop:serve":"cd workshop && reveal-md slides.md -w","workshop:export":"reveal-md workshop/slides.md --static workshop/build","workshop:pdf":"reveal-md workshop/slides.md --print workshop/Visor-Workshop.pdf --print-size letter","workshop:pdf:ci":"reveal-md workshop/slides.md --print workshop/Visor-Workshop.pdf --print-size letter --puppeteer-launch-args=\\"--no-sandbox --disable-dev-shm-usage\\"","workshop:pdf:a4":"reveal-md workshop/slides.md --print workshop/Visor-Workshop-A4.pdf --print-size A4","workshop:build":"npm run workshop:export && npm run workshop:pdf","simulate:issue":"TS_NODE_TRANSPILE_ONLY=1 ts-node scripts/simulate-gh-run.ts --event issues --action opened --debug","simulate:comment":"TS_NODE_TRANSPILE_ONLY=1 ts-node scripts/simulate-gh-run.ts --event issue_comment --action created --debug"},"keywords":["code-review","ai","github-action","cli","pr-review","visor"],"author":"Probe Labs","license":"MIT","description":"AI workflow engine for code review, assistants, and automation — orchestrate checks, MCP tools, and AI providers with YAML-driven pipelines","repository":{"type":"git","url":"git+https://github.com/probelabs/visor.git"},"bugs":{"url":"https://github.com/probelabs/visor/issues"},"homepage":"https://github.com/probelabs/visor#readme","dependencies":{"@actions/core":"^1.11.1","@apidevtools/swagger-parser":"^12.1.0","@grammyjs/runner":"^2.0.3","@modelcontextprotocol/sdk":"^1.25.3","@nyariv/sandboxjs":"github:probelabs/SandboxJS#23c4bb611f7d05f3cb8c523917b5f57103e48108","@octokit/action":"^8.0.2","@octokit/auth-app":"^8.1.0","@octokit/core":"^7.0.3","@octokit/rest":"^22.0.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.203.0","@opentelemetry/core":"^1.30.1","@opentelemetry/exporter-logs-otlp-http":"^0.203.0","@opentelemetry/exporter-metrics-otlp-http":"^0.203.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.203.0","@opentelemetry/exporter-trace-otlp-http":"^0.203.0","@opentelemetry/instrumentation":"^0.203.0","@opentelemetry/resources":"^1.30.1","@opentelemetry/sdk-logs":"^0.203.0","@opentelemetry/sdk-metrics":"^1.30.1","@opentelemetry/sdk-node":"^0.203.0","@opentelemetry/sdk-trace-base":"^1.30.1","@opentelemetry/semantic-conventions":"^1.30.1","@probelabs/probe":"^0.6.0-rc291","@types/commander":"^2.12.0","@types/uuid":"^10.0.0","acorn":"^8.16.0","acorn-walk":"^8.3.5","ajv":"^8.17.1","ajv-formats":"^3.0.1","better-sqlite3":"^11.0.0","blessed":"^0.1.81","botbuilder":"^4.23.3","botframework-connector":"^4.23.3","cli-table3":"^0.6.5","commander":"^14.0.0","deepmerge":"^4.3.1","dotenv":"^17.2.3","grammy":"^1.41.1","ignore":"^7.0.5","imapflow":"^1.2.12","js-yaml":"^4.1.0","jsonpath-plus":"^10.4.0","liquidjs":"^10.21.1","mailparser":"^3.9.3","minimatch":"^10.2.2","node-cron":"^3.0.3","nodemailer":"^8.0.1","open":"^9.1.0","resend":"^6.9.3","simple-git":"^3.28.0","uuid":"^11.1.0","ws":"^8.18.3"},"optionalDependencies":{"@anthropic/claude-code-sdk":"npm:null@*","@open-policy-agent/opa-wasm":"^1.10.0","knex":"^3.1.0","mysql2":"^3.11.0","pg":"^8.13.0","tedious":"^19.0.0"},"devDependencies":{"@eslint/js":"^9.34.0","@kie/act-js":"^2.6.2","@kie/mock-github":"^2.0.1","@swc/core":"^1.13.2","@swc/jest":"^0.2.37","@types/better-sqlite3":"^7.6.0","@types/blessed":"^0.1.27","@types/jest":"^30.0.0","@types/js-yaml":"^4.0.9","@types/mailparser":"^3.4.6","@types/node":"^24.3.0","@types/node-cron":"^3.0.11","@types/nodemailer":"^7.0.11","@types/ws":"^8.18.1","@typescript-eslint/eslint-plugin":"^8.42.0","@typescript-eslint/parser":"^8.42.0","@vercel/ncc":"^0.38.4","eslint":"^9.34.0","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.4","husky":"^9.1.7","jest":"^30.1.3","lint-staged":"^16.1.6","prettier":"^3.6.2","reveal-md":"^6.1.2","ts-json-schema-generator":"^1.5.1","ts-node":"^10.9.2","tsup":"^8.5.0","typescript":"^5.9.2","wrangler":"^3.0.0"},"peerDependenciesMeta":{"@anthropic/claude-code-sdk":{"optional":true}},"directories":{"test":"tests"},"lint-staged":{"src/**/*.{ts,js}":["eslint --fix","prettier --write"],"tests/**/*.{ts,js}":["eslint --fix","prettier --write"],"*.{json,md,yml,yaml}":["prettier --write"]}}');
610495
+ module.exports = /*#__PURE__*/JSON.parse('{"name":"@probelabs/visor","version":"0.1.42","main":"dist/index.js","bin":{"visor":"./dist/index.js"},"exports":{".":{"require":"./dist/index.js","import":"./dist/index.js"},"./sdk":{"types":"./dist/sdk/sdk.d.ts","import":"./dist/sdk/sdk.mjs","require":"./dist/sdk/sdk.js"},"./cli":{"require":"./dist/index.js"}},"files":["dist/","defaults/","action.yml","README.md","LICENSE"],"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"scripts":{"build:cli":"ncc build src/index.ts -o dist && cp -r defaults dist/ && cp -r output dist/ && cp -r docs dist/ && cp -r examples dist/ && cp -r src/debug-visualizer/ui dist/debug-visualizer/ && node scripts/inject-version.js && echo \'#!/usr/bin/env node\' | cat - dist/index.js > temp && mv temp dist/index.js && chmod +x dist/index.js","build:sdk":"tsup src/sdk.ts --dts --sourcemap --format esm,cjs --out-dir dist/sdk","build":"./scripts/build-oss.sh","build:ee":"npm run build:cli && npm run build:sdk","test":"jest && npm run test:yaml","test:unit":"jest","prepublishOnly":"npm run build","test:watch":"jest --watch","test:coverage":"jest --coverage","test:ee":"jest --testPathPatterns=\'tests/ee\' --testPathIgnorePatterns=\'/node_modules/\' --no-coverage","test:manual:bash":"RUN_MANUAL_TESTS=true jest tests/manual/bash-config-manual.test.ts","lint":"eslint src tests --ext .ts","lint:fix":"eslint src tests --ext .ts --fix","format":"prettier --write src tests","format:check":"prettier --check src tests","clean":"","clean:traces":"node scripts/clean-traces.js","prebuild":"npm run clean && node scripts/generate-config-schema.js","pretest":"npm run clean:traces && node scripts/generate-config-schema.js && npm run build:cli","pretest:unit":"npm run clean:traces && node scripts/generate-config-schema.js && npm run build:cli","test:with-build":"npm run build:cli && jest","test:yaml":"node dist/index.js test --progress compact","test:yaml:parallel":"node dist/index.js test --progress compact --max-parallel 4","prepare":"husky","pre-commit":"lint-staged","deploy:site":"cd site && npx wrangler pages deploy . --project-name=visor-site --commit-dirty=true","deploy:worker":"npx wrangler deploy","deploy":"npm run deploy:site && npm run deploy:worker","publish:ee":"./scripts/publish-ee.sh","release":"./scripts/release.sh","release:patch":"./scripts/release.sh patch","release:minor":"./scripts/release.sh minor","release:major":"./scripts/release.sh major","release:prerelease":"./scripts/release.sh prerelease","docs:validate":"node scripts/validate-readme-links.js","workshop:setup":"npm install -D reveal-md@6.1.2","workshop:serve":"cd workshop && reveal-md slides.md -w","workshop:export":"reveal-md workshop/slides.md --static workshop/build","workshop:pdf":"reveal-md workshop/slides.md --print workshop/Visor-Workshop.pdf --print-size letter","workshop:pdf:ci":"reveal-md workshop/slides.md --print workshop/Visor-Workshop.pdf --print-size letter --puppeteer-launch-args=\\"--no-sandbox --disable-dev-shm-usage\\"","workshop:pdf:a4":"reveal-md workshop/slides.md --print workshop/Visor-Workshop-A4.pdf --print-size A4","workshop:build":"npm run workshop:export && npm run workshop:pdf","simulate:issue":"TS_NODE_TRANSPILE_ONLY=1 ts-node scripts/simulate-gh-run.ts --event issues --action opened --debug","simulate:comment":"TS_NODE_TRANSPILE_ONLY=1 ts-node scripts/simulate-gh-run.ts --event issue_comment --action created --debug"},"keywords":["code-review","ai","github-action","cli","pr-review","visor"],"author":"Probe Labs","license":"MIT","description":"AI workflow engine for code review, assistants, and automation — orchestrate checks, MCP tools, and AI providers with YAML-driven pipelines","repository":{"type":"git","url":"git+https://github.com/probelabs/visor.git"},"bugs":{"url":"https://github.com/probelabs/visor/issues"},"homepage":"https://github.com/probelabs/visor#readme","dependencies":{"@actions/core":"^1.11.1","@apidevtools/swagger-parser":"^12.1.0","@grammyjs/runner":"^2.0.3","@modelcontextprotocol/sdk":"^1.25.3","@nyariv/sandboxjs":"github:probelabs/SandboxJS#23c4bb611f7d05f3cb8c523917b5f57103e48108","@octokit/action":"^8.0.2","@octokit/auth-app":"^8.1.0","@octokit/core":"^7.0.3","@octokit/rest":"^22.0.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.203.0","@opentelemetry/core":"^1.30.1","@opentelemetry/exporter-logs-otlp-http":"^0.203.0","@opentelemetry/exporter-metrics-otlp-http":"^0.203.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.203.0","@opentelemetry/exporter-trace-otlp-http":"^0.203.0","@opentelemetry/instrumentation":"^0.203.0","@opentelemetry/resources":"^1.30.1","@opentelemetry/sdk-logs":"^0.203.0","@opentelemetry/sdk-metrics":"^1.30.1","@opentelemetry/sdk-node":"^0.203.0","@opentelemetry/sdk-trace-base":"^1.30.1","@opentelemetry/semantic-conventions":"^1.30.1","@probelabs/probe":"^0.6.0-rc291","@types/commander":"^2.12.0","@types/uuid":"^10.0.0","acorn":"^8.16.0","acorn-walk":"^8.3.5","ajv":"^8.17.1","ajv-formats":"^3.0.1","better-sqlite3":"^11.0.0","blessed":"^0.1.81","botbuilder":"^4.23.3","botframework-connector":"^4.23.3","cli-table3":"^0.6.5","commander":"^14.0.0","deepmerge":"^4.3.1","dotenv":"^17.2.3","grammy":"^1.41.1","ignore":"^7.0.5","imapflow":"^1.2.12","js-yaml":"^4.1.0","jsonpath-plus":"^10.4.0","liquidjs":"^10.21.1","mailparser":"^3.9.3","minimatch":"^10.2.2","node-cron":"^3.0.3","nodemailer":"^8.0.1","open":"^9.1.0","resend":"^6.9.3","simple-git":"^3.28.0","uuid":"^11.1.0","ws":"^8.18.3"},"optionalDependencies":{"@anthropic/claude-code-sdk":"npm:null@*","@open-policy-agent/opa-wasm":"^1.10.0","knex":"^3.1.0","mysql2":"^3.11.0","pg":"^8.13.0","tedious":"^19.0.0"},"devDependencies":{"@eslint/js":"^9.34.0","@kie/act-js":"^2.6.2","@kie/mock-github":"^2.0.1","@swc/core":"^1.13.2","@swc/jest":"^0.2.37","@types/better-sqlite3":"^7.6.0","@types/blessed":"^0.1.27","@types/jest":"^30.0.0","@types/js-yaml":"^4.0.9","@types/mailparser":"^3.4.6","@types/node":"^24.3.0","@types/node-cron":"^3.0.11","@types/nodemailer":"^7.0.11","@types/ws":"^8.18.1","@typescript-eslint/eslint-plugin":"^8.42.0","@typescript-eslint/parser":"^8.42.0","@vercel/ncc":"^0.38.4","eslint":"^9.34.0","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.4","husky":"^9.1.7","jest":"^30.1.3","lint-staged":"^16.1.6","prettier":"^3.6.2","reveal-md":"^6.1.2","ts-json-schema-generator":"^1.5.1","ts-node":"^10.9.2","tsup":"^8.5.0","typescript":"^5.9.2","wrangler":"^3.0.0"},"peerDependenciesMeta":{"@anthropic/claude-code-sdk":{"optional":true}},"directories":{"test":"tests"},"lint-staged":{"src/**/*.{ts,js}":["eslint --fix","prettier --write"],"tests/**/*.{ts,js}":["eslint --fix","prettier --write"],"*.{json,md,yml,yaml}":["prettier --write"]}}');
608374
610496
 
608375
610497
  /***/ })
608376
610498