@probelabs/visor 0.1.174-ee → 0.1.175

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 +352 -1864
  10. package/dist/output/traces/run-2026-03-09T18-49-07-663Z.ndjson +138 -0
  11. package/dist/output/traces/run-2026-03-09T18-49-46-345Z.ndjson +2296 -0
  12. package/dist/providers/ai-check-provider.d.ts.map +1 -1
  13. package/dist/providers/mcp-custom-sse-server.d.ts +4 -0
  14. package/dist/providers/mcp-custom-sse-server.d.ts.map +1 -1
  15. package/dist/sdk/a2a-frontend-ORLAU5GK.mjs +1658 -0
  16. package/dist/sdk/a2a-frontend-ORLAU5GK.mjs.map +1 -0
  17. package/dist/sdk/{check-provider-registry-53C2ZIXJ.mjs → check-provider-registry-7JPPJHVM.mjs} +3 -3
  18. package/dist/sdk/{check-provider-registry-UPQNHHFF.mjs → check-provider-registry-O36CQEGD.mjs} +3 -3
  19. package/dist/sdk/check-provider-registry-QCDV3SI6.mjs +30 -0
  20. package/dist/sdk/chunk-4FGX4SA6.mjs +516 -0
  21. package/dist/sdk/chunk-4FGX4SA6.mjs.map +1 -0
  22. package/dist/sdk/{chunk-2PL2YH3B.mjs → chunk-FZPCP444.mjs} +153 -14
  23. package/dist/sdk/chunk-FZPCP444.mjs.map +1 -0
  24. package/dist/sdk/chunk-HNK5ZJ2L.mjs +739 -0
  25. package/dist/sdk/chunk-HNK5ZJ2L.mjs.map +1 -0
  26. package/dist/sdk/{chunk-W4KCJM6J.mjs → chunk-MLXGCLZJ.mjs} +29 -8
  27. package/dist/sdk/chunk-MLXGCLZJ.mjs.map +1 -0
  28. package/dist/sdk/chunk-QAO73GUX.mjs +1502 -0
  29. package/dist/sdk/chunk-QAO73GUX.mjs.map +1 -0
  30. package/dist/sdk/{chunk-GKSSG5IM.mjs → chunk-TAK5HLAR.mjs} +155 -16
  31. package/dist/sdk/chunk-TAK5HLAR.mjs.map +1 -0
  32. package/dist/sdk/chunk-YVVOG7RP.mjs +45155 -0
  33. package/dist/sdk/chunk-YVVOG7RP.mjs.map +1 -0
  34. package/dist/sdk/{config-BVL3KFMB.mjs → config-4JMBJKWS.mjs} +2 -2
  35. package/dist/sdk/failure-condition-evaluator-RM5JJS4Q.mjs +18 -0
  36. package/dist/sdk/github-frontend-O5IAWXL5.mjs +1386 -0
  37. package/dist/sdk/github-frontend-O5IAWXL5.mjs.map +1 -0
  38. package/dist/sdk/{host-LRWIKURZ.mjs → host-WTJBWO4T.mjs} +3 -3
  39. package/dist/sdk/routing-AWOHU2WP.mjs +26 -0
  40. package/dist/sdk/{schedule-tool-5KDBDCFO.mjs → schedule-tool-DF5WUVYV.mjs} +3 -3
  41. package/dist/sdk/schedule-tool-L5G2BRIG.mjs +36 -0
  42. package/dist/sdk/{schedule-tool-UMDRCNO5.mjs → schedule-tool-XVSYLH4Z.mjs} +3 -3
  43. package/dist/sdk/{schedule-tool-handler-5EPTHBLS.mjs → schedule-tool-handler-CFMFHDUL.mjs} +3 -3
  44. package/dist/sdk/schedule-tool-handler-CFMFHDUL.mjs.map +1 -0
  45. package/dist/sdk/{schedule-tool-handler-MUF5V36L.mjs → schedule-tool-handler-JGWA4N3C.mjs} +3 -3
  46. package/dist/sdk/schedule-tool-handler-JGWA4N3C.mjs.map +1 -0
  47. package/dist/sdk/schedule-tool-handler-UJ4RFTW2.mjs +40 -0
  48. package/dist/sdk/schedule-tool-handler-UJ4RFTW2.mjs.map +1 -0
  49. package/dist/sdk/sdk.d.mts +9 -1
  50. package/dist/sdk/sdk.d.ts +9 -1
  51. package/dist/sdk/sdk.js +453 -1667
  52. package/dist/sdk/sdk.js.map +1 -1
  53. package/dist/sdk/sdk.mjs +5 -5
  54. package/dist/sdk/trace-helpers-4ERTVCZG.mjs +29 -0
  55. package/dist/sdk/trace-helpers-4ERTVCZG.mjs.map +1 -0
  56. package/dist/sdk/{workflow-check-provider-EWMZEEES.mjs → workflow-check-provider-ETM452BO.mjs} +3 -3
  57. package/dist/sdk/workflow-check-provider-ETM452BO.mjs.map +1 -0
  58. package/dist/sdk/workflow-check-provider-I3XLJP6V.mjs +30 -0
  59. package/dist/sdk/workflow-check-provider-I3XLJP6V.mjs.map +1 -0
  60. package/dist/sdk/{workflow-check-provider-RQUCBAYY.mjs → workflow-check-provider-Z6U7FZAF.mjs} +3 -3
  61. package/dist/sdk/workflow-check-provider-Z6U7FZAF.mjs.map +1 -0
  62. package/dist/test-runner/conversation-sugar.d.ts.map +1 -1
  63. package/dist/test-runner/index.d.ts +19 -0
  64. package/dist/test-runner/index.d.ts.map +1 -1
  65. package/dist/test-runner/validator.d.ts.map +1 -1
  66. package/dist/traces/run-2026-03-09T18-49-07-663Z.ndjson +138 -0
  67. package/dist/traces/run-2026-03-09T18-49-46-345Z.ndjson +2296 -0
  68. package/dist/types/config.d.ts +9 -1
  69. package/dist/types/config.d.ts.map +1 -1
  70. package/package.json +1 -1
  71. package/dist/sdk/chunk-2PL2YH3B.mjs.map +0 -1
  72. package/dist/sdk/chunk-GKSSG5IM.mjs.map +0 -1
  73. package/dist/sdk/chunk-W4KCJM6J.mjs.map +0 -1
  74. package/dist/sdk/knex-store-QCEW4I4R.mjs +0 -527
  75. package/dist/sdk/knex-store-QCEW4I4R.mjs.map +0 -1
  76. package/dist/sdk/loader-Q7K76ZIY.mjs +0 -89
  77. package/dist/sdk/loader-Q7K76ZIY.mjs.map +0 -1
  78. package/dist/sdk/opa-policy-engine-QCSSIMUF.mjs +0 -655
  79. package/dist/sdk/opa-policy-engine-QCSSIMUF.mjs.map +0 -1
  80. package/dist/sdk/validator-XTZJZZJH.mjs +0 -134
  81. package/dist/sdk/validator-XTZJZZJH.mjs.map +0 -1
  82. /package/dist/sdk/{check-provider-registry-53C2ZIXJ.mjs.map → check-provider-registry-7JPPJHVM.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/{config-BVL3KFMB.mjs.map → check-provider-registry-QCDV3SI6.mjs.map} +0 -0
  85. /package/dist/sdk/{schedule-tool-5KDBDCFO.mjs.map → config-4JMBJKWS.mjs.map} +0 -0
  86. /package/dist/sdk/{schedule-tool-UMDRCNO5.mjs.map → failure-condition-evaluator-RM5JJS4Q.mjs.map} +0 -0
  87. /package/dist/sdk/{host-LRWIKURZ.mjs.map → host-WTJBWO4T.mjs.map} +0 -0
  88. /package/dist/sdk/{schedule-tool-handler-5EPTHBLS.mjs.map → routing-AWOHU2WP.mjs.map} +0 -0
  89. /package/dist/sdk/{schedule-tool-handler-MUF5V36L.mjs.map → schedule-tool-DF5WUVYV.mjs.map} +0 -0
  90. /package/dist/sdk/{workflow-check-provider-EWMZEEES.mjs.map → schedule-tool-L5G2BRIG.mjs.map} +0 -0
  91. /package/dist/sdk/{workflow-check-provider-RQUCBAYY.mjs.map → schedule-tool-XVSYLH4Z.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 = 'e8809d0';
4
+ process.env.VISOR_COMMIT_SHA = '5b303b06870720f90057ff3f58f0e72f34bf80cb';
5
+ process.env.VISOR_COMMIT_SHORT = '5b303b06';
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__(17117)));
302954
+ const mod = await Promise.resolve().then(() => __importStar(__nccwpck_require__(71370)));
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,1810 +311019,6 @@ class EmailPollingRunner {
311018
311019
  exports.EmailPollingRunner = EmailPollingRunner;
311019
311020
 
311020
311021
 
311021
- /***/ }),
311022
-
311023
- /***/ 50069:
311024
- /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
311025
-
311026
- "use strict";
311027
-
311028
- /**
311029
- * Copyright (c) ProbeLabs. All rights reserved.
311030
- * Licensed under the Elastic License 2.0; you may not use this file except
311031
- * in compliance with the Elastic License 2.0.
311032
- */
311033
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
311034
- if (k2 === undefined) k2 = k;
311035
- var desc = Object.getOwnPropertyDescriptor(m, k);
311036
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
311037
- desc = { enumerable: true, get: function() { return m[k]; } };
311038
- }
311039
- Object.defineProperty(o, k2, desc);
311040
- }) : (function(o, m, k, k2) {
311041
- if (k2 === undefined) k2 = k;
311042
- o[k2] = m[k];
311043
- }));
311044
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
311045
- Object.defineProperty(o, "default", { enumerable: true, value: v });
311046
- }) : function(o, v) {
311047
- o["default"] = v;
311048
- });
311049
- var __importStar = (this && this.__importStar) || (function () {
311050
- var ownKeys = function(o) {
311051
- ownKeys = Object.getOwnPropertyNames || function (o) {
311052
- var ar = [];
311053
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
311054
- return ar;
311055
- };
311056
- return ownKeys(o);
311057
- };
311058
- return function (mod) {
311059
- if (mod && mod.__esModule) return mod;
311060
- var result = {};
311061
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
311062
- __setModuleDefault(result, mod);
311063
- return result;
311064
- };
311065
- })();
311066
- Object.defineProperty(exports, "__esModule", ({ value: true }));
311067
- exports.LicenseValidator = void 0;
311068
- const crypto = __importStar(__nccwpck_require__(76982));
311069
- const fs = __importStar(__nccwpck_require__(79896));
311070
- const path = __importStar(__nccwpck_require__(16928));
311071
- class LicenseValidator {
311072
- /** Ed25519 public key for license verification (PEM format). */
311073
- static PUBLIC_KEY = '-----BEGIN PUBLIC KEY-----\n' +
311074
- 'MCowBQYDK2VwAyEAI/Zd08EFmgIdrDm/HXd0l3/5GBt7R1PrdvhdmEXhJlU=\n' +
311075
- '-----END PUBLIC KEY-----\n';
311076
- cache = null;
311077
- static CACHE_TTL = 5 * 60 * 1000; // 5 minutes
311078
- static GRACE_PERIOD = 72 * 3600 * 1000; // 72 hours after expiry
311079
- /**
311080
- * Load and validate license from environment or file.
311081
- *
311082
- * Resolution order:
311083
- * 1. VISOR_LICENSE env var (JWT string)
311084
- * 2. VISOR_LICENSE_FILE env var (path to file)
311085
- * 3. .visor-license in project root (cwd)
311086
- * 4. .visor-license in ~/.config/visor/
311087
- */
311088
- async loadAndValidate() {
311089
- // Return cached result if still fresh
311090
- if (this.cache && Date.now() - this.cache.validatedAt < LicenseValidator.CACHE_TTL) {
311091
- return this.cache.payload;
311092
- }
311093
- const token = this.resolveToken();
311094
- if (!token)
311095
- return null;
311096
- const payload = this.verifyAndDecode(token);
311097
- if (!payload)
311098
- return null;
311099
- this.cache = { payload, validatedAt: Date.now() };
311100
- return payload;
311101
- }
311102
- /** Check if a specific feature is licensed */
311103
- hasFeature(feature) {
311104
- if (!this.cache)
311105
- return false;
311106
- return this.cache.payload.features.includes(feature);
311107
- }
311108
- /** Check if license is valid (with grace period) */
311109
- isValid() {
311110
- if (!this.cache)
311111
- return false;
311112
- const now = Date.now();
311113
- const expiryMs = this.cache.payload.exp * 1000;
311114
- return now < expiryMs + LicenseValidator.GRACE_PERIOD;
311115
- }
311116
- /** Check if the license is within its grace period (expired but still valid) */
311117
- isInGracePeriod() {
311118
- if (!this.cache)
311119
- return false;
311120
- const now = Date.now();
311121
- const expiryMs = this.cache.payload.exp * 1000;
311122
- return now >= expiryMs && now < expiryMs + LicenseValidator.GRACE_PERIOD;
311123
- }
311124
- resolveToken() {
311125
- // 1. Direct env var
311126
- if (process.env.VISOR_LICENSE) {
311127
- return process.env.VISOR_LICENSE.trim();
311128
- }
311129
- // 2. File path from env (validate against path traversal)
311130
- if (process.env.VISOR_LICENSE_FILE) {
311131
- // path.resolve() produces an absolute path with all '..' segments resolved,
311132
- // so a separate resolved.includes('..') check is unnecessary.
311133
- const resolved = path.resolve(process.env.VISOR_LICENSE_FILE);
311134
- const home = process.env.HOME || process.env.USERPROFILE || '';
311135
- const allowedPrefixes = [path.normalize(process.cwd())];
311136
- if (home)
311137
- allowedPrefixes.push(path.normalize(path.join(home, '.config', 'visor')));
311138
- // Resolve symlinks so an attacker cannot create a symlink inside an
311139
- // allowed prefix that points to an arbitrary file outside it.
311140
- let realPath;
311141
- try {
311142
- realPath = fs.realpathSync(resolved);
311143
- }
311144
- catch {
311145
- return null; // File doesn't exist or isn't accessible
311146
- }
311147
- const isSafe = allowedPrefixes.some(prefix => realPath === prefix || realPath.startsWith(prefix + path.sep));
311148
- if (!isSafe)
311149
- return null;
311150
- return this.readFile(realPath);
311151
- }
311152
- // 3. .visor-license in cwd
311153
- const cwdPath = path.join(process.cwd(), '.visor-license');
311154
- const cwdToken = this.readFile(cwdPath);
311155
- if (cwdToken)
311156
- return cwdToken;
311157
- // 4. ~/.config/visor/.visor-license
311158
- const home = process.env.HOME || process.env.USERPROFILE || '';
311159
- if (home) {
311160
- const configPath = path.join(home, '.config', 'visor', '.visor-license');
311161
- const configToken = this.readFile(configPath);
311162
- if (configToken)
311163
- return configToken;
311164
- }
311165
- return null;
311166
- }
311167
- readFile(filePath) {
311168
- try {
311169
- return fs.readFileSync(filePath, 'utf-8').trim();
311170
- }
311171
- catch {
311172
- return null;
311173
- }
311174
- }
311175
- verifyAndDecode(token) {
311176
- try {
311177
- const parts = token.split('.');
311178
- if (parts.length !== 3)
311179
- return null;
311180
- const [headerB64, payloadB64, signatureB64] = parts;
311181
- // Decode header to verify algorithm
311182
- const header = JSON.parse(Buffer.from(headerB64, 'base64url').toString());
311183
- if (header.alg !== 'EdDSA')
311184
- return null;
311185
- // Verify signature
311186
- const data = `${headerB64}.${payloadB64}`;
311187
- const signature = Buffer.from(signatureB64, 'base64url');
311188
- const publicKey = crypto.createPublicKey(LicenseValidator.PUBLIC_KEY);
311189
- // Validate that the loaded public key is actually Ed25519 (OID 1.3.101.112).
311190
- // This prevents algorithm-confusion attacks if the embedded key were ever
311191
- // swapped to a different type.
311192
- if (publicKey.asymmetricKeyType !== 'ed25519') {
311193
- return null;
311194
- }
311195
- // Ed25519 verification: algorithm must be null because EdDSA performs its
311196
- // own internal hashing (SHA-512) — passing a digest algorithm here would
311197
- // cause Node.js to throw. The key type is validated above.
311198
- const isValid = crypto.verify(null, Buffer.from(data), publicKey, signature);
311199
- if (!isValid)
311200
- return null;
311201
- // Decode payload
311202
- const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString());
311203
- // Validate required fields
311204
- if (!payload.org ||
311205
- !Array.isArray(payload.features) ||
311206
- typeof payload.exp !== 'number' ||
311207
- typeof payload.iat !== 'number' ||
311208
- !payload.sub) {
311209
- return null;
311210
- }
311211
- // Check expiry (with grace period)
311212
- const now = Date.now();
311213
- const expiryMs = payload.exp * 1000;
311214
- if (now >= expiryMs + LicenseValidator.GRACE_PERIOD) {
311215
- return null;
311216
- }
311217
- return payload;
311218
- }
311219
- catch {
311220
- return null;
311221
- }
311222
- }
311223
- }
311224
- exports.LicenseValidator = LicenseValidator;
311225
-
311226
-
311227
- /***/ }),
311228
-
311229
- /***/ 87068:
311230
- /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
311231
-
311232
- "use strict";
311233
-
311234
- /**
311235
- * Copyright (c) ProbeLabs. All rights reserved.
311236
- * Licensed under the Elastic License 2.0; you may not use this file except
311237
- * in compliance with the Elastic License 2.0.
311238
- */
311239
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
311240
- if (k2 === undefined) k2 = k;
311241
- var desc = Object.getOwnPropertyDescriptor(m, k);
311242
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
311243
- desc = { enumerable: true, get: function() { return m[k]; } };
311244
- }
311245
- Object.defineProperty(o, k2, desc);
311246
- }) : (function(o, m, k, k2) {
311247
- if (k2 === undefined) k2 = k;
311248
- o[k2] = m[k];
311249
- }));
311250
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
311251
- Object.defineProperty(o, "default", { enumerable: true, value: v });
311252
- }) : function(o, v) {
311253
- o["default"] = v;
311254
- });
311255
- var __importStar = (this && this.__importStar) || (function () {
311256
- var ownKeys = function(o) {
311257
- ownKeys = Object.getOwnPropertyNames || function (o) {
311258
- var ar = [];
311259
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
311260
- return ar;
311261
- };
311262
- return ownKeys(o);
311263
- };
311264
- return function (mod) {
311265
- if (mod && mod.__esModule) return mod;
311266
- var result = {};
311267
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
311268
- __setModuleDefault(result, mod);
311269
- return result;
311270
- };
311271
- })();
311272
- Object.defineProperty(exports, "__esModule", ({ value: true }));
311273
- exports.loadEnterprisePolicyEngine = loadEnterprisePolicyEngine;
311274
- exports.loadEnterpriseStoreBackend = loadEnterpriseStoreBackend;
311275
- const default_engine_1 = __nccwpck_require__(93866);
311276
- /**
311277
- * Load the enterprise policy engine if licensed, otherwise return the default no-op engine.
311278
- *
311279
- * This is the sole import boundary between OSS and enterprise code. Core code
311280
- * must only import from this module (via dynamic `await import()`), never from
311281
- * individual enterprise submodules.
311282
- */
311283
- async function loadEnterprisePolicyEngine(config) {
311284
- try {
311285
- const { LicenseValidator } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(50069)));
311286
- const validator = new LicenseValidator();
311287
- const license = await validator.loadAndValidate();
311288
- if (!license || !validator.hasFeature('policy')) {
311289
- return new default_engine_1.DefaultPolicyEngine();
311290
- }
311291
- if (validator.isInGracePeriod()) {
311292
- // eslint-disable-next-line no-console
311293
- console.warn('[visor:enterprise] License has expired but is within the 72-hour grace period. ' +
311294
- 'Please renew your license.');
311295
- }
311296
- const { OpaPolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(39530)));
311297
- const engine = new OpaPolicyEngine(config);
311298
- await engine.initialize(config);
311299
- return engine;
311300
- }
311301
- catch (err) {
311302
- // Enterprise code not available or initialization failed
311303
- const msg = err instanceof Error ? err.message : String(err);
311304
- try {
311305
- const { logger } = __nccwpck_require__(86999);
311306
- logger.warn(`[PolicyEngine] Enterprise policy init failed, falling back to default: ${msg}`);
311307
- }
311308
- catch {
311309
- // silent
311310
- }
311311
- return new default_engine_1.DefaultPolicyEngine();
311312
- }
311313
- }
311314
- /**
311315
- * Load the enterprise schedule store backend if licensed.
311316
- *
311317
- * @param driver Database driver ('postgresql', 'mysql', or 'mssql')
311318
- * @param storageConfig Storage configuration with connection details
311319
- * @param haConfig Optional HA configuration
311320
- * @throws Error if enterprise license is not available or missing 'scheduler-sql' feature
311321
- */
311322
- async function loadEnterpriseStoreBackend(driver, storageConfig, haConfig) {
311323
- const { LicenseValidator } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(50069)));
311324
- const validator = new LicenseValidator();
311325
- const license = await validator.loadAndValidate();
311326
- if (!license || !validator.hasFeature('scheduler-sql')) {
311327
- throw new Error(`The ${driver} schedule storage driver requires a Visor Enterprise license ` +
311328
- `with the 'scheduler-sql' feature. Please upgrade or use driver: 'sqlite' (default).`);
311329
- }
311330
- if (validator.isInGracePeriod()) {
311331
- // eslint-disable-next-line no-console
311332
- console.warn('[visor:enterprise] License has expired but is within the 72-hour grace period. ' +
311333
- 'Please renew your license.');
311334
- }
311335
- const { KnexStoreBackend } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(63737)));
311336
- return new KnexStoreBackend(driver, storageConfig, haConfig);
311337
- }
311338
-
311339
-
311340
- /***/ }),
311341
-
311342
- /***/ 628:
311343
- /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
311344
-
311345
- "use strict";
311346
-
311347
- /**
311348
- * Copyright (c) ProbeLabs. All rights reserved.
311349
- * Licensed under the Elastic License 2.0; you may not use this file except
311350
- * in compliance with the Elastic License 2.0.
311351
- */
311352
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
311353
- if (k2 === undefined) k2 = k;
311354
- var desc = Object.getOwnPropertyDescriptor(m, k);
311355
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
311356
- desc = { enumerable: true, get: function() { return m[k]; } };
311357
- }
311358
- Object.defineProperty(o, k2, desc);
311359
- }) : (function(o, m, k, k2) {
311360
- if (k2 === undefined) k2 = k;
311361
- o[k2] = m[k];
311362
- }));
311363
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
311364
- Object.defineProperty(o, "default", { enumerable: true, value: v });
311365
- }) : function(o, v) {
311366
- o["default"] = v;
311367
- });
311368
- var __importStar = (this && this.__importStar) || (function () {
311369
- var ownKeys = function(o) {
311370
- ownKeys = Object.getOwnPropertyNames || function (o) {
311371
- var ar = [];
311372
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
311373
- return ar;
311374
- };
311375
- return ownKeys(o);
311376
- };
311377
- return function (mod) {
311378
- if (mod && mod.__esModule) return mod;
311379
- var result = {};
311380
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
311381
- __setModuleDefault(result, mod);
311382
- return result;
311383
- };
311384
- })();
311385
- Object.defineProperty(exports, "__esModule", ({ value: true }));
311386
- exports.OpaCompiler = void 0;
311387
- const fs = __importStar(__nccwpck_require__(79896));
311388
- const path = __importStar(__nccwpck_require__(16928));
311389
- const os = __importStar(__nccwpck_require__(70857));
311390
- const crypto = __importStar(__nccwpck_require__(76982));
311391
- const child_process_1 = __nccwpck_require__(35317);
311392
- /**
311393
- * OPA Rego Compiler - compiles .rego policy files to WASM bundles using the `opa` CLI.
311394
- *
311395
- * Handles:
311396
- * - Resolving input paths to WASM bytes (direct .wasm, directory with policy.wasm, or .rego files)
311397
- * - Compiling .rego files to WASM via `opa build`
311398
- * - Caching compiled bundles based on content hashes
311399
- * - Extracting policy.wasm from OPA tar.gz bundles
311400
- *
311401
- * Requires:
311402
- * - `opa` CLI on PATH (only when auto-compiling .rego files)
311403
- */
311404
- class OpaCompiler {
311405
- static CACHE_DIR = path.join(os.tmpdir(), 'visor-opa-cache');
311406
- /**
311407
- * Resolve the input paths to WASM bytes.
311408
- *
311409
- * Strategy:
311410
- * 1. If any path is a .wasm file, read it directly
311411
- * 2. If a directory contains policy.wasm, read it
311412
- * 3. Otherwise, collect all .rego files and auto-compile via `opa build`
311413
- */
311414
- async resolveWasmBytes(paths) {
311415
- // Collect .rego files and check for existing .wasm
311416
- const regoFiles = [];
311417
- for (const p of paths) {
311418
- const resolved = path.resolve(p);
311419
- // Reject paths containing '..' after resolution (path traversal)
311420
- if (path.normalize(resolved).includes('..')) {
311421
- throw new Error(`Policy path contains traversal sequences: ${p}`);
311422
- }
311423
- // Direct .wasm file
311424
- if (resolved.endsWith('.wasm') && fs.existsSync(resolved)) {
311425
- return fs.readFileSync(resolved);
311426
- }
311427
- if (!fs.existsSync(resolved))
311428
- continue;
311429
- const stat = fs.statSync(resolved);
311430
- if (stat.isDirectory()) {
311431
- // Check for pre-compiled policy.wasm in directory
311432
- const wasmCandidate = path.join(resolved, 'policy.wasm');
311433
- if (fs.existsSync(wasmCandidate)) {
311434
- return fs.readFileSync(wasmCandidate);
311435
- }
311436
- // Collect all .rego files from directory
311437
- const files = fs.readdirSync(resolved);
311438
- for (const f of files) {
311439
- if (f.endsWith('.rego')) {
311440
- regoFiles.push(path.join(resolved, f));
311441
- }
311442
- }
311443
- }
311444
- else if (resolved.endsWith('.rego')) {
311445
- regoFiles.push(resolved);
311446
- }
311447
- }
311448
- if (regoFiles.length === 0) {
311449
- throw new Error(`OPA WASM evaluator: no .wasm bundle or .rego files found in: ${paths.join(', ')}`);
311450
- }
311451
- // Auto-compile .rego -> .wasm
311452
- return this.compileRego(regoFiles);
311453
- }
311454
- /**
311455
- * Auto-compile .rego files to a WASM bundle using the `opa` CLI.
311456
- *
311457
- * Caches the compiled bundle based on a content hash of all input .rego files
311458
- * so subsequent runs skip compilation if policies haven't changed.
311459
- */
311460
- compileRego(regoFiles) {
311461
- // Check that `opa` CLI is available
311462
- try {
311463
- (0, child_process_1.execFileSync)('opa', ['version'], { stdio: 'pipe' });
311464
- }
311465
- catch {
311466
- throw new Error('OPA CLI (`opa`) not found on PATH. Install it from https://www.openpolicyagent.org/docs/latest/#running-opa\n' +
311467
- 'Or pre-compile your .rego files: opa build -t wasm -e visor -o bundle.tar.gz ' +
311468
- regoFiles.join(' '));
311469
- }
311470
- // Compute content hash for cache key
311471
- const hash = crypto.createHash('sha256');
311472
- for (const f of regoFiles.sort()) {
311473
- hash.update(fs.readFileSync(f));
311474
- hash.update(f); // include filename for disambiguation
311475
- }
311476
- const cacheKey = hash.digest('hex').slice(0, 16);
311477
- const cacheDir = OpaCompiler.CACHE_DIR;
311478
- const cachedWasm = path.join(cacheDir, `${cacheKey}.wasm`);
311479
- // Return cached bundle if still valid
311480
- if (fs.existsSync(cachedWasm)) {
311481
- return fs.readFileSync(cachedWasm);
311482
- }
311483
- // Compile to WASM via opa build
311484
- fs.mkdirSync(cacheDir, { recursive: true });
311485
- const bundleTar = path.join(cacheDir, `${cacheKey}-bundle.tar.gz`);
311486
- try {
311487
- const args = [
311488
- 'build',
311489
- '-t',
311490
- 'wasm',
311491
- '-e',
311492
- 'visor', // entrypoint: the visor package tree
311493
- '-o',
311494
- bundleTar,
311495
- ...regoFiles,
311496
- ];
311497
- (0, child_process_1.execFileSync)('opa', args, {
311498
- stdio: 'pipe',
311499
- timeout: 30000,
311500
- });
311501
- }
311502
- catch (err) {
311503
- const stderr = err?.stderr?.toString() || '';
311504
- throw new Error(`Failed to compile .rego files to WASM:\n${stderr}\n` +
311505
- 'Ensure your .rego files are valid and the `opa` CLI is installed.');
311506
- }
311507
- // Extract policy.wasm from the tar.gz bundle
311508
- // OPA bundles are tar.gz with /policy.wasm inside
311509
- try {
311510
- (0, child_process_1.execFileSync)('tar', ['-xzf', bundleTar, '-C', cacheDir, '/policy.wasm'], {
311511
- stdio: 'pipe',
311512
- });
311513
- const extractedWasm = path.join(cacheDir, 'policy.wasm');
311514
- if (fs.existsSync(extractedWasm)) {
311515
- // Move to cache-key named file
311516
- fs.renameSync(extractedWasm, cachedWasm);
311517
- }
311518
- }
311519
- catch {
311520
- // Some tar implementations don't like leading /
311521
- try {
311522
- (0, child_process_1.execFileSync)('tar', ['-xzf', bundleTar, '-C', cacheDir, 'policy.wasm'], {
311523
- stdio: 'pipe',
311524
- });
311525
- const extractedWasm = path.join(cacheDir, 'policy.wasm');
311526
- if (fs.existsSync(extractedWasm)) {
311527
- fs.renameSync(extractedWasm, cachedWasm);
311528
- }
311529
- }
311530
- catch (err2) {
311531
- throw new Error(`Failed to extract policy.wasm from OPA bundle: ${err2?.message || err2}`);
311532
- }
311533
- }
311534
- // Clean up tar
311535
- try {
311536
- fs.unlinkSync(bundleTar);
311537
- }
311538
- catch { }
311539
- if (!fs.existsSync(cachedWasm)) {
311540
- throw new Error('OPA build succeeded but policy.wasm was not found in the bundle');
311541
- }
311542
- return fs.readFileSync(cachedWasm);
311543
- }
311544
- }
311545
- exports.OpaCompiler = OpaCompiler;
311546
-
311547
-
311548
- /***/ }),
311549
-
311550
- /***/ 44693:
311551
- /***/ ((__unused_webpack_module, exports) => {
311552
-
311553
- "use strict";
311554
-
311555
- /**
311556
- * Copyright (c) ProbeLabs. All rights reserved.
311557
- * Licensed under the Elastic License 2.0; you may not use this file except
311558
- * in compliance with the Elastic License 2.0.
311559
- */
311560
- Object.defineProperty(exports, "__esModule", ({ value: true }));
311561
- exports.OpaHttpEvaluator = void 0;
311562
- /**
311563
- * OPA HTTP Evaluator - evaluates policies via an external OPA server's REST API.
311564
- *
311565
- * Uses the built-in `fetch` API (Node 18+), so no extra dependencies are needed.
311566
- */
311567
- class OpaHttpEvaluator {
311568
- baseUrl;
311569
- timeout;
311570
- constructor(baseUrl, timeout = 5000) {
311571
- // Validate URL format and protocol
311572
- let parsed;
311573
- try {
311574
- parsed = new URL(baseUrl);
311575
- }
311576
- catch {
311577
- throw new Error(`OPA HTTP evaluator: invalid URL: ${baseUrl}`);
311578
- }
311579
- if (!['http:', 'https:'].includes(parsed.protocol)) {
311580
- throw new Error(`OPA HTTP evaluator: url must use http:// or https:// protocol, got: ${baseUrl}`);
311581
- }
311582
- // Block cloud metadata, loopback, link-local, and private network addresses
311583
- const hostname = parsed.hostname;
311584
- if (this.isBlockedHostname(hostname)) {
311585
- throw new Error(`OPA HTTP evaluator: url must not point to internal, loopback, or private network addresses`);
311586
- }
311587
- // Normalize: strip trailing slash
311588
- this.baseUrl = baseUrl.replace(/\/+$/, '');
311589
- this.timeout = timeout;
311590
- }
311591
- /**
311592
- * Check if a hostname is blocked due to SSRF concerns.
311593
- *
311594
- * Blocks:
311595
- * - Loopback addresses (127.x.x.x, localhost, 0.0.0.0, ::1)
311596
- * - Link-local addresses (169.254.x.x)
311597
- * - Private networks (10.x.x.x, 172.16-31.x.x, 192.168.x.x)
311598
- * - IPv6 unique local addresses (fd00::/8)
311599
- * - Cloud metadata services (*.internal)
311600
- */
311601
- isBlockedHostname(hostname) {
311602
- if (!hostname)
311603
- return true; // block empty hostnames
311604
- // Normalize hostname: lowercase and remove brackets for IPv6
311605
- const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, '');
311606
- // Block .internal domains (cloud metadata services)
311607
- if (normalized === 'metadata.google.internal' || normalized.endsWith('.internal')) {
311608
- return true;
311609
- }
311610
- // Block localhost variants
311611
- if (normalized === 'localhost' || normalized === 'localhost.localdomain') {
311612
- return true;
311613
- }
311614
- // Block IPv6 loopback
311615
- if (normalized === '::1' || normalized === '0:0:0:0:0:0:0:1') {
311616
- return true;
311617
- }
311618
- // Check IPv4 patterns
311619
- const ipv4Pattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
311620
- const ipv4Match = normalized.match(ipv4Pattern);
311621
- if (ipv4Match) {
311622
- const octets = ipv4Match.slice(1, 5).map(Number);
311623
- // Validate octets are in range [0, 255]
311624
- if (octets.some(octet => octet > 255)) {
311625
- return false;
311626
- }
311627
- const [a, b] = octets;
311628
- // Block loopback: 127.0.0.0/8
311629
- if (a === 127) {
311630
- return true;
311631
- }
311632
- // Block 0.0.0.0/8 (this host)
311633
- if (a === 0) {
311634
- return true;
311635
- }
311636
- // Block link-local: 169.254.0.0/16
311637
- if (a === 169 && b === 254) {
311638
- return true;
311639
- }
311640
- // Block private networks
311641
- // 10.0.0.0/8
311642
- if (a === 10) {
311643
- return true;
311644
- }
311645
- // 172.16.0.0/12 (172.16.x.x through 172.31.x.x)
311646
- if (a === 172 && b >= 16 && b <= 31) {
311647
- return true;
311648
- }
311649
- // 192.168.0.0/16
311650
- if (a === 192 && b === 168) {
311651
- return true;
311652
- }
311653
- }
311654
- // Check IPv6 patterns
311655
- // Block unique local addresses: fd00::/8
311656
- if (normalized.startsWith('fd') || normalized.startsWith('fc')) {
311657
- return true;
311658
- }
311659
- // Block link-local: fe80::/10
311660
- if (normalized.startsWith('fe80:')) {
311661
- return true;
311662
- }
311663
- return false;
311664
- }
311665
- /**
311666
- * Evaluate a policy rule against an input document via OPA REST API.
311667
- *
311668
- * @param input - The input document to evaluate
311669
- * @param rulePath - OPA rule path (e.g., 'visor/check/execute')
311670
- * @returns The result object from OPA, or undefined on error
311671
- */
311672
- async evaluate(input, rulePath) {
311673
- // OPA Data API: POST /v1/data/<path>
311674
- const encodedPath = rulePath
311675
- .split('/')
311676
- .map(s => encodeURIComponent(s))
311677
- .join('/');
311678
- const url = `${this.baseUrl}/v1/data/${encodedPath}`;
311679
- const controller = new AbortController();
311680
- const timer = setTimeout(() => controller.abort(), this.timeout);
311681
- try {
311682
- const response = await fetch(url, {
311683
- method: 'POST',
311684
- headers: { 'Content-Type': 'application/json' },
311685
- body: JSON.stringify({ input }),
311686
- signal: controller.signal,
311687
- });
311688
- if (!response.ok) {
311689
- throw new Error(`OPA HTTP ${response.status}: ${response.statusText}`);
311690
- }
311691
- let body;
311692
- try {
311693
- body = await response.json();
311694
- }
311695
- catch (jsonErr) {
311696
- throw new Error(`OPA HTTP evaluator: failed to parse JSON response: ${jsonErr instanceof Error ? jsonErr.message : String(jsonErr)}`);
311697
- }
311698
- // OPA returns { result: { ... } }
311699
- return body?.result;
311700
- }
311701
- finally {
311702
- clearTimeout(timer);
311703
- }
311704
- }
311705
- async shutdown() {
311706
- // No persistent connections to close
311707
- }
311708
- }
311709
- exports.OpaHttpEvaluator = OpaHttpEvaluator;
311710
-
311711
-
311712
- /***/ }),
311713
-
311714
- /***/ 39530:
311715
- /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
311716
-
311717
- "use strict";
311718
-
311719
- /**
311720
- * Copyright (c) ProbeLabs. All rights reserved.
311721
- * Licensed under the Elastic License 2.0; you may not use this file except
311722
- * in compliance with the Elastic License 2.0.
311723
- */
311724
- Object.defineProperty(exports, "__esModule", ({ value: true }));
311725
- exports.OpaPolicyEngine = void 0;
311726
- const opa_wasm_evaluator_1 = __nccwpck_require__(8613);
311727
- const opa_http_evaluator_1 = __nccwpck_require__(44693);
311728
- const policy_input_builder_1 = __nccwpck_require__(17117);
311729
- /**
311730
- * Enterprise OPA Policy Engine.
311731
- *
311732
- * Wraps both WASM (local) and HTTP (remote) OPA evaluators behind the
311733
- * OSS PolicyEngine interface. All OPA input building and role resolution
311734
- * is handled internally — the OSS call sites pass only plain types.
311735
- */
311736
- class OpaPolicyEngine {
311737
- evaluator = null;
311738
- fallback;
311739
- timeout;
311740
- config;
311741
- inputBuilder = null;
311742
- logger = null;
311743
- constructor(config) {
311744
- this.config = config;
311745
- this.fallback = config.fallback || 'deny';
311746
- this.timeout = config.timeout || 5000;
311747
- }
311748
- async initialize(config) {
311749
- // Resolve logger once at initialization
311750
- try {
311751
- this.logger = (__nccwpck_require__(86999).logger);
311752
- }
311753
- catch {
311754
- // logger not available in this context
311755
- }
311756
- // Build actor/repo context from environment (available at engine init time)
311757
- const actor = {
311758
- authorAssociation: process.env.VISOR_AUTHOR_ASSOCIATION,
311759
- login: process.env.VISOR_AUTHOR_LOGIN || process.env.GITHUB_ACTOR,
311760
- isLocalMode: !process.env.GITHUB_ACTIONS,
311761
- };
311762
- const repo = {
311763
- owner: process.env.GITHUB_REPOSITORY_OWNER,
311764
- name: process.env.GITHUB_REPOSITORY?.split('/')[1],
311765
- branch: process.env.GITHUB_HEAD_REF,
311766
- baseBranch: process.env.GITHUB_BASE_REF,
311767
- event: process.env.GITHUB_EVENT_NAME,
311768
- };
311769
- const prNum = process.env.GITHUB_PR_NUMBER
311770
- ? parseInt(process.env.GITHUB_PR_NUMBER, 10)
311771
- : undefined;
311772
- const pullRequest = {
311773
- number: prNum !== undefined && Number.isFinite(prNum) ? prNum : undefined,
311774
- };
311775
- this.inputBuilder = new policy_input_builder_1.PolicyInputBuilder(config, actor, repo, pullRequest);
311776
- if (config.engine === 'local') {
311777
- if (!config.rules) {
311778
- throw new Error('OPA local mode requires `policy.rules` path to .wasm or .rego files');
311779
- }
311780
- const wasm = new opa_wasm_evaluator_1.OpaWasmEvaluator();
311781
- await wasm.initialize(config.rules);
311782
- if (config.data) {
311783
- wasm.loadData(config.data);
311784
- }
311785
- this.evaluator = wasm;
311786
- }
311787
- else if (config.engine === 'remote') {
311788
- if (!config.url) {
311789
- throw new Error('OPA remote mode requires `policy.url` pointing to OPA server');
311790
- }
311791
- this.evaluator = new opa_http_evaluator_1.OpaHttpEvaluator(config.url, this.timeout);
311792
- }
311793
- else {
311794
- this.evaluator = null;
311795
- }
311796
- }
311797
- /**
311798
- * Update actor/repo/PR context (e.g., after PR info becomes available).
311799
- * Called by the enterprise loader when engine context is enriched.
311800
- */
311801
- setActorContext(actor, repo, pullRequest) {
311802
- this.inputBuilder = new policy_input_builder_1.PolicyInputBuilder(this.config, actor, repo, pullRequest);
311803
- }
311804
- async evaluateCheckExecution(checkId, checkConfig) {
311805
- if (!this.evaluator || !this.inputBuilder)
311806
- return { allowed: true };
311807
- const cfg = checkConfig && typeof checkConfig === 'object'
311808
- ? checkConfig
311809
- : {};
311810
- const policyOverride = cfg.policy;
311811
- const input = this.inputBuilder.forCheckExecution({
311812
- id: checkId,
311813
- type: cfg.type || 'ai',
311814
- group: cfg.group,
311815
- tags: cfg.tags,
311816
- criticality: cfg.criticality,
311817
- sandbox: cfg.sandbox,
311818
- policy: policyOverride,
311819
- });
311820
- return this.doEvaluate(input, this.resolveRulePath('check.execute', policyOverride?.rule));
311821
- }
311822
- async evaluateToolInvocation(serverName, methodName, transport) {
311823
- if (!this.evaluator || !this.inputBuilder)
311824
- return { allowed: true };
311825
- const input = this.inputBuilder.forToolInvocation(serverName, methodName, transport);
311826
- return this.doEvaluate(input, 'visor/tool/invoke');
311827
- }
311828
- async evaluateCapabilities(checkId, capabilities) {
311829
- if (!this.evaluator || !this.inputBuilder)
311830
- return { allowed: true };
311831
- const input = this.inputBuilder.forCapabilityResolve(checkId, capabilities);
311832
- return this.doEvaluate(input, 'visor/capability/resolve');
311833
- }
311834
- async shutdown() {
311835
- if (this.evaluator && 'shutdown' in this.evaluator) {
311836
- await this.evaluator.shutdown();
311837
- }
311838
- this.evaluator = null;
311839
- this.inputBuilder = null;
311840
- }
311841
- resolveRulePath(defaultScope, override) {
311842
- if (override) {
311843
- return override.startsWith('visor/') ? override : `visor/${override}`;
311844
- }
311845
- return `visor/${defaultScope.replace(/\./g, '/')}`;
311846
- }
311847
- async doEvaluate(input, rulePath) {
311848
- try {
311849
- this.logger?.debug(`[PolicyEngine] Evaluating ${rulePath}`, JSON.stringify(input));
311850
- let timer;
311851
- const timeoutPromise = new Promise((_resolve, reject) => {
311852
- timer = setTimeout(() => reject(new Error('policy evaluation timeout')), this.timeout);
311853
- });
311854
- try {
311855
- const result = await Promise.race([this.rawEvaluate(input, rulePath), timeoutPromise]);
311856
- const decision = this.parseDecision(result);
311857
- // In warn mode, override denied decisions to allowed but flag as warn
311858
- if (!decision.allowed && this.fallback === 'warn') {
311859
- decision.allowed = true;
311860
- decision.warn = true;
311861
- decision.reason = `audit: ${decision.reason || 'policy denied'}`;
311862
- }
311863
- this.logger?.debug(`[PolicyEngine] Decision for ${rulePath}: allowed=${decision.allowed}, warn=${decision.warn || false}, reason=${decision.reason || 'none'}`);
311864
- return decision;
311865
- }
311866
- finally {
311867
- if (timer)
311868
- clearTimeout(timer);
311869
- }
311870
- }
311871
- catch (err) {
311872
- const msg = err instanceof Error ? err.message : String(err);
311873
- this.logger?.warn(`[PolicyEngine] Evaluation failed for ${rulePath}: ${msg}`);
311874
- return {
311875
- allowed: this.fallback === 'allow' || this.fallback === 'warn',
311876
- warn: this.fallback === 'warn' ? true : undefined,
311877
- reason: `policy evaluation failed, fallback=${this.fallback}`,
311878
- };
311879
- }
311880
- }
311881
- async rawEvaluate(input, rulePath) {
311882
- if (this.evaluator instanceof opa_wasm_evaluator_1.OpaWasmEvaluator) {
311883
- const result = await this.evaluator.evaluate(input);
311884
- // WASM compiled with `-e visor` entrypoint returns the full visor package tree.
311885
- // Navigate to the specific rule subtree using rulePath segments.
311886
- // e.g., 'visor/check/execute' → result.check.execute
311887
- return this.navigateWasmResult(result, rulePath);
311888
- }
311889
- return this.evaluator.evaluate(input, rulePath);
311890
- }
311891
- /**
311892
- * Navigate nested OPA WASM result tree to reach the specific rule's output.
311893
- * The WASM entrypoint `-e visor` means the result root IS the visor package,
311894
- * so we strip the `visor/` prefix and walk the remaining segments.
311895
- */
311896
- navigateWasmResult(result, rulePath) {
311897
- if (!result || typeof result !== 'object')
311898
- return result;
311899
- // Strip the 'visor/' prefix (matches our compilation entrypoint)
311900
- const segments = rulePath.replace(/^visor\//, '').split('/');
311901
- let current = result;
311902
- for (const seg of segments) {
311903
- if (current && typeof current === 'object' && seg in current) {
311904
- current = current[seg];
311905
- }
311906
- else {
311907
- return undefined; // path not found in result tree
311908
- }
311909
- }
311910
- return current;
311911
- }
311912
- parseDecision(result) {
311913
- if (result === undefined || result === null) {
311914
- return {
311915
- allowed: this.fallback === 'allow' || this.fallback === 'warn',
311916
- warn: this.fallback === 'warn' ? true : undefined,
311917
- reason: this.fallback === 'warn' ? 'audit: no policy result' : 'no policy result',
311918
- };
311919
- }
311920
- const allowed = result.allowed !== false;
311921
- const decision = {
311922
- allowed,
311923
- reason: result.reason,
311924
- };
311925
- if (result.capabilities) {
311926
- decision.capabilities = result.capabilities;
311927
- }
311928
- return decision;
311929
- }
311930
- }
311931
- exports.OpaPolicyEngine = OpaPolicyEngine;
311932
-
311933
-
311934
- /***/ }),
311935
-
311936
- /***/ 8613:
311937
- /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
311938
-
311939
- "use strict";
311940
-
311941
- /**
311942
- * Copyright (c) ProbeLabs. All rights reserved.
311943
- * Licensed under the Elastic License 2.0; you may not use this file except
311944
- * in compliance with the Elastic License 2.0.
311945
- */
311946
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
311947
- if (k2 === undefined) k2 = k;
311948
- var desc = Object.getOwnPropertyDescriptor(m, k);
311949
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
311950
- desc = { enumerable: true, get: function() { return m[k]; } };
311951
- }
311952
- Object.defineProperty(o, k2, desc);
311953
- }) : (function(o, m, k, k2) {
311954
- if (k2 === undefined) k2 = k;
311955
- o[k2] = m[k];
311956
- }));
311957
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
311958
- Object.defineProperty(o, "default", { enumerable: true, value: v });
311959
- }) : function(o, v) {
311960
- o["default"] = v;
311961
- });
311962
- var __importStar = (this && this.__importStar) || (function () {
311963
- var ownKeys = function(o) {
311964
- ownKeys = Object.getOwnPropertyNames || function (o) {
311965
- var ar = [];
311966
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
311967
- return ar;
311968
- };
311969
- return ownKeys(o);
311970
- };
311971
- return function (mod) {
311972
- if (mod && mod.__esModule) return mod;
311973
- var result = {};
311974
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
311975
- __setModuleDefault(result, mod);
311976
- return result;
311977
- };
311978
- })();
311979
- Object.defineProperty(exports, "__esModule", ({ value: true }));
311980
- exports.OpaWasmEvaluator = void 0;
311981
- const fs = __importStar(__nccwpck_require__(79896));
311982
- const path = __importStar(__nccwpck_require__(16928));
311983
- const opa_compiler_1 = __nccwpck_require__(628);
311984
- /**
311985
- * OPA WASM Evaluator - loads and evaluates OPA policies locally.
311986
- *
311987
- * Supports three input formats:
311988
- * 1. Pre-compiled `.wasm` bundle — loaded directly (fastest startup)
311989
- * 2. `.rego` files or directory — auto-compiled to WASM via `opa build` CLI
311990
- * 3. Directory with `policy.wasm` inside — loaded directly
311991
- *
311992
- * Compilation and caching of .rego files is delegated to {@link OpaCompiler}.
311993
- *
311994
- * Requires:
311995
- * - `@open-policy-agent/opa-wasm` npm package (optional dep)
311996
- * - `opa` CLI on PATH (only when auto-compiling .rego files)
311997
- */
311998
- class OpaWasmEvaluator {
311999
- policy = null;
312000
- dataDocument = {};
312001
- compiler = new opa_compiler_1.OpaCompiler();
312002
- async initialize(rulesPath) {
312003
- const paths = Array.isArray(rulesPath) ? rulesPath : [rulesPath];
312004
- const wasmBytes = await this.compiler.resolveWasmBytes(paths);
312005
- try {
312006
- // Use createRequire to load the optional dep at runtime without ncc bundling it.
312007
- // `new Function('id', 'return require(id)')` fails in ncc bundles because
312008
- // `require` is not in the `new Function` scope. `createRequire` works correctly
312009
- // because it creates a real Node.js require rooted at the given path.
312010
- // eslint-disable-next-line @typescript-eslint/no-var-requires
312011
- const { createRequire } = __nccwpck_require__(73339);
312012
- const runtimeRequire = createRequire(__filename);
312013
- const opaWasm = runtimeRequire('@open-policy-agent/opa-wasm');
312014
- const loadPolicy = opaWasm.loadPolicy || opaWasm.default?.loadPolicy;
312015
- if (!loadPolicy) {
312016
- throw new Error('loadPolicy not found in @open-policy-agent/opa-wasm');
312017
- }
312018
- this.policy = await loadPolicy(wasmBytes);
312019
- }
312020
- catch (err) {
312021
- if (err?.code === 'MODULE_NOT_FOUND' || err?.code === 'ERR_MODULE_NOT_FOUND') {
312022
- throw new Error('OPA WASM evaluator requires @open-policy-agent/opa-wasm. ' +
312023
- 'Install it with: npm install @open-policy-agent/opa-wasm');
312024
- }
312025
- throw err;
312026
- }
312027
- }
312028
- /**
312029
- * Load external data from a JSON file to use as the OPA data document.
312030
- * The loaded data will be passed to `policy.setData()` during evaluation,
312031
- * making it available in Rego via `data.<key>`.
312032
- */
312033
- loadData(dataPath) {
312034
- const resolved = path.resolve(dataPath);
312035
- if (path.normalize(resolved).includes('..')) {
312036
- throw new Error(`Data path contains traversal sequences: ${dataPath}`);
312037
- }
312038
- if (!fs.existsSync(resolved)) {
312039
- throw new Error(`OPA data file not found: ${resolved}`);
312040
- }
312041
- const stat = fs.statSync(resolved);
312042
- if (stat.size > 10 * 1024 * 1024) {
312043
- throw new Error(`OPA data file exceeds 10MB limit: ${resolved} (${stat.size} bytes)`);
312044
- }
312045
- const raw = fs.readFileSync(resolved, 'utf-8');
312046
- try {
312047
- const parsed = JSON.parse(raw);
312048
- if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
312049
- throw new Error('OPA data file must contain a JSON object (not an array or primitive)');
312050
- }
312051
- this.dataDocument = parsed;
312052
- }
312053
- catch (err) {
312054
- if (err.message.startsWith('OPA data file must')) {
312055
- throw err;
312056
- }
312057
- throw new Error(`Failed to parse OPA data file ${resolved}: ${err.message}`);
312058
- }
312059
- }
312060
- async evaluate(input) {
312061
- if (!this.policy) {
312062
- throw new Error('OPA WASM evaluator not initialized');
312063
- }
312064
- this.policy.setData(this.dataDocument);
312065
- const resultSet = this.policy.evaluate(input);
312066
- if (Array.isArray(resultSet) && resultSet.length > 0) {
312067
- return resultSet[0].result;
312068
- }
312069
- return undefined;
312070
- }
312071
- async shutdown() {
312072
- if (this.policy) {
312073
- // opa-wasm policy objects may have a close/free method for WASM cleanup
312074
- if (typeof this.policy.close === 'function') {
312075
- try {
312076
- this.policy.close();
312077
- }
312078
- catch { }
312079
- }
312080
- else if (typeof this.policy.free === 'function') {
312081
- try {
312082
- this.policy.free();
312083
- }
312084
- catch { }
312085
- }
312086
- }
312087
- this.policy = null;
312088
- }
312089
- }
312090
- exports.OpaWasmEvaluator = OpaWasmEvaluator;
312091
-
312092
-
312093
- /***/ }),
312094
-
312095
- /***/ 17117:
312096
- /***/ ((__unused_webpack_module, exports) => {
312097
-
312098
- "use strict";
312099
-
312100
- /**
312101
- * Copyright (c) ProbeLabs. All rights reserved.
312102
- * Licensed under the Elastic License 2.0; you may not use this file except
312103
- * in compliance with the Elastic License 2.0.
312104
- */
312105
- Object.defineProperty(exports, "__esModule", ({ value: true }));
312106
- exports.PolicyInputBuilder = void 0;
312107
- /**
312108
- * Builds OPA-compatible input documents from engine context.
312109
- *
312110
- * Resolves actor roles from the `policy.roles` config section by matching
312111
- * the actor's authorAssociation and login against role definitions.
312112
- */
312113
- class PolicyInputBuilder {
312114
- roles;
312115
- actor;
312116
- repository;
312117
- pullRequest;
312118
- constructor(policyConfig, actor, repository, pullRequest) {
312119
- this.roles = policyConfig.roles || {};
312120
- this.actor = actor;
312121
- this.repository = repository;
312122
- this.pullRequest = pullRequest;
312123
- }
312124
- /** Resolve which roles apply to the current actor. */
312125
- resolveRoles() {
312126
- const matched = [];
312127
- for (const [roleName, roleConfig] of Object.entries(this.roles)) {
312128
- let identityMatch = false;
312129
- if (roleConfig.author_association &&
312130
- this.actor.authorAssociation &&
312131
- roleConfig.author_association.includes(this.actor.authorAssociation)) {
312132
- identityMatch = true;
312133
- }
312134
- if (!identityMatch &&
312135
- roleConfig.users &&
312136
- this.actor.login &&
312137
- roleConfig.users.includes(this.actor.login)) {
312138
- identityMatch = true;
312139
- }
312140
- // Slack user ID match
312141
- if (!identityMatch &&
312142
- roleConfig.slack_users &&
312143
- this.actor.slack?.userId &&
312144
- roleConfig.slack_users.includes(this.actor.slack.userId)) {
312145
- identityMatch = true;
312146
- }
312147
- // Email match (case-insensitive)
312148
- if (!identityMatch && roleConfig.emails && this.actor.slack?.email) {
312149
- const actorEmail = this.actor.slack.email.toLowerCase();
312150
- if (roleConfig.emails.some(e => e.toLowerCase() === actorEmail)) {
312151
- identityMatch = true;
312152
- }
312153
- }
312154
- // Note: teams-based role resolution requires GitHub API access (read:org scope)
312155
- // and is not yet implemented. If configured, the role will not match via teams.
312156
- if (!identityMatch)
312157
- continue;
312158
- // slack_channels gate: if set, the role only applies when triggered from one of these channels
312159
- if (roleConfig.slack_channels && roleConfig.slack_channels.length > 0) {
312160
- if (!this.actor.slack?.channelId ||
312161
- !roleConfig.slack_channels.includes(this.actor.slack.channelId)) {
312162
- continue;
312163
- }
312164
- }
312165
- matched.push(roleName);
312166
- }
312167
- return matched;
312168
- }
312169
- buildActor() {
312170
- return {
312171
- authorAssociation: this.actor.authorAssociation,
312172
- login: this.actor.login,
312173
- roles: this.resolveRoles(),
312174
- isLocalMode: this.actor.isLocalMode,
312175
- ...(this.actor.slack && { slack: this.actor.slack }),
312176
- };
312177
- }
312178
- forCheckExecution(check) {
312179
- return {
312180
- scope: 'check.execute',
312181
- check: {
312182
- id: check.id,
312183
- type: check.type,
312184
- group: check.group,
312185
- tags: check.tags,
312186
- criticality: check.criticality,
312187
- sandbox: check.sandbox,
312188
- policy: check.policy,
312189
- },
312190
- actor: this.buildActor(),
312191
- repository: this.repository,
312192
- pullRequest: this.pullRequest,
312193
- };
312194
- }
312195
- forToolInvocation(serverName, methodName, transport) {
312196
- return {
312197
- scope: 'tool.invoke',
312198
- tool: { serverName, methodName, transport },
312199
- actor: this.buildActor(),
312200
- repository: this.repository,
312201
- pullRequest: this.pullRequest,
312202
- };
312203
- }
312204
- forCapabilityResolve(checkId, capabilities) {
312205
- return {
312206
- scope: 'capability.resolve',
312207
- check: { id: checkId, type: 'ai' },
312208
- capability: capabilities,
312209
- actor: this.buildActor(),
312210
- repository: this.repository,
312211
- pullRequest: this.pullRequest,
312212
- };
312213
- }
312214
- }
312215
- exports.PolicyInputBuilder = PolicyInputBuilder;
312216
-
312217
-
312218
- /***/ }),
312219
-
312220
- /***/ 63737:
312221
- /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
312222
-
312223
- "use strict";
312224
-
312225
- /**
312226
- * Copyright (c) ProbeLabs. All rights reserved.
312227
- * Licensed under the Elastic License 2.0; you may not use this file except
312228
- * in compliance with the Elastic License 2.0.
312229
- */
312230
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
312231
- if (k2 === undefined) k2 = k;
312232
- var desc = Object.getOwnPropertyDescriptor(m, k);
312233
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
312234
- desc = { enumerable: true, get: function() { return m[k]; } };
312235
- }
312236
- Object.defineProperty(o, k2, desc);
312237
- }) : (function(o, m, k, k2) {
312238
- if (k2 === undefined) k2 = k;
312239
- o[k2] = m[k];
312240
- }));
312241
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
312242
- Object.defineProperty(o, "default", { enumerable: true, value: v });
312243
- }) : function(o, v) {
312244
- o["default"] = v;
312245
- });
312246
- var __importStar = (this && this.__importStar) || (function () {
312247
- var ownKeys = function(o) {
312248
- ownKeys = Object.getOwnPropertyNames || function (o) {
312249
- var ar = [];
312250
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
312251
- return ar;
312252
- };
312253
- return ownKeys(o);
312254
- };
312255
- return function (mod) {
312256
- if (mod && mod.__esModule) return mod;
312257
- var result = {};
312258
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
312259
- __setModuleDefault(result, mod);
312260
- return result;
312261
- };
312262
- })();
312263
- Object.defineProperty(exports, "__esModule", ({ value: true }));
312264
- exports.KnexStoreBackend = void 0;
312265
- /**
312266
- * Knex-backed schedule store for PostgreSQL, MySQL, and MSSQL (Enterprise)
312267
- *
312268
- * Uses Knex query builder for database-agnostic SQL. Same schema as SQLite backend
312269
- * but with real distributed locking via row-level claims (claimed_by/claimed_at/lock_token).
312270
- */
312271
- const fs = __importStar(__nccwpck_require__(79896));
312272
- const path = __importStar(__nccwpck_require__(16928));
312273
- const uuid_1 = __nccwpck_require__(31914);
312274
- const logger_1 = __nccwpck_require__(86999);
312275
- function toNum(val) {
312276
- if (val === null || val === undefined)
312277
- return undefined;
312278
- return typeof val === 'string' ? parseInt(val, 10) : val;
312279
- }
312280
- function safeJsonParse(value) {
312281
- if (!value)
312282
- return undefined;
312283
- try {
312284
- return JSON.parse(value);
312285
- }
312286
- catch {
312287
- return undefined;
312288
- }
312289
- }
312290
- function fromTriggerRow(row) {
312291
- return {
312292
- id: row.id,
312293
- creatorId: row.creator_id,
312294
- creatorContext: row.creator_context ?? undefined,
312295
- creatorName: row.creator_name ?? undefined,
312296
- description: row.description ?? undefined,
312297
- channels: safeJsonParse(row.channels),
312298
- fromUsers: safeJsonParse(row.from_users),
312299
- fromBots: row.from_bots === true || row.from_bots === 1,
312300
- contains: safeJsonParse(row.contains),
312301
- matchPattern: row.match_pattern ?? undefined,
312302
- threads: row.threads,
312303
- workflow: row.workflow,
312304
- inputs: safeJsonParse(row.inputs),
312305
- outputContext: safeJsonParse(row.output_context),
312306
- status: row.status,
312307
- enabled: row.enabled === true || row.enabled === 1,
312308
- createdAt: toNum(row.created_at),
312309
- };
312310
- }
312311
- function toTriggerInsertRow(trigger) {
312312
- return {
312313
- id: trigger.id,
312314
- creator_id: trigger.creatorId,
312315
- creator_context: trigger.creatorContext ?? null,
312316
- creator_name: trigger.creatorName ?? null,
312317
- description: trigger.description ?? null,
312318
- channels: trigger.channels ? JSON.stringify(trigger.channels) : null,
312319
- from_users: trigger.fromUsers ? JSON.stringify(trigger.fromUsers) : null,
312320
- from_bots: trigger.fromBots,
312321
- contains: trigger.contains ? JSON.stringify(trigger.contains) : null,
312322
- match_pattern: trigger.matchPattern ?? null,
312323
- threads: trigger.threads,
312324
- workflow: trigger.workflow,
312325
- inputs: trigger.inputs ? JSON.stringify(trigger.inputs) : null,
312326
- output_context: trigger.outputContext ? JSON.stringify(trigger.outputContext) : null,
312327
- status: trigger.status,
312328
- enabled: trigger.enabled,
312329
- created_at: trigger.createdAt,
312330
- };
312331
- }
312332
- function fromDbRow(row) {
312333
- return {
312334
- id: row.id,
312335
- creatorId: row.creator_id,
312336
- creatorContext: row.creator_context ?? undefined,
312337
- creatorName: row.creator_name ?? undefined,
312338
- timezone: row.timezone,
312339
- schedule: row.schedule_expr,
312340
- runAt: toNum(row.run_at),
312341
- isRecurring: row.is_recurring === true || row.is_recurring === 1,
312342
- originalExpression: row.original_expression,
312343
- workflow: row.workflow ?? undefined,
312344
- workflowInputs: safeJsonParse(row.workflow_inputs),
312345
- outputContext: safeJsonParse(row.output_context),
312346
- status: row.status,
312347
- createdAt: toNum(row.created_at),
312348
- lastRunAt: toNum(row.last_run_at),
312349
- nextRunAt: toNum(row.next_run_at),
312350
- runCount: row.run_count,
312351
- failureCount: row.failure_count,
312352
- lastError: row.last_error ?? undefined,
312353
- previousResponse: row.previous_response ?? undefined,
312354
- };
312355
- }
312356
- function toInsertRow(schedule) {
312357
- return {
312358
- id: schedule.id,
312359
- creator_id: schedule.creatorId,
312360
- creator_context: schedule.creatorContext ?? null,
312361
- creator_name: schedule.creatorName ?? null,
312362
- timezone: schedule.timezone,
312363
- schedule_expr: schedule.schedule,
312364
- run_at: schedule.runAt ?? null,
312365
- is_recurring: schedule.isRecurring,
312366
- original_expression: schedule.originalExpression,
312367
- workflow: schedule.workflow ?? null,
312368
- workflow_inputs: schedule.workflowInputs ? JSON.stringify(schedule.workflowInputs) : null,
312369
- output_context: schedule.outputContext ? JSON.stringify(schedule.outputContext) : null,
312370
- status: schedule.status,
312371
- created_at: schedule.createdAt,
312372
- last_run_at: schedule.lastRunAt ?? null,
312373
- next_run_at: schedule.nextRunAt ?? null,
312374
- run_count: schedule.runCount,
312375
- failure_count: schedule.failureCount,
312376
- last_error: schedule.lastError ?? null,
312377
- previous_response: schedule.previousResponse ?? null,
312378
- };
312379
- }
312380
- /**
312381
- * Enterprise Knex-backed store for PostgreSQL, MySQL, and MSSQL
312382
- */
312383
- class KnexStoreBackend {
312384
- knex = null;
312385
- driver;
312386
- connection;
312387
- constructor(driver, storageConfig, _haConfig) {
312388
- this.driver = driver;
312389
- this.connection = (storageConfig.connection || {});
312390
- }
312391
- async initialize() {
312392
- // Load knex dynamically
312393
- const { createRequire } = __nccwpck_require__(73339);
312394
- const runtimeRequire = createRequire(__filename);
312395
- let knexFactory;
312396
- try {
312397
- knexFactory = runtimeRequire('knex');
312398
- }
312399
- catch (err) {
312400
- const code = err?.code;
312401
- if (code === 'MODULE_NOT_FOUND' || code === 'ERR_MODULE_NOT_FOUND') {
312402
- throw new Error('knex is required for PostgreSQL/MySQL/MSSQL schedule storage. ' +
312403
- 'Install it with: npm install knex');
312404
- }
312405
- throw err;
312406
- }
312407
- const clientMap = {
312408
- postgresql: 'pg',
312409
- mysql: 'mysql2',
312410
- mssql: 'tedious',
312411
- };
312412
- const client = clientMap[this.driver];
312413
- // Build connection config
312414
- let connection;
312415
- if (this.connection.connection_string) {
312416
- connection = this.connection.connection_string;
312417
- }
312418
- else if (this.driver === 'mssql') {
312419
- connection = this.buildMssqlConnection();
312420
- }
312421
- else {
312422
- connection = this.buildStandardConnection();
312423
- }
312424
- this.knex = knexFactory({
312425
- client,
312426
- connection,
312427
- pool: {
312428
- min: this.connection.pool?.min ?? 0,
312429
- max: this.connection.pool?.max ?? 10,
312430
- },
312431
- });
312432
- // Run schema migration
312433
- await this.migrateSchema();
312434
- logger_1.logger.info(`[KnexStore] Initialized (${this.driver})`);
312435
- }
312436
- buildStandardConnection() {
312437
- return {
312438
- host: this.connection.host || 'localhost',
312439
- port: this.connection.port,
312440
- database: this.connection.database || 'visor',
312441
- user: this.connection.user,
312442
- password: this.connection.password,
312443
- ssl: this.resolveSslConfig(),
312444
- };
312445
- }
312446
- buildMssqlConnection() {
312447
- const ssl = this.connection.ssl;
312448
- const sslEnabled = ssl === true || (typeof ssl === 'object' && ssl.enabled !== false);
312449
- return {
312450
- server: this.connection.host || 'localhost',
312451
- port: this.connection.port,
312452
- database: this.connection.database || 'visor',
312453
- user: this.connection.user,
312454
- password: this.connection.password,
312455
- options: {
312456
- encrypt: sslEnabled,
312457
- trustServerCertificate: typeof ssl === 'object' ? ssl.reject_unauthorized === false : !sslEnabled,
312458
- },
312459
- };
312460
- }
312461
- resolveSslConfig() {
312462
- const ssl = this.connection.ssl;
312463
- if (ssl === false || ssl === undefined)
312464
- return false;
312465
- if (ssl === true)
312466
- return { rejectUnauthorized: true };
312467
- // Object config
312468
- if (ssl.enabled === false)
312469
- return false;
312470
- const result = {
312471
- rejectUnauthorized: ssl.reject_unauthorized !== false,
312472
- };
312473
- if (ssl.ca) {
312474
- const caPath = this.validateSslPath(ssl.ca, 'CA certificate');
312475
- result.ca = fs.readFileSync(caPath, 'utf8');
312476
- }
312477
- if (ssl.cert) {
312478
- const certPath = this.validateSslPath(ssl.cert, 'client certificate');
312479
- result.cert = fs.readFileSync(certPath, 'utf8');
312480
- }
312481
- if (ssl.key) {
312482
- const keyPath = this.validateSslPath(ssl.key, 'client key');
312483
- result.key = fs.readFileSync(keyPath, 'utf8');
312484
- }
312485
- return result;
312486
- }
312487
- validateSslPath(filePath, label) {
312488
- const resolved = path.resolve(filePath);
312489
- if (resolved !== path.normalize(resolved)) {
312490
- throw new Error(`SSL ${label} path contains invalid sequences: ${filePath}`);
312491
- }
312492
- if (!fs.existsSync(resolved)) {
312493
- throw new Error(`SSL ${label} not found: ${filePath}`);
312494
- }
312495
- return resolved;
312496
- }
312497
- async shutdown() {
312498
- if (this.knex) {
312499
- await this.knex.destroy();
312500
- this.knex = null;
312501
- }
312502
- }
312503
- async migrateSchema() {
312504
- const knex = this.getKnex();
312505
- const exists = await knex.schema.hasTable('schedules');
312506
- if (!exists) {
312507
- await knex.schema.createTable('schedules', table => {
312508
- table.string('id', 36).primary();
312509
- table.string('creator_id', 255).notNullable().index();
312510
- table.string('creator_context', 255);
312511
- table.string('creator_name', 255);
312512
- table.string('timezone', 64).notNullable().defaultTo('UTC');
312513
- table.string('schedule_expr', 255);
312514
- table.bigInteger('run_at');
312515
- table.boolean('is_recurring').notNullable();
312516
- table.text('original_expression');
312517
- table.string('workflow', 255);
312518
- table.text('workflow_inputs');
312519
- table.text('output_context');
312520
- table.string('status', 20).notNullable().index();
312521
- table.bigInteger('created_at').notNullable();
312522
- table.bigInteger('last_run_at');
312523
- table.bigInteger('next_run_at');
312524
- table.integer('run_count').notNullable().defaultTo(0);
312525
- table.integer('failure_count').notNullable().defaultTo(0);
312526
- table.text('last_error');
312527
- table.text('previous_response');
312528
- table.index(['status', 'next_run_at']);
312529
- });
312530
- }
312531
- // Create message_triggers table
312532
- const triggersExist = await knex.schema.hasTable('message_triggers');
312533
- if (!triggersExist) {
312534
- await knex.schema.createTable('message_triggers', table => {
312535
- table.string('id', 36).primary();
312536
- table.string('creator_id', 255).notNullable().index();
312537
- table.string('creator_context', 255);
312538
- table.string('creator_name', 255);
312539
- table.text('description');
312540
- table.text('channels'); // JSON array
312541
- table.text('from_users'); // JSON array
312542
- table.boolean('from_bots').notNullable().defaultTo(false);
312543
- table.text('contains'); // JSON array
312544
- table.text('match_pattern');
312545
- table.string('threads', 20).notNullable().defaultTo('any');
312546
- table.string('workflow', 255).notNullable();
312547
- table.text('inputs'); // JSON
312548
- table.text('output_context'); // JSON
312549
- table.string('status', 20).notNullable().defaultTo('active').index();
312550
- table.boolean('enabled').notNullable().defaultTo(true);
312551
- table.bigInteger('created_at').notNullable();
312552
- });
312553
- }
312554
- // Create scheduler_locks table for distributed locking
312555
- const locksExist = await knex.schema.hasTable('scheduler_locks');
312556
- if (!locksExist) {
312557
- await knex.schema.createTable('scheduler_locks', table => {
312558
- table.string('lock_id', 255).primary();
312559
- table.string('node_id', 255).notNullable();
312560
- table.string('lock_token', 36).notNullable();
312561
- table.bigInteger('acquired_at').notNullable();
312562
- table.bigInteger('expires_at').notNullable();
312563
- });
312564
- }
312565
- }
312566
- getKnex() {
312567
- if (!this.knex) {
312568
- throw new Error('[KnexStore] Not initialized. Call initialize() first.');
312569
- }
312570
- return this.knex;
312571
- }
312572
- // --- CRUD ---
312573
- async create(schedule) {
312574
- const knex = this.getKnex();
312575
- const newSchedule = {
312576
- ...schedule,
312577
- id: (0, uuid_1.v4)(),
312578
- createdAt: Date.now(),
312579
- runCount: 0,
312580
- failureCount: 0,
312581
- status: 'active',
312582
- };
312583
- await knex('schedules').insert(toInsertRow(newSchedule));
312584
- logger_1.logger.info(`[KnexStore] Created schedule ${newSchedule.id} for user ${newSchedule.creatorId}`);
312585
- return newSchedule;
312586
- }
312587
- async importSchedule(schedule) {
312588
- const knex = this.getKnex();
312589
- const existing = await knex('schedules').where('id', schedule.id).first();
312590
- if (existing)
312591
- return; // Already imported (idempotent)
312592
- await knex('schedules').insert(toInsertRow(schedule));
312593
- }
312594
- async get(id) {
312595
- const knex = this.getKnex();
312596
- const row = await knex('schedules').where('id', id).first();
312597
- return row ? fromDbRow(row) : undefined;
312598
- }
312599
- async update(id, patch) {
312600
- const knex = this.getKnex();
312601
- const existing = await knex('schedules').where('id', id).first();
312602
- if (!existing)
312603
- return undefined;
312604
- const current = fromDbRow(existing);
312605
- const updated = { ...current, ...patch, id: current.id };
312606
- const row = toInsertRow(updated);
312607
- // Remove id from update (PK cannot change)
312608
- delete row.id;
312609
- await knex('schedules').where('id', id).update(row);
312610
- return updated;
312611
- }
312612
- async delete(id) {
312613
- const knex = this.getKnex();
312614
- const deleted = await knex('schedules').where('id', id).del();
312615
- if (deleted > 0) {
312616
- logger_1.logger.info(`[KnexStore] Deleted schedule ${id}`);
312617
- return true;
312618
- }
312619
- return false;
312620
- }
312621
- // --- Queries ---
312622
- async getByCreator(creatorId) {
312623
- const knex = this.getKnex();
312624
- const rows = await knex('schedules').where('creator_id', creatorId);
312625
- return rows.map((r) => fromDbRow(r));
312626
- }
312627
- async getActiveSchedules() {
312628
- const knex = this.getKnex();
312629
- const rows = await knex('schedules').where('status', 'active');
312630
- return rows.map((r) => fromDbRow(r));
312631
- }
312632
- async getDueSchedules(now) {
312633
- const ts = now ?? Date.now();
312634
- const knex = this.getKnex();
312635
- // MSSQL uses 1/0 for booleans
312636
- const bFalse = this.driver === 'mssql' ? 0 : false;
312637
- const bTrue = this.driver === 'mssql' ? 1 : true;
312638
- const rows = await knex('schedules')
312639
- .where('status', 'active')
312640
- .andWhere(function () {
312641
- this.where(function () {
312642
- this.where('is_recurring', bFalse)
312643
- .whereNotNull('run_at')
312644
- .where('run_at', '<=', ts);
312645
- }).orWhere(function () {
312646
- this.where('is_recurring', bTrue)
312647
- .whereNotNull('next_run_at')
312648
- .where('next_run_at', '<=', ts);
312649
- });
312650
- });
312651
- return rows.map((r) => fromDbRow(r));
312652
- }
312653
- async findByWorkflow(creatorId, workflowName) {
312654
- const knex = this.getKnex();
312655
- const escaped = workflowName.toLowerCase().replace(/[%_\\]/g, '\\$&');
312656
- const pattern = `%${escaped}%`;
312657
- const rows = await knex('schedules')
312658
- .where('creator_id', creatorId)
312659
- .where('status', 'active')
312660
- .whereRaw("LOWER(workflow) LIKE ? ESCAPE '\\'", [pattern]);
312661
- return rows.map((r) => fromDbRow(r));
312662
- }
312663
- async getAll() {
312664
- const knex = this.getKnex();
312665
- const rows = await knex('schedules');
312666
- return rows.map((r) => fromDbRow(r));
312667
- }
312668
- async getStats() {
312669
- const knex = this.getKnex();
312670
- // MSSQL uses 1/0 for booleans; PostgreSQL/MySQL accept both true/1
312671
- const boolTrue = this.driver === 'mssql' ? '1' : 'true';
312672
- const boolFalse = this.driver === 'mssql' ? '0' : 'false';
312673
- const result = await knex('schedules')
312674
- .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`))
312675
- .first();
312676
- return {
312677
- total: Number(result.total) || 0,
312678
- active: Number(result.active) || 0,
312679
- paused: Number(result.paused) || 0,
312680
- completed: Number(result.completed) || 0,
312681
- failed: Number(result.failed) || 0,
312682
- recurring: Number(result.recurring) || 0,
312683
- oneTime: Number(result.one_time) || 0,
312684
- };
312685
- }
312686
- async validateLimits(creatorId, isRecurring, limits) {
312687
- const knex = this.getKnex();
312688
- if (limits.maxGlobal) {
312689
- const result = await knex('schedules').count('* as cnt').first();
312690
- if (Number(result?.cnt) >= limits.maxGlobal) {
312691
- throw new Error(`Global schedule limit reached (${limits.maxGlobal})`);
312692
- }
312693
- }
312694
- if (limits.maxPerUser) {
312695
- const result = await knex('schedules')
312696
- .where('creator_id', creatorId)
312697
- .count('* as cnt')
312698
- .first();
312699
- if (Number(result?.cnt) >= limits.maxPerUser) {
312700
- throw new Error(`You have reached the maximum number of schedules (${limits.maxPerUser})`);
312701
- }
312702
- }
312703
- if (isRecurring && limits.maxRecurringPerUser) {
312704
- const bTrue = this.driver === 'mssql' ? 1 : true;
312705
- const result = await knex('schedules')
312706
- .where('creator_id', creatorId)
312707
- .where('is_recurring', bTrue)
312708
- .count('* as cnt')
312709
- .first();
312710
- if (Number(result?.cnt) >= limits.maxRecurringPerUser) {
312711
- throw new Error(`You have reached the maximum number of recurring schedules (${limits.maxRecurringPerUser})`);
312712
- }
312713
- }
312714
- }
312715
- // --- HA Distributed Locking (via scheduler_locks table) ---
312716
- async tryAcquireLock(lockId, nodeId, ttlSeconds) {
312717
- const knex = this.getKnex();
312718
- const now = Date.now();
312719
- const expiresAt = now + ttlSeconds * 1000;
312720
- const token = (0, uuid_1.v4)();
312721
- // Step 1: Try to claim an existing expired lock
312722
- const updated = await knex('scheduler_locks')
312723
- .where('lock_id', lockId)
312724
- .where('expires_at', '<', now)
312725
- .update({
312726
- node_id: nodeId,
312727
- lock_token: token,
312728
- acquired_at: now,
312729
- expires_at: expiresAt,
312730
- });
312731
- if (updated > 0)
312732
- return token;
312733
- // Step 2: Try to INSERT a new lock row
312734
- try {
312735
- await knex('scheduler_locks').insert({
312736
- lock_id: lockId,
312737
- node_id: nodeId,
312738
- lock_token: token,
312739
- acquired_at: now,
312740
- expires_at: expiresAt,
312741
- });
312742
- return token;
312743
- }
312744
- catch {
312745
- // Unique constraint violation — another node holds the lock
312746
- return null;
312747
- }
312748
- }
312749
- async releaseLock(lockId, lockToken) {
312750
- const knex = this.getKnex();
312751
- await knex('scheduler_locks').where('lock_id', lockId).where('lock_token', lockToken).del();
312752
- }
312753
- async renewLock(lockId, lockToken, ttlSeconds) {
312754
- const knex = this.getKnex();
312755
- const now = Date.now();
312756
- const expiresAt = now + ttlSeconds * 1000;
312757
- const updated = await knex('scheduler_locks')
312758
- .where('lock_id', lockId)
312759
- .where('lock_token', lockToken)
312760
- .update({ acquired_at: now, expires_at: expiresAt });
312761
- return updated > 0;
312762
- }
312763
- async flush() {
312764
- // No-op for server-based backends
312765
- }
312766
- // --- Message Trigger CRUD ---
312767
- async createTrigger(trigger) {
312768
- const knex = this.getKnex();
312769
- const newTrigger = {
312770
- ...trigger,
312771
- id: (0, uuid_1.v4)(),
312772
- createdAt: Date.now(),
312773
- };
312774
- await knex('message_triggers').insert(toTriggerInsertRow(newTrigger));
312775
- logger_1.logger.info(`[KnexStore] Created trigger ${newTrigger.id} for user ${newTrigger.creatorId}`);
312776
- return newTrigger;
312777
- }
312778
- async getTrigger(id) {
312779
- const knex = this.getKnex();
312780
- const row = await knex('message_triggers').where('id', id).first();
312781
- return row ? fromTriggerRow(row) : undefined;
312782
- }
312783
- async updateTrigger(id, patch) {
312784
- const knex = this.getKnex();
312785
- const existing = await knex('message_triggers').where('id', id).first();
312786
- if (!existing)
312787
- return undefined;
312788
- const current = fromTriggerRow(existing);
312789
- const updated = {
312790
- ...current,
312791
- ...patch,
312792
- id: current.id,
312793
- createdAt: current.createdAt,
312794
- };
312795
- const row = toTriggerInsertRow(updated);
312796
- delete row.id;
312797
- await knex('message_triggers').where('id', id).update(row);
312798
- return updated;
312799
- }
312800
- async deleteTrigger(id) {
312801
- const knex = this.getKnex();
312802
- const deleted = await knex('message_triggers').where('id', id).del();
312803
- if (deleted > 0) {
312804
- logger_1.logger.info(`[KnexStore] Deleted trigger ${id}`);
312805
- return true;
312806
- }
312807
- return false;
312808
- }
312809
- async getTriggersByCreator(creatorId) {
312810
- const knex = this.getKnex();
312811
- const rows = await knex('message_triggers').where('creator_id', creatorId);
312812
- return rows.map((r) => fromTriggerRow(r));
312813
- }
312814
- async getActiveTriggers() {
312815
- const knex = this.getKnex();
312816
- const rows = await knex('message_triggers')
312817
- .where('status', 'active')
312818
- .where('enabled', this.driver === 'mssql' ? 1 : true);
312819
- return rows.map((r) => fromTriggerRow(r));
312820
- }
312821
- }
312822
- exports.KnexStoreBackend = KnexStoreBackend;
312823
-
312824
-
312825
311022
  /***/ }),
312826
311023
 
312827
311024
  /***/ 83864:
@@ -316131,7 +314328,7 @@ exports.configSchema = {
316131
314328
  properties: {
316132
314329
  type: {
316133
314330
  type: 'string',
316134
- enum: ['command', 'api', 'workflow'],
314331
+ enum: ['command', 'api', 'workflow', 'http_client'],
316135
314332
  description: "Tool implementation type (defaults to 'command')",
316136
314333
  },
316137
314334
  name: {
@@ -316328,6 +314525,27 @@ exports.configSchema = {
316328
314525
  type: 'number',
316329
314526
  description: 'Alias for requestTimeoutMs (snake_case)',
316330
314527
  },
314528
+ base_url: {
314529
+ type: 'string',
314530
+ description: 'Base URL for HTTP client tools',
314531
+ },
314532
+ auth: {
314533
+ type: 'object',
314534
+ properties: {
314535
+ type: {
314536
+ type: 'string',
314537
+ },
314538
+ token: {
314539
+ type: 'string',
314540
+ },
314541
+ },
314542
+ required: ['type'],
314543
+ additionalProperties: {},
314544
+ description: 'Authentication config for HTTP client tools',
314545
+ patternProperties: {
314546
+ '^x-': {},
314547
+ },
314548
+ },
316331
314549
  workflow: {
316332
314550
  type: 'string',
316333
314551
  description: "Workflow ID (registry lookup) or file path (for type: 'workflow')",
@@ -316867,7 +315085,7 @@ exports.configSchema = {
316867
315085
  description: 'Arguments/inputs for the workflow',
316868
315086
  },
316869
315087
  overrides: {
316870
- $ref: '#/definitions/Record%3Cstring%2CPartial%3Cinterface-src_types_config.ts-14017-28611-src_types_config.ts-0-56833%3E%3E',
315088
+ $ref: '#/definitions/Record%3Cstring%2CPartial%3Cinterface-src_types_config.ts-14017-28611-src_types_config.ts-0-57090%3E%3E',
316871
315089
  description: 'Override specific step configurations in the workflow',
316872
315090
  },
316873
315091
  output_mapping: {
@@ -316883,7 +315101,7 @@ exports.configSchema = {
316883
315101
  description: 'Config file path - alternative to workflow ID (loads a Visor config file as workflow)',
316884
315102
  },
316885
315103
  workflow_overrides: {
316886
- $ref: '#/definitions/Record%3Cstring%2CPartial%3Cinterface-src_types_config.ts-14017-28611-src_types_config.ts-0-56833%3E%3E',
315104
+ $ref: '#/definitions/Record%3Cstring%2CPartial%3Cinterface-src_types_config.ts-14017-28611-src_types_config.ts-0-57090%3E%3E',
316887
315105
  description: 'Alias for overrides - workflow step overrides (backward compatibility)',
316888
315106
  },
316889
315107
  ref: {
@@ -317585,7 +315803,7 @@ exports.configSchema = {
317585
315803
  description: 'Custom output name (defaults to workflow name)',
317586
315804
  },
317587
315805
  overrides: {
317588
- $ref: '#/definitions/Record%3Cstring%2CPartial%3Cinterface-src_types_config.ts-14017-28611-src_types_config.ts-0-56833%3E%3E',
315806
+ $ref: '#/definitions/Record%3Cstring%2CPartial%3Cinterface-src_types_config.ts-14017-28611-src_types_config.ts-0-57090%3E%3E',
317589
315807
  description: 'Step overrides',
317590
315808
  },
317591
315809
  output_mapping: {
@@ -317600,13 +315818,13 @@ exports.configSchema = {
317600
315818
  '^x-': {},
317601
315819
  },
317602
315820
  },
317603
- 'Record<string,Partial<interface-src_types_config.ts-14017-28611-src_types_config.ts-0-56833>>': {
315821
+ 'Record<string,Partial<interface-src_types_config.ts-14017-28611-src_types_config.ts-0-57090>>': {
317604
315822
  type: 'object',
317605
315823
  additionalProperties: {
317606
- $ref: '#/definitions/Partial%3Cinterface-src_types_config.ts-14017-28611-src_types_config.ts-0-56833%3E',
315824
+ $ref: '#/definitions/Partial%3Cinterface-src_types_config.ts-14017-28611-src_types_config.ts-0-57090%3E',
317607
315825
  },
317608
315826
  },
317609
- 'Partial<interface-src_types_config.ts-14017-28611-src_types_config.ts-0-56833>': {
315827
+ 'Partial<interface-src_types_config.ts-14017-28611-src_types_config.ts-0-57090>': {
317610
315828
  type: 'object',
317611
315829
  additionalProperties: false,
317612
315830
  },
@@ -325335,35 +323553,6 @@ class OutputFormatters {
325335
323553
  exports.OutputFormatters = OutputFormatters;
325336
323554
 
325337
323555
 
325338
- /***/ }),
325339
-
325340
- /***/ 93866:
325341
- /***/ ((__unused_webpack_module, exports) => {
325342
-
325343
- "use strict";
325344
-
325345
- Object.defineProperty(exports, "__esModule", ({ value: true }));
325346
- exports.DefaultPolicyEngine = void 0;
325347
- /**
325348
- * Default (no-op) policy engine — always allows everything.
325349
- * Used when no enterprise license is present or policy is disabled.
325350
- */
325351
- class DefaultPolicyEngine {
325352
- async initialize(_config) { }
325353
- async evaluateCheckExecution(_checkId, _checkConfig) {
325354
- return { allowed: true };
325355
- }
325356
- async evaluateToolInvocation(_serverName, _methodName, _transport) {
325357
- return { allowed: true };
325358
- }
325359
- async evaluateCapabilities(_checkId, _capabilities) {
325360
- return { allowed: true };
325361
- }
325362
- async shutdown() { }
325363
- }
325364
- exports.DefaultPolicyEngine = DefaultPolicyEngine;
325365
-
325366
-
325367
323556
  /***/ }),
325368
323557
 
325369
323558
  /***/ 96611:
@@ -327614,12 +325803,14 @@ class AICheckProvider extends check_provider_interface_1.CheckProvider {
327614
325803
  break; // Only support one custom tools server per check
327615
325804
  }
327616
325805
  }
327617
- // Option 4: Extract workflow and tool entries from ai_mcp_servers/ai_mcp_servers_js
325806
+ // Option 4: Extract workflow, tool, and http_client entries from ai_mcp_servers/ai_mcp_servers_js
327618
325807
  // Unified format:
327619
325808
  // { workflow: 'name', inputs: {...} } → workflow tool
327620
325809
  // { tool: 'name' } → custom tool from tools: section or built-in (e.g., 'schedule')
325810
+ // { type: 'http_client', base_url: '...', ... } → HTTP client tool (REST API proxy)
327621
325811
  const workflowEntriesFromMcp = [];
327622
325812
  const toolEntriesFromMcp = [];
325813
+ const httpClientEntriesFromMcp = [];
327623
325814
  const mcpEntriesToRemove = [];
327624
325815
  for (const [serverName, serverConfig] of Object.entries(mcpServers)) {
327625
325816
  const cfg = serverConfig;
@@ -327634,6 +325825,12 @@ class AICheckProvider extends check_provider_interface_1.CheckProvider {
327634
325825
  mcpEntriesToRemove.push(serverName);
327635
325826
  logger_1.logger.debug(`[AICheckProvider] Extracted workflow tool '${serverName}' (workflow=${cfg.workflow}) from ai_mcp_servers`);
327636
325827
  }
325828
+ else if (cfg.type === 'http_client' && (cfg.base_url || cfg.url)) {
325829
+ // HTTP client tool entry — REST API proxy exposed as an MCP tool
325830
+ httpClientEntriesFromMcp.push({ name: serverName, config: cfg });
325831
+ mcpEntriesToRemove.push(serverName);
325832
+ logger_1.logger.debug(`[AICheckProvider] Extracted http_client tool '${serverName}' (base_url=${cfg.base_url || cfg.url}) from ai_mcp_servers`);
325833
+ }
327637
325834
  else if (cfg.tool && typeof cfg.tool === 'string') {
327638
325835
  // Custom tool or built-in tool entry
327639
325836
  toolEntriesFromMcp.push(cfg.tool);
@@ -327692,8 +325889,10 @@ class AICheckProvider extends check_provider_interface_1.CheckProvider {
327692
325889
  }
327693
325890
  // Legacy support: enable_scheduler: true also enables the schedule tool
327694
325891
  const scheduleToolEnabled = scheduleToolRequested || (config.ai?.enable_scheduler === true && !config.ai?.disableTools);
327695
- if ((customToolsToLoad.length > 0 || scheduleToolEnabled) &&
327696
- (customToolsServerName || scheduleToolEnabled) &&
325892
+ if ((customToolsToLoad.length > 0 ||
325893
+ scheduleToolEnabled ||
325894
+ httpClientEntriesFromMcp.length > 0) &&
325895
+ (customToolsServerName || scheduleToolEnabled || httpClientEntriesFromMcp.length > 0) &&
327697
325896
  !config.ai?.disableTools) {
327698
325897
  if (!customToolsServerName) {
327699
325898
  customToolsServerName = '__tools__';
@@ -327729,6 +325928,49 @@ class AICheckProvider extends check_provider_interface_1.CheckProvider {
327729
325928
  customTools.set(scheduleTool.name, scheduleTool);
327730
325929
  logger_1.logger.debug(`[AICheckProvider] Added built-in schedule tool`);
327731
325930
  }
325931
+ // Add http_client tools extracted from ai_mcp_servers
325932
+ for (const entry of httpClientEntriesFromMcp) {
325933
+ const httpTool = {
325934
+ name: entry.name,
325935
+ type: 'http_client',
325936
+ description: entry.config.description ||
325937
+ `Call ${entry.name} HTTP API (base: ${entry.config.base_url || entry.config.url})`,
325938
+ base_url: (entry.config.base_url || entry.config.url),
325939
+ auth: entry.config.auth,
325940
+ headers: entry.config.headers,
325941
+ timeout: entry.config.timeout || 30000,
325942
+ inputSchema: {
325943
+ type: 'object',
325944
+ properties: {
325945
+ path: {
325946
+ type: 'string',
325947
+ description: 'API path (e.g. /jobs, /candidates/{id})',
325948
+ },
325949
+ method: {
325950
+ type: 'string',
325951
+ description: 'HTTP method (default: GET)',
325952
+ enum: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
325953
+ },
325954
+ query: {
325955
+ type: 'object',
325956
+ description: 'Query string parameters',
325957
+ additionalProperties: { type: 'string' },
325958
+ },
325959
+ body: {
325960
+ type: 'object',
325961
+ description: 'Request body for POST/PUT/PATCH',
325962
+ },
325963
+ },
325964
+ required: ['path'],
325965
+ },
325966
+ };
325967
+ customTools.set(entry.name, httpTool);
325968
+ logger_1.logger.debug(`[AICheckProvider] Added http_client tool '${entry.name}' (base_url=${httpTool.base_url})`);
325969
+ }
325970
+ // Ensure SSE server is created when http_client tools are present
325971
+ if (httpClientEntriesFromMcp.length > 0 && !customToolsServerName) {
325972
+ customToolsServerName = '__tools__';
325973
+ }
327732
325974
  if (customTools.size > 0) {
327733
325975
  const sessionId = config.checkName || `ai-check-${Date.now()}`;
327734
325976
  const debug = aiConfig.debug || process.env.VISOR_DEBUG === 'true';
@@ -335570,6 +333812,13 @@ const workflow_registry_1 = __nccwpck_require__(82824);
335570
333812
  const schedule_tool_1 = __nccwpck_require__(13395);
335571
333813
  // Legacy Slack-specific imports for backwards compatibility
335572
333814
  const schedule_tool_handler_1 = __nccwpck_require__(28883);
333815
+ const env_resolver_1 = __nccwpck_require__(58749);
333816
+ /**
333817
+ * Check if a tool definition is an http_client tool
333818
+ */
333819
+ function isHttpClientTool(tool) {
333820
+ return Boolean(tool && tool.type === 'http_client' && (tool.base_url || tool.url));
333821
+ }
335573
333822
  /**
335574
333823
  * SSE-based MCP server that exposes custom tools from YAML configuration
335575
333824
  * Implements the Model Context Protocol over Server-Sent Events
@@ -335608,14 +333857,16 @@ class CustomToolsSSEServer {
335608
333857
  }
335609
333858
  }
335610
333859
  }
335611
- // Second pass: separate workflow tools from regular tools
333860
+ // Second pass: separate workflow and http_client tools from regular tools
335612
333861
  for (const [name, tool] of this.tools.entries()) {
335613
- // Skip workflow tools - they're handled separately
335614
- if (!(0, workflow_tool_executor_1.isWorkflowTool)(tool)) {
335615
- toolsRecord[name] = tool;
333862
+ // Skip workflow and http_client tools - they're handled separately
333863
+ if ((0, workflow_tool_executor_1.isWorkflowTool)(tool) || isHttpClientTool(tool)) {
333864
+ if ((0, workflow_tool_executor_1.isWorkflowTool)(tool)) {
333865
+ workflowToolNames.push(name);
333866
+ }
335616
333867
  }
335617
333868
  else {
335618
- workflowToolNames.push(name);
333869
+ toolsRecord[name] = tool;
335619
333870
  }
335620
333871
  }
335621
333872
  // Warn if workflow tools are present but no context is provided
@@ -336089,7 +334340,14 @@ class CustomToolsSSEServer {
336089
334340
  description: tool.description || `Execute ${tool.name}`,
336090
334341
  inputSchema: normalizeInputSchema(tool.inputSchema),
336091
334342
  }));
336092
- const allTools = [...regularTools, ...workflowTools];
334343
+ const httpClientTools = Array.from(this.tools.values())
334344
+ .filter(isHttpClientTool)
334345
+ .map(tool => ({
334346
+ name: tool.name,
334347
+ description: tool.description || `Call ${tool.name} HTTP API`,
334348
+ inputSchema: normalizeInputSchema(tool.inputSchema),
334349
+ }));
334350
+ const allTools = [...regularTools, ...workflowTools, ...httpClientTools];
336093
334351
  if (this.debug) {
336094
334352
  logger_1.logger.debug(`[CustomToolsSSEServer:${this.sessionId}] Listing ${allTools.length} tools: ${allTools.map(t => t.name).join(', ')}`);
336095
334353
  }
@@ -336211,6 +334469,10 @@ class CustomToolsSSEServer {
336211
334469
  const workflowTool = tool;
336212
334470
  result = await (0, workflow_tool_executor_1.executeWorkflowAsTool)(workflowTool.__workflowId, args, this.workflowContext, workflowTool.__argsOverrides);
336213
334471
  }
334472
+ else if (tool && isHttpClientTool(tool)) {
334473
+ // Execute HTTP client tool — proxy REST API calls
334474
+ result = await this.executeHttpClientTool(tool, args);
334475
+ }
336214
334476
  else {
336215
334477
  // Execute regular custom tool
336216
334478
  result = await this.toolExecutor.execute(toolName, args);
@@ -336275,6 +334537,88 @@ class CustomToolsSSEServer {
336275
334537
  }
336276
334538
  }
336277
334539
  }
334540
+ /**
334541
+ * Execute an http_client tool — proxy REST API calls through the configured base URL.
334542
+ */
334543
+ async executeHttpClientTool(tool, args) {
334544
+ const baseUrl = (tool.base_url || tool.url).replace(/\/+$/, '');
334545
+ const apiPath = args.path || '';
334546
+ const method = (args.method || 'GET').toUpperCase();
334547
+ const queryParams = args.query || {};
334548
+ const body = args.body;
334549
+ const toolHeaders = tool.headers || {};
334550
+ const timeout = tool.timeout || 30000;
334551
+ // Build full URL
334552
+ let url = apiPath.startsWith('http') ? apiPath : `${baseUrl}/${apiPath.replace(/^\/+/, '')}`;
334553
+ // Append query parameters
334554
+ if (Object.keys(queryParams).length > 0) {
334555
+ const qs = new URLSearchParams(queryParams).toString();
334556
+ url += `${url.includes('?') ? '&' : '?'}${qs}`;
334557
+ }
334558
+ // Resolve environment variables in headers
334559
+ const resolvedHeaders = {};
334560
+ for (const [key, value] of Object.entries(toolHeaders)) {
334561
+ resolvedHeaders[key] = String(env_resolver_1.EnvironmentResolver.resolveValue(value));
334562
+ }
334563
+ // Handle auth
334564
+ if (tool.auth) {
334565
+ const authType = tool.auth.type;
334566
+ if (authType === 'bearer' && tool.auth.token) {
334567
+ const token = String(env_resolver_1.EnvironmentResolver.resolveValue(tool.auth.token));
334568
+ resolvedHeaders['Authorization'] = `Bearer ${token}`;
334569
+ }
334570
+ }
334571
+ if (this.debug) {
334572
+ logger_1.logger.debug(`[CustomToolsSSEServer:${this.sessionId}] HTTP client: ${method} ${url}`);
334573
+ }
334574
+ const controller = new AbortController();
334575
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
334576
+ try {
334577
+ const requestOptions = {
334578
+ method,
334579
+ headers: resolvedHeaders,
334580
+ signal: controller.signal,
334581
+ };
334582
+ if (method !== 'GET' && body) {
334583
+ requestOptions.body = typeof body === 'string' ? body : JSON.stringify(body);
334584
+ if (!resolvedHeaders['Content-Type'] && !resolvedHeaders['content-type']) {
334585
+ resolvedHeaders['Content-Type'] = 'application/json';
334586
+ }
334587
+ }
334588
+ const response = await fetch(url, requestOptions);
334589
+ clearTimeout(timeoutId);
334590
+ if (!response.ok) {
334591
+ let errorBody = '';
334592
+ try {
334593
+ errorBody = await response.text();
334594
+ }
334595
+ catch { }
334596
+ throw new Error(`HTTP ${response.status}: ${response.statusText}${errorBody ? ` - ${errorBody.substring(0, 500)}` : ''}`);
334597
+ }
334598
+ // Parse response
334599
+ const contentType = response.headers.get('content-type');
334600
+ if (contentType && contentType.includes('application/json')) {
334601
+ return await response.json();
334602
+ }
334603
+ const text = await response.text();
334604
+ if (text.trim().startsWith('{') || text.trim().startsWith('[')) {
334605
+ try {
334606
+ return JSON.parse(text);
334607
+ }
334608
+ catch {
334609
+ return text;
334610
+ }
334611
+ }
334612
+ return text;
334613
+ }
334614
+ catch (error) {
334615
+ clearTimeout(timeoutId);
334616
+ if (error instanceof Error && error.name === 'AbortError') {
334617
+ throw new Error(`HTTP client request timed out after ${timeout}ms`);
334618
+ }
334619
+ throw error;
334620
+ }
334621
+ }
336278
334622
  /**
336279
334623
  * Convert a type: 'workflow' tool definition into a WorkflowToolDefinition marker.
336280
334624
  *
@@ -348355,7 +346699,7 @@ class StateMachineExecutionEngine {
348355
346699
  try {
348356
346700
  logger_1.logger.debug(`[PolicyEngine] Loading enterprise policy engine (engine=${configWithTagFilter.policy.engine})`);
348357
346701
  // @ts-ignore — enterprise/ may not exist in OSS builds (caught at runtime)
348358
- const { loadEnterprisePolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(87068)));
346702
+ const { loadEnterprisePolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(7065)));
348359
346703
  context.policyEngine = await loadEnterprisePolicyEngine(configWithTagFilter.policy);
348360
346704
  logger_1.logger.debug(`[PolicyEngine] Initialized: ${context.policyEngine?.constructor?.name || 'unknown'}`);
348361
346705
  }
@@ -360094,7 +358438,7 @@ async function initTelemetry(opts = {}) {
360094
358438
  const path = __nccwpck_require__(16928);
360095
358439
  const outDir = opts.file?.dir ||
360096
358440
  process.env.VISOR_TRACE_DIR ||
360097
- path.join(process.cwd(), 'output', 'traces');
358441
+ __nccwpck_require__.ab + "traces";
360098
358442
  fs.mkdirSync(outDir, { recursive: true });
360099
358443
  const ts = new Date().toISOString().replace(/[:.]/g, '-');
360100
358444
  process.env.VISOR_FALLBACK_TRACE_FILE = path.join(outDir, `run-${ts}.ndjson`);
@@ -360344,7 +358688,7 @@ async function shutdownTelemetry() {
360344
358688
  if (process.env.VISOR_TRACE_REPORT === 'true') {
360345
358689
  const fs = __nccwpck_require__(79896);
360346
358690
  const path = __nccwpck_require__(16928);
360347
- const outDir = process.env.VISOR_TRACE_DIR || path.join(process.cwd(), 'output', 'traces');
358691
+ const outDir = process.env.VISOR_TRACE_DIR || __nccwpck_require__.ab + "traces";
360348
358692
  if (!fs.existsSync(outDir))
360349
358693
  fs.mkdirSync(outDir, { recursive: true });
360350
358694
  const ts = new Date().toISOString().replace(/[:.]/g, '-');
@@ -360895,7 +359239,7 @@ function __getOrCreateNdjsonPath() {
360895
359239
  fs.mkdirSync(dir, { recursive: true });
360896
359240
  return __ndjsonPath;
360897
359241
  }
360898
- const outDir = process.env.VISOR_TRACE_DIR || path.join(process.cwd(), 'output', 'traces');
359242
+ const outDir = process.env.VISOR_TRACE_DIR || __nccwpck_require__.ab + "traces";
360899
359243
  if (!fs.existsSync(outDir))
360900
359244
  fs.mkdirSync(outDir, { recursive: true });
360901
359245
  if (!__ndjsonPath) {
@@ -361384,9 +359728,11 @@ function expandConversationToFlow(testCase) {
361384
359728
  flow.push(stage);
361385
359729
  // After this stage, add user message + assumed assistant response to history
361386
359730
  messageHistory.push({ role: 'user', text: turn.text });
361387
- // Look for mock response text to add as assistant message for next turn
359731
+ // Look for mock response text to add as assistant message for next turn.
359732
+ // Record the index so the runner can replace it with the real response in --no-mocks mode.
361388
359733
  const assistantText = extractMockResponseText(turn.mocks);
361389
359734
  if (assistantText) {
359735
+ stage._mockAssistantMsgIndex = messageHistory.length; // index of the assistant msg about to be pushed
361390
359736
  messageHistory.push({ role: 'assistant', text: assistantText });
361391
359737
  }
361392
359738
  }
@@ -363514,6 +361860,31 @@ class VisorTestRunner {
363514
361860
  const pad = Math.max(1, width - title.length - 2);
363515
361861
  return `${char.repeat(2)} ${title} ${char.repeat(pad)}`;
363516
361862
  }
361863
+ /**
361864
+ * Execute a lifecycle hook (shell command). Returns true on success, false on failure.
361865
+ */
361866
+ async runHook(hook, label, cwd) {
361867
+ if (!hook)
361868
+ return { ok: true };
361869
+ const timeoutMs = hook.timeout || 30_000;
361870
+ console.log(this.gray(` ⚙ ${label}: ${hook.exec}`));
361871
+ try {
361872
+ const { execSync } = __nccwpck_require__(35317);
361873
+ execSync(hook.exec, {
361874
+ cwd,
361875
+ stdio: ['ignore', 'pipe', 'pipe'],
361876
+ timeout: timeoutMs,
361877
+ env: { ...process.env },
361878
+ });
361879
+ return { ok: true };
361880
+ }
361881
+ catch (err) {
361882
+ const stderr = err.stderr ? err.stderr.toString().trim() : '';
361883
+ const msg = stderr || err.message || String(err);
361884
+ console.log(this.color(` ✖ ${label} failed: ${msg}`, '31'));
361885
+ return { ok: false, error: `${label} failed: ${msg}` };
361886
+ }
361887
+ }
363517
361888
  // Extracted helper: prepare engine/recorder, prompts/mocks, env, and checksToRun for a single-event case
363518
361889
  setupTestCase(_case, cfg, defaultStrict, defaultPromptCap, ghRec, defaultIncludeTags, defaultExcludeTags, noMocks, noMocksFor) {
363519
361890
  const name = _case.name || '(unnamed)';
@@ -363915,6 +362286,7 @@ class VisorTestRunner {
363915
362286
  extends: doc.extends,
363916
362287
  tests: {
363917
362288
  defaults: tests.defaults || {},
362289
+ hooks: tests.hooks || undefined,
363918
362290
  fixtures: tests.fixtures || [],
363919
362291
  cases: tests.cases,
363920
362292
  },
@@ -364104,6 +362476,18 @@ class VisorTestRunner {
364104
362476
  }
364105
362477
  }
364106
362478
  catch { }
362479
+ // Lifecycle hooks
362480
+ const suiteHooks = suite.tests.hooks || {};
362481
+ const suiteCwd = path_1.default.dirname(testsPath);
362482
+ const beforeAllResult = await this.runHook(suiteHooks.before_all, 'before_all', suiteCwd);
362483
+ if (!beforeAllResult.ok) {
362484
+ // Skip all cases when before_all fails
362485
+ for (const c of selected) {
362486
+ caseResults.push({ name: c.name, passed: false, errors: [beforeAllResult.error] });
362487
+ }
362488
+ clearInterval(__keepAlive);
362489
+ return { failures: selected.length, results: caseResults };
362490
+ }
364107
362491
  const runOne = async (_caseOrig) => {
364108
362492
  // Expand conversation sugar to flow stages before any processing
364109
362493
  const { expandConversationToFlow } = __nccwpck_require__(15921);
@@ -364123,11 +362507,32 @@ class VisorTestRunner {
364123
362507
  caseResults.push({ name: _case.name, passed: true, errors: [] });
364124
362508
  return { name: _case.name, failed: 0 };
364125
362509
  }
362510
+ // Run before_each (suite-level) and before (case-level) hooks
362511
+ const caseHooks = _case.hooks || {};
362512
+ const beforeEachRes = await this.runHook(suiteHooks.before_each, 'before_each', suiteCwd);
362513
+ if (!beforeEachRes.ok) {
362514
+ caseResults.push({ name: _case.name, passed: false, errors: [beforeEachRes.error] });
362515
+ return { name: _case.name, failed: 1 };
362516
+ }
362517
+ const beforeRes = await this.runHook(caseHooks.before, `before (${_case.name})`, suiteCwd);
362518
+ if (!beforeRes.ok) {
362519
+ // after_each still runs even if before fails
362520
+ await this.runHook(suiteHooks.after_each, 'after_each', suiteCwd);
362521
+ caseResults.push({ name: _case.name, passed: false, errors: [beforeRes.error] });
362522
+ return { name: _case.name, failed: 1 };
362523
+ }
364126
362524
  if (Array.isArray(_case.flow) && _case.flow.length > 0) {
364127
- const flowRes = await this.runFlowCase(_case, cfg, defaultStrict, options.bail || false, defaultPromptCap, stageFilter, noMocksMode);
364128
- const failed = flowRes.failures;
364129
- caseResults.push({ name: _case.name, passed: failed === 0, stages: flowRes.stages });
364130
- return { name: _case.name, failed };
362525
+ try {
362526
+ const flowRes = await this.runFlowCase(_case, cfg, defaultStrict, options.bail || false, defaultPromptCap, stageFilter, noMocksMode);
362527
+ const failed = flowRes.failures;
362528
+ caseResults.push({ name: _case.name, passed: failed === 0, stages: flowRes.stages });
362529
+ return { name: _case.name, failed };
362530
+ }
362531
+ finally {
362532
+ // after (case-level) and after_each (suite-level) always run
362533
+ await this.runHook(caseHooks.after, `after (${_case.name})`, suiteCwd);
362534
+ await this.runHook(suiteHooks.after_each, 'after_each', suiteCwd);
362535
+ }
364131
362536
  }
364132
362537
  // Per-case AI override: include code context when requested
364133
362538
  const suiteDefaults = this.suiteDefaults || {};
@@ -364356,6 +362761,9 @@ class VisorTestRunner {
364356
362761
  return { name: _case.name, failed: 1 };
364357
362762
  }
364358
362763
  finally {
362764
+ // after (case-level) and after_each (suite-level) always run
362765
+ await this.runHook(caseHooks.after, `after (${_case.name})`, suiteCwd);
362766
+ await this.runHook(suiteHooks.after_each, 'after_each', suiteCwd);
364359
362767
  try {
364360
362768
  // Restore env for this case using original setup
364361
362769
  setup.restoreEnv();
@@ -364386,6 +362794,8 @@ class VisorTestRunner {
364386
362794
  };
364387
362795
  await Promise.all(Array.from({ length: workers }, runWorker));
364388
362796
  }
362797
+ // after_all always runs (like finally), even if tests failed
362798
+ await this.runHook(suiteHooks.after_all, 'after_all', suiteCwd);
364389
362799
  // Summary (suppressible for embedded runs)
364390
362800
  const failedCases = caseResults.filter(r => !r.passed);
364391
362801
  const passedCases = caseResults.filter(r => r.passed);
@@ -364594,6 +363004,24 @@ class VisorTestRunner {
364594
363004
  const defaultExcludeTags = parseTags(suiteDefaults?.exclude_tags);
364595
363005
  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);
364596
363006
  const outcome = await stageRunner.run(stage, flowCase, strict);
363007
+ // In conversation sugar + --no-mocks: replace mock assistant text in
363008
+ // subsequent stages' message history with the real AI response.
363009
+ if (noMocks &&
363010
+ flowCase._conversationSugar &&
363011
+ typeof stage._mockAssistantMsgIndex === 'number') {
363012
+ const realText = this.extractLastResponseText(cumulativeOutputHistory);
363013
+ if (realText) {
363014
+ for (let j = i + 1; j < flowCase.flow.length; j++) {
363015
+ const nextMsgs = flowCase.flow[j]?.execution_context?.conversation?.messages;
363016
+ if (Array.isArray(nextMsgs) && nextMsgs[stage._mockAssistantMsgIndex]) {
363017
+ nextMsgs[stage._mockAssistantMsgIndex] = {
363018
+ ...nextMsgs[stage._mockAssistantMsgIndex],
363019
+ text: realText,
363020
+ };
363021
+ }
363022
+ }
363023
+ }
363024
+ }
364597
363025
  const expect = stage.expect || {};
364598
363026
  if (outcome.stats)
364599
363027
  this.printCoverage(outcome.name, outcome.stats, expect);
@@ -364638,6 +363066,21 @@ class VisorTestRunner {
364638
363066
  console.log(`${this.tagFail ? this.tagFail() : '❌ FAIL'} ${flowName} (${failures} stage error${failures > 1 ? 's' : ''})`);
364639
363067
  return { failures, stages: stagesSummary };
364640
363068
  }
363069
+ /**
363070
+ * Extract the last response text from cumulative output history (for conversation sugar).
363071
+ * Looks for 'chat' step outputs with a 'text' field.
363072
+ */
363073
+ extractLastResponseText(history) {
363074
+ // The assistant workflow emits output on the 'chat' step with a 'text' field
363075
+ const chatOutputs = history['chat'];
363076
+ if (!Array.isArray(chatOutputs) || chatOutputs.length === 0)
363077
+ return undefined;
363078
+ const last = chatOutputs[chatOutputs.length - 1];
363079
+ if (last && typeof last === 'object' && typeof last.text === 'string') {
363080
+ return last.text;
363081
+ }
363082
+ return undefined;
363083
+ }
364641
363084
  mapEventFromFixtureName(name) {
364642
363085
  if (!name)
364643
363086
  return 'manual';
@@ -365495,6 +363938,7 @@ const schema = {
365495
363938
  },
365496
363939
  },
365497
363940
  },
363941
+ hooks: { $ref: '#/$defs/suiteHooks' },
365498
363942
  fixtures: { type: 'array' },
365499
363943
  cases: {
365500
363944
  type: 'array',
@@ -365506,6 +363950,33 @@ const schema = {
365506
363950
  },
365507
363951
  required: ['tests'],
365508
363952
  $defs: {
363953
+ hookDef: {
363954
+ type: 'object',
363955
+ additionalProperties: false,
363956
+ properties: {
363957
+ exec: { type: 'string' },
363958
+ timeout: { type: 'number' },
363959
+ },
363960
+ required: ['exec'],
363961
+ },
363962
+ suiteHooks: {
363963
+ type: 'object',
363964
+ additionalProperties: false,
363965
+ properties: {
363966
+ before_all: { $ref: '#/$defs/hookDef' },
363967
+ after_all: { $ref: '#/$defs/hookDef' },
363968
+ before_each: { $ref: '#/$defs/hookDef' },
363969
+ after_each: { $ref: '#/$defs/hookDef' },
363970
+ },
363971
+ },
363972
+ caseHooks: {
363973
+ type: 'object',
363974
+ additionalProperties: false,
363975
+ properties: {
363976
+ before: { $ref: '#/$defs/hookDef' },
363977
+ after: { $ref: '#/$defs/hookDef' },
363978
+ },
363979
+ },
365509
363980
  fixtureRef: {
365510
363981
  oneOf: [
365511
363982
  { type: 'string' },
@@ -365584,6 +364055,7 @@ const schema = {
365584
364055
  },
365585
364056
  // Workflow testing: input values to pass to the workflow
365586
364057
  workflow_input: { type: 'object' },
364058
+ hooks: { $ref: '#/$defs/caseHooks' },
365587
364059
  expect: { $ref: '#/$defs/expectBlock' },
365588
364060
  // Flow cases
365589
364061
  flow: {
@@ -376821,6 +375293,22 @@ class WorkflowRegistry {
376821
375293
  exports.WorkflowRegistry = WorkflowRegistry;
376822
375294
 
376823
375295
 
375296
+ /***/ }),
375297
+
375298
+ /***/ 7065:
375299
+ /***/ ((module) => {
375300
+
375301
+ module.exports = eval("require")("./enterprise/loader");
375302
+
375303
+
375304
+ /***/ }),
375305
+
375306
+ /***/ 71370:
375307
+ /***/ ((module) => {
375308
+
375309
+ module.exports = eval("require")("./enterprise/policy/policy-input-builder");
375310
+
375311
+
376824
375312
  /***/ }),
376825
375313
 
376826
375314
  /***/ 18327:
@@ -610187,7 +608675,7 @@ module.exports = /*#__PURE__*/JSON.parse('["aaa","aarp","abb","abbott","abbvie",
610187
608675
  /***/ ((module) => {
610188
608676
 
610189
608677
  "use strict";
610190
- 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"]}}');
608678
+ module.exports = /*#__PURE__*/JSON.parse('{"name":"@probelabs/visor","version":"0.1.175","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"]}}');
610191
608679
 
610192
608680
  /***/ })
610193
608681