@probelabs/visor 0.1.166 → 0.1.167-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/config.d.ts.map +1 -1
  2. package/dist/frontends/github-frontend.d.ts.map +1 -1
  3. package/dist/index.js +2182 -50
  4. package/dist/sdk/{check-provider-registry-V6C4LUYJ.mjs → check-provider-registry-6WR2SG66.mjs} +3 -3
  5. package/dist/sdk/{check-provider-registry-TGPICTHD.mjs → check-provider-registry-CWLPAM5U.mjs} +3 -3
  6. package/dist/sdk/{chunk-WSYVK6ML.mjs → chunk-2G2PJKHM.mjs} +297 -31
  7. package/dist/sdk/chunk-2G2PJKHM.mjs.map +1 -0
  8. package/dist/sdk/{chunk-KKGMGB4X.mjs → chunk-3LXYZ2OQ.mjs} +298 -32
  9. package/dist/sdk/chunk-3LXYZ2OQ.mjs.map +1 -0
  10. package/dist/sdk/{chunk-DEAPFYNX.mjs → chunk-KYBKVKBS.mjs} +7 -1
  11. package/dist/sdk/{chunk-DEAPFYNX.mjs.map → chunk-KYBKVKBS.mjs.map} +1 -1
  12. package/dist/sdk/{config-D6WF2U4B.mjs → config-DP5QU3XC.mjs} +2 -2
  13. package/dist/sdk/{github-frontend-P274ISBJ.mjs → github-frontend-VM52NX7N.mjs} +19 -1
  14. package/dist/sdk/{github-frontend-BPRRUIGB.mjs.map → github-frontend-VM52NX7N.mjs.map} +1 -1
  15. package/dist/sdk/{host-753E6PKF.mjs → host-7MGCKSHM.mjs} +2 -2
  16. package/dist/sdk/{host-AIMRV5YL.mjs → host-BTHRY6NS.mjs} +2 -2
  17. package/dist/sdk/knex-store-CRORFJE6.mjs +527 -0
  18. package/dist/sdk/knex-store-CRORFJE6.mjs.map +1 -0
  19. package/dist/sdk/loader-NJCF7DUS.mjs +89 -0
  20. package/dist/sdk/loader-NJCF7DUS.mjs.map +1 -0
  21. package/dist/sdk/opa-policy-engine-S2S2ULEI.mjs +655 -0
  22. package/dist/sdk/opa-policy-engine-S2S2ULEI.mjs.map +1 -0
  23. package/dist/sdk/{schedule-tool-OCZGLKMJ.mjs → schedule-tool-KKQ4W7KU.mjs} +3 -3
  24. package/dist/sdk/{schedule-tool-MQHISNJ6.mjs → schedule-tool-MPHHE2IM.mjs} +3 -3
  25. package/dist/sdk/{schedule-tool-handler-BGOL2TOP.mjs → schedule-tool-handler-6NUB2IHV.mjs} +3 -3
  26. package/dist/sdk/{schedule-tool-handler-TZYXM664.mjs → schedule-tool-handler-V7A4AQGS.mjs} +3 -3
  27. package/dist/sdk/sdk.js +1940 -276
  28. package/dist/sdk/sdk.js.map +1 -1
  29. package/dist/sdk/sdk.mjs +5 -5
  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-3M5LXLLX.mjs → workflow-check-provider-N4ZTFOH6.mjs} +3 -3
  33. package/dist/sdk/{workflow-check-provider-QKHL6AFT.mjs → workflow-check-provider-PI7VJT25.mjs} +3 -3
  34. package/dist/state-machine/context/build-engine-context.d.ts.map +1 -1
  35. package/dist/utils/fair-concurrency-limiter.d.ts +56 -0
  36. package/dist/utils/fair-concurrency-limiter.d.ts.map +1 -0
  37. package/dist/utils/interactive-prompt.d.ts.map +1 -1
  38. package/package.json +1 -1
  39. package/dist/output/traces/run-2026-03-06T13-08-34-152Z.ndjson +0 -138
  40. package/dist/output/traces/run-2026-03-06T13-09-10-593Z.ndjson +0 -2235
  41. package/dist/sdk/check-provider-registry-WXEBJWXY.mjs +0 -29
  42. package/dist/sdk/chunk-HFCOZPAS.mjs +0 -443
  43. package/dist/sdk/chunk-HFCOZPAS.mjs.map +0 -1
  44. package/dist/sdk/chunk-KBTFMYZQ.mjs +0 -739
  45. package/dist/sdk/chunk-KBTFMYZQ.mjs.map +0 -1
  46. package/dist/sdk/chunk-KKGMGB4X.mjs.map +0 -1
  47. package/dist/sdk/chunk-OQ3CML4F.mjs +0 -1502
  48. package/dist/sdk/chunk-OQ3CML4F.mjs.map +0 -1
  49. package/dist/sdk/chunk-WSYVK6ML.mjs.map +0 -1
  50. package/dist/sdk/chunk-ZQR4AGS3.mjs +0 -44057
  51. package/dist/sdk/chunk-ZQR4AGS3.mjs.map +0 -1
  52. package/dist/sdk/failure-condition-evaluator-5EAESM44.mjs +0 -17
  53. package/dist/sdk/github-frontend-BPRRUIGB.mjs +0 -1368
  54. package/dist/sdk/github-frontend-P274ISBJ.mjs.map +0 -1
  55. package/dist/sdk/routing-QHWSMAIH.mjs +0 -25
  56. package/dist/sdk/schedule-tool-ZVOSSFN2.mjs +0 -35
  57. package/dist/sdk/schedule-tool-handler-4NCS4ARE.mjs +0 -39
  58. package/dist/sdk/schedule-tool-handler-4NCS4ARE.mjs.map +0 -1
  59. package/dist/sdk/schedule-tool-handler-BGOL2TOP.mjs.map +0 -1
  60. package/dist/sdk/schedule-tool-handler-TZYXM664.mjs.map +0 -1
  61. package/dist/sdk/trace-helpers-CTHTK6V5.mjs +0 -25
  62. package/dist/sdk/trace-helpers-CTHTK6V5.mjs.map +0 -1
  63. package/dist/sdk/workflow-check-provider-3M5LXLLX.mjs.map +0 -1
  64. package/dist/sdk/workflow-check-provider-QKHL6AFT.mjs.map +0 -1
  65. package/dist/sdk/workflow-check-provider-UTNO6XN6.mjs +0 -29
  66. package/dist/sdk/workflow-check-provider-UTNO6XN6.mjs.map +0 -1
  67. package/dist/traces/run-2026-03-06T13-08-34-152Z.ndjson +0 -138
  68. package/dist/traces/run-2026-03-06T13-09-10-593Z.ndjson +0 -2235
  69. /package/dist/sdk/{check-provider-registry-TGPICTHD.mjs.map → check-provider-registry-6WR2SG66.mjs.map} +0 -0
  70. /package/dist/sdk/{check-provider-registry-V6C4LUYJ.mjs.map → check-provider-registry-CWLPAM5U.mjs.map} +0 -0
  71. /package/dist/sdk/{check-provider-registry-WXEBJWXY.mjs.map → config-DP5QU3XC.mjs.map} +0 -0
  72. /package/dist/sdk/{host-753E6PKF.mjs.map → host-7MGCKSHM.mjs.map} +0 -0
  73. /package/dist/sdk/{host-AIMRV5YL.mjs.map → host-BTHRY6NS.mjs.map} +0 -0
  74. /package/dist/sdk/{config-D6WF2U4B.mjs.map → schedule-tool-KKQ4W7KU.mjs.map} +0 -0
  75. /package/dist/sdk/{failure-condition-evaluator-5EAESM44.mjs.map → schedule-tool-MPHHE2IM.mjs.map} +0 -0
  76. /package/dist/sdk/{routing-QHWSMAIH.mjs.map → schedule-tool-handler-6NUB2IHV.mjs.map} +0 -0
  77. /package/dist/sdk/{schedule-tool-MQHISNJ6.mjs.map → schedule-tool-handler-V7A4AQGS.mjs.map} +0 -0
  78. /package/dist/sdk/{schedule-tool-OCZGLKMJ.mjs.map → workflow-check-provider-N4ZTFOH6.mjs.map} +0 -0
  79. /package/dist/sdk/{schedule-tool-ZVOSSFN2.mjs.map → workflow-check-provider-PI7VJT25.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.166';
2
+ process.env.VISOR_VERSION = '0.1.167';
3
3
  process.env.PROBE_VERSION = '0.6.0-rc280';
4
- process.env.VISOR_COMMIT_SHA = 'eff5ed2df07d89e22e1c88d7d96b97572b0fd908';
5
- process.env.VISOR_COMMIT_SHORT = 'eff5ed2df';
4
+ process.env.VISOR_COMMIT_SHA = '1e0341f43c4243f35be19f2043e34b954fdecde1';
5
+ process.env.VISOR_COMMIT_SHORT = '1e0341f';
6
6
  /******/ (() => { // webpackBootstrap
7
7
  /******/ var __webpack_modules__ = ({
8
8
 
@@ -161217,7 +161217,7 @@ async function handleDumpPolicyInput(checkId, argv) {
161217
161217
  let PolicyInputBuilder;
161218
161218
  try {
161219
161219
  // @ts-ignore — enterprise/ may not exist in OSS builds (caught at runtime)
161220
- const mod = await Promise.resolve().then(() => __importStar(__nccwpck_require__(71370)));
161220
+ const mod = await Promise.resolve().then(() => __importStar(__nccwpck_require__(17117)));
161221
161221
  PolicyInputBuilder = mod.PolicyInputBuilder;
161222
161222
  }
161223
161223
  catch {
@@ -164097,6 +164097,12 @@ class ConfigManager {
164097
164097
  if (workflowData.on) {
164098
164098
  visorConfig.on = workflowData.on;
164099
164099
  }
164100
+ if (workflowData.sandboxes) {
164101
+ visorConfig.sandboxes = workflowData.sandboxes;
164102
+ }
164103
+ if (workflowData.sandbox) {
164104
+ visorConfig.sandbox = workflowData.sandbox;
164105
+ }
164100
164106
  logger_1.logger.debug(`Standalone workflow config has ${Object.keys(workflowSteps).length} workflow steps as checks`);
164101
164107
  logger_1.logger.debug(`Workflow step names: ${Object.keys(workflowSteps).join(', ')}`);
164102
164108
  logger_1.logger.debug(`Config keys after conversion: ${Object.keys(visorConfig).join(', ')}`);
@@ -167104,6 +167110,1810 @@ class DependencyResolver {
167104
167110
  exports.DependencyResolver = DependencyResolver;
167105
167111
 
167106
167112
 
167113
+ /***/ }),
167114
+
167115
+ /***/ 50069:
167116
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
167117
+
167118
+ "use strict";
167119
+
167120
+ /**
167121
+ * Copyright (c) ProbeLabs. All rights reserved.
167122
+ * Licensed under the Elastic License 2.0; you may not use this file except
167123
+ * in compliance with the Elastic License 2.0.
167124
+ */
167125
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
167126
+ if (k2 === undefined) k2 = k;
167127
+ var desc = Object.getOwnPropertyDescriptor(m, k);
167128
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
167129
+ desc = { enumerable: true, get: function() { return m[k]; } };
167130
+ }
167131
+ Object.defineProperty(o, k2, desc);
167132
+ }) : (function(o, m, k, k2) {
167133
+ if (k2 === undefined) k2 = k;
167134
+ o[k2] = m[k];
167135
+ }));
167136
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
167137
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
167138
+ }) : function(o, v) {
167139
+ o["default"] = v;
167140
+ });
167141
+ var __importStar = (this && this.__importStar) || (function () {
167142
+ var ownKeys = function(o) {
167143
+ ownKeys = Object.getOwnPropertyNames || function (o) {
167144
+ var ar = [];
167145
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
167146
+ return ar;
167147
+ };
167148
+ return ownKeys(o);
167149
+ };
167150
+ return function (mod) {
167151
+ if (mod && mod.__esModule) return mod;
167152
+ var result = {};
167153
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
167154
+ __setModuleDefault(result, mod);
167155
+ return result;
167156
+ };
167157
+ })();
167158
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
167159
+ exports.LicenseValidator = void 0;
167160
+ const crypto = __importStar(__nccwpck_require__(76982));
167161
+ const fs = __importStar(__nccwpck_require__(79896));
167162
+ const path = __importStar(__nccwpck_require__(16928));
167163
+ class LicenseValidator {
167164
+ /** Ed25519 public key for license verification (PEM format). */
167165
+ static PUBLIC_KEY = '-----BEGIN PUBLIC KEY-----\n' +
167166
+ 'MCowBQYDK2VwAyEAI/Zd08EFmgIdrDm/HXd0l3/5GBt7R1PrdvhdmEXhJlU=\n' +
167167
+ '-----END PUBLIC KEY-----\n';
167168
+ cache = null;
167169
+ static CACHE_TTL = 5 * 60 * 1000; // 5 minutes
167170
+ static GRACE_PERIOD = 72 * 3600 * 1000; // 72 hours after expiry
167171
+ /**
167172
+ * Load and validate license from environment or file.
167173
+ *
167174
+ * Resolution order:
167175
+ * 1. VISOR_LICENSE env var (JWT string)
167176
+ * 2. VISOR_LICENSE_FILE env var (path to file)
167177
+ * 3. .visor-license in project root (cwd)
167178
+ * 4. .visor-license in ~/.config/visor/
167179
+ */
167180
+ async loadAndValidate() {
167181
+ // Return cached result if still fresh
167182
+ if (this.cache && Date.now() - this.cache.validatedAt < LicenseValidator.CACHE_TTL) {
167183
+ return this.cache.payload;
167184
+ }
167185
+ const token = this.resolveToken();
167186
+ if (!token)
167187
+ return null;
167188
+ const payload = this.verifyAndDecode(token);
167189
+ if (!payload)
167190
+ return null;
167191
+ this.cache = { payload, validatedAt: Date.now() };
167192
+ return payload;
167193
+ }
167194
+ /** Check if a specific feature is licensed */
167195
+ hasFeature(feature) {
167196
+ if (!this.cache)
167197
+ return false;
167198
+ return this.cache.payload.features.includes(feature);
167199
+ }
167200
+ /** Check if license is valid (with grace period) */
167201
+ isValid() {
167202
+ if (!this.cache)
167203
+ return false;
167204
+ const now = Date.now();
167205
+ const expiryMs = this.cache.payload.exp * 1000;
167206
+ return now < expiryMs + LicenseValidator.GRACE_PERIOD;
167207
+ }
167208
+ /** Check if the license is within its grace period (expired but still valid) */
167209
+ isInGracePeriod() {
167210
+ if (!this.cache)
167211
+ return false;
167212
+ const now = Date.now();
167213
+ const expiryMs = this.cache.payload.exp * 1000;
167214
+ return now >= expiryMs && now < expiryMs + LicenseValidator.GRACE_PERIOD;
167215
+ }
167216
+ resolveToken() {
167217
+ // 1. Direct env var
167218
+ if (process.env.VISOR_LICENSE) {
167219
+ return process.env.VISOR_LICENSE.trim();
167220
+ }
167221
+ // 2. File path from env (validate against path traversal)
167222
+ if (process.env.VISOR_LICENSE_FILE) {
167223
+ // path.resolve() produces an absolute path with all '..' segments resolved,
167224
+ // so a separate resolved.includes('..') check is unnecessary.
167225
+ const resolved = path.resolve(process.env.VISOR_LICENSE_FILE);
167226
+ const home = process.env.HOME || process.env.USERPROFILE || '';
167227
+ const allowedPrefixes = [path.normalize(process.cwd())];
167228
+ if (home)
167229
+ allowedPrefixes.push(path.normalize(path.join(home, '.config', 'visor')));
167230
+ // Resolve symlinks so an attacker cannot create a symlink inside an
167231
+ // allowed prefix that points to an arbitrary file outside it.
167232
+ let realPath;
167233
+ try {
167234
+ realPath = fs.realpathSync(resolved);
167235
+ }
167236
+ catch {
167237
+ return null; // File doesn't exist or isn't accessible
167238
+ }
167239
+ const isSafe = allowedPrefixes.some(prefix => realPath === prefix || realPath.startsWith(prefix + path.sep));
167240
+ if (!isSafe)
167241
+ return null;
167242
+ return this.readFile(realPath);
167243
+ }
167244
+ // 3. .visor-license in cwd
167245
+ const cwdPath = path.join(process.cwd(), '.visor-license');
167246
+ const cwdToken = this.readFile(cwdPath);
167247
+ if (cwdToken)
167248
+ return cwdToken;
167249
+ // 4. ~/.config/visor/.visor-license
167250
+ const home = process.env.HOME || process.env.USERPROFILE || '';
167251
+ if (home) {
167252
+ const configPath = path.join(home, '.config', 'visor', '.visor-license');
167253
+ const configToken = this.readFile(configPath);
167254
+ if (configToken)
167255
+ return configToken;
167256
+ }
167257
+ return null;
167258
+ }
167259
+ readFile(filePath) {
167260
+ try {
167261
+ return fs.readFileSync(filePath, 'utf-8').trim();
167262
+ }
167263
+ catch {
167264
+ return null;
167265
+ }
167266
+ }
167267
+ verifyAndDecode(token) {
167268
+ try {
167269
+ const parts = token.split('.');
167270
+ if (parts.length !== 3)
167271
+ return null;
167272
+ const [headerB64, payloadB64, signatureB64] = parts;
167273
+ // Decode header to verify algorithm
167274
+ const header = JSON.parse(Buffer.from(headerB64, 'base64url').toString());
167275
+ if (header.alg !== 'EdDSA')
167276
+ return null;
167277
+ // Verify signature
167278
+ const data = `${headerB64}.${payloadB64}`;
167279
+ const signature = Buffer.from(signatureB64, 'base64url');
167280
+ const publicKey = crypto.createPublicKey(LicenseValidator.PUBLIC_KEY);
167281
+ // Validate that the loaded public key is actually Ed25519 (OID 1.3.101.112).
167282
+ // This prevents algorithm-confusion attacks if the embedded key were ever
167283
+ // swapped to a different type.
167284
+ if (publicKey.asymmetricKeyType !== 'ed25519') {
167285
+ return null;
167286
+ }
167287
+ // Ed25519 verification: algorithm must be null because EdDSA performs its
167288
+ // own internal hashing (SHA-512) — passing a digest algorithm here would
167289
+ // cause Node.js to throw. The key type is validated above.
167290
+ const isValid = crypto.verify(null, Buffer.from(data), publicKey, signature);
167291
+ if (!isValid)
167292
+ return null;
167293
+ // Decode payload
167294
+ const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString());
167295
+ // Validate required fields
167296
+ if (!payload.org ||
167297
+ !Array.isArray(payload.features) ||
167298
+ typeof payload.exp !== 'number' ||
167299
+ typeof payload.iat !== 'number' ||
167300
+ !payload.sub) {
167301
+ return null;
167302
+ }
167303
+ // Check expiry (with grace period)
167304
+ const now = Date.now();
167305
+ const expiryMs = payload.exp * 1000;
167306
+ if (now >= expiryMs + LicenseValidator.GRACE_PERIOD) {
167307
+ return null;
167308
+ }
167309
+ return payload;
167310
+ }
167311
+ catch {
167312
+ return null;
167313
+ }
167314
+ }
167315
+ }
167316
+ exports.LicenseValidator = LicenseValidator;
167317
+
167318
+
167319
+ /***/ }),
167320
+
167321
+ /***/ 87068:
167322
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
167323
+
167324
+ "use strict";
167325
+
167326
+ /**
167327
+ * Copyright (c) ProbeLabs. All rights reserved.
167328
+ * Licensed under the Elastic License 2.0; you may not use this file except
167329
+ * in compliance with the Elastic License 2.0.
167330
+ */
167331
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
167332
+ if (k2 === undefined) k2 = k;
167333
+ var desc = Object.getOwnPropertyDescriptor(m, k);
167334
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
167335
+ desc = { enumerable: true, get: function() { return m[k]; } };
167336
+ }
167337
+ Object.defineProperty(o, k2, desc);
167338
+ }) : (function(o, m, k, k2) {
167339
+ if (k2 === undefined) k2 = k;
167340
+ o[k2] = m[k];
167341
+ }));
167342
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
167343
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
167344
+ }) : function(o, v) {
167345
+ o["default"] = v;
167346
+ });
167347
+ var __importStar = (this && this.__importStar) || (function () {
167348
+ var ownKeys = function(o) {
167349
+ ownKeys = Object.getOwnPropertyNames || function (o) {
167350
+ var ar = [];
167351
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
167352
+ return ar;
167353
+ };
167354
+ return ownKeys(o);
167355
+ };
167356
+ return function (mod) {
167357
+ if (mod && mod.__esModule) return mod;
167358
+ var result = {};
167359
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
167360
+ __setModuleDefault(result, mod);
167361
+ return result;
167362
+ };
167363
+ })();
167364
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
167365
+ exports.loadEnterprisePolicyEngine = loadEnterprisePolicyEngine;
167366
+ exports.loadEnterpriseStoreBackend = loadEnterpriseStoreBackend;
167367
+ const default_engine_1 = __nccwpck_require__(93866);
167368
+ /**
167369
+ * Load the enterprise policy engine if licensed, otherwise return the default no-op engine.
167370
+ *
167371
+ * This is the sole import boundary between OSS and enterprise code. Core code
167372
+ * must only import from this module (via dynamic `await import()`), never from
167373
+ * individual enterprise submodules.
167374
+ */
167375
+ async function loadEnterprisePolicyEngine(config) {
167376
+ try {
167377
+ const { LicenseValidator } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(50069)));
167378
+ const validator = new LicenseValidator();
167379
+ const license = await validator.loadAndValidate();
167380
+ if (!license || !validator.hasFeature('policy')) {
167381
+ return new default_engine_1.DefaultPolicyEngine();
167382
+ }
167383
+ if (validator.isInGracePeriod()) {
167384
+ // eslint-disable-next-line no-console
167385
+ console.warn('[visor:enterprise] License has expired but is within the 72-hour grace period. ' +
167386
+ 'Please renew your license.');
167387
+ }
167388
+ const { OpaPolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(39530)));
167389
+ const engine = new OpaPolicyEngine(config);
167390
+ await engine.initialize(config);
167391
+ return engine;
167392
+ }
167393
+ catch (err) {
167394
+ // Enterprise code not available or initialization failed
167395
+ const msg = err instanceof Error ? err.message : String(err);
167396
+ try {
167397
+ const { logger } = __nccwpck_require__(86999);
167398
+ logger.warn(`[PolicyEngine] Enterprise policy init failed, falling back to default: ${msg}`);
167399
+ }
167400
+ catch {
167401
+ // silent
167402
+ }
167403
+ return new default_engine_1.DefaultPolicyEngine();
167404
+ }
167405
+ }
167406
+ /**
167407
+ * Load the enterprise schedule store backend if licensed.
167408
+ *
167409
+ * @param driver Database driver ('postgresql', 'mysql', or 'mssql')
167410
+ * @param storageConfig Storage configuration with connection details
167411
+ * @param haConfig Optional HA configuration
167412
+ * @throws Error if enterprise license is not available or missing 'scheduler-sql' feature
167413
+ */
167414
+ async function loadEnterpriseStoreBackend(driver, storageConfig, haConfig) {
167415
+ const { LicenseValidator } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(50069)));
167416
+ const validator = new LicenseValidator();
167417
+ const license = await validator.loadAndValidate();
167418
+ if (!license || !validator.hasFeature('scheduler-sql')) {
167419
+ throw new Error(`The ${driver} schedule storage driver requires a Visor Enterprise license ` +
167420
+ `with the 'scheduler-sql' feature. Please upgrade or use driver: 'sqlite' (default).`);
167421
+ }
167422
+ if (validator.isInGracePeriod()) {
167423
+ // eslint-disable-next-line no-console
167424
+ console.warn('[visor:enterprise] License has expired but is within the 72-hour grace period. ' +
167425
+ 'Please renew your license.');
167426
+ }
167427
+ const { KnexStoreBackend } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(63737)));
167428
+ return new KnexStoreBackend(driver, storageConfig, haConfig);
167429
+ }
167430
+
167431
+
167432
+ /***/ }),
167433
+
167434
+ /***/ 628:
167435
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
167436
+
167437
+ "use strict";
167438
+
167439
+ /**
167440
+ * Copyright (c) ProbeLabs. All rights reserved.
167441
+ * Licensed under the Elastic License 2.0; you may not use this file except
167442
+ * in compliance with the Elastic License 2.0.
167443
+ */
167444
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
167445
+ if (k2 === undefined) k2 = k;
167446
+ var desc = Object.getOwnPropertyDescriptor(m, k);
167447
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
167448
+ desc = { enumerable: true, get: function() { return m[k]; } };
167449
+ }
167450
+ Object.defineProperty(o, k2, desc);
167451
+ }) : (function(o, m, k, k2) {
167452
+ if (k2 === undefined) k2 = k;
167453
+ o[k2] = m[k];
167454
+ }));
167455
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
167456
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
167457
+ }) : function(o, v) {
167458
+ o["default"] = v;
167459
+ });
167460
+ var __importStar = (this && this.__importStar) || (function () {
167461
+ var ownKeys = function(o) {
167462
+ ownKeys = Object.getOwnPropertyNames || function (o) {
167463
+ var ar = [];
167464
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
167465
+ return ar;
167466
+ };
167467
+ return ownKeys(o);
167468
+ };
167469
+ return function (mod) {
167470
+ if (mod && mod.__esModule) return mod;
167471
+ var result = {};
167472
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
167473
+ __setModuleDefault(result, mod);
167474
+ return result;
167475
+ };
167476
+ })();
167477
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
167478
+ exports.OpaCompiler = void 0;
167479
+ const fs = __importStar(__nccwpck_require__(79896));
167480
+ const path = __importStar(__nccwpck_require__(16928));
167481
+ const os = __importStar(__nccwpck_require__(70857));
167482
+ const crypto = __importStar(__nccwpck_require__(76982));
167483
+ const child_process_1 = __nccwpck_require__(35317);
167484
+ /**
167485
+ * OPA Rego Compiler - compiles .rego policy files to WASM bundles using the `opa` CLI.
167486
+ *
167487
+ * Handles:
167488
+ * - Resolving input paths to WASM bytes (direct .wasm, directory with policy.wasm, or .rego files)
167489
+ * - Compiling .rego files to WASM via `opa build`
167490
+ * - Caching compiled bundles based on content hashes
167491
+ * - Extracting policy.wasm from OPA tar.gz bundles
167492
+ *
167493
+ * Requires:
167494
+ * - `opa` CLI on PATH (only when auto-compiling .rego files)
167495
+ */
167496
+ class OpaCompiler {
167497
+ static CACHE_DIR = path.join(os.tmpdir(), 'visor-opa-cache');
167498
+ /**
167499
+ * Resolve the input paths to WASM bytes.
167500
+ *
167501
+ * Strategy:
167502
+ * 1. If any path is a .wasm file, read it directly
167503
+ * 2. If a directory contains policy.wasm, read it
167504
+ * 3. Otherwise, collect all .rego files and auto-compile via `opa build`
167505
+ */
167506
+ async resolveWasmBytes(paths) {
167507
+ // Collect .rego files and check for existing .wasm
167508
+ const regoFiles = [];
167509
+ for (const p of paths) {
167510
+ const resolved = path.resolve(p);
167511
+ // Reject paths containing '..' after resolution (path traversal)
167512
+ if (path.normalize(resolved).includes('..')) {
167513
+ throw new Error(`Policy path contains traversal sequences: ${p}`);
167514
+ }
167515
+ // Direct .wasm file
167516
+ if (resolved.endsWith('.wasm') && fs.existsSync(resolved)) {
167517
+ return fs.readFileSync(resolved);
167518
+ }
167519
+ if (!fs.existsSync(resolved))
167520
+ continue;
167521
+ const stat = fs.statSync(resolved);
167522
+ if (stat.isDirectory()) {
167523
+ // Check for pre-compiled policy.wasm in directory
167524
+ const wasmCandidate = path.join(resolved, 'policy.wasm');
167525
+ if (fs.existsSync(wasmCandidate)) {
167526
+ return fs.readFileSync(wasmCandidate);
167527
+ }
167528
+ // Collect all .rego files from directory
167529
+ const files = fs.readdirSync(resolved);
167530
+ for (const f of files) {
167531
+ if (f.endsWith('.rego')) {
167532
+ regoFiles.push(path.join(resolved, f));
167533
+ }
167534
+ }
167535
+ }
167536
+ else if (resolved.endsWith('.rego')) {
167537
+ regoFiles.push(resolved);
167538
+ }
167539
+ }
167540
+ if (regoFiles.length === 0) {
167541
+ throw new Error(`OPA WASM evaluator: no .wasm bundle or .rego files found in: ${paths.join(', ')}`);
167542
+ }
167543
+ // Auto-compile .rego -> .wasm
167544
+ return this.compileRego(regoFiles);
167545
+ }
167546
+ /**
167547
+ * Auto-compile .rego files to a WASM bundle using the `opa` CLI.
167548
+ *
167549
+ * Caches the compiled bundle based on a content hash of all input .rego files
167550
+ * so subsequent runs skip compilation if policies haven't changed.
167551
+ */
167552
+ compileRego(regoFiles) {
167553
+ // Check that `opa` CLI is available
167554
+ try {
167555
+ (0, child_process_1.execFileSync)('opa', ['version'], { stdio: 'pipe' });
167556
+ }
167557
+ catch {
167558
+ throw new Error('OPA CLI (`opa`) not found on PATH. Install it from https://www.openpolicyagent.org/docs/latest/#running-opa\n' +
167559
+ 'Or pre-compile your .rego files: opa build -t wasm -e visor -o bundle.tar.gz ' +
167560
+ regoFiles.join(' '));
167561
+ }
167562
+ // Compute content hash for cache key
167563
+ const hash = crypto.createHash('sha256');
167564
+ for (const f of regoFiles.sort()) {
167565
+ hash.update(fs.readFileSync(f));
167566
+ hash.update(f); // include filename for disambiguation
167567
+ }
167568
+ const cacheKey = hash.digest('hex').slice(0, 16);
167569
+ const cacheDir = OpaCompiler.CACHE_DIR;
167570
+ const cachedWasm = path.join(cacheDir, `${cacheKey}.wasm`);
167571
+ // Return cached bundle if still valid
167572
+ if (fs.existsSync(cachedWasm)) {
167573
+ return fs.readFileSync(cachedWasm);
167574
+ }
167575
+ // Compile to WASM via opa build
167576
+ fs.mkdirSync(cacheDir, { recursive: true });
167577
+ const bundleTar = path.join(cacheDir, `${cacheKey}-bundle.tar.gz`);
167578
+ try {
167579
+ const args = [
167580
+ 'build',
167581
+ '-t',
167582
+ 'wasm',
167583
+ '-e',
167584
+ 'visor', // entrypoint: the visor package tree
167585
+ '-o',
167586
+ bundleTar,
167587
+ ...regoFiles,
167588
+ ];
167589
+ (0, child_process_1.execFileSync)('opa', args, {
167590
+ stdio: 'pipe',
167591
+ timeout: 30000,
167592
+ });
167593
+ }
167594
+ catch (err) {
167595
+ const stderr = err?.stderr?.toString() || '';
167596
+ throw new Error(`Failed to compile .rego files to WASM:\n${stderr}\n` +
167597
+ 'Ensure your .rego files are valid and the `opa` CLI is installed.');
167598
+ }
167599
+ // Extract policy.wasm from the tar.gz bundle
167600
+ // OPA bundles are tar.gz with /policy.wasm inside
167601
+ try {
167602
+ (0, child_process_1.execFileSync)('tar', ['-xzf', bundleTar, '-C', cacheDir, '/policy.wasm'], {
167603
+ stdio: 'pipe',
167604
+ });
167605
+ const extractedWasm = path.join(cacheDir, 'policy.wasm');
167606
+ if (fs.existsSync(extractedWasm)) {
167607
+ // Move to cache-key named file
167608
+ fs.renameSync(extractedWasm, cachedWasm);
167609
+ }
167610
+ }
167611
+ catch {
167612
+ // Some tar implementations don't like leading /
167613
+ try {
167614
+ (0, child_process_1.execFileSync)('tar', ['-xzf', bundleTar, '-C', cacheDir, 'policy.wasm'], {
167615
+ stdio: 'pipe',
167616
+ });
167617
+ const extractedWasm = path.join(cacheDir, 'policy.wasm');
167618
+ if (fs.existsSync(extractedWasm)) {
167619
+ fs.renameSync(extractedWasm, cachedWasm);
167620
+ }
167621
+ }
167622
+ catch (err2) {
167623
+ throw new Error(`Failed to extract policy.wasm from OPA bundle: ${err2?.message || err2}`);
167624
+ }
167625
+ }
167626
+ // Clean up tar
167627
+ try {
167628
+ fs.unlinkSync(bundleTar);
167629
+ }
167630
+ catch { }
167631
+ if (!fs.existsSync(cachedWasm)) {
167632
+ throw new Error('OPA build succeeded but policy.wasm was not found in the bundle');
167633
+ }
167634
+ return fs.readFileSync(cachedWasm);
167635
+ }
167636
+ }
167637
+ exports.OpaCompiler = OpaCompiler;
167638
+
167639
+
167640
+ /***/ }),
167641
+
167642
+ /***/ 44693:
167643
+ /***/ ((__unused_webpack_module, exports) => {
167644
+
167645
+ "use strict";
167646
+
167647
+ /**
167648
+ * Copyright (c) ProbeLabs. All rights reserved.
167649
+ * Licensed under the Elastic License 2.0; you may not use this file except
167650
+ * in compliance with the Elastic License 2.0.
167651
+ */
167652
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
167653
+ exports.OpaHttpEvaluator = void 0;
167654
+ /**
167655
+ * OPA HTTP Evaluator - evaluates policies via an external OPA server's REST API.
167656
+ *
167657
+ * Uses the built-in `fetch` API (Node 18+), so no extra dependencies are needed.
167658
+ */
167659
+ class OpaHttpEvaluator {
167660
+ baseUrl;
167661
+ timeout;
167662
+ constructor(baseUrl, timeout = 5000) {
167663
+ // Validate URL format and protocol
167664
+ let parsed;
167665
+ try {
167666
+ parsed = new URL(baseUrl);
167667
+ }
167668
+ catch {
167669
+ throw new Error(`OPA HTTP evaluator: invalid URL: ${baseUrl}`);
167670
+ }
167671
+ if (!['http:', 'https:'].includes(parsed.protocol)) {
167672
+ throw new Error(`OPA HTTP evaluator: url must use http:// or https:// protocol, got: ${baseUrl}`);
167673
+ }
167674
+ // Block cloud metadata, loopback, link-local, and private network addresses
167675
+ const hostname = parsed.hostname;
167676
+ if (this.isBlockedHostname(hostname)) {
167677
+ throw new Error(`OPA HTTP evaluator: url must not point to internal, loopback, or private network addresses`);
167678
+ }
167679
+ // Normalize: strip trailing slash
167680
+ this.baseUrl = baseUrl.replace(/\/+$/, '');
167681
+ this.timeout = timeout;
167682
+ }
167683
+ /**
167684
+ * Check if a hostname is blocked due to SSRF concerns.
167685
+ *
167686
+ * Blocks:
167687
+ * - Loopback addresses (127.x.x.x, localhost, 0.0.0.0, ::1)
167688
+ * - Link-local addresses (169.254.x.x)
167689
+ * - Private networks (10.x.x.x, 172.16-31.x.x, 192.168.x.x)
167690
+ * - IPv6 unique local addresses (fd00::/8)
167691
+ * - Cloud metadata services (*.internal)
167692
+ */
167693
+ isBlockedHostname(hostname) {
167694
+ if (!hostname)
167695
+ return true; // block empty hostnames
167696
+ // Normalize hostname: lowercase and remove brackets for IPv6
167697
+ const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, '');
167698
+ // Block .internal domains (cloud metadata services)
167699
+ if (normalized === 'metadata.google.internal' || normalized.endsWith('.internal')) {
167700
+ return true;
167701
+ }
167702
+ // Block localhost variants
167703
+ if (normalized === 'localhost' || normalized === 'localhost.localdomain') {
167704
+ return true;
167705
+ }
167706
+ // Block IPv6 loopback
167707
+ if (normalized === '::1' || normalized === '0:0:0:0:0:0:0:1') {
167708
+ return true;
167709
+ }
167710
+ // Check IPv4 patterns
167711
+ const ipv4Pattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
167712
+ const ipv4Match = normalized.match(ipv4Pattern);
167713
+ if (ipv4Match) {
167714
+ const octets = ipv4Match.slice(1, 5).map(Number);
167715
+ // Validate octets are in range [0, 255]
167716
+ if (octets.some(octet => octet > 255)) {
167717
+ return false;
167718
+ }
167719
+ const [a, b] = octets;
167720
+ // Block loopback: 127.0.0.0/8
167721
+ if (a === 127) {
167722
+ return true;
167723
+ }
167724
+ // Block 0.0.0.0/8 (this host)
167725
+ if (a === 0) {
167726
+ return true;
167727
+ }
167728
+ // Block link-local: 169.254.0.0/16
167729
+ if (a === 169 && b === 254) {
167730
+ return true;
167731
+ }
167732
+ // Block private networks
167733
+ // 10.0.0.0/8
167734
+ if (a === 10) {
167735
+ return true;
167736
+ }
167737
+ // 172.16.0.0/12 (172.16.x.x through 172.31.x.x)
167738
+ if (a === 172 && b >= 16 && b <= 31) {
167739
+ return true;
167740
+ }
167741
+ // 192.168.0.0/16
167742
+ if (a === 192 && b === 168) {
167743
+ return true;
167744
+ }
167745
+ }
167746
+ // Check IPv6 patterns
167747
+ // Block unique local addresses: fd00::/8
167748
+ if (normalized.startsWith('fd') || normalized.startsWith('fc')) {
167749
+ return true;
167750
+ }
167751
+ // Block link-local: fe80::/10
167752
+ if (normalized.startsWith('fe80:')) {
167753
+ return true;
167754
+ }
167755
+ return false;
167756
+ }
167757
+ /**
167758
+ * Evaluate a policy rule against an input document via OPA REST API.
167759
+ *
167760
+ * @param input - The input document to evaluate
167761
+ * @param rulePath - OPA rule path (e.g., 'visor/check/execute')
167762
+ * @returns The result object from OPA, or undefined on error
167763
+ */
167764
+ async evaluate(input, rulePath) {
167765
+ // OPA Data API: POST /v1/data/<path>
167766
+ const encodedPath = rulePath
167767
+ .split('/')
167768
+ .map(s => encodeURIComponent(s))
167769
+ .join('/');
167770
+ const url = `${this.baseUrl}/v1/data/${encodedPath}`;
167771
+ const controller = new AbortController();
167772
+ const timer = setTimeout(() => controller.abort(), this.timeout);
167773
+ try {
167774
+ const response = await fetch(url, {
167775
+ method: 'POST',
167776
+ headers: { 'Content-Type': 'application/json' },
167777
+ body: JSON.stringify({ input }),
167778
+ signal: controller.signal,
167779
+ });
167780
+ if (!response.ok) {
167781
+ throw new Error(`OPA HTTP ${response.status}: ${response.statusText}`);
167782
+ }
167783
+ let body;
167784
+ try {
167785
+ body = await response.json();
167786
+ }
167787
+ catch (jsonErr) {
167788
+ throw new Error(`OPA HTTP evaluator: failed to parse JSON response: ${jsonErr instanceof Error ? jsonErr.message : String(jsonErr)}`);
167789
+ }
167790
+ // OPA returns { result: { ... } }
167791
+ return body?.result;
167792
+ }
167793
+ finally {
167794
+ clearTimeout(timer);
167795
+ }
167796
+ }
167797
+ async shutdown() {
167798
+ // No persistent connections to close
167799
+ }
167800
+ }
167801
+ exports.OpaHttpEvaluator = OpaHttpEvaluator;
167802
+
167803
+
167804
+ /***/ }),
167805
+
167806
+ /***/ 39530:
167807
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
167808
+
167809
+ "use strict";
167810
+
167811
+ /**
167812
+ * Copyright (c) ProbeLabs. All rights reserved.
167813
+ * Licensed under the Elastic License 2.0; you may not use this file except
167814
+ * in compliance with the Elastic License 2.0.
167815
+ */
167816
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
167817
+ exports.OpaPolicyEngine = void 0;
167818
+ const opa_wasm_evaluator_1 = __nccwpck_require__(8613);
167819
+ const opa_http_evaluator_1 = __nccwpck_require__(44693);
167820
+ const policy_input_builder_1 = __nccwpck_require__(17117);
167821
+ /**
167822
+ * Enterprise OPA Policy Engine.
167823
+ *
167824
+ * Wraps both WASM (local) and HTTP (remote) OPA evaluators behind the
167825
+ * OSS PolicyEngine interface. All OPA input building and role resolution
167826
+ * is handled internally — the OSS call sites pass only plain types.
167827
+ */
167828
+ class OpaPolicyEngine {
167829
+ evaluator = null;
167830
+ fallback;
167831
+ timeout;
167832
+ config;
167833
+ inputBuilder = null;
167834
+ logger = null;
167835
+ constructor(config) {
167836
+ this.config = config;
167837
+ this.fallback = config.fallback || 'deny';
167838
+ this.timeout = config.timeout || 5000;
167839
+ }
167840
+ async initialize(config) {
167841
+ // Resolve logger once at initialization
167842
+ try {
167843
+ this.logger = (__nccwpck_require__(86999).logger);
167844
+ }
167845
+ catch {
167846
+ // logger not available in this context
167847
+ }
167848
+ // Build actor/repo context from environment (available at engine init time)
167849
+ const actor = {
167850
+ authorAssociation: process.env.VISOR_AUTHOR_ASSOCIATION,
167851
+ login: process.env.VISOR_AUTHOR_LOGIN || process.env.GITHUB_ACTOR,
167852
+ isLocalMode: !process.env.GITHUB_ACTIONS,
167853
+ };
167854
+ const repo = {
167855
+ owner: process.env.GITHUB_REPOSITORY_OWNER,
167856
+ name: process.env.GITHUB_REPOSITORY?.split('/')[1],
167857
+ branch: process.env.GITHUB_HEAD_REF,
167858
+ baseBranch: process.env.GITHUB_BASE_REF,
167859
+ event: process.env.GITHUB_EVENT_NAME,
167860
+ };
167861
+ const prNum = process.env.GITHUB_PR_NUMBER
167862
+ ? parseInt(process.env.GITHUB_PR_NUMBER, 10)
167863
+ : undefined;
167864
+ const pullRequest = {
167865
+ number: prNum !== undefined && Number.isFinite(prNum) ? prNum : undefined,
167866
+ };
167867
+ this.inputBuilder = new policy_input_builder_1.PolicyInputBuilder(config, actor, repo, pullRequest);
167868
+ if (config.engine === 'local') {
167869
+ if (!config.rules) {
167870
+ throw new Error('OPA local mode requires `policy.rules` path to .wasm or .rego files');
167871
+ }
167872
+ const wasm = new opa_wasm_evaluator_1.OpaWasmEvaluator();
167873
+ await wasm.initialize(config.rules);
167874
+ if (config.data) {
167875
+ wasm.loadData(config.data);
167876
+ }
167877
+ this.evaluator = wasm;
167878
+ }
167879
+ else if (config.engine === 'remote') {
167880
+ if (!config.url) {
167881
+ throw new Error('OPA remote mode requires `policy.url` pointing to OPA server');
167882
+ }
167883
+ this.evaluator = new opa_http_evaluator_1.OpaHttpEvaluator(config.url, this.timeout);
167884
+ }
167885
+ else {
167886
+ this.evaluator = null;
167887
+ }
167888
+ }
167889
+ /**
167890
+ * Update actor/repo/PR context (e.g., after PR info becomes available).
167891
+ * Called by the enterprise loader when engine context is enriched.
167892
+ */
167893
+ setActorContext(actor, repo, pullRequest) {
167894
+ this.inputBuilder = new policy_input_builder_1.PolicyInputBuilder(this.config, actor, repo, pullRequest);
167895
+ }
167896
+ async evaluateCheckExecution(checkId, checkConfig) {
167897
+ if (!this.evaluator || !this.inputBuilder)
167898
+ return { allowed: true };
167899
+ const cfg = checkConfig && typeof checkConfig === 'object'
167900
+ ? checkConfig
167901
+ : {};
167902
+ const policyOverride = cfg.policy;
167903
+ const input = this.inputBuilder.forCheckExecution({
167904
+ id: checkId,
167905
+ type: cfg.type || 'ai',
167906
+ group: cfg.group,
167907
+ tags: cfg.tags,
167908
+ criticality: cfg.criticality,
167909
+ sandbox: cfg.sandbox,
167910
+ policy: policyOverride,
167911
+ });
167912
+ return this.doEvaluate(input, this.resolveRulePath('check.execute', policyOverride?.rule));
167913
+ }
167914
+ async evaluateToolInvocation(serverName, methodName, transport) {
167915
+ if (!this.evaluator || !this.inputBuilder)
167916
+ return { allowed: true };
167917
+ const input = this.inputBuilder.forToolInvocation(serverName, methodName, transport);
167918
+ return this.doEvaluate(input, 'visor/tool/invoke');
167919
+ }
167920
+ async evaluateCapabilities(checkId, capabilities) {
167921
+ if (!this.evaluator || !this.inputBuilder)
167922
+ return { allowed: true };
167923
+ const input = this.inputBuilder.forCapabilityResolve(checkId, capabilities);
167924
+ return this.doEvaluate(input, 'visor/capability/resolve');
167925
+ }
167926
+ async shutdown() {
167927
+ if (this.evaluator && 'shutdown' in this.evaluator) {
167928
+ await this.evaluator.shutdown();
167929
+ }
167930
+ this.evaluator = null;
167931
+ this.inputBuilder = null;
167932
+ }
167933
+ resolveRulePath(defaultScope, override) {
167934
+ if (override) {
167935
+ return override.startsWith('visor/') ? override : `visor/${override}`;
167936
+ }
167937
+ return `visor/${defaultScope.replace(/\./g, '/')}`;
167938
+ }
167939
+ async doEvaluate(input, rulePath) {
167940
+ try {
167941
+ this.logger?.debug(`[PolicyEngine] Evaluating ${rulePath}`, JSON.stringify(input));
167942
+ let timer;
167943
+ const timeoutPromise = new Promise((_resolve, reject) => {
167944
+ timer = setTimeout(() => reject(new Error('policy evaluation timeout')), this.timeout);
167945
+ });
167946
+ try {
167947
+ const result = await Promise.race([this.rawEvaluate(input, rulePath), timeoutPromise]);
167948
+ const decision = this.parseDecision(result);
167949
+ // In warn mode, override denied decisions to allowed but flag as warn
167950
+ if (!decision.allowed && this.fallback === 'warn') {
167951
+ decision.allowed = true;
167952
+ decision.warn = true;
167953
+ decision.reason = `audit: ${decision.reason || 'policy denied'}`;
167954
+ }
167955
+ this.logger?.debug(`[PolicyEngine] Decision for ${rulePath}: allowed=${decision.allowed}, warn=${decision.warn || false}, reason=${decision.reason || 'none'}`);
167956
+ return decision;
167957
+ }
167958
+ finally {
167959
+ if (timer)
167960
+ clearTimeout(timer);
167961
+ }
167962
+ }
167963
+ catch (err) {
167964
+ const msg = err instanceof Error ? err.message : String(err);
167965
+ this.logger?.warn(`[PolicyEngine] Evaluation failed for ${rulePath}: ${msg}`);
167966
+ return {
167967
+ allowed: this.fallback === 'allow' || this.fallback === 'warn',
167968
+ warn: this.fallback === 'warn' ? true : undefined,
167969
+ reason: `policy evaluation failed, fallback=${this.fallback}`,
167970
+ };
167971
+ }
167972
+ }
167973
+ async rawEvaluate(input, rulePath) {
167974
+ if (this.evaluator instanceof opa_wasm_evaluator_1.OpaWasmEvaluator) {
167975
+ const result = await this.evaluator.evaluate(input);
167976
+ // WASM compiled with `-e visor` entrypoint returns the full visor package tree.
167977
+ // Navigate to the specific rule subtree using rulePath segments.
167978
+ // e.g., 'visor/check/execute' → result.check.execute
167979
+ return this.navigateWasmResult(result, rulePath);
167980
+ }
167981
+ return this.evaluator.evaluate(input, rulePath);
167982
+ }
167983
+ /**
167984
+ * Navigate nested OPA WASM result tree to reach the specific rule's output.
167985
+ * The WASM entrypoint `-e visor` means the result root IS the visor package,
167986
+ * so we strip the `visor/` prefix and walk the remaining segments.
167987
+ */
167988
+ navigateWasmResult(result, rulePath) {
167989
+ if (!result || typeof result !== 'object')
167990
+ return result;
167991
+ // Strip the 'visor/' prefix (matches our compilation entrypoint)
167992
+ const segments = rulePath.replace(/^visor\//, '').split('/');
167993
+ let current = result;
167994
+ for (const seg of segments) {
167995
+ if (current && typeof current === 'object' && seg in current) {
167996
+ current = current[seg];
167997
+ }
167998
+ else {
167999
+ return undefined; // path not found in result tree
168000
+ }
168001
+ }
168002
+ return current;
168003
+ }
168004
+ parseDecision(result) {
168005
+ if (result === undefined || result === null) {
168006
+ return {
168007
+ allowed: this.fallback === 'allow' || this.fallback === 'warn',
168008
+ warn: this.fallback === 'warn' ? true : undefined,
168009
+ reason: this.fallback === 'warn' ? 'audit: no policy result' : 'no policy result',
168010
+ };
168011
+ }
168012
+ const allowed = result.allowed !== false;
168013
+ const decision = {
168014
+ allowed,
168015
+ reason: result.reason,
168016
+ };
168017
+ if (result.capabilities) {
168018
+ decision.capabilities = result.capabilities;
168019
+ }
168020
+ return decision;
168021
+ }
168022
+ }
168023
+ exports.OpaPolicyEngine = OpaPolicyEngine;
168024
+
168025
+
168026
+ /***/ }),
168027
+
168028
+ /***/ 8613:
168029
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
168030
+
168031
+ "use strict";
168032
+
168033
+ /**
168034
+ * Copyright (c) ProbeLabs. All rights reserved.
168035
+ * Licensed under the Elastic License 2.0; you may not use this file except
168036
+ * in compliance with the Elastic License 2.0.
168037
+ */
168038
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
168039
+ if (k2 === undefined) k2 = k;
168040
+ var desc = Object.getOwnPropertyDescriptor(m, k);
168041
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
168042
+ desc = { enumerable: true, get: function() { return m[k]; } };
168043
+ }
168044
+ Object.defineProperty(o, k2, desc);
168045
+ }) : (function(o, m, k, k2) {
168046
+ if (k2 === undefined) k2 = k;
168047
+ o[k2] = m[k];
168048
+ }));
168049
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
168050
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
168051
+ }) : function(o, v) {
168052
+ o["default"] = v;
168053
+ });
168054
+ var __importStar = (this && this.__importStar) || (function () {
168055
+ var ownKeys = function(o) {
168056
+ ownKeys = Object.getOwnPropertyNames || function (o) {
168057
+ var ar = [];
168058
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
168059
+ return ar;
168060
+ };
168061
+ return ownKeys(o);
168062
+ };
168063
+ return function (mod) {
168064
+ if (mod && mod.__esModule) return mod;
168065
+ var result = {};
168066
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
168067
+ __setModuleDefault(result, mod);
168068
+ return result;
168069
+ };
168070
+ })();
168071
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
168072
+ exports.OpaWasmEvaluator = void 0;
168073
+ const fs = __importStar(__nccwpck_require__(79896));
168074
+ const path = __importStar(__nccwpck_require__(16928));
168075
+ const opa_compiler_1 = __nccwpck_require__(628);
168076
+ /**
168077
+ * OPA WASM Evaluator - loads and evaluates OPA policies locally.
168078
+ *
168079
+ * Supports three input formats:
168080
+ * 1. Pre-compiled `.wasm` bundle — loaded directly (fastest startup)
168081
+ * 2. `.rego` files or directory — auto-compiled to WASM via `opa build` CLI
168082
+ * 3. Directory with `policy.wasm` inside — loaded directly
168083
+ *
168084
+ * Compilation and caching of .rego files is delegated to {@link OpaCompiler}.
168085
+ *
168086
+ * Requires:
168087
+ * - `@open-policy-agent/opa-wasm` npm package (optional dep)
168088
+ * - `opa` CLI on PATH (only when auto-compiling .rego files)
168089
+ */
168090
+ class OpaWasmEvaluator {
168091
+ policy = null;
168092
+ dataDocument = {};
168093
+ compiler = new opa_compiler_1.OpaCompiler();
168094
+ async initialize(rulesPath) {
168095
+ const paths = Array.isArray(rulesPath) ? rulesPath : [rulesPath];
168096
+ const wasmBytes = await this.compiler.resolveWasmBytes(paths);
168097
+ try {
168098
+ // Use createRequire to load the optional dep at runtime without ncc bundling it.
168099
+ // `new Function('id', 'return require(id)')` fails in ncc bundles because
168100
+ // `require` is not in the `new Function` scope. `createRequire` works correctly
168101
+ // because it creates a real Node.js require rooted at the given path.
168102
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
168103
+ const { createRequire } = __nccwpck_require__(73339);
168104
+ const runtimeRequire = createRequire(__filename);
168105
+ const opaWasm = runtimeRequire('@open-policy-agent/opa-wasm');
168106
+ const loadPolicy = opaWasm.loadPolicy || opaWasm.default?.loadPolicy;
168107
+ if (!loadPolicy) {
168108
+ throw new Error('loadPolicy not found in @open-policy-agent/opa-wasm');
168109
+ }
168110
+ this.policy = await loadPolicy(wasmBytes);
168111
+ }
168112
+ catch (err) {
168113
+ if (err?.code === 'MODULE_NOT_FOUND' || err?.code === 'ERR_MODULE_NOT_FOUND') {
168114
+ throw new Error('OPA WASM evaluator requires @open-policy-agent/opa-wasm. ' +
168115
+ 'Install it with: npm install @open-policy-agent/opa-wasm');
168116
+ }
168117
+ throw err;
168118
+ }
168119
+ }
168120
+ /**
168121
+ * Load external data from a JSON file to use as the OPA data document.
168122
+ * The loaded data will be passed to `policy.setData()` during evaluation,
168123
+ * making it available in Rego via `data.<key>`.
168124
+ */
168125
+ loadData(dataPath) {
168126
+ const resolved = path.resolve(dataPath);
168127
+ if (path.normalize(resolved).includes('..')) {
168128
+ throw new Error(`Data path contains traversal sequences: ${dataPath}`);
168129
+ }
168130
+ if (!fs.existsSync(resolved)) {
168131
+ throw new Error(`OPA data file not found: ${resolved}`);
168132
+ }
168133
+ const stat = fs.statSync(resolved);
168134
+ if (stat.size > 10 * 1024 * 1024) {
168135
+ throw new Error(`OPA data file exceeds 10MB limit: ${resolved} (${stat.size} bytes)`);
168136
+ }
168137
+ const raw = fs.readFileSync(resolved, 'utf-8');
168138
+ try {
168139
+ const parsed = JSON.parse(raw);
168140
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
168141
+ throw new Error('OPA data file must contain a JSON object (not an array or primitive)');
168142
+ }
168143
+ this.dataDocument = parsed;
168144
+ }
168145
+ catch (err) {
168146
+ if (err.message.startsWith('OPA data file must')) {
168147
+ throw err;
168148
+ }
168149
+ throw new Error(`Failed to parse OPA data file ${resolved}: ${err.message}`);
168150
+ }
168151
+ }
168152
+ async evaluate(input) {
168153
+ if (!this.policy) {
168154
+ throw new Error('OPA WASM evaluator not initialized');
168155
+ }
168156
+ this.policy.setData(this.dataDocument);
168157
+ const resultSet = this.policy.evaluate(input);
168158
+ if (Array.isArray(resultSet) && resultSet.length > 0) {
168159
+ return resultSet[0].result;
168160
+ }
168161
+ return undefined;
168162
+ }
168163
+ async shutdown() {
168164
+ if (this.policy) {
168165
+ // opa-wasm policy objects may have a close/free method for WASM cleanup
168166
+ if (typeof this.policy.close === 'function') {
168167
+ try {
168168
+ this.policy.close();
168169
+ }
168170
+ catch { }
168171
+ }
168172
+ else if (typeof this.policy.free === 'function') {
168173
+ try {
168174
+ this.policy.free();
168175
+ }
168176
+ catch { }
168177
+ }
168178
+ }
168179
+ this.policy = null;
168180
+ }
168181
+ }
168182
+ exports.OpaWasmEvaluator = OpaWasmEvaluator;
168183
+
168184
+
168185
+ /***/ }),
168186
+
168187
+ /***/ 17117:
168188
+ /***/ ((__unused_webpack_module, exports) => {
168189
+
168190
+ "use strict";
168191
+
168192
+ /**
168193
+ * Copyright (c) ProbeLabs. All rights reserved.
168194
+ * Licensed under the Elastic License 2.0; you may not use this file except
168195
+ * in compliance with the Elastic License 2.0.
168196
+ */
168197
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
168198
+ exports.PolicyInputBuilder = void 0;
168199
+ /**
168200
+ * Builds OPA-compatible input documents from engine context.
168201
+ *
168202
+ * Resolves actor roles from the `policy.roles` config section by matching
168203
+ * the actor's authorAssociation and login against role definitions.
168204
+ */
168205
+ class PolicyInputBuilder {
168206
+ roles;
168207
+ actor;
168208
+ repository;
168209
+ pullRequest;
168210
+ constructor(policyConfig, actor, repository, pullRequest) {
168211
+ this.roles = policyConfig.roles || {};
168212
+ this.actor = actor;
168213
+ this.repository = repository;
168214
+ this.pullRequest = pullRequest;
168215
+ }
168216
+ /** Resolve which roles apply to the current actor. */
168217
+ resolveRoles() {
168218
+ const matched = [];
168219
+ for (const [roleName, roleConfig] of Object.entries(this.roles)) {
168220
+ let identityMatch = false;
168221
+ if (roleConfig.author_association &&
168222
+ this.actor.authorAssociation &&
168223
+ roleConfig.author_association.includes(this.actor.authorAssociation)) {
168224
+ identityMatch = true;
168225
+ }
168226
+ if (!identityMatch &&
168227
+ roleConfig.users &&
168228
+ this.actor.login &&
168229
+ roleConfig.users.includes(this.actor.login)) {
168230
+ identityMatch = true;
168231
+ }
168232
+ // Slack user ID match
168233
+ if (!identityMatch &&
168234
+ roleConfig.slack_users &&
168235
+ this.actor.slack?.userId &&
168236
+ roleConfig.slack_users.includes(this.actor.slack.userId)) {
168237
+ identityMatch = true;
168238
+ }
168239
+ // Email match (case-insensitive)
168240
+ if (!identityMatch && roleConfig.emails && this.actor.slack?.email) {
168241
+ const actorEmail = this.actor.slack.email.toLowerCase();
168242
+ if (roleConfig.emails.some(e => e.toLowerCase() === actorEmail)) {
168243
+ identityMatch = true;
168244
+ }
168245
+ }
168246
+ // Note: teams-based role resolution requires GitHub API access (read:org scope)
168247
+ // and is not yet implemented. If configured, the role will not match via teams.
168248
+ if (!identityMatch)
168249
+ continue;
168250
+ // slack_channels gate: if set, the role only applies when triggered from one of these channels
168251
+ if (roleConfig.slack_channels && roleConfig.slack_channels.length > 0) {
168252
+ if (!this.actor.slack?.channelId ||
168253
+ !roleConfig.slack_channels.includes(this.actor.slack.channelId)) {
168254
+ continue;
168255
+ }
168256
+ }
168257
+ matched.push(roleName);
168258
+ }
168259
+ return matched;
168260
+ }
168261
+ buildActor() {
168262
+ return {
168263
+ authorAssociation: this.actor.authorAssociation,
168264
+ login: this.actor.login,
168265
+ roles: this.resolveRoles(),
168266
+ isLocalMode: this.actor.isLocalMode,
168267
+ ...(this.actor.slack && { slack: this.actor.slack }),
168268
+ };
168269
+ }
168270
+ forCheckExecution(check) {
168271
+ return {
168272
+ scope: 'check.execute',
168273
+ check: {
168274
+ id: check.id,
168275
+ type: check.type,
168276
+ group: check.group,
168277
+ tags: check.tags,
168278
+ criticality: check.criticality,
168279
+ sandbox: check.sandbox,
168280
+ policy: check.policy,
168281
+ },
168282
+ actor: this.buildActor(),
168283
+ repository: this.repository,
168284
+ pullRequest: this.pullRequest,
168285
+ };
168286
+ }
168287
+ forToolInvocation(serverName, methodName, transport) {
168288
+ return {
168289
+ scope: 'tool.invoke',
168290
+ tool: { serverName, methodName, transport },
168291
+ actor: this.buildActor(),
168292
+ repository: this.repository,
168293
+ pullRequest: this.pullRequest,
168294
+ };
168295
+ }
168296
+ forCapabilityResolve(checkId, capabilities) {
168297
+ return {
168298
+ scope: 'capability.resolve',
168299
+ check: { id: checkId, type: 'ai' },
168300
+ capability: capabilities,
168301
+ actor: this.buildActor(),
168302
+ repository: this.repository,
168303
+ pullRequest: this.pullRequest,
168304
+ };
168305
+ }
168306
+ }
168307
+ exports.PolicyInputBuilder = PolicyInputBuilder;
168308
+
168309
+
168310
+ /***/ }),
168311
+
168312
+ /***/ 63737:
168313
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
168314
+
168315
+ "use strict";
168316
+
168317
+ /**
168318
+ * Copyright (c) ProbeLabs. All rights reserved.
168319
+ * Licensed under the Elastic License 2.0; you may not use this file except
168320
+ * in compliance with the Elastic License 2.0.
168321
+ */
168322
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
168323
+ if (k2 === undefined) k2 = k;
168324
+ var desc = Object.getOwnPropertyDescriptor(m, k);
168325
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
168326
+ desc = { enumerable: true, get: function() { return m[k]; } };
168327
+ }
168328
+ Object.defineProperty(o, k2, desc);
168329
+ }) : (function(o, m, k, k2) {
168330
+ if (k2 === undefined) k2 = k;
168331
+ o[k2] = m[k];
168332
+ }));
168333
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
168334
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
168335
+ }) : function(o, v) {
168336
+ o["default"] = v;
168337
+ });
168338
+ var __importStar = (this && this.__importStar) || (function () {
168339
+ var ownKeys = function(o) {
168340
+ ownKeys = Object.getOwnPropertyNames || function (o) {
168341
+ var ar = [];
168342
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
168343
+ return ar;
168344
+ };
168345
+ return ownKeys(o);
168346
+ };
168347
+ return function (mod) {
168348
+ if (mod && mod.__esModule) return mod;
168349
+ var result = {};
168350
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
168351
+ __setModuleDefault(result, mod);
168352
+ return result;
168353
+ };
168354
+ })();
168355
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
168356
+ exports.KnexStoreBackend = void 0;
168357
+ /**
168358
+ * Knex-backed schedule store for PostgreSQL, MySQL, and MSSQL (Enterprise)
168359
+ *
168360
+ * Uses Knex query builder for database-agnostic SQL. Same schema as SQLite backend
168361
+ * but with real distributed locking via row-level claims (claimed_by/claimed_at/lock_token).
168362
+ */
168363
+ const fs = __importStar(__nccwpck_require__(79896));
168364
+ const path = __importStar(__nccwpck_require__(16928));
168365
+ const uuid_1 = __nccwpck_require__(31914);
168366
+ const logger_1 = __nccwpck_require__(86999);
168367
+ function toNum(val) {
168368
+ if (val === null || val === undefined)
168369
+ return undefined;
168370
+ return typeof val === 'string' ? parseInt(val, 10) : val;
168371
+ }
168372
+ function safeJsonParse(value) {
168373
+ if (!value)
168374
+ return undefined;
168375
+ try {
168376
+ return JSON.parse(value);
168377
+ }
168378
+ catch {
168379
+ return undefined;
168380
+ }
168381
+ }
168382
+ function fromTriggerRow(row) {
168383
+ return {
168384
+ id: row.id,
168385
+ creatorId: row.creator_id,
168386
+ creatorContext: row.creator_context ?? undefined,
168387
+ creatorName: row.creator_name ?? undefined,
168388
+ description: row.description ?? undefined,
168389
+ channels: safeJsonParse(row.channels),
168390
+ fromUsers: safeJsonParse(row.from_users),
168391
+ fromBots: row.from_bots === true || row.from_bots === 1,
168392
+ contains: safeJsonParse(row.contains),
168393
+ matchPattern: row.match_pattern ?? undefined,
168394
+ threads: row.threads,
168395
+ workflow: row.workflow,
168396
+ inputs: safeJsonParse(row.inputs),
168397
+ outputContext: safeJsonParse(row.output_context),
168398
+ status: row.status,
168399
+ enabled: row.enabled === true || row.enabled === 1,
168400
+ createdAt: toNum(row.created_at),
168401
+ };
168402
+ }
168403
+ function toTriggerInsertRow(trigger) {
168404
+ return {
168405
+ id: trigger.id,
168406
+ creator_id: trigger.creatorId,
168407
+ creator_context: trigger.creatorContext ?? null,
168408
+ creator_name: trigger.creatorName ?? null,
168409
+ description: trigger.description ?? null,
168410
+ channels: trigger.channels ? JSON.stringify(trigger.channels) : null,
168411
+ from_users: trigger.fromUsers ? JSON.stringify(trigger.fromUsers) : null,
168412
+ from_bots: trigger.fromBots,
168413
+ contains: trigger.contains ? JSON.stringify(trigger.contains) : null,
168414
+ match_pattern: trigger.matchPattern ?? null,
168415
+ threads: trigger.threads,
168416
+ workflow: trigger.workflow,
168417
+ inputs: trigger.inputs ? JSON.stringify(trigger.inputs) : null,
168418
+ output_context: trigger.outputContext ? JSON.stringify(trigger.outputContext) : null,
168419
+ status: trigger.status,
168420
+ enabled: trigger.enabled,
168421
+ created_at: trigger.createdAt,
168422
+ };
168423
+ }
168424
+ function fromDbRow(row) {
168425
+ return {
168426
+ id: row.id,
168427
+ creatorId: row.creator_id,
168428
+ creatorContext: row.creator_context ?? undefined,
168429
+ creatorName: row.creator_name ?? undefined,
168430
+ timezone: row.timezone,
168431
+ schedule: row.schedule_expr,
168432
+ runAt: toNum(row.run_at),
168433
+ isRecurring: row.is_recurring === true || row.is_recurring === 1,
168434
+ originalExpression: row.original_expression,
168435
+ workflow: row.workflow ?? undefined,
168436
+ workflowInputs: safeJsonParse(row.workflow_inputs),
168437
+ outputContext: safeJsonParse(row.output_context),
168438
+ status: row.status,
168439
+ createdAt: toNum(row.created_at),
168440
+ lastRunAt: toNum(row.last_run_at),
168441
+ nextRunAt: toNum(row.next_run_at),
168442
+ runCount: row.run_count,
168443
+ failureCount: row.failure_count,
168444
+ lastError: row.last_error ?? undefined,
168445
+ previousResponse: row.previous_response ?? undefined,
168446
+ };
168447
+ }
168448
+ function toInsertRow(schedule) {
168449
+ return {
168450
+ id: schedule.id,
168451
+ creator_id: schedule.creatorId,
168452
+ creator_context: schedule.creatorContext ?? null,
168453
+ creator_name: schedule.creatorName ?? null,
168454
+ timezone: schedule.timezone,
168455
+ schedule_expr: schedule.schedule,
168456
+ run_at: schedule.runAt ?? null,
168457
+ is_recurring: schedule.isRecurring,
168458
+ original_expression: schedule.originalExpression,
168459
+ workflow: schedule.workflow ?? null,
168460
+ workflow_inputs: schedule.workflowInputs ? JSON.stringify(schedule.workflowInputs) : null,
168461
+ output_context: schedule.outputContext ? JSON.stringify(schedule.outputContext) : null,
168462
+ status: schedule.status,
168463
+ created_at: schedule.createdAt,
168464
+ last_run_at: schedule.lastRunAt ?? null,
168465
+ next_run_at: schedule.nextRunAt ?? null,
168466
+ run_count: schedule.runCount,
168467
+ failure_count: schedule.failureCount,
168468
+ last_error: schedule.lastError ?? null,
168469
+ previous_response: schedule.previousResponse ?? null,
168470
+ };
168471
+ }
168472
+ /**
168473
+ * Enterprise Knex-backed store for PostgreSQL, MySQL, and MSSQL
168474
+ */
168475
+ class KnexStoreBackend {
168476
+ knex = null;
168477
+ driver;
168478
+ connection;
168479
+ constructor(driver, storageConfig, _haConfig) {
168480
+ this.driver = driver;
168481
+ this.connection = (storageConfig.connection || {});
168482
+ }
168483
+ async initialize() {
168484
+ // Load knex dynamically
168485
+ const { createRequire } = __nccwpck_require__(73339);
168486
+ const runtimeRequire = createRequire(__filename);
168487
+ let knexFactory;
168488
+ try {
168489
+ knexFactory = runtimeRequire('knex');
168490
+ }
168491
+ catch (err) {
168492
+ const code = err?.code;
168493
+ if (code === 'MODULE_NOT_FOUND' || code === 'ERR_MODULE_NOT_FOUND') {
168494
+ throw new Error('knex is required for PostgreSQL/MySQL/MSSQL schedule storage. ' +
168495
+ 'Install it with: npm install knex');
168496
+ }
168497
+ throw err;
168498
+ }
168499
+ const clientMap = {
168500
+ postgresql: 'pg',
168501
+ mysql: 'mysql2',
168502
+ mssql: 'tedious',
168503
+ };
168504
+ const client = clientMap[this.driver];
168505
+ // Build connection config
168506
+ let connection;
168507
+ if (this.connection.connection_string) {
168508
+ connection = this.connection.connection_string;
168509
+ }
168510
+ else if (this.driver === 'mssql') {
168511
+ connection = this.buildMssqlConnection();
168512
+ }
168513
+ else {
168514
+ connection = this.buildStandardConnection();
168515
+ }
168516
+ this.knex = knexFactory({
168517
+ client,
168518
+ connection,
168519
+ pool: {
168520
+ min: this.connection.pool?.min ?? 0,
168521
+ max: this.connection.pool?.max ?? 10,
168522
+ },
168523
+ });
168524
+ // Run schema migration
168525
+ await this.migrateSchema();
168526
+ logger_1.logger.info(`[KnexStore] Initialized (${this.driver})`);
168527
+ }
168528
+ buildStandardConnection() {
168529
+ return {
168530
+ host: this.connection.host || 'localhost',
168531
+ port: this.connection.port,
168532
+ database: this.connection.database || 'visor',
168533
+ user: this.connection.user,
168534
+ password: this.connection.password,
168535
+ ssl: this.resolveSslConfig(),
168536
+ };
168537
+ }
168538
+ buildMssqlConnection() {
168539
+ const ssl = this.connection.ssl;
168540
+ const sslEnabled = ssl === true || (typeof ssl === 'object' && ssl.enabled !== false);
168541
+ return {
168542
+ server: this.connection.host || 'localhost',
168543
+ port: this.connection.port,
168544
+ database: this.connection.database || 'visor',
168545
+ user: this.connection.user,
168546
+ password: this.connection.password,
168547
+ options: {
168548
+ encrypt: sslEnabled,
168549
+ trustServerCertificate: typeof ssl === 'object' ? ssl.reject_unauthorized === false : !sslEnabled,
168550
+ },
168551
+ };
168552
+ }
168553
+ resolveSslConfig() {
168554
+ const ssl = this.connection.ssl;
168555
+ if (ssl === false || ssl === undefined)
168556
+ return false;
168557
+ if (ssl === true)
168558
+ return { rejectUnauthorized: true };
168559
+ // Object config
168560
+ if (ssl.enabled === false)
168561
+ return false;
168562
+ const result = {
168563
+ rejectUnauthorized: ssl.reject_unauthorized !== false,
168564
+ };
168565
+ if (ssl.ca) {
168566
+ const caPath = this.validateSslPath(ssl.ca, 'CA certificate');
168567
+ result.ca = fs.readFileSync(caPath, 'utf8');
168568
+ }
168569
+ if (ssl.cert) {
168570
+ const certPath = this.validateSslPath(ssl.cert, 'client certificate');
168571
+ result.cert = fs.readFileSync(certPath, 'utf8');
168572
+ }
168573
+ if (ssl.key) {
168574
+ const keyPath = this.validateSslPath(ssl.key, 'client key');
168575
+ result.key = fs.readFileSync(keyPath, 'utf8');
168576
+ }
168577
+ return result;
168578
+ }
168579
+ validateSslPath(filePath, label) {
168580
+ const resolved = path.resolve(filePath);
168581
+ if (resolved !== path.normalize(resolved)) {
168582
+ throw new Error(`SSL ${label} path contains invalid sequences: ${filePath}`);
168583
+ }
168584
+ if (!fs.existsSync(resolved)) {
168585
+ throw new Error(`SSL ${label} not found: ${filePath}`);
168586
+ }
168587
+ return resolved;
168588
+ }
168589
+ async shutdown() {
168590
+ if (this.knex) {
168591
+ await this.knex.destroy();
168592
+ this.knex = null;
168593
+ }
168594
+ }
168595
+ async migrateSchema() {
168596
+ const knex = this.getKnex();
168597
+ const exists = await knex.schema.hasTable('schedules');
168598
+ if (!exists) {
168599
+ await knex.schema.createTable('schedules', table => {
168600
+ table.string('id', 36).primary();
168601
+ table.string('creator_id', 255).notNullable().index();
168602
+ table.string('creator_context', 255);
168603
+ table.string('creator_name', 255);
168604
+ table.string('timezone', 64).notNullable().defaultTo('UTC');
168605
+ table.string('schedule_expr', 255);
168606
+ table.bigInteger('run_at');
168607
+ table.boolean('is_recurring').notNullable();
168608
+ table.text('original_expression');
168609
+ table.string('workflow', 255);
168610
+ table.text('workflow_inputs');
168611
+ table.text('output_context');
168612
+ table.string('status', 20).notNullable().index();
168613
+ table.bigInteger('created_at').notNullable();
168614
+ table.bigInteger('last_run_at');
168615
+ table.bigInteger('next_run_at');
168616
+ table.integer('run_count').notNullable().defaultTo(0);
168617
+ table.integer('failure_count').notNullable().defaultTo(0);
168618
+ table.text('last_error');
168619
+ table.text('previous_response');
168620
+ table.index(['status', 'next_run_at']);
168621
+ });
168622
+ }
168623
+ // Create message_triggers table
168624
+ const triggersExist = await knex.schema.hasTable('message_triggers');
168625
+ if (!triggersExist) {
168626
+ await knex.schema.createTable('message_triggers', table => {
168627
+ table.string('id', 36).primary();
168628
+ table.string('creator_id', 255).notNullable().index();
168629
+ table.string('creator_context', 255);
168630
+ table.string('creator_name', 255);
168631
+ table.text('description');
168632
+ table.text('channels'); // JSON array
168633
+ table.text('from_users'); // JSON array
168634
+ table.boolean('from_bots').notNullable().defaultTo(false);
168635
+ table.text('contains'); // JSON array
168636
+ table.text('match_pattern');
168637
+ table.string('threads', 20).notNullable().defaultTo('any');
168638
+ table.string('workflow', 255).notNullable();
168639
+ table.text('inputs'); // JSON
168640
+ table.text('output_context'); // JSON
168641
+ table.string('status', 20).notNullable().defaultTo('active').index();
168642
+ table.boolean('enabled').notNullable().defaultTo(true);
168643
+ table.bigInteger('created_at').notNullable();
168644
+ });
168645
+ }
168646
+ // Create scheduler_locks table for distributed locking
168647
+ const locksExist = await knex.schema.hasTable('scheduler_locks');
168648
+ if (!locksExist) {
168649
+ await knex.schema.createTable('scheduler_locks', table => {
168650
+ table.string('lock_id', 255).primary();
168651
+ table.string('node_id', 255).notNullable();
168652
+ table.string('lock_token', 36).notNullable();
168653
+ table.bigInteger('acquired_at').notNullable();
168654
+ table.bigInteger('expires_at').notNullable();
168655
+ });
168656
+ }
168657
+ }
168658
+ getKnex() {
168659
+ if (!this.knex) {
168660
+ throw new Error('[KnexStore] Not initialized. Call initialize() first.');
168661
+ }
168662
+ return this.knex;
168663
+ }
168664
+ // --- CRUD ---
168665
+ async create(schedule) {
168666
+ const knex = this.getKnex();
168667
+ const newSchedule = {
168668
+ ...schedule,
168669
+ id: (0, uuid_1.v4)(),
168670
+ createdAt: Date.now(),
168671
+ runCount: 0,
168672
+ failureCount: 0,
168673
+ status: 'active',
168674
+ };
168675
+ await knex('schedules').insert(toInsertRow(newSchedule));
168676
+ logger_1.logger.info(`[KnexStore] Created schedule ${newSchedule.id} for user ${newSchedule.creatorId}`);
168677
+ return newSchedule;
168678
+ }
168679
+ async importSchedule(schedule) {
168680
+ const knex = this.getKnex();
168681
+ const existing = await knex('schedules').where('id', schedule.id).first();
168682
+ if (existing)
168683
+ return; // Already imported (idempotent)
168684
+ await knex('schedules').insert(toInsertRow(schedule));
168685
+ }
168686
+ async get(id) {
168687
+ const knex = this.getKnex();
168688
+ const row = await knex('schedules').where('id', id).first();
168689
+ return row ? fromDbRow(row) : undefined;
168690
+ }
168691
+ async update(id, patch) {
168692
+ const knex = this.getKnex();
168693
+ const existing = await knex('schedules').where('id', id).first();
168694
+ if (!existing)
168695
+ return undefined;
168696
+ const current = fromDbRow(existing);
168697
+ const updated = { ...current, ...patch, id: current.id };
168698
+ const row = toInsertRow(updated);
168699
+ // Remove id from update (PK cannot change)
168700
+ delete row.id;
168701
+ await knex('schedules').where('id', id).update(row);
168702
+ return updated;
168703
+ }
168704
+ async delete(id) {
168705
+ const knex = this.getKnex();
168706
+ const deleted = await knex('schedules').where('id', id).del();
168707
+ if (deleted > 0) {
168708
+ logger_1.logger.info(`[KnexStore] Deleted schedule ${id}`);
168709
+ return true;
168710
+ }
168711
+ return false;
168712
+ }
168713
+ // --- Queries ---
168714
+ async getByCreator(creatorId) {
168715
+ const knex = this.getKnex();
168716
+ const rows = await knex('schedules').where('creator_id', creatorId);
168717
+ return rows.map((r) => fromDbRow(r));
168718
+ }
168719
+ async getActiveSchedules() {
168720
+ const knex = this.getKnex();
168721
+ const rows = await knex('schedules').where('status', 'active');
168722
+ return rows.map((r) => fromDbRow(r));
168723
+ }
168724
+ async getDueSchedules(now) {
168725
+ const ts = now ?? Date.now();
168726
+ const knex = this.getKnex();
168727
+ // MSSQL uses 1/0 for booleans
168728
+ const bFalse = this.driver === 'mssql' ? 0 : false;
168729
+ const bTrue = this.driver === 'mssql' ? 1 : true;
168730
+ const rows = await knex('schedules')
168731
+ .where('status', 'active')
168732
+ .andWhere(function () {
168733
+ this.where(function () {
168734
+ this.where('is_recurring', bFalse)
168735
+ .whereNotNull('run_at')
168736
+ .where('run_at', '<=', ts);
168737
+ }).orWhere(function () {
168738
+ this.where('is_recurring', bTrue)
168739
+ .whereNotNull('next_run_at')
168740
+ .where('next_run_at', '<=', ts);
168741
+ });
168742
+ });
168743
+ return rows.map((r) => fromDbRow(r));
168744
+ }
168745
+ async findByWorkflow(creatorId, workflowName) {
168746
+ const knex = this.getKnex();
168747
+ const escaped = workflowName.toLowerCase().replace(/[%_\\]/g, '\\$&');
168748
+ const pattern = `%${escaped}%`;
168749
+ const rows = await knex('schedules')
168750
+ .where('creator_id', creatorId)
168751
+ .where('status', 'active')
168752
+ .whereRaw("LOWER(workflow) LIKE ? ESCAPE '\\'", [pattern]);
168753
+ return rows.map((r) => fromDbRow(r));
168754
+ }
168755
+ async getAll() {
168756
+ const knex = this.getKnex();
168757
+ const rows = await knex('schedules');
168758
+ return rows.map((r) => fromDbRow(r));
168759
+ }
168760
+ async getStats() {
168761
+ const knex = this.getKnex();
168762
+ // MSSQL uses 1/0 for booleans; PostgreSQL/MySQL accept both true/1
168763
+ const boolTrue = this.driver === 'mssql' ? '1' : 'true';
168764
+ const boolFalse = this.driver === 'mssql' ? '0' : 'false';
168765
+ const result = await knex('schedules')
168766
+ .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`))
168767
+ .first();
168768
+ return {
168769
+ total: Number(result.total) || 0,
168770
+ active: Number(result.active) || 0,
168771
+ paused: Number(result.paused) || 0,
168772
+ completed: Number(result.completed) || 0,
168773
+ failed: Number(result.failed) || 0,
168774
+ recurring: Number(result.recurring) || 0,
168775
+ oneTime: Number(result.one_time) || 0,
168776
+ };
168777
+ }
168778
+ async validateLimits(creatorId, isRecurring, limits) {
168779
+ const knex = this.getKnex();
168780
+ if (limits.maxGlobal) {
168781
+ const result = await knex('schedules').count('* as cnt').first();
168782
+ if (Number(result?.cnt) >= limits.maxGlobal) {
168783
+ throw new Error(`Global schedule limit reached (${limits.maxGlobal})`);
168784
+ }
168785
+ }
168786
+ if (limits.maxPerUser) {
168787
+ const result = await knex('schedules')
168788
+ .where('creator_id', creatorId)
168789
+ .count('* as cnt')
168790
+ .first();
168791
+ if (Number(result?.cnt) >= limits.maxPerUser) {
168792
+ throw new Error(`You have reached the maximum number of schedules (${limits.maxPerUser})`);
168793
+ }
168794
+ }
168795
+ if (isRecurring && limits.maxRecurringPerUser) {
168796
+ const bTrue = this.driver === 'mssql' ? 1 : true;
168797
+ const result = await knex('schedules')
168798
+ .where('creator_id', creatorId)
168799
+ .where('is_recurring', bTrue)
168800
+ .count('* as cnt')
168801
+ .first();
168802
+ if (Number(result?.cnt) >= limits.maxRecurringPerUser) {
168803
+ throw new Error(`You have reached the maximum number of recurring schedules (${limits.maxRecurringPerUser})`);
168804
+ }
168805
+ }
168806
+ }
168807
+ // --- HA Distributed Locking (via scheduler_locks table) ---
168808
+ async tryAcquireLock(lockId, nodeId, ttlSeconds) {
168809
+ const knex = this.getKnex();
168810
+ const now = Date.now();
168811
+ const expiresAt = now + ttlSeconds * 1000;
168812
+ const token = (0, uuid_1.v4)();
168813
+ // Step 1: Try to claim an existing expired lock
168814
+ const updated = await knex('scheduler_locks')
168815
+ .where('lock_id', lockId)
168816
+ .where('expires_at', '<', now)
168817
+ .update({
168818
+ node_id: nodeId,
168819
+ lock_token: token,
168820
+ acquired_at: now,
168821
+ expires_at: expiresAt,
168822
+ });
168823
+ if (updated > 0)
168824
+ return token;
168825
+ // Step 2: Try to INSERT a new lock row
168826
+ try {
168827
+ await knex('scheduler_locks').insert({
168828
+ lock_id: lockId,
168829
+ node_id: nodeId,
168830
+ lock_token: token,
168831
+ acquired_at: now,
168832
+ expires_at: expiresAt,
168833
+ });
168834
+ return token;
168835
+ }
168836
+ catch {
168837
+ // Unique constraint violation — another node holds the lock
168838
+ return null;
168839
+ }
168840
+ }
168841
+ async releaseLock(lockId, lockToken) {
168842
+ const knex = this.getKnex();
168843
+ await knex('scheduler_locks').where('lock_id', lockId).where('lock_token', lockToken).del();
168844
+ }
168845
+ async renewLock(lockId, lockToken, ttlSeconds) {
168846
+ const knex = this.getKnex();
168847
+ const now = Date.now();
168848
+ const expiresAt = now + ttlSeconds * 1000;
168849
+ const updated = await knex('scheduler_locks')
168850
+ .where('lock_id', lockId)
168851
+ .where('lock_token', lockToken)
168852
+ .update({ acquired_at: now, expires_at: expiresAt });
168853
+ return updated > 0;
168854
+ }
168855
+ async flush() {
168856
+ // No-op for server-based backends
168857
+ }
168858
+ // --- Message Trigger CRUD ---
168859
+ async createTrigger(trigger) {
168860
+ const knex = this.getKnex();
168861
+ const newTrigger = {
168862
+ ...trigger,
168863
+ id: (0, uuid_1.v4)(),
168864
+ createdAt: Date.now(),
168865
+ };
168866
+ await knex('message_triggers').insert(toTriggerInsertRow(newTrigger));
168867
+ logger_1.logger.info(`[KnexStore] Created trigger ${newTrigger.id} for user ${newTrigger.creatorId}`);
168868
+ return newTrigger;
168869
+ }
168870
+ async getTrigger(id) {
168871
+ const knex = this.getKnex();
168872
+ const row = await knex('message_triggers').where('id', id).first();
168873
+ return row ? fromTriggerRow(row) : undefined;
168874
+ }
168875
+ async updateTrigger(id, patch) {
168876
+ const knex = this.getKnex();
168877
+ const existing = await knex('message_triggers').where('id', id).first();
168878
+ if (!existing)
168879
+ return undefined;
168880
+ const current = fromTriggerRow(existing);
168881
+ const updated = {
168882
+ ...current,
168883
+ ...patch,
168884
+ id: current.id,
168885
+ createdAt: current.createdAt,
168886
+ };
168887
+ const row = toTriggerInsertRow(updated);
168888
+ delete row.id;
168889
+ await knex('message_triggers').where('id', id).update(row);
168890
+ return updated;
168891
+ }
168892
+ async deleteTrigger(id) {
168893
+ const knex = this.getKnex();
168894
+ const deleted = await knex('message_triggers').where('id', id).del();
168895
+ if (deleted > 0) {
168896
+ logger_1.logger.info(`[KnexStore] Deleted trigger ${id}`);
168897
+ return true;
168898
+ }
168899
+ return false;
168900
+ }
168901
+ async getTriggersByCreator(creatorId) {
168902
+ const knex = this.getKnex();
168903
+ const rows = await knex('message_triggers').where('creator_id', creatorId);
168904
+ return rows.map((r) => fromTriggerRow(r));
168905
+ }
168906
+ async getActiveTriggers() {
168907
+ const knex = this.getKnex();
168908
+ const rows = await knex('message_triggers')
168909
+ .where('status', 'active')
168910
+ .where('enabled', this.driver === 'mssql' ? 1 : true);
168911
+ return rows.map((r) => fromTriggerRow(r));
168912
+ }
168913
+ }
168914
+ exports.KnexStoreBackend = KnexStoreBackend;
168915
+
168916
+
167107
168917
  /***/ }),
167108
168918
 
167109
168919
  /***/ 83864:
@@ -168178,8 +169988,14 @@ ${end}`);
168178
169988
  // Immediately set our lock so subsequent callers will wait for us
168179
169989
  this.updateLocks.set(group, ourLock);
168180
169990
  try {
168181
- // Wait for the previous lock to complete (if any)
169991
+ // Wait for the previous update to complete (if any)
168182
169992
  if (existingLock) {
169993
+ logger_1.logger.info(`[github-frontend] Comment update for group "${group}" queued, waiting for previous update to finish...`);
169994
+ const queuedAt = Date.now();
169995
+ const reminder = setInterval(() => {
169996
+ const waited = Math.round((Date.now() - queuedAt) / 1000);
169997
+ logger_1.logger.info(`[github-frontend] Comment update for group "${group}" still queued (${waited}s).`);
169998
+ }, 10000);
168183
169999
  try {
168184
170000
  await existingLock;
168185
170001
  }
@@ -168187,6 +170003,13 @@ ${end}`);
168187
170003
  logger_1.logger.warn(`[github-frontend] Previous update for group ${group} failed: ${error instanceof Error ? error.message : error}`);
168188
170004
  // Continue with current update despite previous failure
168189
170005
  }
170006
+ finally {
170007
+ clearInterval(reminder);
170008
+ const waitedMs = Date.now() - queuedAt;
170009
+ if (waitedMs > 100) {
170010
+ logger_1.logger.info(`[github-frontend] Comment update for group "${group}" dequeued after ${Math.round(waitedMs / 1000)}s.`);
170011
+ }
170012
+ }
168190
170013
  }
168191
170014
  // Now perform our update
168192
170015
  await this.performGroupedCommentUpdate(ctx, comments, group, changedIds);
@@ -178117,6 +179940,35 @@ class OutputFormatters {
178117
179940
  exports.OutputFormatters = OutputFormatters;
178118
179941
 
178119
179942
 
179943
+ /***/ }),
179944
+
179945
+ /***/ 93866:
179946
+ /***/ ((__unused_webpack_module, exports) => {
179947
+
179948
+ "use strict";
179949
+
179950
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
179951
+ exports.DefaultPolicyEngine = void 0;
179952
+ /**
179953
+ * Default (no-op) policy engine — always allows everything.
179954
+ * Used when no enterprise license is present or policy is disabled.
179955
+ */
179956
+ class DefaultPolicyEngine {
179957
+ async initialize(_config) { }
179958
+ async evaluateCheckExecution(_checkId, _checkConfig) {
179959
+ return { allowed: true };
179960
+ }
179961
+ async evaluateToolInvocation(_serverName, _methodName, _transport) {
179962
+ return { allowed: true };
179963
+ }
179964
+ async evaluateCapabilities(_checkId, _capabilities) {
179965
+ return { allowed: true };
179966
+ }
179967
+ async shutdown() { }
179968
+ }
179969
+ exports.DefaultPolicyEngine = DefaultPolicyEngine;
179970
+
179971
+
178120
179972
  /***/ }),
178121
179973
 
178122
179974
  /***/ 96611:
@@ -200329,7 +202181,7 @@ class StateMachineExecutionEngine {
200329
202181
  try {
200330
202182
  logger_1.logger.debug(`[PolicyEngine] Loading enterprise policy engine (engine=${configWithTagFilter.policy.engine})`);
200331
202183
  // @ts-ignore — enterprise/ may not exist in OSS builds (caught at runtime)
200332
- const { loadEnterprisePolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(7065)));
202184
+ const { loadEnterprisePolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(87068)));
200333
202185
  context.policyEngine = await loadEnterprisePolicyEngine(configWithTagFilter.policy);
200334
202186
  logger_1.logger.debug(`[PolicyEngine] Initialized: ${context.policyEngine?.constructor?.name || 'unknown'}`);
200335
202187
  }
@@ -201271,20 +203123,7 @@ const memory_store_1 = __nccwpck_require__(18216);
201271
203123
  const human_id_1 = __nccwpck_require__(30920);
201272
203124
  const logger_1 = __nccwpck_require__(86999);
201273
203125
  const workspace_manager_1 = __nccwpck_require__(6134);
201274
- // Lazy-resolve DelegationManager from @probelabs/probe.
201275
- // The class may not be exported in older published versions, so we
201276
- // fall back gracefully to avoid breaking the build.
201277
- let _DelegationManager = null;
201278
- try {
201279
- // eslint-disable-next-line @typescript-eslint/no-var-requires
201280
- const probe = __nccwpck_require__(83841);
201281
- if (probe && typeof probe.DelegationManager === 'function') {
201282
- _DelegationManager = probe.DelegationManager;
201283
- }
201284
- }
201285
- catch {
201286
- // Not available — max_ai_concurrency will be silently ignored
201287
- }
203126
+ const fair_concurrency_limiter_1 = __nccwpck_require__(13656);
201288
203127
  /**
201289
203128
  * Apply minimal criticality defaults in-place.
201290
203129
  * This is a no-behavior-change scaffold: we only default missing
@@ -201358,14 +203197,40 @@ function buildEngineContextForRun(workingDirectory, config, prInfo, debug, maxPa
201358
203197
  // Initialize journal and memory
201359
203198
  const journal = new snapshot_store_1.ExecutionJournal();
201360
203199
  const memory = memory_store_1.MemoryStore.getInstance(clonedConfig.memory);
201361
- // Create shared AI concurrency limiter if configured
203200
+ // Create shared AI concurrency limiter if configured.
203201
+ // Uses a global singleton fair limiter: round-robin across sessions so
203202
+ // no single user/task can starve others.
201362
203203
  let sharedConcurrencyLimiter = undefined;
201363
- if (clonedConfig.max_ai_concurrency && _DelegationManager) {
201364
- sharedConcurrencyLimiter = new _DelegationManager({
201365
- maxConcurrent: clonedConfig.max_ai_concurrency,
201366
- maxPerSession: 999, // No per-session limit needed for global AI gating
201367
- });
201368
- logger_1.logger.debug(`[EngineContext] Created shared AI concurrency limiter (max: ${clonedConfig.max_ai_concurrency})`);
203204
+ const sessionId = (0, human_id_1.generateHumanId)();
203205
+ if (clonedConfig.max_ai_concurrency) {
203206
+ const fairLimiter = fair_concurrency_limiter_1.FairConcurrencyLimiter.getInstance(clonedConfig.max_ai_concurrency);
203207
+ // Bind this engine run's session ID into acquire/release so the fair limiter
203208
+ // knows which user/task each call belongs to. Probe calls acquire(null)
203209
+ // we intercept and inject our session ID.
203210
+ sharedConcurrencyLimiter = {
203211
+ async acquire(parentSessionId, _dbg, queueTimeout) {
203212
+ // Use visor session ID if probe didn't provide one
203213
+ const sid = parentSessionId || sessionId;
203214
+ return fairLimiter.acquire(sid, _dbg, queueTimeout);
203215
+ },
203216
+ release(parentSessionId, _dbg) {
203217
+ const sid = parentSessionId || sessionId;
203218
+ return fairLimiter.release(sid, _dbg);
203219
+ },
203220
+ tryAcquire(parentSessionId) {
203221
+ const sid = parentSessionId || sessionId;
203222
+ return fairLimiter.tryAcquire(sid);
203223
+ },
203224
+ getStats() {
203225
+ return fairLimiter.getStats();
203226
+ },
203227
+ shutdown() {
203228
+ // Don't destroy the singleton — other sessions may still use it
203229
+ },
203230
+ cleanup() {
203231
+ // Don't destroy the singleton — other sessions may still use it
203232
+ },
203233
+ };
201369
203234
  }
201370
203235
  return {
201371
203236
  mode: 'state-machine',
@@ -201375,7 +203240,7 @@ function buildEngineContextForRun(workingDirectory, config, prInfo, debug, maxPa
201375
203240
  memory,
201376
203241
  workingDirectory,
201377
203242
  originalWorkingDirectory: workingDirectory,
201378
- sessionId: (0, human_id_1.generateHumanId)(),
203243
+ sessionId,
201379
203244
  event: prInfo.eventType,
201380
203245
  debug,
201381
203246
  maxParallelism,
@@ -204805,7 +206670,27 @@ async function executeCheckGroup(checks, context, state, maxParallelism, emitEve
204805
206670
  catch { }
204806
206671
  // Wait if pool is full
204807
206672
  if (pool.length >= maxParallelism) {
204808
- await Promise.race(pool);
206673
+ const activeCount = pool.filter(p => !p._settled).length;
206674
+ logger_1.logger.info(`[LevelDispatch] Check pool full (${activeCount}/${maxParallelism} active). ` +
206675
+ `Check "${checkId}" queued, waiting for a slot...`);
206676
+ const queuedAt = Date.now();
206677
+ // Periodic reminder while waiting
206678
+ const reminder = setInterval(() => {
206679
+ const waited = Math.round((Date.now() - queuedAt) / 1000);
206680
+ const stillActive = pool.filter(p => !p._settled).length;
206681
+ logger_1.logger.info(`[LevelDispatch] Check "${checkId}" still queued (${waited}s). ` +
206682
+ `${stillActive}/${maxParallelism} slots busy.`);
206683
+ }, 15000);
206684
+ try {
206685
+ await Promise.race(pool);
206686
+ }
206687
+ finally {
206688
+ clearInterval(reminder);
206689
+ }
206690
+ const waitedMs = Date.now() - queuedAt;
206691
+ if (waitedMs > 100) {
206692
+ logger_1.logger.info(`[LevelDispatch] Check "${checkId}" dequeued after ${Math.round(waitedMs / 1000)}s wait.`);
206693
+ }
204809
206694
  // Remove completed promises
204810
206695
  pool.splice(0, pool.length, ...pool.filter(p => {
204811
206696
  const settled = p._settled;
@@ -210603,7 +212488,7 @@ async function initTelemetry(opts = {}) {
210603
212488
  const path = __nccwpck_require__(16928);
210604
212489
  const outDir = opts.file?.dir ||
210605
212490
  process.env.VISOR_TRACE_DIR ||
210606
- __nccwpck_require__.ab + "traces";
212491
+ path.join(process.cwd(), 'output', 'traces');
210607
212492
  fs.mkdirSync(outDir, { recursive: true });
210608
212493
  const ts = new Date().toISOString().replace(/[:.]/g, '-');
210609
212494
  process.env.VISOR_FALLBACK_TRACE_FILE = path.join(outDir, `run-${ts}.ndjson`);
@@ -210808,7 +212693,7 @@ async function shutdownTelemetry() {
210808
212693
  if (process.env.VISOR_TRACE_REPORT === 'true') {
210809
212694
  const fs = __nccwpck_require__(79896);
210810
212695
  const path = __nccwpck_require__(16928);
210811
- const outDir = process.env.VISOR_TRACE_DIR || __nccwpck_require__.ab + "traces";
212696
+ const outDir = process.env.VISOR_TRACE_DIR || path.join(process.cwd(), 'output', 'traces');
210812
212697
  if (!fs.existsSync(outDir))
210813
212698
  fs.mkdirSync(outDir, { recursive: true });
210814
212699
  const ts = new Date().toISOString().replace(/[:.]/g, '-');
@@ -211307,7 +213192,7 @@ function __getOrCreateNdjsonPath() {
211307
213192
  fs.mkdirSync(dir, { recursive: true });
211308
213193
  return __ndjsonPath;
211309
213194
  }
211310
- const outDir = process.env.VISOR_TRACE_DIR || __nccwpck_require__.ab + "traces";
213195
+ const outDir = process.env.VISOR_TRACE_DIR || path.join(process.cwd(), 'output', 'traces');
211311
213196
  if (!fs.existsSync(outDir))
211312
213197
  fs.mkdirSync(outDir, { recursive: true });
211313
213198
  if (!__ndjsonPath) {
@@ -220391,6 +222276,254 @@ class EnvironmentResolver {
220391
222276
  exports.EnvironmentResolver = EnvironmentResolver;
220392
222277
 
220393
222278
 
222279
+ /***/ }),
222280
+
222281
+ /***/ 13656:
222282
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
222283
+
222284
+ "use strict";
222285
+
222286
+ /**
222287
+ * Fair round-robin concurrency limiter.
222288
+ *
222289
+ * Single global limiter for all AI/delegation calls in the process.
222290
+ * Instead of FIFO (which lets one session hog all slots), this grants
222291
+ * slots in round-robin order across sessions so every user gets fair access.
222292
+ *
222293
+ * Usage:
222294
+ * const limiter = FairConcurrencyLimiter.getInstance(maxConcurrent);
222295
+ * await limiter.acquire(sessionId); // blocks until slot available
222296
+ * try { ... } finally { limiter.release(sessionId); }
222297
+ */
222298
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
222299
+ exports.FairConcurrencyLimiter = void 0;
222300
+ const logger_1 = __nccwpck_require__(86999);
222301
+ class FairConcurrencyLimiter {
222302
+ maxConcurrent;
222303
+ globalActive = 0;
222304
+ // Per-session FIFO queues
222305
+ sessionQueues = new Map();
222306
+ // Round-robin order of sessions with waiting entries
222307
+ roundRobinSessions = [];
222308
+ roundRobinIndex = 0;
222309
+ // Per-session active count (for stats)
222310
+ sessionActive = new Map();
222311
+ constructor(maxConcurrent) {
222312
+ this.maxConcurrent = maxConcurrent;
222313
+ }
222314
+ static getInstance(maxConcurrent) {
222315
+ const key = Symbol.for('visor.fairConcurrencyLimiter');
222316
+ let instance = globalThis[key];
222317
+ if (!instance) {
222318
+ instance = new FairConcurrencyLimiter(maxConcurrent);
222319
+ globalThis[key] = instance;
222320
+ logger_1.logger.info(`[FairLimiter] Created global fair concurrency limiter (max: ${maxConcurrent})`);
222321
+ }
222322
+ else if (instance.maxConcurrent !== maxConcurrent) {
222323
+ // Config changed — update max (live resize)
222324
+ const old = instance.maxConcurrent;
222325
+ instance.maxConcurrent = maxConcurrent;
222326
+ logger_1.logger.info(`[FairLimiter] Updated max concurrency: ${old} -> ${maxConcurrent}`);
222327
+ // Process queue in case new slots opened up
222328
+ instance._processQueue();
222329
+ }
222330
+ return instance;
222331
+ }
222332
+ /**
222333
+ * Try to acquire a slot immediately (non-blocking).
222334
+ */
222335
+ tryAcquire(sessionId) {
222336
+ if (this.globalActive >= this.maxConcurrent) {
222337
+ return false;
222338
+ }
222339
+ this.globalActive++;
222340
+ const sid = sessionId || '__anonymous__';
222341
+ this.sessionActive.set(sid, (this.sessionActive.get(sid) || 0) + 1);
222342
+ return true;
222343
+ }
222344
+ /**
222345
+ * Acquire a slot, waiting in a fair queue if necessary.
222346
+ * Sessions are served round-robin so no single session can starve others.
222347
+ */
222348
+ async acquire(sessionId, _debug, queueTimeout) {
222349
+ const sid = sessionId || '__anonymous__';
222350
+ // Fast path — slot available
222351
+ if (this.tryAcquire(sid)) {
222352
+ return true;
222353
+ }
222354
+ // Compute queue stats for logging
222355
+ const totalQueued = this._totalQueued();
222356
+ const sessionsWaiting = this.sessionQueues.size;
222357
+ const sessionQueueLen = this.sessionQueues.get(sid)?.length || 0;
222358
+ logger_1.logger.info(`[FairLimiter] Slot unavailable (${this.globalActive}/${this.maxConcurrent} active). ` +
222359
+ `Session "${sid}" queued (${sessionQueueLen} own + ${totalQueued} total across ${sessionsWaiting} sessions). Waiting...`);
222360
+ const queuedAt = Date.now();
222361
+ const effectiveTimeout = queueTimeout ?? 120000; // default 2 min
222362
+ return new Promise((resolve, reject) => {
222363
+ const entry = { resolve, reject, queuedAt };
222364
+ // Periodic reminder every 15s
222365
+ entry.reminder = setInterval(() => {
222366
+ const waited = Math.round((Date.now() - queuedAt) / 1000);
222367
+ const curQueued = this._totalQueued();
222368
+ const curSessions = this._waitingSessions();
222369
+ logger_1.logger.info(`[FairLimiter] Session "${sid}" still waiting (${waited}s). ` +
222370
+ `${this.globalActive}/${this.maxConcurrent} active, ` +
222371
+ `${curQueued} queued across ${curSessions} sessions.`);
222372
+ }, 15000);
222373
+ // Add to this session's queue
222374
+ let queue = this.sessionQueues.get(sid);
222375
+ if (!queue) {
222376
+ queue = [];
222377
+ this.sessionQueues.set(sid, queue);
222378
+ // Add to round-robin rotation
222379
+ this.roundRobinSessions.push(sid);
222380
+ }
222381
+ queue.push(entry);
222382
+ // Timeout
222383
+ if (effectiveTimeout > 0) {
222384
+ setTimeout(() => {
222385
+ // Remove from queue if still there
222386
+ const q = this.sessionQueues.get(sid);
222387
+ if (q) {
222388
+ const idx = q.indexOf(entry);
222389
+ if (idx !== -1) {
222390
+ q.splice(idx, 1);
222391
+ if (q.length === 0) {
222392
+ this.sessionQueues.delete(sid);
222393
+ this._removeFromRoundRobin(sid);
222394
+ }
222395
+ this._clearReminder(entry);
222396
+ reject(new Error(`[FairLimiter] Queue timeout: session "${sid}" waited ${effectiveTimeout}ms for a slot`));
222397
+ }
222398
+ }
222399
+ }, effectiveTimeout);
222400
+ }
222401
+ });
222402
+ }
222403
+ /**
222404
+ * Release a slot and grant the next one fairly (round-robin across sessions).
222405
+ */
222406
+ release(sessionId, _debug) {
222407
+ const sid = sessionId || '__anonymous__';
222408
+ this.globalActive = Math.max(0, this.globalActive - 1);
222409
+ const active = this.sessionActive.get(sid);
222410
+ if (active !== undefined) {
222411
+ if (active <= 1) {
222412
+ this.sessionActive.delete(sid);
222413
+ }
222414
+ else {
222415
+ this.sessionActive.set(sid, active - 1);
222416
+ }
222417
+ }
222418
+ this._processQueue();
222419
+ }
222420
+ /**
222421
+ * Round-robin queue processing: cycle through sessions and grant one slot per session per round.
222422
+ */
222423
+ _processQueue() {
222424
+ const toGrant = [];
222425
+ while (this.globalActive < this.maxConcurrent && this.roundRobinSessions.length > 0) {
222426
+ // Wrap index
222427
+ if (this.roundRobinIndex >= this.roundRobinSessions.length) {
222428
+ this.roundRobinIndex = 0;
222429
+ }
222430
+ const sid = this.roundRobinSessions[this.roundRobinIndex];
222431
+ const queue = this.sessionQueues.get(sid);
222432
+ if (!queue || queue.length === 0) {
222433
+ // Session has no more waiters — remove from rotation
222434
+ this.sessionQueues.delete(sid);
222435
+ this.roundRobinSessions.splice(this.roundRobinIndex, 1);
222436
+ // Don't increment index — next session slides into this position
222437
+ continue;
222438
+ }
222439
+ // Grant the oldest entry from this session
222440
+ const entry = queue.shift();
222441
+ if (queue.length === 0) {
222442
+ this.sessionQueues.delete(sid);
222443
+ this.roundRobinSessions.splice(this.roundRobinIndex, 1);
222444
+ // Don't increment — next session slides in
222445
+ }
222446
+ else {
222447
+ this.roundRobinIndex++;
222448
+ }
222449
+ this.globalActive++;
222450
+ this.sessionActive.set(sid, (this.sessionActive.get(sid) || 0) + 1);
222451
+ toGrant.push({ entry, sid });
222452
+ }
222453
+ // Resolve outside the loop to avoid reentrancy issues
222454
+ for (const { entry, sid } of toGrant) {
222455
+ this._clearReminder(entry);
222456
+ const waitedMs = Date.now() - entry.queuedAt;
222457
+ if (waitedMs > 100) {
222458
+ logger_1.logger.info(`[FairLimiter] Session "${sid}" acquired slot after ${Math.round(waitedMs / 1000)}s wait.`);
222459
+ }
222460
+ // Defer to next tick to avoid blocking event loop
222461
+ setImmediate(() => entry.resolve(true));
222462
+ }
222463
+ }
222464
+ getStats() {
222465
+ const perSession = {};
222466
+ const allSessions = new Set([...this.sessionActive.keys(), ...this.sessionQueues.keys()]);
222467
+ for (const sid of allSessions) {
222468
+ perSession[sid] = {
222469
+ active: this.sessionActive.get(sid) || 0,
222470
+ queued: this.sessionQueues.get(sid)?.length || 0,
222471
+ };
222472
+ }
222473
+ return {
222474
+ globalActive: this.globalActive,
222475
+ maxConcurrent: this.maxConcurrent,
222476
+ queueSize: this._totalQueued(),
222477
+ waitingSessions: this._waitingSessions(),
222478
+ perSession,
222479
+ };
222480
+ }
222481
+ cleanup() {
222482
+ // Clear all reminders
222483
+ for (const queue of this.sessionQueues.values()) {
222484
+ for (const entry of queue) {
222485
+ this._clearReminder(entry);
222486
+ }
222487
+ }
222488
+ this.sessionQueues.clear();
222489
+ this.roundRobinSessions = [];
222490
+ this.roundRobinIndex = 0;
222491
+ // Remove singleton
222492
+ const key = Symbol.for('visor.fairConcurrencyLimiter');
222493
+ delete globalThis[key];
222494
+ }
222495
+ shutdown() {
222496
+ this.cleanup();
222497
+ }
222498
+ // -- helpers --
222499
+ _totalQueued() {
222500
+ let n = 0;
222501
+ for (const q of this.sessionQueues.values())
222502
+ n += q.length;
222503
+ return n;
222504
+ }
222505
+ _waitingSessions() {
222506
+ return this.roundRobinSessions.length;
222507
+ }
222508
+ _removeFromRoundRobin(sid) {
222509
+ const idx = this.roundRobinSessions.indexOf(sid);
222510
+ if (idx !== -1) {
222511
+ this.roundRobinSessions.splice(idx, 1);
222512
+ if (this.roundRobinIndex > idx) {
222513
+ this.roundRobinIndex--;
222514
+ }
222515
+ }
222516
+ }
222517
+ _clearReminder(entry) {
222518
+ if (entry.reminder) {
222519
+ clearInterval(entry.reminder);
222520
+ entry.reminder = undefined;
222521
+ }
222522
+ }
222523
+ }
222524
+ exports.FairConcurrencyLimiter = FairConcurrencyLimiter;
222525
+
222526
+
220394
222527
  /***/ }),
220395
222528
 
220396
222529
  /***/ 69342:
@@ -220789,7 +222922,22 @@ async function acquirePromptLock() {
220789
222922
  activePrompt = true;
220790
222923
  return;
220791
222924
  }
220792
- await new Promise(resolve => waiters.push(resolve));
222925
+ console.error(`[human-input] Prompt queued, waiting for active prompt to finish (${waiters.length} already waiting).`);
222926
+ const queuedAt = Date.now();
222927
+ const reminder = setInterval(() => {
222928
+ const waited = Math.round((Date.now() - queuedAt) / 1000);
222929
+ console.error(`[human-input] Still waiting for prompt lock (${waited}s, ${waiters.length} in queue).`);
222930
+ }, 10000);
222931
+ try {
222932
+ await new Promise(resolve => waiters.push(resolve));
222933
+ }
222934
+ finally {
222935
+ clearInterval(reminder);
222936
+ const waitedMs = Date.now() - queuedAt;
222937
+ if (waitedMs > 100) {
222938
+ console.error(`[human-input] Prompt lock acquired after ${Math.round(waitedMs / 1000)}s wait.`);
222939
+ }
222940
+ }
220793
222941
  activePrompt = true;
220794
222942
  }
220795
222943
  function releasePromptLock() {
@@ -225392,22 +227540,6 @@ class WorkflowRegistry {
225392
227540
  exports.WorkflowRegistry = WorkflowRegistry;
225393
227541
 
225394
227542
 
225395
- /***/ }),
225396
-
225397
- /***/ 7065:
225398
- /***/ ((module) => {
225399
-
225400
- module.exports = eval("require")("./enterprise/loader");
225401
-
225402
-
225403
- /***/ }),
225404
-
225405
- /***/ 71370:
225406
- /***/ ((module) => {
225407
-
225408
- module.exports = eval("require")("./enterprise/policy/policy-input-builder");
225409
-
225410
-
225411
227543
  /***/ }),
225412
227544
 
225413
227545
  /***/ 18327:
@@ -396151,7 +398283,7 @@ module.exports = /*#__PURE__*/JSON.parse('{"100":"Continue","101":"Switching Pro
396151
398283
  /***/ ((module) => {
396152
398284
 
396153
398285
  "use strict";
396154
- module.exports = /*#__PURE__*/JSON.parse('{"name":"@probelabs/visor","version":"0.1.166","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-rc280","@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"]}}');
398286
+ 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-rc280","@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"]}}');
396155
398287
 
396156
398288
  /***/ })
396157
398289