@probelabs/visor 0.1.151 → 0.1.152-ee

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/dist/index.js +1850 -27
  2. package/dist/sdk/{check-provider-registry-IGIIFX67.mjs → check-provider-registry-HR6YM5MI.mjs} +5 -5
  3. package/dist/sdk/{check-provider-registry-OQE2DVYM.mjs → check-provider-registry-QBURXJ6B.mjs} +5 -5
  4. package/dist/sdk/{chunk-I2OWVR63.mjs → chunk-JRDGCUEG.mjs} +16 -16
  5. package/dist/sdk/{chunk-I2OWVR63.mjs.map → chunk-JRDGCUEG.mjs.map} +1 -1
  6. package/dist/sdk/{chunk-U4ZJWL63.mjs → chunk-QRR6OJQN.mjs} +15 -15
  7. package/dist/sdk/{chunk-MITJQ2QS.mjs → chunk-WG7P66MJ.mjs} +2 -2
  8. package/dist/sdk/{chunk-NE3OOOB2.mjs → chunk-Y3XWPKFP.mjs} +2 -2
  9. package/dist/sdk/{chunk-NE3OOOB2.mjs.map → chunk-Y3XWPKFP.mjs.map} +1 -1
  10. package/dist/sdk/{chunk-BBV64BPF.mjs → chunk-ZCUGMT7X.mjs} +3 -3
  11. package/dist/sdk/{failure-condition-evaluator-XYC6LZAV.mjs → failure-condition-evaluator-R3UE4PE7.mjs} +3 -3
  12. package/dist/sdk/{github-frontend-4DISXYOR.mjs → github-frontend-6KZSVSPC.mjs} +3 -3
  13. package/dist/sdk/{host-7WIF5HKA.mjs → host-A5HS6F6G.mjs} +2 -2
  14. package/dist/sdk/{host-V6ZZYETT.mjs → host-X7ID5EW7.mjs} +2 -2
  15. package/dist/sdk/knex-store-CRORFJE6.mjs +527 -0
  16. package/dist/sdk/knex-store-CRORFJE6.mjs.map +1 -0
  17. package/dist/sdk/loader-NJCF7DUS.mjs +89 -0
  18. package/dist/sdk/loader-NJCF7DUS.mjs.map +1 -0
  19. package/dist/sdk/opa-policy-engine-S2S2ULEI.mjs +655 -0
  20. package/dist/sdk/opa-policy-engine-S2S2ULEI.mjs.map +1 -0
  21. package/dist/sdk/{routing-6SKBL7AX.mjs → routing-MMEOAH34.mjs} +4 -4
  22. package/dist/sdk/{schedule-tool-GPRPNHIH.mjs → schedule-tool-62XTFB6K.mjs} +5 -5
  23. package/dist/sdk/{schedule-tool-SFHR3T3S.mjs → schedule-tool-6NALFGQR.mjs} +5 -5
  24. package/dist/sdk/{schedule-tool-handler-3C6DATDV.mjs → schedule-tool-handler-5K275UT6.mjs} +5 -5
  25. package/dist/sdk/{schedule-tool-handler-JCOBGMRA.mjs → schedule-tool-handler-RLAKPPPX.mjs} +5 -5
  26. package/dist/sdk/sdk.js +1634 -260
  27. package/dist/sdk/sdk.js.map +1 -1
  28. package/dist/sdk/sdk.mjs +4 -4
  29. package/dist/sdk/{trace-helpers-LKAADSNB.mjs → trace-helpers-JJLVZ2RJ.mjs} +2 -2
  30. package/dist/sdk/validator-XTZJZZJH.mjs +134 -0
  31. package/dist/sdk/validator-XTZJZZJH.mjs.map +1 -0
  32. package/dist/sdk/{workflow-check-provider-CH3ARLBE.mjs → workflow-check-provider-6TEZHBZJ.mjs} +5 -5
  33. package/dist/sdk/{workflow-check-provider-G46WE4EJ.mjs → workflow-check-provider-KG6IFH6W.mjs} +5 -5
  34. package/package.json +2 -2
  35. package/dist/output/traces/run-2026-03-04T06-08-59-294Z.ndjson +0 -138
  36. package/dist/output/traces/run-2026-03-04T06-09-44-093Z.ndjson +0 -2197
  37. package/dist/sdk/check-provider-registry-EBH64VK3.mjs +0 -29
  38. package/dist/sdk/chunk-3ITUIFJW.mjs +0 -443
  39. package/dist/sdk/chunk-3ITUIFJW.mjs.map +0 -1
  40. package/dist/sdk/chunk-CZOKADR7.mjs +0 -1502
  41. package/dist/sdk/chunk-CZOKADR7.mjs.map +0 -1
  42. package/dist/sdk/chunk-LH3PEGKM.mjs +0 -739
  43. package/dist/sdk/chunk-MITJQ2QS.mjs.map +0 -1
  44. package/dist/sdk/chunk-OVALXWC6.mjs +0 -43715
  45. package/dist/sdk/chunk-OVALXWC6.mjs.map +0 -1
  46. package/dist/sdk/failure-condition-evaluator-V5KJ3HQP.mjs +0 -17
  47. package/dist/sdk/github-frontend-NWH4ZK77.mjs +0 -1368
  48. package/dist/sdk/github-frontend-NWH4ZK77.mjs.map +0 -1
  49. package/dist/sdk/routing-ODVQHICC.mjs +0 -25
  50. package/dist/sdk/schedule-tool-C2GJJRLH.mjs +0 -35
  51. package/dist/sdk/schedule-tool-handler-JCOBGMRA.mjs.map +0 -1
  52. package/dist/sdk/schedule-tool-handler-Q6FWPGEB.mjs +0 -39
  53. package/dist/sdk/schedule-tool-handler-Q6FWPGEB.mjs.map +0 -1
  54. package/dist/sdk/trace-helpers-LKAADSNB.mjs.map +0 -1
  55. package/dist/sdk/trace-helpers-NGQVPQE3.mjs +0 -25
  56. package/dist/sdk/trace-helpers-NGQVPQE3.mjs.map +0 -1
  57. package/dist/sdk/workflow-check-provider-3QZCXXKD.mjs +0 -29
  58. package/dist/sdk/workflow-check-provider-3QZCXXKD.mjs.map +0 -1
  59. package/dist/sdk/workflow-check-provider-CH3ARLBE.mjs.map +0 -1
  60. package/dist/sdk/workflow-check-provider-G46WE4EJ.mjs.map +0 -1
  61. package/dist/traces/run-2026-03-04T06-08-59-294Z.ndjson +0 -138
  62. package/dist/traces/run-2026-03-04T06-09-44-093Z.ndjson +0 -2197
  63. /package/dist/sdk/{check-provider-registry-EBH64VK3.mjs.map → check-provider-registry-HR6YM5MI.mjs.map} +0 -0
  64. /package/dist/sdk/{check-provider-registry-IGIIFX67.mjs.map → check-provider-registry-QBURXJ6B.mjs.map} +0 -0
  65. /package/dist/sdk/{chunk-U4ZJWL63.mjs.map → chunk-QRR6OJQN.mjs.map} +0 -0
  66. /package/dist/sdk/{chunk-LH3PEGKM.mjs.map → chunk-WG7P66MJ.mjs.map} +0 -0
  67. /package/dist/sdk/{chunk-BBV64BPF.mjs.map → chunk-ZCUGMT7X.mjs.map} +0 -0
  68. /package/dist/sdk/{check-provider-registry-OQE2DVYM.mjs.map → failure-condition-evaluator-R3UE4PE7.mjs.map} +0 -0
  69. /package/dist/sdk/{github-frontend-4DISXYOR.mjs.map → github-frontend-6KZSVSPC.mjs.map} +0 -0
  70. /package/dist/sdk/{host-7WIF5HKA.mjs.map → host-A5HS6F6G.mjs.map} +0 -0
  71. /package/dist/sdk/{host-V6ZZYETT.mjs.map → host-X7ID5EW7.mjs.map} +0 -0
  72. /package/dist/sdk/{failure-condition-evaluator-V5KJ3HQP.mjs.map → routing-MMEOAH34.mjs.map} +0 -0
  73. /package/dist/sdk/{failure-condition-evaluator-XYC6LZAV.mjs.map → schedule-tool-62XTFB6K.mjs.map} +0 -0
  74. /package/dist/sdk/{routing-6SKBL7AX.mjs.map → schedule-tool-6NALFGQR.mjs.map} +0 -0
  75. /package/dist/sdk/{routing-ODVQHICC.mjs.map → schedule-tool-handler-5K275UT6.mjs.map} +0 -0
  76. /package/dist/sdk/{schedule-tool-C2GJJRLH.mjs.map → schedule-tool-handler-RLAKPPPX.mjs.map} +0 -0
  77. /package/dist/sdk/{schedule-tool-GPRPNHIH.mjs.map → trace-helpers-JJLVZ2RJ.mjs.map} +0 -0
  78. /package/dist/sdk/{schedule-tool-SFHR3T3S.mjs.map → workflow-check-provider-6TEZHBZJ.mjs.map} +0 -0
  79. /package/dist/sdk/{schedule-tool-handler-3C6DATDV.mjs.map → workflow-check-provider-KG6IFH6W.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.151';
3
- process.env.PROBE_VERSION = '0.6.0-rc268';
4
- process.env.VISOR_COMMIT_SHA = 'b06d244c0580c243801a29bbeae739a8198bea09';
5
- process.env.VISOR_COMMIT_SHORT = 'b06d244c0';
2
+ process.env.VISOR_VERSION = '0.1.152';
3
+ process.env.PROBE_VERSION = '0.6.0-rc269';
4
+ process.env.VISOR_COMMIT_SHA = 'fa1265c0b241f426e6fe44449a8c2f0a0aea1ba7';
5
+ process.env.VISOR_COMMIT_SHORT = 'fa1265c';
6
6
  /******/ (() => { // webpackBootstrap
7
7
  /******/ var __webpack_modules__ = ({
8
8
 
@@ -161210,7 +161210,7 @@ async function handleDumpPolicyInput(checkId, argv) {
161210
161210
  let PolicyInputBuilder;
161211
161211
  try {
161212
161212
  // @ts-ignore — enterprise/ may not exist in OSS builds (caught at runtime)
161213
- const mod = await Promise.resolve().then(() => __importStar(__nccwpck_require__(71370)));
161213
+ const mod = await Promise.resolve().then(() => __importStar(__nccwpck_require__(17117)));
161214
161214
  PolicyInputBuilder = mod.PolicyInputBuilder;
161215
161215
  }
161216
161216
  catch {
@@ -167053,6 +167053,1810 @@ class DependencyResolver {
167053
167053
  exports.DependencyResolver = DependencyResolver;
167054
167054
 
167055
167055
 
167056
+ /***/ }),
167057
+
167058
+ /***/ 50069:
167059
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
167060
+
167061
+ "use strict";
167062
+
167063
+ /**
167064
+ * Copyright (c) ProbeLabs. All rights reserved.
167065
+ * Licensed under the Elastic License 2.0; you may not use this file except
167066
+ * in compliance with the Elastic License 2.0.
167067
+ */
167068
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
167069
+ if (k2 === undefined) k2 = k;
167070
+ var desc = Object.getOwnPropertyDescriptor(m, k);
167071
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
167072
+ desc = { enumerable: true, get: function() { return m[k]; } };
167073
+ }
167074
+ Object.defineProperty(o, k2, desc);
167075
+ }) : (function(o, m, k, k2) {
167076
+ if (k2 === undefined) k2 = k;
167077
+ o[k2] = m[k];
167078
+ }));
167079
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
167080
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
167081
+ }) : function(o, v) {
167082
+ o["default"] = v;
167083
+ });
167084
+ var __importStar = (this && this.__importStar) || (function () {
167085
+ var ownKeys = function(o) {
167086
+ ownKeys = Object.getOwnPropertyNames || function (o) {
167087
+ var ar = [];
167088
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
167089
+ return ar;
167090
+ };
167091
+ return ownKeys(o);
167092
+ };
167093
+ return function (mod) {
167094
+ if (mod && mod.__esModule) return mod;
167095
+ var result = {};
167096
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
167097
+ __setModuleDefault(result, mod);
167098
+ return result;
167099
+ };
167100
+ })();
167101
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
167102
+ exports.LicenseValidator = void 0;
167103
+ const crypto = __importStar(__nccwpck_require__(76982));
167104
+ const fs = __importStar(__nccwpck_require__(79896));
167105
+ const path = __importStar(__nccwpck_require__(16928));
167106
+ class LicenseValidator {
167107
+ /** Ed25519 public key for license verification (PEM format). */
167108
+ static PUBLIC_KEY = '-----BEGIN PUBLIC KEY-----\n' +
167109
+ 'MCowBQYDK2VwAyEAI/Zd08EFmgIdrDm/HXd0l3/5GBt7R1PrdvhdmEXhJlU=\n' +
167110
+ '-----END PUBLIC KEY-----\n';
167111
+ cache = null;
167112
+ static CACHE_TTL = 5 * 60 * 1000; // 5 minutes
167113
+ static GRACE_PERIOD = 72 * 3600 * 1000; // 72 hours after expiry
167114
+ /**
167115
+ * Load and validate license from environment or file.
167116
+ *
167117
+ * Resolution order:
167118
+ * 1. VISOR_LICENSE env var (JWT string)
167119
+ * 2. VISOR_LICENSE_FILE env var (path to file)
167120
+ * 3. .visor-license in project root (cwd)
167121
+ * 4. .visor-license in ~/.config/visor/
167122
+ */
167123
+ async loadAndValidate() {
167124
+ // Return cached result if still fresh
167125
+ if (this.cache && Date.now() - this.cache.validatedAt < LicenseValidator.CACHE_TTL) {
167126
+ return this.cache.payload;
167127
+ }
167128
+ const token = this.resolveToken();
167129
+ if (!token)
167130
+ return null;
167131
+ const payload = this.verifyAndDecode(token);
167132
+ if (!payload)
167133
+ return null;
167134
+ this.cache = { payload, validatedAt: Date.now() };
167135
+ return payload;
167136
+ }
167137
+ /** Check if a specific feature is licensed */
167138
+ hasFeature(feature) {
167139
+ if (!this.cache)
167140
+ return false;
167141
+ return this.cache.payload.features.includes(feature);
167142
+ }
167143
+ /** Check if license is valid (with grace period) */
167144
+ isValid() {
167145
+ if (!this.cache)
167146
+ return false;
167147
+ const now = Date.now();
167148
+ const expiryMs = this.cache.payload.exp * 1000;
167149
+ return now < expiryMs + LicenseValidator.GRACE_PERIOD;
167150
+ }
167151
+ /** Check if the license is within its grace period (expired but still valid) */
167152
+ isInGracePeriod() {
167153
+ if (!this.cache)
167154
+ return false;
167155
+ const now = Date.now();
167156
+ const expiryMs = this.cache.payload.exp * 1000;
167157
+ return now >= expiryMs && now < expiryMs + LicenseValidator.GRACE_PERIOD;
167158
+ }
167159
+ resolveToken() {
167160
+ // 1. Direct env var
167161
+ if (process.env.VISOR_LICENSE) {
167162
+ return process.env.VISOR_LICENSE.trim();
167163
+ }
167164
+ // 2. File path from env (validate against path traversal)
167165
+ if (process.env.VISOR_LICENSE_FILE) {
167166
+ // path.resolve() produces an absolute path with all '..' segments resolved,
167167
+ // so a separate resolved.includes('..') check is unnecessary.
167168
+ const resolved = path.resolve(process.env.VISOR_LICENSE_FILE);
167169
+ const home = process.env.HOME || process.env.USERPROFILE || '';
167170
+ const allowedPrefixes = [path.normalize(process.cwd())];
167171
+ if (home)
167172
+ allowedPrefixes.push(path.normalize(path.join(home, '.config', 'visor')));
167173
+ // Resolve symlinks so an attacker cannot create a symlink inside an
167174
+ // allowed prefix that points to an arbitrary file outside it.
167175
+ let realPath;
167176
+ try {
167177
+ realPath = fs.realpathSync(resolved);
167178
+ }
167179
+ catch {
167180
+ return null; // File doesn't exist or isn't accessible
167181
+ }
167182
+ const isSafe = allowedPrefixes.some(prefix => realPath === prefix || realPath.startsWith(prefix + path.sep));
167183
+ if (!isSafe)
167184
+ return null;
167185
+ return this.readFile(realPath);
167186
+ }
167187
+ // 3. .visor-license in cwd
167188
+ const cwdPath = path.join(process.cwd(), '.visor-license');
167189
+ const cwdToken = this.readFile(cwdPath);
167190
+ if (cwdToken)
167191
+ return cwdToken;
167192
+ // 4. ~/.config/visor/.visor-license
167193
+ const home = process.env.HOME || process.env.USERPROFILE || '';
167194
+ if (home) {
167195
+ const configPath = path.join(home, '.config', 'visor', '.visor-license');
167196
+ const configToken = this.readFile(configPath);
167197
+ if (configToken)
167198
+ return configToken;
167199
+ }
167200
+ return null;
167201
+ }
167202
+ readFile(filePath) {
167203
+ try {
167204
+ return fs.readFileSync(filePath, 'utf-8').trim();
167205
+ }
167206
+ catch {
167207
+ return null;
167208
+ }
167209
+ }
167210
+ verifyAndDecode(token) {
167211
+ try {
167212
+ const parts = token.split('.');
167213
+ if (parts.length !== 3)
167214
+ return null;
167215
+ const [headerB64, payloadB64, signatureB64] = parts;
167216
+ // Decode header to verify algorithm
167217
+ const header = JSON.parse(Buffer.from(headerB64, 'base64url').toString());
167218
+ if (header.alg !== 'EdDSA')
167219
+ return null;
167220
+ // Verify signature
167221
+ const data = `${headerB64}.${payloadB64}`;
167222
+ const signature = Buffer.from(signatureB64, 'base64url');
167223
+ const publicKey = crypto.createPublicKey(LicenseValidator.PUBLIC_KEY);
167224
+ // Validate that the loaded public key is actually Ed25519 (OID 1.3.101.112).
167225
+ // This prevents algorithm-confusion attacks if the embedded key were ever
167226
+ // swapped to a different type.
167227
+ if (publicKey.asymmetricKeyType !== 'ed25519') {
167228
+ return null;
167229
+ }
167230
+ // Ed25519 verification: algorithm must be null because EdDSA performs its
167231
+ // own internal hashing (SHA-512) — passing a digest algorithm here would
167232
+ // cause Node.js to throw. The key type is validated above.
167233
+ const isValid = crypto.verify(null, Buffer.from(data), publicKey, signature);
167234
+ if (!isValid)
167235
+ return null;
167236
+ // Decode payload
167237
+ const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString());
167238
+ // Validate required fields
167239
+ if (!payload.org ||
167240
+ !Array.isArray(payload.features) ||
167241
+ typeof payload.exp !== 'number' ||
167242
+ typeof payload.iat !== 'number' ||
167243
+ !payload.sub) {
167244
+ return null;
167245
+ }
167246
+ // Check expiry (with grace period)
167247
+ const now = Date.now();
167248
+ const expiryMs = payload.exp * 1000;
167249
+ if (now >= expiryMs + LicenseValidator.GRACE_PERIOD) {
167250
+ return null;
167251
+ }
167252
+ return payload;
167253
+ }
167254
+ catch {
167255
+ return null;
167256
+ }
167257
+ }
167258
+ }
167259
+ exports.LicenseValidator = LicenseValidator;
167260
+
167261
+
167262
+ /***/ }),
167263
+
167264
+ /***/ 87068:
167265
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
167266
+
167267
+ "use strict";
167268
+
167269
+ /**
167270
+ * Copyright (c) ProbeLabs. All rights reserved.
167271
+ * Licensed under the Elastic License 2.0; you may not use this file except
167272
+ * in compliance with the Elastic License 2.0.
167273
+ */
167274
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
167275
+ if (k2 === undefined) k2 = k;
167276
+ var desc = Object.getOwnPropertyDescriptor(m, k);
167277
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
167278
+ desc = { enumerable: true, get: function() { return m[k]; } };
167279
+ }
167280
+ Object.defineProperty(o, k2, desc);
167281
+ }) : (function(o, m, k, k2) {
167282
+ if (k2 === undefined) k2 = k;
167283
+ o[k2] = m[k];
167284
+ }));
167285
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
167286
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
167287
+ }) : function(o, v) {
167288
+ o["default"] = v;
167289
+ });
167290
+ var __importStar = (this && this.__importStar) || (function () {
167291
+ var ownKeys = function(o) {
167292
+ ownKeys = Object.getOwnPropertyNames || function (o) {
167293
+ var ar = [];
167294
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
167295
+ return ar;
167296
+ };
167297
+ return ownKeys(o);
167298
+ };
167299
+ return function (mod) {
167300
+ if (mod && mod.__esModule) return mod;
167301
+ var result = {};
167302
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
167303
+ __setModuleDefault(result, mod);
167304
+ return result;
167305
+ };
167306
+ })();
167307
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
167308
+ exports.loadEnterprisePolicyEngine = loadEnterprisePolicyEngine;
167309
+ exports.loadEnterpriseStoreBackend = loadEnterpriseStoreBackend;
167310
+ const default_engine_1 = __nccwpck_require__(93866);
167311
+ /**
167312
+ * Load the enterprise policy engine if licensed, otherwise return the default no-op engine.
167313
+ *
167314
+ * This is the sole import boundary between OSS and enterprise code. Core code
167315
+ * must only import from this module (via dynamic `await import()`), never from
167316
+ * individual enterprise submodules.
167317
+ */
167318
+ async function loadEnterprisePolicyEngine(config) {
167319
+ try {
167320
+ const { LicenseValidator } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(50069)));
167321
+ const validator = new LicenseValidator();
167322
+ const license = await validator.loadAndValidate();
167323
+ if (!license || !validator.hasFeature('policy')) {
167324
+ return new default_engine_1.DefaultPolicyEngine();
167325
+ }
167326
+ if (validator.isInGracePeriod()) {
167327
+ // eslint-disable-next-line no-console
167328
+ console.warn('[visor:enterprise] License has expired but is within the 72-hour grace period. ' +
167329
+ 'Please renew your license.');
167330
+ }
167331
+ const { OpaPolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(39530)));
167332
+ const engine = new OpaPolicyEngine(config);
167333
+ await engine.initialize(config);
167334
+ return engine;
167335
+ }
167336
+ catch (err) {
167337
+ // Enterprise code not available or initialization failed
167338
+ const msg = err instanceof Error ? err.message : String(err);
167339
+ try {
167340
+ const { logger } = __nccwpck_require__(86999);
167341
+ logger.warn(`[PolicyEngine] Enterprise policy init failed, falling back to default: ${msg}`);
167342
+ }
167343
+ catch {
167344
+ // silent
167345
+ }
167346
+ return new default_engine_1.DefaultPolicyEngine();
167347
+ }
167348
+ }
167349
+ /**
167350
+ * Load the enterprise schedule store backend if licensed.
167351
+ *
167352
+ * @param driver Database driver ('postgresql', 'mysql', or 'mssql')
167353
+ * @param storageConfig Storage configuration with connection details
167354
+ * @param haConfig Optional HA configuration
167355
+ * @throws Error if enterprise license is not available or missing 'scheduler-sql' feature
167356
+ */
167357
+ async function loadEnterpriseStoreBackend(driver, storageConfig, haConfig) {
167358
+ const { LicenseValidator } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(50069)));
167359
+ const validator = new LicenseValidator();
167360
+ const license = await validator.loadAndValidate();
167361
+ if (!license || !validator.hasFeature('scheduler-sql')) {
167362
+ throw new Error(`The ${driver} schedule storage driver requires a Visor Enterprise license ` +
167363
+ `with the 'scheduler-sql' feature. Please upgrade or use driver: 'sqlite' (default).`);
167364
+ }
167365
+ if (validator.isInGracePeriod()) {
167366
+ // eslint-disable-next-line no-console
167367
+ console.warn('[visor:enterprise] License has expired but is within the 72-hour grace period. ' +
167368
+ 'Please renew your license.');
167369
+ }
167370
+ const { KnexStoreBackend } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(63737)));
167371
+ return new KnexStoreBackend(driver, storageConfig, haConfig);
167372
+ }
167373
+
167374
+
167375
+ /***/ }),
167376
+
167377
+ /***/ 628:
167378
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
167379
+
167380
+ "use strict";
167381
+
167382
+ /**
167383
+ * Copyright (c) ProbeLabs. All rights reserved.
167384
+ * Licensed under the Elastic License 2.0; you may not use this file except
167385
+ * in compliance with the Elastic License 2.0.
167386
+ */
167387
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
167388
+ if (k2 === undefined) k2 = k;
167389
+ var desc = Object.getOwnPropertyDescriptor(m, k);
167390
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
167391
+ desc = { enumerable: true, get: function() { return m[k]; } };
167392
+ }
167393
+ Object.defineProperty(o, k2, desc);
167394
+ }) : (function(o, m, k, k2) {
167395
+ if (k2 === undefined) k2 = k;
167396
+ o[k2] = m[k];
167397
+ }));
167398
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
167399
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
167400
+ }) : function(o, v) {
167401
+ o["default"] = v;
167402
+ });
167403
+ var __importStar = (this && this.__importStar) || (function () {
167404
+ var ownKeys = function(o) {
167405
+ ownKeys = Object.getOwnPropertyNames || function (o) {
167406
+ var ar = [];
167407
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
167408
+ return ar;
167409
+ };
167410
+ return ownKeys(o);
167411
+ };
167412
+ return function (mod) {
167413
+ if (mod && mod.__esModule) return mod;
167414
+ var result = {};
167415
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
167416
+ __setModuleDefault(result, mod);
167417
+ return result;
167418
+ };
167419
+ })();
167420
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
167421
+ exports.OpaCompiler = void 0;
167422
+ const fs = __importStar(__nccwpck_require__(79896));
167423
+ const path = __importStar(__nccwpck_require__(16928));
167424
+ const os = __importStar(__nccwpck_require__(70857));
167425
+ const crypto = __importStar(__nccwpck_require__(76982));
167426
+ const child_process_1 = __nccwpck_require__(35317);
167427
+ /**
167428
+ * OPA Rego Compiler - compiles .rego policy files to WASM bundles using the `opa` CLI.
167429
+ *
167430
+ * Handles:
167431
+ * - Resolving input paths to WASM bytes (direct .wasm, directory with policy.wasm, or .rego files)
167432
+ * - Compiling .rego files to WASM via `opa build`
167433
+ * - Caching compiled bundles based on content hashes
167434
+ * - Extracting policy.wasm from OPA tar.gz bundles
167435
+ *
167436
+ * Requires:
167437
+ * - `opa` CLI on PATH (only when auto-compiling .rego files)
167438
+ */
167439
+ class OpaCompiler {
167440
+ static CACHE_DIR = path.join(os.tmpdir(), 'visor-opa-cache');
167441
+ /**
167442
+ * Resolve the input paths to WASM bytes.
167443
+ *
167444
+ * Strategy:
167445
+ * 1. If any path is a .wasm file, read it directly
167446
+ * 2. If a directory contains policy.wasm, read it
167447
+ * 3. Otherwise, collect all .rego files and auto-compile via `opa build`
167448
+ */
167449
+ async resolveWasmBytes(paths) {
167450
+ // Collect .rego files and check for existing .wasm
167451
+ const regoFiles = [];
167452
+ for (const p of paths) {
167453
+ const resolved = path.resolve(p);
167454
+ // Reject paths containing '..' after resolution (path traversal)
167455
+ if (path.normalize(resolved).includes('..')) {
167456
+ throw new Error(`Policy path contains traversal sequences: ${p}`);
167457
+ }
167458
+ // Direct .wasm file
167459
+ if (resolved.endsWith('.wasm') && fs.existsSync(resolved)) {
167460
+ return fs.readFileSync(resolved);
167461
+ }
167462
+ if (!fs.existsSync(resolved))
167463
+ continue;
167464
+ const stat = fs.statSync(resolved);
167465
+ if (stat.isDirectory()) {
167466
+ // Check for pre-compiled policy.wasm in directory
167467
+ const wasmCandidate = path.join(resolved, 'policy.wasm');
167468
+ if (fs.existsSync(wasmCandidate)) {
167469
+ return fs.readFileSync(wasmCandidate);
167470
+ }
167471
+ // Collect all .rego files from directory
167472
+ const files = fs.readdirSync(resolved);
167473
+ for (const f of files) {
167474
+ if (f.endsWith('.rego')) {
167475
+ regoFiles.push(path.join(resolved, f));
167476
+ }
167477
+ }
167478
+ }
167479
+ else if (resolved.endsWith('.rego')) {
167480
+ regoFiles.push(resolved);
167481
+ }
167482
+ }
167483
+ if (regoFiles.length === 0) {
167484
+ throw new Error(`OPA WASM evaluator: no .wasm bundle or .rego files found in: ${paths.join(', ')}`);
167485
+ }
167486
+ // Auto-compile .rego -> .wasm
167487
+ return this.compileRego(regoFiles);
167488
+ }
167489
+ /**
167490
+ * Auto-compile .rego files to a WASM bundle using the `opa` CLI.
167491
+ *
167492
+ * Caches the compiled bundle based on a content hash of all input .rego files
167493
+ * so subsequent runs skip compilation if policies haven't changed.
167494
+ */
167495
+ compileRego(regoFiles) {
167496
+ // Check that `opa` CLI is available
167497
+ try {
167498
+ (0, child_process_1.execFileSync)('opa', ['version'], { stdio: 'pipe' });
167499
+ }
167500
+ catch {
167501
+ throw new Error('OPA CLI (`opa`) not found on PATH. Install it from https://www.openpolicyagent.org/docs/latest/#running-opa\n' +
167502
+ 'Or pre-compile your .rego files: opa build -t wasm -e visor -o bundle.tar.gz ' +
167503
+ regoFiles.join(' '));
167504
+ }
167505
+ // Compute content hash for cache key
167506
+ const hash = crypto.createHash('sha256');
167507
+ for (const f of regoFiles.sort()) {
167508
+ hash.update(fs.readFileSync(f));
167509
+ hash.update(f); // include filename for disambiguation
167510
+ }
167511
+ const cacheKey = hash.digest('hex').slice(0, 16);
167512
+ const cacheDir = OpaCompiler.CACHE_DIR;
167513
+ const cachedWasm = path.join(cacheDir, `${cacheKey}.wasm`);
167514
+ // Return cached bundle if still valid
167515
+ if (fs.existsSync(cachedWasm)) {
167516
+ return fs.readFileSync(cachedWasm);
167517
+ }
167518
+ // Compile to WASM via opa build
167519
+ fs.mkdirSync(cacheDir, { recursive: true });
167520
+ const bundleTar = path.join(cacheDir, `${cacheKey}-bundle.tar.gz`);
167521
+ try {
167522
+ const args = [
167523
+ 'build',
167524
+ '-t',
167525
+ 'wasm',
167526
+ '-e',
167527
+ 'visor', // entrypoint: the visor package tree
167528
+ '-o',
167529
+ bundleTar,
167530
+ ...regoFiles,
167531
+ ];
167532
+ (0, child_process_1.execFileSync)('opa', args, {
167533
+ stdio: 'pipe',
167534
+ timeout: 30000,
167535
+ });
167536
+ }
167537
+ catch (err) {
167538
+ const stderr = err?.stderr?.toString() || '';
167539
+ throw new Error(`Failed to compile .rego files to WASM:\n${stderr}\n` +
167540
+ 'Ensure your .rego files are valid and the `opa` CLI is installed.');
167541
+ }
167542
+ // Extract policy.wasm from the tar.gz bundle
167543
+ // OPA bundles are tar.gz with /policy.wasm inside
167544
+ try {
167545
+ (0, child_process_1.execFileSync)('tar', ['-xzf', bundleTar, '-C', cacheDir, '/policy.wasm'], {
167546
+ stdio: 'pipe',
167547
+ });
167548
+ const extractedWasm = path.join(cacheDir, 'policy.wasm');
167549
+ if (fs.existsSync(extractedWasm)) {
167550
+ // Move to cache-key named file
167551
+ fs.renameSync(extractedWasm, cachedWasm);
167552
+ }
167553
+ }
167554
+ catch {
167555
+ // Some tar implementations don't like leading /
167556
+ try {
167557
+ (0, child_process_1.execFileSync)('tar', ['-xzf', bundleTar, '-C', cacheDir, 'policy.wasm'], {
167558
+ stdio: 'pipe',
167559
+ });
167560
+ const extractedWasm = path.join(cacheDir, 'policy.wasm');
167561
+ if (fs.existsSync(extractedWasm)) {
167562
+ fs.renameSync(extractedWasm, cachedWasm);
167563
+ }
167564
+ }
167565
+ catch (err2) {
167566
+ throw new Error(`Failed to extract policy.wasm from OPA bundle: ${err2?.message || err2}`);
167567
+ }
167568
+ }
167569
+ // Clean up tar
167570
+ try {
167571
+ fs.unlinkSync(bundleTar);
167572
+ }
167573
+ catch { }
167574
+ if (!fs.existsSync(cachedWasm)) {
167575
+ throw new Error('OPA build succeeded but policy.wasm was not found in the bundle');
167576
+ }
167577
+ return fs.readFileSync(cachedWasm);
167578
+ }
167579
+ }
167580
+ exports.OpaCompiler = OpaCompiler;
167581
+
167582
+
167583
+ /***/ }),
167584
+
167585
+ /***/ 44693:
167586
+ /***/ ((__unused_webpack_module, exports) => {
167587
+
167588
+ "use strict";
167589
+
167590
+ /**
167591
+ * Copyright (c) ProbeLabs. All rights reserved.
167592
+ * Licensed under the Elastic License 2.0; you may not use this file except
167593
+ * in compliance with the Elastic License 2.0.
167594
+ */
167595
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
167596
+ exports.OpaHttpEvaluator = void 0;
167597
+ /**
167598
+ * OPA HTTP Evaluator - evaluates policies via an external OPA server's REST API.
167599
+ *
167600
+ * Uses the built-in `fetch` API (Node 18+), so no extra dependencies are needed.
167601
+ */
167602
+ class OpaHttpEvaluator {
167603
+ baseUrl;
167604
+ timeout;
167605
+ constructor(baseUrl, timeout = 5000) {
167606
+ // Validate URL format and protocol
167607
+ let parsed;
167608
+ try {
167609
+ parsed = new URL(baseUrl);
167610
+ }
167611
+ catch {
167612
+ throw new Error(`OPA HTTP evaluator: invalid URL: ${baseUrl}`);
167613
+ }
167614
+ if (!['http:', 'https:'].includes(parsed.protocol)) {
167615
+ throw new Error(`OPA HTTP evaluator: url must use http:// or https:// protocol, got: ${baseUrl}`);
167616
+ }
167617
+ // Block cloud metadata, loopback, link-local, and private network addresses
167618
+ const hostname = parsed.hostname;
167619
+ if (this.isBlockedHostname(hostname)) {
167620
+ throw new Error(`OPA HTTP evaluator: url must not point to internal, loopback, or private network addresses`);
167621
+ }
167622
+ // Normalize: strip trailing slash
167623
+ this.baseUrl = baseUrl.replace(/\/+$/, '');
167624
+ this.timeout = timeout;
167625
+ }
167626
+ /**
167627
+ * Check if a hostname is blocked due to SSRF concerns.
167628
+ *
167629
+ * Blocks:
167630
+ * - Loopback addresses (127.x.x.x, localhost, 0.0.0.0, ::1)
167631
+ * - Link-local addresses (169.254.x.x)
167632
+ * - Private networks (10.x.x.x, 172.16-31.x.x, 192.168.x.x)
167633
+ * - IPv6 unique local addresses (fd00::/8)
167634
+ * - Cloud metadata services (*.internal)
167635
+ */
167636
+ isBlockedHostname(hostname) {
167637
+ if (!hostname)
167638
+ return true; // block empty hostnames
167639
+ // Normalize hostname: lowercase and remove brackets for IPv6
167640
+ const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, '');
167641
+ // Block .internal domains (cloud metadata services)
167642
+ if (normalized === 'metadata.google.internal' || normalized.endsWith('.internal')) {
167643
+ return true;
167644
+ }
167645
+ // Block localhost variants
167646
+ if (normalized === 'localhost' || normalized === 'localhost.localdomain') {
167647
+ return true;
167648
+ }
167649
+ // Block IPv6 loopback
167650
+ if (normalized === '::1' || normalized === '0:0:0:0:0:0:0:1') {
167651
+ return true;
167652
+ }
167653
+ // Check IPv4 patterns
167654
+ const ipv4Pattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
167655
+ const ipv4Match = normalized.match(ipv4Pattern);
167656
+ if (ipv4Match) {
167657
+ const octets = ipv4Match.slice(1, 5).map(Number);
167658
+ // Validate octets are in range [0, 255]
167659
+ if (octets.some(octet => octet > 255)) {
167660
+ return false;
167661
+ }
167662
+ const [a, b] = octets;
167663
+ // Block loopback: 127.0.0.0/8
167664
+ if (a === 127) {
167665
+ return true;
167666
+ }
167667
+ // Block 0.0.0.0/8 (this host)
167668
+ if (a === 0) {
167669
+ return true;
167670
+ }
167671
+ // Block link-local: 169.254.0.0/16
167672
+ if (a === 169 && b === 254) {
167673
+ return true;
167674
+ }
167675
+ // Block private networks
167676
+ // 10.0.0.0/8
167677
+ if (a === 10) {
167678
+ return true;
167679
+ }
167680
+ // 172.16.0.0/12 (172.16.x.x through 172.31.x.x)
167681
+ if (a === 172 && b >= 16 && b <= 31) {
167682
+ return true;
167683
+ }
167684
+ // 192.168.0.0/16
167685
+ if (a === 192 && b === 168) {
167686
+ return true;
167687
+ }
167688
+ }
167689
+ // Check IPv6 patterns
167690
+ // Block unique local addresses: fd00::/8
167691
+ if (normalized.startsWith('fd') || normalized.startsWith('fc')) {
167692
+ return true;
167693
+ }
167694
+ // Block link-local: fe80::/10
167695
+ if (normalized.startsWith('fe80:')) {
167696
+ return true;
167697
+ }
167698
+ return false;
167699
+ }
167700
+ /**
167701
+ * Evaluate a policy rule against an input document via OPA REST API.
167702
+ *
167703
+ * @param input - The input document to evaluate
167704
+ * @param rulePath - OPA rule path (e.g., 'visor/check/execute')
167705
+ * @returns The result object from OPA, or undefined on error
167706
+ */
167707
+ async evaluate(input, rulePath) {
167708
+ // OPA Data API: POST /v1/data/<path>
167709
+ const encodedPath = rulePath
167710
+ .split('/')
167711
+ .map(s => encodeURIComponent(s))
167712
+ .join('/');
167713
+ const url = `${this.baseUrl}/v1/data/${encodedPath}`;
167714
+ const controller = new AbortController();
167715
+ const timer = setTimeout(() => controller.abort(), this.timeout);
167716
+ try {
167717
+ const response = await fetch(url, {
167718
+ method: 'POST',
167719
+ headers: { 'Content-Type': 'application/json' },
167720
+ body: JSON.stringify({ input }),
167721
+ signal: controller.signal,
167722
+ });
167723
+ if (!response.ok) {
167724
+ throw new Error(`OPA HTTP ${response.status}: ${response.statusText}`);
167725
+ }
167726
+ let body;
167727
+ try {
167728
+ body = await response.json();
167729
+ }
167730
+ catch (jsonErr) {
167731
+ throw new Error(`OPA HTTP evaluator: failed to parse JSON response: ${jsonErr instanceof Error ? jsonErr.message : String(jsonErr)}`);
167732
+ }
167733
+ // OPA returns { result: { ... } }
167734
+ return body?.result;
167735
+ }
167736
+ finally {
167737
+ clearTimeout(timer);
167738
+ }
167739
+ }
167740
+ async shutdown() {
167741
+ // No persistent connections to close
167742
+ }
167743
+ }
167744
+ exports.OpaHttpEvaluator = OpaHttpEvaluator;
167745
+
167746
+
167747
+ /***/ }),
167748
+
167749
+ /***/ 39530:
167750
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
167751
+
167752
+ "use strict";
167753
+
167754
+ /**
167755
+ * Copyright (c) ProbeLabs. All rights reserved.
167756
+ * Licensed under the Elastic License 2.0; you may not use this file except
167757
+ * in compliance with the Elastic License 2.0.
167758
+ */
167759
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
167760
+ exports.OpaPolicyEngine = void 0;
167761
+ const opa_wasm_evaluator_1 = __nccwpck_require__(8613);
167762
+ const opa_http_evaluator_1 = __nccwpck_require__(44693);
167763
+ const policy_input_builder_1 = __nccwpck_require__(17117);
167764
+ /**
167765
+ * Enterprise OPA Policy Engine.
167766
+ *
167767
+ * Wraps both WASM (local) and HTTP (remote) OPA evaluators behind the
167768
+ * OSS PolicyEngine interface. All OPA input building and role resolution
167769
+ * is handled internally — the OSS call sites pass only plain types.
167770
+ */
167771
+ class OpaPolicyEngine {
167772
+ evaluator = null;
167773
+ fallback;
167774
+ timeout;
167775
+ config;
167776
+ inputBuilder = null;
167777
+ logger = null;
167778
+ constructor(config) {
167779
+ this.config = config;
167780
+ this.fallback = config.fallback || 'deny';
167781
+ this.timeout = config.timeout || 5000;
167782
+ }
167783
+ async initialize(config) {
167784
+ // Resolve logger once at initialization
167785
+ try {
167786
+ this.logger = (__nccwpck_require__(86999).logger);
167787
+ }
167788
+ catch {
167789
+ // logger not available in this context
167790
+ }
167791
+ // Build actor/repo context from environment (available at engine init time)
167792
+ const actor = {
167793
+ authorAssociation: process.env.VISOR_AUTHOR_ASSOCIATION,
167794
+ login: process.env.VISOR_AUTHOR_LOGIN || process.env.GITHUB_ACTOR,
167795
+ isLocalMode: !process.env.GITHUB_ACTIONS,
167796
+ };
167797
+ const repo = {
167798
+ owner: process.env.GITHUB_REPOSITORY_OWNER,
167799
+ name: process.env.GITHUB_REPOSITORY?.split('/')[1],
167800
+ branch: process.env.GITHUB_HEAD_REF,
167801
+ baseBranch: process.env.GITHUB_BASE_REF,
167802
+ event: process.env.GITHUB_EVENT_NAME,
167803
+ };
167804
+ const prNum = process.env.GITHUB_PR_NUMBER
167805
+ ? parseInt(process.env.GITHUB_PR_NUMBER, 10)
167806
+ : undefined;
167807
+ const pullRequest = {
167808
+ number: prNum !== undefined && Number.isFinite(prNum) ? prNum : undefined,
167809
+ };
167810
+ this.inputBuilder = new policy_input_builder_1.PolicyInputBuilder(config, actor, repo, pullRequest);
167811
+ if (config.engine === 'local') {
167812
+ if (!config.rules) {
167813
+ throw new Error('OPA local mode requires `policy.rules` path to .wasm or .rego files');
167814
+ }
167815
+ const wasm = new opa_wasm_evaluator_1.OpaWasmEvaluator();
167816
+ await wasm.initialize(config.rules);
167817
+ if (config.data) {
167818
+ wasm.loadData(config.data);
167819
+ }
167820
+ this.evaluator = wasm;
167821
+ }
167822
+ else if (config.engine === 'remote') {
167823
+ if (!config.url) {
167824
+ throw new Error('OPA remote mode requires `policy.url` pointing to OPA server');
167825
+ }
167826
+ this.evaluator = new opa_http_evaluator_1.OpaHttpEvaluator(config.url, this.timeout);
167827
+ }
167828
+ else {
167829
+ this.evaluator = null;
167830
+ }
167831
+ }
167832
+ /**
167833
+ * Update actor/repo/PR context (e.g., after PR info becomes available).
167834
+ * Called by the enterprise loader when engine context is enriched.
167835
+ */
167836
+ setActorContext(actor, repo, pullRequest) {
167837
+ this.inputBuilder = new policy_input_builder_1.PolicyInputBuilder(this.config, actor, repo, pullRequest);
167838
+ }
167839
+ async evaluateCheckExecution(checkId, checkConfig) {
167840
+ if (!this.evaluator || !this.inputBuilder)
167841
+ return { allowed: true };
167842
+ const cfg = checkConfig && typeof checkConfig === 'object'
167843
+ ? checkConfig
167844
+ : {};
167845
+ const policyOverride = cfg.policy;
167846
+ const input = this.inputBuilder.forCheckExecution({
167847
+ id: checkId,
167848
+ type: cfg.type || 'ai',
167849
+ group: cfg.group,
167850
+ tags: cfg.tags,
167851
+ criticality: cfg.criticality,
167852
+ sandbox: cfg.sandbox,
167853
+ policy: policyOverride,
167854
+ });
167855
+ return this.doEvaluate(input, this.resolveRulePath('check.execute', policyOverride?.rule));
167856
+ }
167857
+ async evaluateToolInvocation(serverName, methodName, transport) {
167858
+ if (!this.evaluator || !this.inputBuilder)
167859
+ return { allowed: true };
167860
+ const input = this.inputBuilder.forToolInvocation(serverName, methodName, transport);
167861
+ return this.doEvaluate(input, 'visor/tool/invoke');
167862
+ }
167863
+ async evaluateCapabilities(checkId, capabilities) {
167864
+ if (!this.evaluator || !this.inputBuilder)
167865
+ return { allowed: true };
167866
+ const input = this.inputBuilder.forCapabilityResolve(checkId, capabilities);
167867
+ return this.doEvaluate(input, 'visor/capability/resolve');
167868
+ }
167869
+ async shutdown() {
167870
+ if (this.evaluator && 'shutdown' in this.evaluator) {
167871
+ await this.evaluator.shutdown();
167872
+ }
167873
+ this.evaluator = null;
167874
+ this.inputBuilder = null;
167875
+ }
167876
+ resolveRulePath(defaultScope, override) {
167877
+ if (override) {
167878
+ return override.startsWith('visor/') ? override : `visor/${override}`;
167879
+ }
167880
+ return `visor/${defaultScope.replace(/\./g, '/')}`;
167881
+ }
167882
+ async doEvaluate(input, rulePath) {
167883
+ try {
167884
+ this.logger?.debug(`[PolicyEngine] Evaluating ${rulePath}`, JSON.stringify(input));
167885
+ let timer;
167886
+ const timeoutPromise = new Promise((_resolve, reject) => {
167887
+ timer = setTimeout(() => reject(new Error('policy evaluation timeout')), this.timeout);
167888
+ });
167889
+ try {
167890
+ const result = await Promise.race([this.rawEvaluate(input, rulePath), timeoutPromise]);
167891
+ const decision = this.parseDecision(result);
167892
+ // In warn mode, override denied decisions to allowed but flag as warn
167893
+ if (!decision.allowed && this.fallback === 'warn') {
167894
+ decision.allowed = true;
167895
+ decision.warn = true;
167896
+ decision.reason = `audit: ${decision.reason || 'policy denied'}`;
167897
+ }
167898
+ this.logger?.debug(`[PolicyEngine] Decision for ${rulePath}: allowed=${decision.allowed}, warn=${decision.warn || false}, reason=${decision.reason || 'none'}`);
167899
+ return decision;
167900
+ }
167901
+ finally {
167902
+ if (timer)
167903
+ clearTimeout(timer);
167904
+ }
167905
+ }
167906
+ catch (err) {
167907
+ const msg = err instanceof Error ? err.message : String(err);
167908
+ this.logger?.warn(`[PolicyEngine] Evaluation failed for ${rulePath}: ${msg}`);
167909
+ return {
167910
+ allowed: this.fallback === 'allow' || this.fallback === 'warn',
167911
+ warn: this.fallback === 'warn' ? true : undefined,
167912
+ reason: `policy evaluation failed, fallback=${this.fallback}`,
167913
+ };
167914
+ }
167915
+ }
167916
+ async rawEvaluate(input, rulePath) {
167917
+ if (this.evaluator instanceof opa_wasm_evaluator_1.OpaWasmEvaluator) {
167918
+ const result = await this.evaluator.evaluate(input);
167919
+ // WASM compiled with `-e visor` entrypoint returns the full visor package tree.
167920
+ // Navigate to the specific rule subtree using rulePath segments.
167921
+ // e.g., 'visor/check/execute' → result.check.execute
167922
+ return this.navigateWasmResult(result, rulePath);
167923
+ }
167924
+ return this.evaluator.evaluate(input, rulePath);
167925
+ }
167926
+ /**
167927
+ * Navigate nested OPA WASM result tree to reach the specific rule's output.
167928
+ * The WASM entrypoint `-e visor` means the result root IS the visor package,
167929
+ * so we strip the `visor/` prefix and walk the remaining segments.
167930
+ */
167931
+ navigateWasmResult(result, rulePath) {
167932
+ if (!result || typeof result !== 'object')
167933
+ return result;
167934
+ // Strip the 'visor/' prefix (matches our compilation entrypoint)
167935
+ const segments = rulePath.replace(/^visor\//, '').split('/');
167936
+ let current = result;
167937
+ for (const seg of segments) {
167938
+ if (current && typeof current === 'object' && seg in current) {
167939
+ current = current[seg];
167940
+ }
167941
+ else {
167942
+ return undefined; // path not found in result tree
167943
+ }
167944
+ }
167945
+ return current;
167946
+ }
167947
+ parseDecision(result) {
167948
+ if (result === undefined || result === null) {
167949
+ return {
167950
+ allowed: this.fallback === 'allow' || this.fallback === 'warn',
167951
+ warn: this.fallback === 'warn' ? true : undefined,
167952
+ reason: this.fallback === 'warn' ? 'audit: no policy result' : 'no policy result',
167953
+ };
167954
+ }
167955
+ const allowed = result.allowed !== false;
167956
+ const decision = {
167957
+ allowed,
167958
+ reason: result.reason,
167959
+ };
167960
+ if (result.capabilities) {
167961
+ decision.capabilities = result.capabilities;
167962
+ }
167963
+ return decision;
167964
+ }
167965
+ }
167966
+ exports.OpaPolicyEngine = OpaPolicyEngine;
167967
+
167968
+
167969
+ /***/ }),
167970
+
167971
+ /***/ 8613:
167972
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
167973
+
167974
+ "use strict";
167975
+
167976
+ /**
167977
+ * Copyright (c) ProbeLabs. All rights reserved.
167978
+ * Licensed under the Elastic License 2.0; you may not use this file except
167979
+ * in compliance with the Elastic License 2.0.
167980
+ */
167981
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
167982
+ if (k2 === undefined) k2 = k;
167983
+ var desc = Object.getOwnPropertyDescriptor(m, k);
167984
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
167985
+ desc = { enumerable: true, get: function() { return m[k]; } };
167986
+ }
167987
+ Object.defineProperty(o, k2, desc);
167988
+ }) : (function(o, m, k, k2) {
167989
+ if (k2 === undefined) k2 = k;
167990
+ o[k2] = m[k];
167991
+ }));
167992
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
167993
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
167994
+ }) : function(o, v) {
167995
+ o["default"] = v;
167996
+ });
167997
+ var __importStar = (this && this.__importStar) || (function () {
167998
+ var ownKeys = function(o) {
167999
+ ownKeys = Object.getOwnPropertyNames || function (o) {
168000
+ var ar = [];
168001
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
168002
+ return ar;
168003
+ };
168004
+ return ownKeys(o);
168005
+ };
168006
+ return function (mod) {
168007
+ if (mod && mod.__esModule) return mod;
168008
+ var result = {};
168009
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
168010
+ __setModuleDefault(result, mod);
168011
+ return result;
168012
+ };
168013
+ })();
168014
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
168015
+ exports.OpaWasmEvaluator = void 0;
168016
+ const fs = __importStar(__nccwpck_require__(79896));
168017
+ const path = __importStar(__nccwpck_require__(16928));
168018
+ const opa_compiler_1 = __nccwpck_require__(628);
168019
+ /**
168020
+ * OPA WASM Evaluator - loads and evaluates OPA policies locally.
168021
+ *
168022
+ * Supports three input formats:
168023
+ * 1. Pre-compiled `.wasm` bundle — loaded directly (fastest startup)
168024
+ * 2. `.rego` files or directory — auto-compiled to WASM via `opa build` CLI
168025
+ * 3. Directory with `policy.wasm` inside — loaded directly
168026
+ *
168027
+ * Compilation and caching of .rego files is delegated to {@link OpaCompiler}.
168028
+ *
168029
+ * Requires:
168030
+ * - `@open-policy-agent/opa-wasm` npm package (optional dep)
168031
+ * - `opa` CLI on PATH (only when auto-compiling .rego files)
168032
+ */
168033
+ class OpaWasmEvaluator {
168034
+ policy = null;
168035
+ dataDocument = {};
168036
+ compiler = new opa_compiler_1.OpaCompiler();
168037
+ async initialize(rulesPath) {
168038
+ const paths = Array.isArray(rulesPath) ? rulesPath : [rulesPath];
168039
+ const wasmBytes = await this.compiler.resolveWasmBytes(paths);
168040
+ try {
168041
+ // Use createRequire to load the optional dep at runtime without ncc bundling it.
168042
+ // `new Function('id', 'return require(id)')` fails in ncc bundles because
168043
+ // `require` is not in the `new Function` scope. `createRequire` works correctly
168044
+ // because it creates a real Node.js require rooted at the given path.
168045
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
168046
+ const { createRequire } = __nccwpck_require__(73339);
168047
+ const runtimeRequire = createRequire(__filename);
168048
+ const opaWasm = runtimeRequire('@open-policy-agent/opa-wasm');
168049
+ const loadPolicy = opaWasm.loadPolicy || opaWasm.default?.loadPolicy;
168050
+ if (!loadPolicy) {
168051
+ throw new Error('loadPolicy not found in @open-policy-agent/opa-wasm');
168052
+ }
168053
+ this.policy = await loadPolicy(wasmBytes);
168054
+ }
168055
+ catch (err) {
168056
+ if (err?.code === 'MODULE_NOT_FOUND' || err?.code === 'ERR_MODULE_NOT_FOUND') {
168057
+ throw new Error('OPA WASM evaluator requires @open-policy-agent/opa-wasm. ' +
168058
+ 'Install it with: npm install @open-policy-agent/opa-wasm');
168059
+ }
168060
+ throw err;
168061
+ }
168062
+ }
168063
+ /**
168064
+ * Load external data from a JSON file to use as the OPA data document.
168065
+ * The loaded data will be passed to `policy.setData()` during evaluation,
168066
+ * making it available in Rego via `data.<key>`.
168067
+ */
168068
+ loadData(dataPath) {
168069
+ const resolved = path.resolve(dataPath);
168070
+ if (path.normalize(resolved).includes('..')) {
168071
+ throw new Error(`Data path contains traversal sequences: ${dataPath}`);
168072
+ }
168073
+ if (!fs.existsSync(resolved)) {
168074
+ throw new Error(`OPA data file not found: ${resolved}`);
168075
+ }
168076
+ const stat = fs.statSync(resolved);
168077
+ if (stat.size > 10 * 1024 * 1024) {
168078
+ throw new Error(`OPA data file exceeds 10MB limit: ${resolved} (${stat.size} bytes)`);
168079
+ }
168080
+ const raw = fs.readFileSync(resolved, 'utf-8');
168081
+ try {
168082
+ const parsed = JSON.parse(raw);
168083
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
168084
+ throw new Error('OPA data file must contain a JSON object (not an array or primitive)');
168085
+ }
168086
+ this.dataDocument = parsed;
168087
+ }
168088
+ catch (err) {
168089
+ if (err.message.startsWith('OPA data file must')) {
168090
+ throw err;
168091
+ }
168092
+ throw new Error(`Failed to parse OPA data file ${resolved}: ${err.message}`);
168093
+ }
168094
+ }
168095
+ async evaluate(input) {
168096
+ if (!this.policy) {
168097
+ throw new Error('OPA WASM evaluator not initialized');
168098
+ }
168099
+ this.policy.setData(this.dataDocument);
168100
+ const resultSet = this.policy.evaluate(input);
168101
+ if (Array.isArray(resultSet) && resultSet.length > 0) {
168102
+ return resultSet[0].result;
168103
+ }
168104
+ return undefined;
168105
+ }
168106
+ async shutdown() {
168107
+ if (this.policy) {
168108
+ // opa-wasm policy objects may have a close/free method for WASM cleanup
168109
+ if (typeof this.policy.close === 'function') {
168110
+ try {
168111
+ this.policy.close();
168112
+ }
168113
+ catch { }
168114
+ }
168115
+ else if (typeof this.policy.free === 'function') {
168116
+ try {
168117
+ this.policy.free();
168118
+ }
168119
+ catch { }
168120
+ }
168121
+ }
168122
+ this.policy = null;
168123
+ }
168124
+ }
168125
+ exports.OpaWasmEvaluator = OpaWasmEvaluator;
168126
+
168127
+
168128
+ /***/ }),
168129
+
168130
+ /***/ 17117:
168131
+ /***/ ((__unused_webpack_module, exports) => {
168132
+
168133
+ "use strict";
168134
+
168135
+ /**
168136
+ * Copyright (c) ProbeLabs. All rights reserved.
168137
+ * Licensed under the Elastic License 2.0; you may not use this file except
168138
+ * in compliance with the Elastic License 2.0.
168139
+ */
168140
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
168141
+ exports.PolicyInputBuilder = void 0;
168142
+ /**
168143
+ * Builds OPA-compatible input documents from engine context.
168144
+ *
168145
+ * Resolves actor roles from the `policy.roles` config section by matching
168146
+ * the actor's authorAssociation and login against role definitions.
168147
+ */
168148
+ class PolicyInputBuilder {
168149
+ roles;
168150
+ actor;
168151
+ repository;
168152
+ pullRequest;
168153
+ constructor(policyConfig, actor, repository, pullRequest) {
168154
+ this.roles = policyConfig.roles || {};
168155
+ this.actor = actor;
168156
+ this.repository = repository;
168157
+ this.pullRequest = pullRequest;
168158
+ }
168159
+ /** Resolve which roles apply to the current actor. */
168160
+ resolveRoles() {
168161
+ const matched = [];
168162
+ for (const [roleName, roleConfig] of Object.entries(this.roles)) {
168163
+ let identityMatch = false;
168164
+ if (roleConfig.author_association &&
168165
+ this.actor.authorAssociation &&
168166
+ roleConfig.author_association.includes(this.actor.authorAssociation)) {
168167
+ identityMatch = true;
168168
+ }
168169
+ if (!identityMatch &&
168170
+ roleConfig.users &&
168171
+ this.actor.login &&
168172
+ roleConfig.users.includes(this.actor.login)) {
168173
+ identityMatch = true;
168174
+ }
168175
+ // Slack user ID match
168176
+ if (!identityMatch &&
168177
+ roleConfig.slack_users &&
168178
+ this.actor.slack?.userId &&
168179
+ roleConfig.slack_users.includes(this.actor.slack.userId)) {
168180
+ identityMatch = true;
168181
+ }
168182
+ // Email match (case-insensitive)
168183
+ if (!identityMatch && roleConfig.emails && this.actor.slack?.email) {
168184
+ const actorEmail = this.actor.slack.email.toLowerCase();
168185
+ if (roleConfig.emails.some(e => e.toLowerCase() === actorEmail)) {
168186
+ identityMatch = true;
168187
+ }
168188
+ }
168189
+ // Note: teams-based role resolution requires GitHub API access (read:org scope)
168190
+ // and is not yet implemented. If configured, the role will not match via teams.
168191
+ if (!identityMatch)
168192
+ continue;
168193
+ // slack_channels gate: if set, the role only applies when triggered from one of these channels
168194
+ if (roleConfig.slack_channels && roleConfig.slack_channels.length > 0) {
168195
+ if (!this.actor.slack?.channelId ||
168196
+ !roleConfig.slack_channels.includes(this.actor.slack.channelId)) {
168197
+ continue;
168198
+ }
168199
+ }
168200
+ matched.push(roleName);
168201
+ }
168202
+ return matched;
168203
+ }
168204
+ buildActor() {
168205
+ return {
168206
+ authorAssociation: this.actor.authorAssociation,
168207
+ login: this.actor.login,
168208
+ roles: this.resolveRoles(),
168209
+ isLocalMode: this.actor.isLocalMode,
168210
+ ...(this.actor.slack && { slack: this.actor.slack }),
168211
+ };
168212
+ }
168213
+ forCheckExecution(check) {
168214
+ return {
168215
+ scope: 'check.execute',
168216
+ check: {
168217
+ id: check.id,
168218
+ type: check.type,
168219
+ group: check.group,
168220
+ tags: check.tags,
168221
+ criticality: check.criticality,
168222
+ sandbox: check.sandbox,
168223
+ policy: check.policy,
168224
+ },
168225
+ actor: this.buildActor(),
168226
+ repository: this.repository,
168227
+ pullRequest: this.pullRequest,
168228
+ };
168229
+ }
168230
+ forToolInvocation(serverName, methodName, transport) {
168231
+ return {
168232
+ scope: 'tool.invoke',
168233
+ tool: { serverName, methodName, transport },
168234
+ actor: this.buildActor(),
168235
+ repository: this.repository,
168236
+ pullRequest: this.pullRequest,
168237
+ };
168238
+ }
168239
+ forCapabilityResolve(checkId, capabilities) {
168240
+ return {
168241
+ scope: 'capability.resolve',
168242
+ check: { id: checkId, type: 'ai' },
168243
+ capability: capabilities,
168244
+ actor: this.buildActor(),
168245
+ repository: this.repository,
168246
+ pullRequest: this.pullRequest,
168247
+ };
168248
+ }
168249
+ }
168250
+ exports.PolicyInputBuilder = PolicyInputBuilder;
168251
+
168252
+
168253
+ /***/ }),
168254
+
168255
+ /***/ 63737:
168256
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
168257
+
168258
+ "use strict";
168259
+
168260
+ /**
168261
+ * Copyright (c) ProbeLabs. All rights reserved.
168262
+ * Licensed under the Elastic License 2.0; you may not use this file except
168263
+ * in compliance with the Elastic License 2.0.
168264
+ */
168265
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
168266
+ if (k2 === undefined) k2 = k;
168267
+ var desc = Object.getOwnPropertyDescriptor(m, k);
168268
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
168269
+ desc = { enumerable: true, get: function() { return m[k]; } };
168270
+ }
168271
+ Object.defineProperty(o, k2, desc);
168272
+ }) : (function(o, m, k, k2) {
168273
+ if (k2 === undefined) k2 = k;
168274
+ o[k2] = m[k];
168275
+ }));
168276
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
168277
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
168278
+ }) : function(o, v) {
168279
+ o["default"] = v;
168280
+ });
168281
+ var __importStar = (this && this.__importStar) || (function () {
168282
+ var ownKeys = function(o) {
168283
+ ownKeys = Object.getOwnPropertyNames || function (o) {
168284
+ var ar = [];
168285
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
168286
+ return ar;
168287
+ };
168288
+ return ownKeys(o);
168289
+ };
168290
+ return function (mod) {
168291
+ if (mod && mod.__esModule) return mod;
168292
+ var result = {};
168293
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
168294
+ __setModuleDefault(result, mod);
168295
+ return result;
168296
+ };
168297
+ })();
168298
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
168299
+ exports.KnexStoreBackend = void 0;
168300
+ /**
168301
+ * Knex-backed schedule store for PostgreSQL, MySQL, and MSSQL (Enterprise)
168302
+ *
168303
+ * Uses Knex query builder for database-agnostic SQL. Same schema as SQLite backend
168304
+ * but with real distributed locking via row-level claims (claimed_by/claimed_at/lock_token).
168305
+ */
168306
+ const fs = __importStar(__nccwpck_require__(79896));
168307
+ const path = __importStar(__nccwpck_require__(16928));
168308
+ const uuid_1 = __nccwpck_require__(31914);
168309
+ const logger_1 = __nccwpck_require__(86999);
168310
+ function toNum(val) {
168311
+ if (val === null || val === undefined)
168312
+ return undefined;
168313
+ return typeof val === 'string' ? parseInt(val, 10) : val;
168314
+ }
168315
+ function safeJsonParse(value) {
168316
+ if (!value)
168317
+ return undefined;
168318
+ try {
168319
+ return JSON.parse(value);
168320
+ }
168321
+ catch {
168322
+ return undefined;
168323
+ }
168324
+ }
168325
+ function fromTriggerRow(row) {
168326
+ return {
168327
+ id: row.id,
168328
+ creatorId: row.creator_id,
168329
+ creatorContext: row.creator_context ?? undefined,
168330
+ creatorName: row.creator_name ?? undefined,
168331
+ description: row.description ?? undefined,
168332
+ channels: safeJsonParse(row.channels),
168333
+ fromUsers: safeJsonParse(row.from_users),
168334
+ fromBots: row.from_bots === true || row.from_bots === 1,
168335
+ contains: safeJsonParse(row.contains),
168336
+ matchPattern: row.match_pattern ?? undefined,
168337
+ threads: row.threads,
168338
+ workflow: row.workflow,
168339
+ inputs: safeJsonParse(row.inputs),
168340
+ outputContext: safeJsonParse(row.output_context),
168341
+ status: row.status,
168342
+ enabled: row.enabled === true || row.enabled === 1,
168343
+ createdAt: toNum(row.created_at),
168344
+ };
168345
+ }
168346
+ function toTriggerInsertRow(trigger) {
168347
+ return {
168348
+ id: trigger.id,
168349
+ creator_id: trigger.creatorId,
168350
+ creator_context: trigger.creatorContext ?? null,
168351
+ creator_name: trigger.creatorName ?? null,
168352
+ description: trigger.description ?? null,
168353
+ channels: trigger.channels ? JSON.stringify(trigger.channels) : null,
168354
+ from_users: trigger.fromUsers ? JSON.stringify(trigger.fromUsers) : null,
168355
+ from_bots: trigger.fromBots,
168356
+ contains: trigger.contains ? JSON.stringify(trigger.contains) : null,
168357
+ match_pattern: trigger.matchPattern ?? null,
168358
+ threads: trigger.threads,
168359
+ workflow: trigger.workflow,
168360
+ inputs: trigger.inputs ? JSON.stringify(trigger.inputs) : null,
168361
+ output_context: trigger.outputContext ? JSON.stringify(trigger.outputContext) : null,
168362
+ status: trigger.status,
168363
+ enabled: trigger.enabled,
168364
+ created_at: trigger.createdAt,
168365
+ };
168366
+ }
168367
+ function fromDbRow(row) {
168368
+ return {
168369
+ id: row.id,
168370
+ creatorId: row.creator_id,
168371
+ creatorContext: row.creator_context ?? undefined,
168372
+ creatorName: row.creator_name ?? undefined,
168373
+ timezone: row.timezone,
168374
+ schedule: row.schedule_expr,
168375
+ runAt: toNum(row.run_at),
168376
+ isRecurring: row.is_recurring === true || row.is_recurring === 1,
168377
+ originalExpression: row.original_expression,
168378
+ workflow: row.workflow ?? undefined,
168379
+ workflowInputs: safeJsonParse(row.workflow_inputs),
168380
+ outputContext: safeJsonParse(row.output_context),
168381
+ status: row.status,
168382
+ createdAt: toNum(row.created_at),
168383
+ lastRunAt: toNum(row.last_run_at),
168384
+ nextRunAt: toNum(row.next_run_at),
168385
+ runCount: row.run_count,
168386
+ failureCount: row.failure_count,
168387
+ lastError: row.last_error ?? undefined,
168388
+ previousResponse: row.previous_response ?? undefined,
168389
+ };
168390
+ }
168391
+ function toInsertRow(schedule) {
168392
+ return {
168393
+ id: schedule.id,
168394
+ creator_id: schedule.creatorId,
168395
+ creator_context: schedule.creatorContext ?? null,
168396
+ creator_name: schedule.creatorName ?? null,
168397
+ timezone: schedule.timezone,
168398
+ schedule_expr: schedule.schedule,
168399
+ run_at: schedule.runAt ?? null,
168400
+ is_recurring: schedule.isRecurring,
168401
+ original_expression: schedule.originalExpression,
168402
+ workflow: schedule.workflow ?? null,
168403
+ workflow_inputs: schedule.workflowInputs ? JSON.stringify(schedule.workflowInputs) : null,
168404
+ output_context: schedule.outputContext ? JSON.stringify(schedule.outputContext) : null,
168405
+ status: schedule.status,
168406
+ created_at: schedule.createdAt,
168407
+ last_run_at: schedule.lastRunAt ?? null,
168408
+ next_run_at: schedule.nextRunAt ?? null,
168409
+ run_count: schedule.runCount,
168410
+ failure_count: schedule.failureCount,
168411
+ last_error: schedule.lastError ?? null,
168412
+ previous_response: schedule.previousResponse ?? null,
168413
+ };
168414
+ }
168415
+ /**
168416
+ * Enterprise Knex-backed store for PostgreSQL, MySQL, and MSSQL
168417
+ */
168418
+ class KnexStoreBackend {
168419
+ knex = null;
168420
+ driver;
168421
+ connection;
168422
+ constructor(driver, storageConfig, _haConfig) {
168423
+ this.driver = driver;
168424
+ this.connection = (storageConfig.connection || {});
168425
+ }
168426
+ async initialize() {
168427
+ // Load knex dynamically
168428
+ const { createRequire } = __nccwpck_require__(73339);
168429
+ const runtimeRequire = createRequire(__filename);
168430
+ let knexFactory;
168431
+ try {
168432
+ knexFactory = runtimeRequire('knex');
168433
+ }
168434
+ catch (err) {
168435
+ const code = err?.code;
168436
+ if (code === 'MODULE_NOT_FOUND' || code === 'ERR_MODULE_NOT_FOUND') {
168437
+ throw new Error('knex is required for PostgreSQL/MySQL/MSSQL schedule storage. ' +
168438
+ 'Install it with: npm install knex');
168439
+ }
168440
+ throw err;
168441
+ }
168442
+ const clientMap = {
168443
+ postgresql: 'pg',
168444
+ mysql: 'mysql2',
168445
+ mssql: 'tedious',
168446
+ };
168447
+ const client = clientMap[this.driver];
168448
+ // Build connection config
168449
+ let connection;
168450
+ if (this.connection.connection_string) {
168451
+ connection = this.connection.connection_string;
168452
+ }
168453
+ else if (this.driver === 'mssql') {
168454
+ connection = this.buildMssqlConnection();
168455
+ }
168456
+ else {
168457
+ connection = this.buildStandardConnection();
168458
+ }
168459
+ this.knex = knexFactory({
168460
+ client,
168461
+ connection,
168462
+ pool: {
168463
+ min: this.connection.pool?.min ?? 0,
168464
+ max: this.connection.pool?.max ?? 10,
168465
+ },
168466
+ });
168467
+ // Run schema migration
168468
+ await this.migrateSchema();
168469
+ logger_1.logger.info(`[KnexStore] Initialized (${this.driver})`);
168470
+ }
168471
+ buildStandardConnection() {
168472
+ return {
168473
+ host: this.connection.host || 'localhost',
168474
+ port: this.connection.port,
168475
+ database: this.connection.database || 'visor',
168476
+ user: this.connection.user,
168477
+ password: this.connection.password,
168478
+ ssl: this.resolveSslConfig(),
168479
+ };
168480
+ }
168481
+ buildMssqlConnection() {
168482
+ const ssl = this.connection.ssl;
168483
+ const sslEnabled = ssl === true || (typeof ssl === 'object' && ssl.enabled !== false);
168484
+ return {
168485
+ server: this.connection.host || 'localhost',
168486
+ port: this.connection.port,
168487
+ database: this.connection.database || 'visor',
168488
+ user: this.connection.user,
168489
+ password: this.connection.password,
168490
+ options: {
168491
+ encrypt: sslEnabled,
168492
+ trustServerCertificate: typeof ssl === 'object' ? ssl.reject_unauthorized === false : !sslEnabled,
168493
+ },
168494
+ };
168495
+ }
168496
+ resolveSslConfig() {
168497
+ const ssl = this.connection.ssl;
168498
+ if (ssl === false || ssl === undefined)
168499
+ return false;
168500
+ if (ssl === true)
168501
+ return { rejectUnauthorized: true };
168502
+ // Object config
168503
+ if (ssl.enabled === false)
168504
+ return false;
168505
+ const result = {
168506
+ rejectUnauthorized: ssl.reject_unauthorized !== false,
168507
+ };
168508
+ if (ssl.ca) {
168509
+ const caPath = this.validateSslPath(ssl.ca, 'CA certificate');
168510
+ result.ca = fs.readFileSync(caPath, 'utf8');
168511
+ }
168512
+ if (ssl.cert) {
168513
+ const certPath = this.validateSslPath(ssl.cert, 'client certificate');
168514
+ result.cert = fs.readFileSync(certPath, 'utf8');
168515
+ }
168516
+ if (ssl.key) {
168517
+ const keyPath = this.validateSslPath(ssl.key, 'client key');
168518
+ result.key = fs.readFileSync(keyPath, 'utf8');
168519
+ }
168520
+ return result;
168521
+ }
168522
+ validateSslPath(filePath, label) {
168523
+ const resolved = path.resolve(filePath);
168524
+ if (resolved !== path.normalize(resolved)) {
168525
+ throw new Error(`SSL ${label} path contains invalid sequences: ${filePath}`);
168526
+ }
168527
+ if (!fs.existsSync(resolved)) {
168528
+ throw new Error(`SSL ${label} not found: ${filePath}`);
168529
+ }
168530
+ return resolved;
168531
+ }
168532
+ async shutdown() {
168533
+ if (this.knex) {
168534
+ await this.knex.destroy();
168535
+ this.knex = null;
168536
+ }
168537
+ }
168538
+ async migrateSchema() {
168539
+ const knex = this.getKnex();
168540
+ const exists = await knex.schema.hasTable('schedules');
168541
+ if (!exists) {
168542
+ await knex.schema.createTable('schedules', table => {
168543
+ table.string('id', 36).primary();
168544
+ table.string('creator_id', 255).notNullable().index();
168545
+ table.string('creator_context', 255);
168546
+ table.string('creator_name', 255);
168547
+ table.string('timezone', 64).notNullable().defaultTo('UTC');
168548
+ table.string('schedule_expr', 255);
168549
+ table.bigInteger('run_at');
168550
+ table.boolean('is_recurring').notNullable();
168551
+ table.text('original_expression');
168552
+ table.string('workflow', 255);
168553
+ table.text('workflow_inputs');
168554
+ table.text('output_context');
168555
+ table.string('status', 20).notNullable().index();
168556
+ table.bigInteger('created_at').notNullable();
168557
+ table.bigInteger('last_run_at');
168558
+ table.bigInteger('next_run_at');
168559
+ table.integer('run_count').notNullable().defaultTo(0);
168560
+ table.integer('failure_count').notNullable().defaultTo(0);
168561
+ table.text('last_error');
168562
+ table.text('previous_response');
168563
+ table.index(['status', 'next_run_at']);
168564
+ });
168565
+ }
168566
+ // Create message_triggers table
168567
+ const triggersExist = await knex.schema.hasTable('message_triggers');
168568
+ if (!triggersExist) {
168569
+ await knex.schema.createTable('message_triggers', table => {
168570
+ table.string('id', 36).primary();
168571
+ table.string('creator_id', 255).notNullable().index();
168572
+ table.string('creator_context', 255);
168573
+ table.string('creator_name', 255);
168574
+ table.text('description');
168575
+ table.text('channels'); // JSON array
168576
+ table.text('from_users'); // JSON array
168577
+ table.boolean('from_bots').notNullable().defaultTo(false);
168578
+ table.text('contains'); // JSON array
168579
+ table.text('match_pattern');
168580
+ table.string('threads', 20).notNullable().defaultTo('any');
168581
+ table.string('workflow', 255).notNullable();
168582
+ table.text('inputs'); // JSON
168583
+ table.text('output_context'); // JSON
168584
+ table.string('status', 20).notNullable().defaultTo('active').index();
168585
+ table.boolean('enabled').notNullable().defaultTo(true);
168586
+ table.bigInteger('created_at').notNullable();
168587
+ });
168588
+ }
168589
+ // Create scheduler_locks table for distributed locking
168590
+ const locksExist = await knex.schema.hasTable('scheduler_locks');
168591
+ if (!locksExist) {
168592
+ await knex.schema.createTable('scheduler_locks', table => {
168593
+ table.string('lock_id', 255).primary();
168594
+ table.string('node_id', 255).notNullable();
168595
+ table.string('lock_token', 36).notNullable();
168596
+ table.bigInteger('acquired_at').notNullable();
168597
+ table.bigInteger('expires_at').notNullable();
168598
+ });
168599
+ }
168600
+ }
168601
+ getKnex() {
168602
+ if (!this.knex) {
168603
+ throw new Error('[KnexStore] Not initialized. Call initialize() first.');
168604
+ }
168605
+ return this.knex;
168606
+ }
168607
+ // --- CRUD ---
168608
+ async create(schedule) {
168609
+ const knex = this.getKnex();
168610
+ const newSchedule = {
168611
+ ...schedule,
168612
+ id: (0, uuid_1.v4)(),
168613
+ createdAt: Date.now(),
168614
+ runCount: 0,
168615
+ failureCount: 0,
168616
+ status: 'active',
168617
+ };
168618
+ await knex('schedules').insert(toInsertRow(newSchedule));
168619
+ logger_1.logger.info(`[KnexStore] Created schedule ${newSchedule.id} for user ${newSchedule.creatorId}`);
168620
+ return newSchedule;
168621
+ }
168622
+ async importSchedule(schedule) {
168623
+ const knex = this.getKnex();
168624
+ const existing = await knex('schedules').where('id', schedule.id).first();
168625
+ if (existing)
168626
+ return; // Already imported (idempotent)
168627
+ await knex('schedules').insert(toInsertRow(schedule));
168628
+ }
168629
+ async get(id) {
168630
+ const knex = this.getKnex();
168631
+ const row = await knex('schedules').where('id', id).first();
168632
+ return row ? fromDbRow(row) : undefined;
168633
+ }
168634
+ async update(id, patch) {
168635
+ const knex = this.getKnex();
168636
+ const existing = await knex('schedules').where('id', id).first();
168637
+ if (!existing)
168638
+ return undefined;
168639
+ const current = fromDbRow(existing);
168640
+ const updated = { ...current, ...patch, id: current.id };
168641
+ const row = toInsertRow(updated);
168642
+ // Remove id from update (PK cannot change)
168643
+ delete row.id;
168644
+ await knex('schedules').where('id', id).update(row);
168645
+ return updated;
168646
+ }
168647
+ async delete(id) {
168648
+ const knex = this.getKnex();
168649
+ const deleted = await knex('schedules').where('id', id).del();
168650
+ if (deleted > 0) {
168651
+ logger_1.logger.info(`[KnexStore] Deleted schedule ${id}`);
168652
+ return true;
168653
+ }
168654
+ return false;
168655
+ }
168656
+ // --- Queries ---
168657
+ async getByCreator(creatorId) {
168658
+ const knex = this.getKnex();
168659
+ const rows = await knex('schedules').where('creator_id', creatorId);
168660
+ return rows.map((r) => fromDbRow(r));
168661
+ }
168662
+ async getActiveSchedules() {
168663
+ const knex = this.getKnex();
168664
+ const rows = await knex('schedules').where('status', 'active');
168665
+ return rows.map((r) => fromDbRow(r));
168666
+ }
168667
+ async getDueSchedules(now) {
168668
+ const ts = now ?? Date.now();
168669
+ const knex = this.getKnex();
168670
+ // MSSQL uses 1/0 for booleans
168671
+ const bFalse = this.driver === 'mssql' ? 0 : false;
168672
+ const bTrue = this.driver === 'mssql' ? 1 : true;
168673
+ const rows = await knex('schedules')
168674
+ .where('status', 'active')
168675
+ .andWhere(function () {
168676
+ this.where(function () {
168677
+ this.where('is_recurring', bFalse)
168678
+ .whereNotNull('run_at')
168679
+ .where('run_at', '<=', ts);
168680
+ }).orWhere(function () {
168681
+ this.where('is_recurring', bTrue)
168682
+ .whereNotNull('next_run_at')
168683
+ .where('next_run_at', '<=', ts);
168684
+ });
168685
+ });
168686
+ return rows.map((r) => fromDbRow(r));
168687
+ }
168688
+ async findByWorkflow(creatorId, workflowName) {
168689
+ const knex = this.getKnex();
168690
+ const escaped = workflowName.toLowerCase().replace(/[%_\\]/g, '\\$&');
168691
+ const pattern = `%${escaped}%`;
168692
+ const rows = await knex('schedules')
168693
+ .where('creator_id', creatorId)
168694
+ .where('status', 'active')
168695
+ .whereRaw("LOWER(workflow) LIKE ? ESCAPE '\\'", [pattern]);
168696
+ return rows.map((r) => fromDbRow(r));
168697
+ }
168698
+ async getAll() {
168699
+ const knex = this.getKnex();
168700
+ const rows = await knex('schedules');
168701
+ return rows.map((r) => fromDbRow(r));
168702
+ }
168703
+ async getStats() {
168704
+ const knex = this.getKnex();
168705
+ // MSSQL uses 1/0 for booleans; PostgreSQL/MySQL accept both true/1
168706
+ const boolTrue = this.driver === 'mssql' ? '1' : 'true';
168707
+ const boolFalse = this.driver === 'mssql' ? '0' : 'false';
168708
+ const result = await knex('schedules')
168709
+ .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`))
168710
+ .first();
168711
+ return {
168712
+ total: Number(result.total) || 0,
168713
+ active: Number(result.active) || 0,
168714
+ paused: Number(result.paused) || 0,
168715
+ completed: Number(result.completed) || 0,
168716
+ failed: Number(result.failed) || 0,
168717
+ recurring: Number(result.recurring) || 0,
168718
+ oneTime: Number(result.one_time) || 0,
168719
+ };
168720
+ }
168721
+ async validateLimits(creatorId, isRecurring, limits) {
168722
+ const knex = this.getKnex();
168723
+ if (limits.maxGlobal) {
168724
+ const result = await knex('schedules').count('* as cnt').first();
168725
+ if (Number(result?.cnt) >= limits.maxGlobal) {
168726
+ throw new Error(`Global schedule limit reached (${limits.maxGlobal})`);
168727
+ }
168728
+ }
168729
+ if (limits.maxPerUser) {
168730
+ const result = await knex('schedules')
168731
+ .where('creator_id', creatorId)
168732
+ .count('* as cnt')
168733
+ .first();
168734
+ if (Number(result?.cnt) >= limits.maxPerUser) {
168735
+ throw new Error(`You have reached the maximum number of schedules (${limits.maxPerUser})`);
168736
+ }
168737
+ }
168738
+ if (isRecurring && limits.maxRecurringPerUser) {
168739
+ const bTrue = this.driver === 'mssql' ? 1 : true;
168740
+ const result = await knex('schedules')
168741
+ .where('creator_id', creatorId)
168742
+ .where('is_recurring', bTrue)
168743
+ .count('* as cnt')
168744
+ .first();
168745
+ if (Number(result?.cnt) >= limits.maxRecurringPerUser) {
168746
+ throw new Error(`You have reached the maximum number of recurring schedules (${limits.maxRecurringPerUser})`);
168747
+ }
168748
+ }
168749
+ }
168750
+ // --- HA Distributed Locking (via scheduler_locks table) ---
168751
+ async tryAcquireLock(lockId, nodeId, ttlSeconds) {
168752
+ const knex = this.getKnex();
168753
+ const now = Date.now();
168754
+ const expiresAt = now + ttlSeconds * 1000;
168755
+ const token = (0, uuid_1.v4)();
168756
+ // Step 1: Try to claim an existing expired lock
168757
+ const updated = await knex('scheduler_locks')
168758
+ .where('lock_id', lockId)
168759
+ .where('expires_at', '<', now)
168760
+ .update({
168761
+ node_id: nodeId,
168762
+ lock_token: token,
168763
+ acquired_at: now,
168764
+ expires_at: expiresAt,
168765
+ });
168766
+ if (updated > 0)
168767
+ return token;
168768
+ // Step 2: Try to INSERT a new lock row
168769
+ try {
168770
+ await knex('scheduler_locks').insert({
168771
+ lock_id: lockId,
168772
+ node_id: nodeId,
168773
+ lock_token: token,
168774
+ acquired_at: now,
168775
+ expires_at: expiresAt,
168776
+ });
168777
+ return token;
168778
+ }
168779
+ catch {
168780
+ // Unique constraint violation — another node holds the lock
168781
+ return null;
168782
+ }
168783
+ }
168784
+ async releaseLock(lockId, lockToken) {
168785
+ const knex = this.getKnex();
168786
+ await knex('scheduler_locks').where('lock_id', lockId).where('lock_token', lockToken).del();
168787
+ }
168788
+ async renewLock(lockId, lockToken, ttlSeconds) {
168789
+ const knex = this.getKnex();
168790
+ const now = Date.now();
168791
+ const expiresAt = now + ttlSeconds * 1000;
168792
+ const updated = await knex('scheduler_locks')
168793
+ .where('lock_id', lockId)
168794
+ .where('lock_token', lockToken)
168795
+ .update({ acquired_at: now, expires_at: expiresAt });
168796
+ return updated > 0;
168797
+ }
168798
+ async flush() {
168799
+ // No-op for server-based backends
168800
+ }
168801
+ // --- Message Trigger CRUD ---
168802
+ async createTrigger(trigger) {
168803
+ const knex = this.getKnex();
168804
+ const newTrigger = {
168805
+ ...trigger,
168806
+ id: (0, uuid_1.v4)(),
168807
+ createdAt: Date.now(),
168808
+ };
168809
+ await knex('message_triggers').insert(toTriggerInsertRow(newTrigger));
168810
+ logger_1.logger.info(`[KnexStore] Created trigger ${newTrigger.id} for user ${newTrigger.creatorId}`);
168811
+ return newTrigger;
168812
+ }
168813
+ async getTrigger(id) {
168814
+ const knex = this.getKnex();
168815
+ const row = await knex('message_triggers').where('id', id).first();
168816
+ return row ? fromTriggerRow(row) : undefined;
168817
+ }
168818
+ async updateTrigger(id, patch) {
168819
+ const knex = this.getKnex();
168820
+ const existing = await knex('message_triggers').where('id', id).first();
168821
+ if (!existing)
168822
+ return undefined;
168823
+ const current = fromTriggerRow(existing);
168824
+ const updated = {
168825
+ ...current,
168826
+ ...patch,
168827
+ id: current.id,
168828
+ createdAt: current.createdAt,
168829
+ };
168830
+ const row = toTriggerInsertRow(updated);
168831
+ delete row.id;
168832
+ await knex('message_triggers').where('id', id).update(row);
168833
+ return updated;
168834
+ }
168835
+ async deleteTrigger(id) {
168836
+ const knex = this.getKnex();
168837
+ const deleted = await knex('message_triggers').where('id', id).del();
168838
+ if (deleted > 0) {
168839
+ logger_1.logger.info(`[KnexStore] Deleted trigger ${id}`);
168840
+ return true;
168841
+ }
168842
+ return false;
168843
+ }
168844
+ async getTriggersByCreator(creatorId) {
168845
+ const knex = this.getKnex();
168846
+ const rows = await knex('message_triggers').where('creator_id', creatorId);
168847
+ return rows.map((r) => fromTriggerRow(r));
168848
+ }
168849
+ async getActiveTriggers() {
168850
+ const knex = this.getKnex();
168851
+ const rows = await knex('message_triggers')
168852
+ .where('status', 'active')
168853
+ .where('enabled', this.driver === 'mssql' ? 1 : true);
168854
+ return rows.map((r) => fromTriggerRow(r));
168855
+ }
168856
+ }
168857
+ exports.KnexStoreBackend = KnexStoreBackend;
168858
+
168859
+
167056
168860
  /***/ }),
167057
168861
 
167058
168862
  /***/ 83864:
@@ -178026,6 +179830,35 @@ class OutputFormatters {
178026
179830
  exports.OutputFormatters = OutputFormatters;
178027
179831
 
178028
179832
 
179833
+ /***/ }),
179834
+
179835
+ /***/ 93866:
179836
+ /***/ ((__unused_webpack_module, exports) => {
179837
+
179838
+ "use strict";
179839
+
179840
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
179841
+ exports.DefaultPolicyEngine = void 0;
179842
+ /**
179843
+ * Default (no-op) policy engine — always allows everything.
179844
+ * Used when no enterprise license is present or policy is disabled.
179845
+ */
179846
+ class DefaultPolicyEngine {
179847
+ async initialize(_config) { }
179848
+ async evaluateCheckExecution(_checkId, _checkConfig) {
179849
+ return { allowed: true };
179850
+ }
179851
+ async evaluateToolInvocation(_serverName, _methodName, _transport) {
179852
+ return { allowed: true };
179853
+ }
179854
+ async evaluateCapabilities(_checkId, _capabilities) {
179855
+ return { allowed: true };
179856
+ }
179857
+ async shutdown() { }
179858
+ }
179859
+ exports.DefaultPolicyEngine = DefaultPolicyEngine;
179860
+
179861
+
178029
179862
  /***/ }),
178030
179863
 
178031
179864
  /***/ 96611:
@@ -199642,7 +201475,7 @@ class StateMachineExecutionEngine {
199642
201475
  try {
199643
201476
  logger_1.logger.debug(`[PolicyEngine] Loading enterprise policy engine (engine=${configWithTagFilter.policy.engine})`);
199644
201477
  // @ts-ignore — enterprise/ may not exist in OSS builds (caught at runtime)
199645
- const { loadEnterprisePolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(7065)));
201478
+ const { loadEnterprisePolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(87068)));
199646
201479
  context.policyEngine = await loadEnterprisePolicyEngine(configWithTagFilter.policy);
199647
201480
  logger_1.logger.debug(`[PolicyEngine] Initialized: ${context.policyEngine?.constructor?.name || 'unknown'}`);
199648
201481
  }
@@ -209913,7 +211746,7 @@ async function initTelemetry(opts = {}) {
209913
211746
  const path = __nccwpck_require__(16928);
209914
211747
  const outDir = opts.file?.dir ||
209915
211748
  process.env.VISOR_TRACE_DIR ||
209916
- __nccwpck_require__.ab + "traces";
211749
+ path.join(process.cwd(), 'output', 'traces');
209917
211750
  fs.mkdirSync(outDir, { recursive: true });
209918
211751
  const ts = new Date().toISOString().replace(/[:.]/g, '-');
209919
211752
  process.env.VISOR_FALLBACK_TRACE_FILE = path.join(outDir, `run-${ts}.ndjson`);
@@ -210118,7 +211951,7 @@ async function shutdownTelemetry() {
210118
211951
  if (process.env.VISOR_TRACE_REPORT === 'true') {
210119
211952
  const fs = __nccwpck_require__(79896);
210120
211953
  const path = __nccwpck_require__(16928);
210121
- const outDir = process.env.VISOR_TRACE_DIR || __nccwpck_require__.ab + "traces";
211954
+ const outDir = process.env.VISOR_TRACE_DIR || path.join(process.cwd(), 'output', 'traces');
210122
211955
  if (!fs.existsSync(outDir))
210123
211956
  fs.mkdirSync(outDir, { recursive: true });
210124
211957
  const ts = new Date().toISOString().replace(/[:.]/g, '-');
@@ -210617,7 +212450,7 @@ function __getOrCreateNdjsonPath() {
210617
212450
  fs.mkdirSync(dir, { recursive: true });
210618
212451
  return __ndjsonPath;
210619
212452
  }
210620
- const outDir = process.env.VISOR_TRACE_DIR || __nccwpck_require__.ab + "traces";
212453
+ const outDir = process.env.VISOR_TRACE_DIR || path.join(process.cwd(), 'output', 'traces');
210621
212454
  if (!fs.existsSync(outDir))
210622
212455
  fs.mkdirSync(outDir, { recursive: true });
210623
212456
  if (!__ndjsonPath) {
@@ -224571,22 +226404,6 @@ class WorkflowRegistry {
224571
226404
  exports.WorkflowRegistry = WorkflowRegistry;
224572
226405
 
224573
226406
 
224574
- /***/ }),
224575
-
224576
- /***/ 7065:
224577
- /***/ ((module) => {
224578
-
224579
- module.exports = eval("require")("./enterprise/loader");
224580
-
224581
-
224582
- /***/ }),
224583
-
224584
- /***/ 71370:
224585
- /***/ ((module) => {
224586
-
224587
- module.exports = eval("require")("./enterprise/policy/policy-input-builder");
224588
-
224589
-
224590
226407
  /***/ }),
224591
226408
 
224592
226409
  /***/ 18327:
@@ -354328,7 +356145,13 @@ var init_ProbeAgent = __esm({
354328
356145
  if (this.mcpBridge && !options._disableTools) {
354329
356146
  const mcpTools = this.mcpBridge.getVercelTools(this._filterMcpTools(this.mcpBridge.getToolNames()));
354330
356147
  for (const [name14, mcpTool] of Object.entries(mcpTools)) {
354331
- nativeTools[name14] = mcpTool;
356148
+ const mcpSchema = mcpTool.inputSchema || mcpTool.parameters;
356149
+ const wrappedSchema = mcpSchema && mcpSchema._def ? mcpSchema : (0, import_ai4.jsonSchema)(mcpSchema || { type: "object", properties: {} });
356150
+ nativeTools[name14] = (0, import_ai4.tool)({
356151
+ description: mcpTool.description || `MCP tool: ${name14}`,
356152
+ inputSchema: wrappedSchema,
356153
+ execute: mcpTool.execute
356154
+ });
354332
356155
  }
354333
356156
  }
354334
356157
  if (this.apiType === "google" && this._geminiToolsEnabled && !options._disableTools) {
@@ -395117,7 +396940,7 @@ module.exports = /*#__PURE__*/JSON.parse('{"100":"Continue","101":"Switching Pro
395117
396940
  /***/ ((module) => {
395118
396941
 
395119
396942
  "use strict";
395120
- module.exports = /*#__PURE__*/JSON.parse('{"name":"@probelabs/visor","version":"0.1.151","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","@modelcontextprotocol/sdk":"^1.25.3","@nyariv/sandboxjs":"github:probelabs/SandboxJS#f1c13b8eee98734a8ea024061eada4aa9a9ff2e9","@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/core":"^1.30.1","@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-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-rc268","@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","cli-table3":"^0.6.5","commander":"^14.0.0","deepmerge":"^4.3.1","dotenv":"^17.2.3","ignore":"^7.0.5","js-yaml":"^4.1.0","jsonpath-plus":"^10.4.0","liquidjs":"^10.21.1","minimatch":"^10.2.2","node-cron":"^3.0.3","open":"^9.1.0","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/node":"^24.3.0","@types/node-cron":"^3.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"]}}');
396943
+ 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","@modelcontextprotocol/sdk":"^1.25.3","@nyariv/sandboxjs":"github:probelabs/SandboxJS#f1c13b8eee98734a8ea024061eada4aa9a9ff2e9","@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/core":"^1.30.1","@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-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-rc269","@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","cli-table3":"^0.6.5","commander":"^14.0.0","deepmerge":"^4.3.1","dotenv":"^17.2.3","ignore":"^7.0.5","js-yaml":"^4.1.0","jsonpath-plus":"^10.4.0","liquidjs":"^10.21.1","minimatch":"^10.2.2","node-cron":"^3.0.3","open":"^9.1.0","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/node":"^24.3.0","@types/node-cron":"^3.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"]}}');
395121
396944
 
395122
396945
  /***/ })
395123
396946