@probelabs/visor 0.1.173 → 0.1.174-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 (105) hide show
  1. package/dist/docs/dashboards/README.md +73 -26
  2. package/dist/docs/dashboards/grafana-visor-overview.json +435 -15
  3. package/dist/docs/telemetry-reference.md +387 -0
  4. package/dist/docs/telemetry-setup.md +2 -0
  5. package/dist/generated/config-schema.d.ts +277 -7
  6. package/dist/generated/config-schema.d.ts.map +1 -1
  7. package/dist/generated/config-schema.json +3803 -0
  8. package/dist/index.js +2202 -51
  9. package/dist/sdk/{a2a-frontend-VHOQ45CR.mjs → a2a-frontend-FUJRKHJB.mjs} +3 -3
  10. package/dist/sdk/{check-provider-registry-65GO3SCO.mjs → check-provider-registry-53C2ZIXJ.mjs} +7 -7
  11. package/dist/sdk/{check-provider-registry-75O5XJMA.mjs → check-provider-registry-UPQNHHFF.mjs} +7 -7
  12. package/dist/sdk/{chunk-Y5MEQW2W.mjs → chunk-2PL2YH3B.mjs} +19 -19
  13. package/dist/sdk/{chunk-4TV2CVVI.mjs → chunk-34QX63WK.mjs} +16 -14
  14. package/dist/sdk/chunk-34QX63WK.mjs.map +1 -0
  15. package/dist/sdk/{chunk-2HXOGRAS.mjs → chunk-65SHRIQF.mjs} +3 -3
  16. package/dist/sdk/{chunk-2HXOGRAS.mjs.map → chunk-65SHRIQF.mjs.map} +1 -1
  17. package/dist/sdk/{chunk-VVHALCWV.mjs → chunk-EFNNJIMY.mjs} +3 -3
  18. package/dist/sdk/{chunk-7CWJNSL2.mjs → chunk-GKSSG5IM.mjs} +20 -20
  19. package/dist/sdk/{chunk-7CWJNSL2.mjs.map → chunk-GKSSG5IM.mjs.map} +1 -1
  20. package/dist/sdk/{chunk-HZEXCJGA.mjs → chunk-W4KCJM6J.mjs} +282 -8
  21. package/dist/sdk/chunk-W4KCJM6J.mjs.map +1 -0
  22. package/dist/sdk/{chunk-GVPMO6QD.mjs → chunk-WJIV7MKY.mjs} +3 -3
  23. package/dist/sdk/{config-UXRHADSE.mjs → config-BVL3KFMB.mjs} +2 -2
  24. package/dist/sdk/{failure-condition-evaluator-Q4KNMX6F.mjs → failure-condition-evaluator-DL6H57NX.mjs} +4 -4
  25. package/dist/sdk/{github-frontend-56UQTA47.mjs → github-frontend-F2YCPK6H.mjs} +4 -4
  26. package/dist/sdk/{host-QRGXXRDA.mjs → host-6TBS44ER.mjs} +3 -3
  27. package/dist/sdk/{host-VYPJ2UGQ.mjs → host-LRWIKURZ.mjs} +3 -3
  28. package/dist/sdk/knex-store-QCEW4I4R.mjs +527 -0
  29. package/dist/sdk/knex-store-QCEW4I4R.mjs.map +1 -0
  30. package/dist/sdk/loader-Q7K76ZIY.mjs +89 -0
  31. package/dist/sdk/loader-Q7K76ZIY.mjs.map +1 -0
  32. package/dist/sdk/{metrics-FU2G5SZ2.mjs → metrics-JTOG2HNO.mjs} +2 -2
  33. package/dist/sdk/opa-policy-engine-QCSSIMUF.mjs +655 -0
  34. package/dist/sdk/opa-policy-engine-QCSSIMUF.mjs.map +1 -0
  35. package/dist/sdk/{routing-DBQHPP2O.mjs → routing-GF2CF3JT.mjs} +5 -5
  36. package/dist/sdk/{schedule-tool-MHICRNCI.mjs → schedule-tool-5KDBDCFO.mjs} +7 -7
  37. package/dist/sdk/{schedule-tool-VRLX54J5.mjs → schedule-tool-UMDRCNO5.mjs} +7 -7
  38. package/dist/sdk/{schedule-tool-handler-3ES4WON7.mjs → schedule-tool-handler-5EPTHBLS.mjs} +7 -7
  39. package/dist/sdk/{schedule-tool-handler-FQGAWC5N.mjs → schedule-tool-handler-MUF5V36L.mjs} +7 -7
  40. package/dist/sdk/sdk.d.mts +137 -133
  41. package/dist/sdk/sdk.d.ts +137 -133
  42. package/dist/sdk/sdk.js +1952 -302
  43. package/dist/sdk/sdk.js.map +1 -1
  44. package/dist/sdk/sdk.mjs +6 -6
  45. package/dist/sdk/{trace-helpers-UKMYHQIK.mjs → trace-helpers-FKM2MEDW.mjs} +3 -3
  46. package/dist/sdk/validator-XTZJZZJH.mjs +134 -0
  47. package/dist/sdk/validator-XTZJZZJH.mjs.map +1 -0
  48. package/dist/sdk/{workflow-check-provider-F5DTEX6E.mjs → workflow-check-provider-EWMZEEES.mjs} +7 -7
  49. package/dist/sdk/{workflow-check-provider-VEOVTCVU.mjs → workflow-check-provider-RQUCBAYY.mjs} +7 -7
  50. package/dist/telemetry/metrics.d.ts.map +1 -1
  51. package/dist/types/config.d.ts +5 -4
  52. package/dist/types/config.d.ts.map +1 -1
  53. package/package.json +2 -2
  54. package/dist/output/traces/run-2026-03-09T15-21-25-122Z.ndjson +0 -138
  55. package/dist/output/traces/run-2026-03-09T15-22-05-255Z.ndjson +0 -2280
  56. package/dist/sdk/a2a-frontend-7CYN3X7M.mjs +0 -1658
  57. package/dist/sdk/a2a-frontend-VHOQ45CR.mjs.map +0 -1
  58. package/dist/sdk/check-provider-registry-DBTS7OXY.mjs +0 -30
  59. package/dist/sdk/chunk-4TV2CVVI.mjs.map +0 -1
  60. package/dist/sdk/chunk-AV6KML52.mjs +0 -45016
  61. package/dist/sdk/chunk-AV6KML52.mjs.map +0 -1
  62. package/dist/sdk/chunk-HZEXCJGA.mjs.map +0 -1
  63. package/dist/sdk/chunk-LTHHE6Z5.mjs +0 -516
  64. package/dist/sdk/chunk-LTHHE6Z5.mjs.map +0 -1
  65. package/dist/sdk/chunk-VK7FUBBU.mjs +0 -739
  66. package/dist/sdk/chunk-VVHALCWV.mjs.map +0 -1
  67. package/dist/sdk/chunk-WYFQQ445.mjs +0 -1502
  68. package/dist/sdk/chunk-WYFQQ445.mjs.map +0 -1
  69. package/dist/sdk/failure-condition-evaluator-SNR5XLGN.mjs +0 -18
  70. package/dist/sdk/github-frontend-OOP26667.mjs +0 -1386
  71. package/dist/sdk/github-frontend-OOP26667.mjs.map +0 -1
  72. package/dist/sdk/routing-ZAUCS3HJ.mjs +0 -26
  73. package/dist/sdk/schedule-tool-2FIVKPVJ.mjs +0 -36
  74. package/dist/sdk/schedule-tool-handler-FQGAWC5N.mjs.map +0 -1
  75. package/dist/sdk/schedule-tool-handler-KYUHU4JR.mjs +0 -40
  76. package/dist/sdk/schedule-tool-handler-KYUHU4JR.mjs.map +0 -1
  77. package/dist/sdk/trace-helpers-UKMYHQIK.mjs.map +0 -1
  78. package/dist/sdk/trace-helpers-ZFDJ55SH.mjs +0 -29
  79. package/dist/sdk/trace-helpers-ZFDJ55SH.mjs.map +0 -1
  80. package/dist/sdk/workflow-check-provider-5KQTXKWS.mjs +0 -30
  81. package/dist/sdk/workflow-check-provider-5KQTXKWS.mjs.map +0 -1
  82. package/dist/sdk/workflow-check-provider-F5DTEX6E.mjs.map +0 -1
  83. package/dist/sdk/workflow-check-provider-VEOVTCVU.mjs.map +0 -1
  84. package/dist/traces/run-2026-03-09T15-21-25-122Z.ndjson +0 -138
  85. package/dist/traces/run-2026-03-09T15-22-05-255Z.ndjson +0 -2280
  86. /package/dist/sdk/{a2a-frontend-7CYN3X7M.mjs.map → a2a-frontend-FUJRKHJB.mjs.map} +0 -0
  87. /package/dist/sdk/{check-provider-registry-65GO3SCO.mjs.map → check-provider-registry-53C2ZIXJ.mjs.map} +0 -0
  88. /package/dist/sdk/{check-provider-registry-75O5XJMA.mjs.map → check-provider-registry-UPQNHHFF.mjs.map} +0 -0
  89. /package/dist/sdk/{chunk-Y5MEQW2W.mjs.map → chunk-2PL2YH3B.mjs.map} +0 -0
  90. /package/dist/sdk/{chunk-VK7FUBBU.mjs.map → chunk-EFNNJIMY.mjs.map} +0 -0
  91. /package/dist/sdk/{chunk-GVPMO6QD.mjs.map → chunk-WJIV7MKY.mjs.map} +0 -0
  92. /package/dist/sdk/{check-provider-registry-DBTS7OXY.mjs.map → config-BVL3KFMB.mjs.map} +0 -0
  93. /package/dist/sdk/{config-UXRHADSE.mjs.map → failure-condition-evaluator-DL6H57NX.mjs.map} +0 -0
  94. /package/dist/sdk/{github-frontend-56UQTA47.mjs.map → github-frontend-F2YCPK6H.mjs.map} +0 -0
  95. /package/dist/sdk/{host-QRGXXRDA.mjs.map → host-6TBS44ER.mjs.map} +0 -0
  96. /package/dist/sdk/{host-VYPJ2UGQ.mjs.map → host-LRWIKURZ.mjs.map} +0 -0
  97. /package/dist/sdk/{failure-condition-evaluator-Q4KNMX6F.mjs.map → metrics-JTOG2HNO.mjs.map} +0 -0
  98. /package/dist/sdk/{failure-condition-evaluator-SNR5XLGN.mjs.map → routing-GF2CF3JT.mjs.map} +0 -0
  99. /package/dist/sdk/{metrics-FU2G5SZ2.mjs.map → schedule-tool-5KDBDCFO.mjs.map} +0 -0
  100. /package/dist/sdk/{routing-DBQHPP2O.mjs.map → schedule-tool-UMDRCNO5.mjs.map} +0 -0
  101. /package/dist/sdk/{routing-ZAUCS3HJ.mjs.map → schedule-tool-handler-5EPTHBLS.mjs.map} +0 -0
  102. /package/dist/sdk/{schedule-tool-2FIVKPVJ.mjs.map → schedule-tool-handler-MUF5V36L.mjs.map} +0 -0
  103. /package/dist/sdk/{schedule-tool-MHICRNCI.mjs.map → trace-helpers-FKM2MEDW.mjs.map} +0 -0
  104. /package/dist/sdk/{schedule-tool-VRLX54J5.mjs.map → workflow-check-provider-EWMZEEES.mjs.map} +0 -0
  105. /package/dist/sdk/{schedule-tool-handler-3ES4WON7.mjs.map → workflow-check-provider-RQUCBAYY.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.173';
3
- process.env.PROBE_VERSION = '0.6.0-rc290';
4
- process.env.VISOR_COMMIT_SHA = 'f90bea6e5af9d8ccb75f03ee9ab69a258e061329';
5
- process.env.VISOR_COMMIT_SHORT = 'f90bea6e';
2
+ process.env.VISOR_VERSION = '0.1.174';
3
+ process.env.PROBE_VERSION = '0.6.0-rc291';
4
+ process.env.VISOR_COMMIT_SHA = 'e8809d0dd7ef9584a6c687826df911bbc12d7fbd';
5
+ process.env.VISOR_COMMIT_SHORT = 'e8809d0';
6
6
  /******/ (() => { // webpackBootstrap
7
7
  /******/ var __webpack_modules__ = ({
8
8
 
@@ -302951,7 +302951,7 @@ async function handleDumpPolicyInput(checkId, argv) {
302951
302951
  let PolicyInputBuilder;
302952
302952
  try {
302953
302953
  // @ts-ignore — enterprise/ may not exist in OSS builds (caught at runtime)
302954
- const mod = await Promise.resolve().then(() => __importStar(__nccwpck_require__(71370)));
302954
+ const mod = await Promise.resolve().then(() => __importStar(__nccwpck_require__(17117)));
302955
302955
  PolicyInputBuilder = mod.PolicyInputBuilder;
302956
302956
  }
302957
302957
  catch {
@@ -311018,6 +311018,1810 @@ class EmailPollingRunner {
311018
311018
  exports.EmailPollingRunner = EmailPollingRunner;
311019
311019
 
311020
311020
 
311021
+ /***/ }),
311022
+
311023
+ /***/ 50069:
311024
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
311025
+
311026
+ "use strict";
311027
+
311028
+ /**
311029
+ * Copyright (c) ProbeLabs. All rights reserved.
311030
+ * Licensed under the Elastic License 2.0; you may not use this file except
311031
+ * in compliance with the Elastic License 2.0.
311032
+ */
311033
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
311034
+ if (k2 === undefined) k2 = k;
311035
+ var desc = Object.getOwnPropertyDescriptor(m, k);
311036
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
311037
+ desc = { enumerable: true, get: function() { return m[k]; } };
311038
+ }
311039
+ Object.defineProperty(o, k2, desc);
311040
+ }) : (function(o, m, k, k2) {
311041
+ if (k2 === undefined) k2 = k;
311042
+ o[k2] = m[k];
311043
+ }));
311044
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
311045
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
311046
+ }) : function(o, v) {
311047
+ o["default"] = v;
311048
+ });
311049
+ var __importStar = (this && this.__importStar) || (function () {
311050
+ var ownKeys = function(o) {
311051
+ ownKeys = Object.getOwnPropertyNames || function (o) {
311052
+ var ar = [];
311053
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
311054
+ return ar;
311055
+ };
311056
+ return ownKeys(o);
311057
+ };
311058
+ return function (mod) {
311059
+ if (mod && mod.__esModule) return mod;
311060
+ var result = {};
311061
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
311062
+ __setModuleDefault(result, mod);
311063
+ return result;
311064
+ };
311065
+ })();
311066
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
311067
+ exports.LicenseValidator = void 0;
311068
+ const crypto = __importStar(__nccwpck_require__(76982));
311069
+ const fs = __importStar(__nccwpck_require__(79896));
311070
+ const path = __importStar(__nccwpck_require__(16928));
311071
+ class LicenseValidator {
311072
+ /** Ed25519 public key for license verification (PEM format). */
311073
+ static PUBLIC_KEY = '-----BEGIN PUBLIC KEY-----\n' +
311074
+ 'MCowBQYDK2VwAyEAI/Zd08EFmgIdrDm/HXd0l3/5GBt7R1PrdvhdmEXhJlU=\n' +
311075
+ '-----END PUBLIC KEY-----\n';
311076
+ cache = null;
311077
+ static CACHE_TTL = 5 * 60 * 1000; // 5 minutes
311078
+ static GRACE_PERIOD = 72 * 3600 * 1000; // 72 hours after expiry
311079
+ /**
311080
+ * Load and validate license from environment or file.
311081
+ *
311082
+ * Resolution order:
311083
+ * 1. VISOR_LICENSE env var (JWT string)
311084
+ * 2. VISOR_LICENSE_FILE env var (path to file)
311085
+ * 3. .visor-license in project root (cwd)
311086
+ * 4. .visor-license in ~/.config/visor/
311087
+ */
311088
+ async loadAndValidate() {
311089
+ // Return cached result if still fresh
311090
+ if (this.cache && Date.now() - this.cache.validatedAt < LicenseValidator.CACHE_TTL) {
311091
+ return this.cache.payload;
311092
+ }
311093
+ const token = this.resolveToken();
311094
+ if (!token)
311095
+ return null;
311096
+ const payload = this.verifyAndDecode(token);
311097
+ if (!payload)
311098
+ return null;
311099
+ this.cache = { payload, validatedAt: Date.now() };
311100
+ return payload;
311101
+ }
311102
+ /** Check if a specific feature is licensed */
311103
+ hasFeature(feature) {
311104
+ if (!this.cache)
311105
+ return false;
311106
+ return this.cache.payload.features.includes(feature);
311107
+ }
311108
+ /** Check if license is valid (with grace period) */
311109
+ isValid() {
311110
+ if (!this.cache)
311111
+ return false;
311112
+ const now = Date.now();
311113
+ const expiryMs = this.cache.payload.exp * 1000;
311114
+ return now < expiryMs + LicenseValidator.GRACE_PERIOD;
311115
+ }
311116
+ /** Check if the license is within its grace period (expired but still valid) */
311117
+ isInGracePeriod() {
311118
+ if (!this.cache)
311119
+ return false;
311120
+ const now = Date.now();
311121
+ const expiryMs = this.cache.payload.exp * 1000;
311122
+ return now >= expiryMs && now < expiryMs + LicenseValidator.GRACE_PERIOD;
311123
+ }
311124
+ resolveToken() {
311125
+ // 1. Direct env var
311126
+ if (process.env.VISOR_LICENSE) {
311127
+ return process.env.VISOR_LICENSE.trim();
311128
+ }
311129
+ // 2. File path from env (validate against path traversal)
311130
+ if (process.env.VISOR_LICENSE_FILE) {
311131
+ // path.resolve() produces an absolute path with all '..' segments resolved,
311132
+ // so a separate resolved.includes('..') check is unnecessary.
311133
+ const resolved = path.resolve(process.env.VISOR_LICENSE_FILE);
311134
+ const home = process.env.HOME || process.env.USERPROFILE || '';
311135
+ const allowedPrefixes = [path.normalize(process.cwd())];
311136
+ if (home)
311137
+ allowedPrefixes.push(path.normalize(path.join(home, '.config', 'visor')));
311138
+ // Resolve symlinks so an attacker cannot create a symlink inside an
311139
+ // allowed prefix that points to an arbitrary file outside it.
311140
+ let realPath;
311141
+ try {
311142
+ realPath = fs.realpathSync(resolved);
311143
+ }
311144
+ catch {
311145
+ return null; // File doesn't exist or isn't accessible
311146
+ }
311147
+ const isSafe = allowedPrefixes.some(prefix => realPath === prefix || realPath.startsWith(prefix + path.sep));
311148
+ if (!isSafe)
311149
+ return null;
311150
+ return this.readFile(realPath);
311151
+ }
311152
+ // 3. .visor-license in cwd
311153
+ const cwdPath = path.join(process.cwd(), '.visor-license');
311154
+ const cwdToken = this.readFile(cwdPath);
311155
+ if (cwdToken)
311156
+ return cwdToken;
311157
+ // 4. ~/.config/visor/.visor-license
311158
+ const home = process.env.HOME || process.env.USERPROFILE || '';
311159
+ if (home) {
311160
+ const configPath = path.join(home, '.config', 'visor', '.visor-license');
311161
+ const configToken = this.readFile(configPath);
311162
+ if (configToken)
311163
+ return configToken;
311164
+ }
311165
+ return null;
311166
+ }
311167
+ readFile(filePath) {
311168
+ try {
311169
+ return fs.readFileSync(filePath, 'utf-8').trim();
311170
+ }
311171
+ catch {
311172
+ return null;
311173
+ }
311174
+ }
311175
+ verifyAndDecode(token) {
311176
+ try {
311177
+ const parts = token.split('.');
311178
+ if (parts.length !== 3)
311179
+ return null;
311180
+ const [headerB64, payloadB64, signatureB64] = parts;
311181
+ // Decode header to verify algorithm
311182
+ const header = JSON.parse(Buffer.from(headerB64, 'base64url').toString());
311183
+ if (header.alg !== 'EdDSA')
311184
+ return null;
311185
+ // Verify signature
311186
+ const data = `${headerB64}.${payloadB64}`;
311187
+ const signature = Buffer.from(signatureB64, 'base64url');
311188
+ const publicKey = crypto.createPublicKey(LicenseValidator.PUBLIC_KEY);
311189
+ // Validate that the loaded public key is actually Ed25519 (OID 1.3.101.112).
311190
+ // This prevents algorithm-confusion attacks if the embedded key were ever
311191
+ // swapped to a different type.
311192
+ if (publicKey.asymmetricKeyType !== 'ed25519') {
311193
+ return null;
311194
+ }
311195
+ // Ed25519 verification: algorithm must be null because EdDSA performs its
311196
+ // own internal hashing (SHA-512) — passing a digest algorithm here would
311197
+ // cause Node.js to throw. The key type is validated above.
311198
+ const isValid = crypto.verify(null, Buffer.from(data), publicKey, signature);
311199
+ if (!isValid)
311200
+ return null;
311201
+ // Decode payload
311202
+ const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString());
311203
+ // Validate required fields
311204
+ if (!payload.org ||
311205
+ !Array.isArray(payload.features) ||
311206
+ typeof payload.exp !== 'number' ||
311207
+ typeof payload.iat !== 'number' ||
311208
+ !payload.sub) {
311209
+ return null;
311210
+ }
311211
+ // Check expiry (with grace period)
311212
+ const now = Date.now();
311213
+ const expiryMs = payload.exp * 1000;
311214
+ if (now >= expiryMs + LicenseValidator.GRACE_PERIOD) {
311215
+ return null;
311216
+ }
311217
+ return payload;
311218
+ }
311219
+ catch {
311220
+ return null;
311221
+ }
311222
+ }
311223
+ }
311224
+ exports.LicenseValidator = LicenseValidator;
311225
+
311226
+
311227
+ /***/ }),
311228
+
311229
+ /***/ 87068:
311230
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
311231
+
311232
+ "use strict";
311233
+
311234
+ /**
311235
+ * Copyright (c) ProbeLabs. All rights reserved.
311236
+ * Licensed under the Elastic License 2.0; you may not use this file except
311237
+ * in compliance with the Elastic License 2.0.
311238
+ */
311239
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
311240
+ if (k2 === undefined) k2 = k;
311241
+ var desc = Object.getOwnPropertyDescriptor(m, k);
311242
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
311243
+ desc = { enumerable: true, get: function() { return m[k]; } };
311244
+ }
311245
+ Object.defineProperty(o, k2, desc);
311246
+ }) : (function(o, m, k, k2) {
311247
+ if (k2 === undefined) k2 = k;
311248
+ o[k2] = m[k];
311249
+ }));
311250
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
311251
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
311252
+ }) : function(o, v) {
311253
+ o["default"] = v;
311254
+ });
311255
+ var __importStar = (this && this.__importStar) || (function () {
311256
+ var ownKeys = function(o) {
311257
+ ownKeys = Object.getOwnPropertyNames || function (o) {
311258
+ var ar = [];
311259
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
311260
+ return ar;
311261
+ };
311262
+ return ownKeys(o);
311263
+ };
311264
+ return function (mod) {
311265
+ if (mod && mod.__esModule) return mod;
311266
+ var result = {};
311267
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
311268
+ __setModuleDefault(result, mod);
311269
+ return result;
311270
+ };
311271
+ })();
311272
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
311273
+ exports.loadEnterprisePolicyEngine = loadEnterprisePolicyEngine;
311274
+ exports.loadEnterpriseStoreBackend = loadEnterpriseStoreBackend;
311275
+ const default_engine_1 = __nccwpck_require__(93866);
311276
+ /**
311277
+ * Load the enterprise policy engine if licensed, otherwise return the default no-op engine.
311278
+ *
311279
+ * This is the sole import boundary between OSS and enterprise code. Core code
311280
+ * must only import from this module (via dynamic `await import()`), never from
311281
+ * individual enterprise submodules.
311282
+ */
311283
+ async function loadEnterprisePolicyEngine(config) {
311284
+ try {
311285
+ const { LicenseValidator } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(50069)));
311286
+ const validator = new LicenseValidator();
311287
+ const license = await validator.loadAndValidate();
311288
+ if (!license || !validator.hasFeature('policy')) {
311289
+ return new default_engine_1.DefaultPolicyEngine();
311290
+ }
311291
+ if (validator.isInGracePeriod()) {
311292
+ // eslint-disable-next-line no-console
311293
+ console.warn('[visor:enterprise] License has expired but is within the 72-hour grace period. ' +
311294
+ 'Please renew your license.');
311295
+ }
311296
+ const { OpaPolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(39530)));
311297
+ const engine = new OpaPolicyEngine(config);
311298
+ await engine.initialize(config);
311299
+ return engine;
311300
+ }
311301
+ catch (err) {
311302
+ // Enterprise code not available or initialization failed
311303
+ const msg = err instanceof Error ? err.message : String(err);
311304
+ try {
311305
+ const { logger } = __nccwpck_require__(86999);
311306
+ logger.warn(`[PolicyEngine] Enterprise policy init failed, falling back to default: ${msg}`);
311307
+ }
311308
+ catch {
311309
+ // silent
311310
+ }
311311
+ return new default_engine_1.DefaultPolicyEngine();
311312
+ }
311313
+ }
311314
+ /**
311315
+ * Load the enterprise schedule store backend if licensed.
311316
+ *
311317
+ * @param driver Database driver ('postgresql', 'mysql', or 'mssql')
311318
+ * @param storageConfig Storage configuration with connection details
311319
+ * @param haConfig Optional HA configuration
311320
+ * @throws Error if enterprise license is not available or missing 'scheduler-sql' feature
311321
+ */
311322
+ async function loadEnterpriseStoreBackend(driver, storageConfig, haConfig) {
311323
+ const { LicenseValidator } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(50069)));
311324
+ const validator = new LicenseValidator();
311325
+ const license = await validator.loadAndValidate();
311326
+ if (!license || !validator.hasFeature('scheduler-sql')) {
311327
+ throw new Error(`The ${driver} schedule storage driver requires a Visor Enterprise license ` +
311328
+ `with the 'scheduler-sql' feature. Please upgrade or use driver: 'sqlite' (default).`);
311329
+ }
311330
+ if (validator.isInGracePeriod()) {
311331
+ // eslint-disable-next-line no-console
311332
+ console.warn('[visor:enterprise] License has expired but is within the 72-hour grace period. ' +
311333
+ 'Please renew your license.');
311334
+ }
311335
+ const { KnexStoreBackend } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(63737)));
311336
+ return new KnexStoreBackend(driver, storageConfig, haConfig);
311337
+ }
311338
+
311339
+
311340
+ /***/ }),
311341
+
311342
+ /***/ 628:
311343
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
311344
+
311345
+ "use strict";
311346
+
311347
+ /**
311348
+ * Copyright (c) ProbeLabs. All rights reserved.
311349
+ * Licensed under the Elastic License 2.0; you may not use this file except
311350
+ * in compliance with the Elastic License 2.0.
311351
+ */
311352
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
311353
+ if (k2 === undefined) k2 = k;
311354
+ var desc = Object.getOwnPropertyDescriptor(m, k);
311355
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
311356
+ desc = { enumerable: true, get: function() { return m[k]; } };
311357
+ }
311358
+ Object.defineProperty(o, k2, desc);
311359
+ }) : (function(o, m, k, k2) {
311360
+ if (k2 === undefined) k2 = k;
311361
+ o[k2] = m[k];
311362
+ }));
311363
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
311364
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
311365
+ }) : function(o, v) {
311366
+ o["default"] = v;
311367
+ });
311368
+ var __importStar = (this && this.__importStar) || (function () {
311369
+ var ownKeys = function(o) {
311370
+ ownKeys = Object.getOwnPropertyNames || function (o) {
311371
+ var ar = [];
311372
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
311373
+ return ar;
311374
+ };
311375
+ return ownKeys(o);
311376
+ };
311377
+ return function (mod) {
311378
+ if (mod && mod.__esModule) return mod;
311379
+ var result = {};
311380
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
311381
+ __setModuleDefault(result, mod);
311382
+ return result;
311383
+ };
311384
+ })();
311385
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
311386
+ exports.OpaCompiler = void 0;
311387
+ const fs = __importStar(__nccwpck_require__(79896));
311388
+ const path = __importStar(__nccwpck_require__(16928));
311389
+ const os = __importStar(__nccwpck_require__(70857));
311390
+ const crypto = __importStar(__nccwpck_require__(76982));
311391
+ const child_process_1 = __nccwpck_require__(35317);
311392
+ /**
311393
+ * OPA Rego Compiler - compiles .rego policy files to WASM bundles using the `opa` CLI.
311394
+ *
311395
+ * Handles:
311396
+ * - Resolving input paths to WASM bytes (direct .wasm, directory with policy.wasm, or .rego files)
311397
+ * - Compiling .rego files to WASM via `opa build`
311398
+ * - Caching compiled bundles based on content hashes
311399
+ * - Extracting policy.wasm from OPA tar.gz bundles
311400
+ *
311401
+ * Requires:
311402
+ * - `opa` CLI on PATH (only when auto-compiling .rego files)
311403
+ */
311404
+ class OpaCompiler {
311405
+ static CACHE_DIR = path.join(os.tmpdir(), 'visor-opa-cache');
311406
+ /**
311407
+ * Resolve the input paths to WASM bytes.
311408
+ *
311409
+ * Strategy:
311410
+ * 1. If any path is a .wasm file, read it directly
311411
+ * 2. If a directory contains policy.wasm, read it
311412
+ * 3. Otherwise, collect all .rego files and auto-compile via `opa build`
311413
+ */
311414
+ async resolveWasmBytes(paths) {
311415
+ // Collect .rego files and check for existing .wasm
311416
+ const regoFiles = [];
311417
+ for (const p of paths) {
311418
+ const resolved = path.resolve(p);
311419
+ // Reject paths containing '..' after resolution (path traversal)
311420
+ if (path.normalize(resolved).includes('..')) {
311421
+ throw new Error(`Policy path contains traversal sequences: ${p}`);
311422
+ }
311423
+ // Direct .wasm file
311424
+ if (resolved.endsWith('.wasm') && fs.existsSync(resolved)) {
311425
+ return fs.readFileSync(resolved);
311426
+ }
311427
+ if (!fs.existsSync(resolved))
311428
+ continue;
311429
+ const stat = fs.statSync(resolved);
311430
+ if (stat.isDirectory()) {
311431
+ // Check for pre-compiled policy.wasm in directory
311432
+ const wasmCandidate = path.join(resolved, 'policy.wasm');
311433
+ if (fs.existsSync(wasmCandidate)) {
311434
+ return fs.readFileSync(wasmCandidate);
311435
+ }
311436
+ // Collect all .rego files from directory
311437
+ const files = fs.readdirSync(resolved);
311438
+ for (const f of files) {
311439
+ if (f.endsWith('.rego')) {
311440
+ regoFiles.push(path.join(resolved, f));
311441
+ }
311442
+ }
311443
+ }
311444
+ else if (resolved.endsWith('.rego')) {
311445
+ regoFiles.push(resolved);
311446
+ }
311447
+ }
311448
+ if (regoFiles.length === 0) {
311449
+ throw new Error(`OPA WASM evaluator: no .wasm bundle or .rego files found in: ${paths.join(', ')}`);
311450
+ }
311451
+ // Auto-compile .rego -> .wasm
311452
+ return this.compileRego(regoFiles);
311453
+ }
311454
+ /**
311455
+ * Auto-compile .rego files to a WASM bundle using the `opa` CLI.
311456
+ *
311457
+ * Caches the compiled bundle based on a content hash of all input .rego files
311458
+ * so subsequent runs skip compilation if policies haven't changed.
311459
+ */
311460
+ compileRego(regoFiles) {
311461
+ // Check that `opa` CLI is available
311462
+ try {
311463
+ (0, child_process_1.execFileSync)('opa', ['version'], { stdio: 'pipe' });
311464
+ }
311465
+ catch {
311466
+ throw new Error('OPA CLI (`opa`) not found on PATH. Install it from https://www.openpolicyagent.org/docs/latest/#running-opa\n' +
311467
+ 'Or pre-compile your .rego files: opa build -t wasm -e visor -o bundle.tar.gz ' +
311468
+ regoFiles.join(' '));
311469
+ }
311470
+ // Compute content hash for cache key
311471
+ const hash = crypto.createHash('sha256');
311472
+ for (const f of regoFiles.sort()) {
311473
+ hash.update(fs.readFileSync(f));
311474
+ hash.update(f); // include filename for disambiguation
311475
+ }
311476
+ const cacheKey = hash.digest('hex').slice(0, 16);
311477
+ const cacheDir = OpaCompiler.CACHE_DIR;
311478
+ const cachedWasm = path.join(cacheDir, `${cacheKey}.wasm`);
311479
+ // Return cached bundle if still valid
311480
+ if (fs.existsSync(cachedWasm)) {
311481
+ return fs.readFileSync(cachedWasm);
311482
+ }
311483
+ // Compile to WASM via opa build
311484
+ fs.mkdirSync(cacheDir, { recursive: true });
311485
+ const bundleTar = path.join(cacheDir, `${cacheKey}-bundle.tar.gz`);
311486
+ try {
311487
+ const args = [
311488
+ 'build',
311489
+ '-t',
311490
+ 'wasm',
311491
+ '-e',
311492
+ 'visor', // entrypoint: the visor package tree
311493
+ '-o',
311494
+ bundleTar,
311495
+ ...regoFiles,
311496
+ ];
311497
+ (0, child_process_1.execFileSync)('opa', args, {
311498
+ stdio: 'pipe',
311499
+ timeout: 30000,
311500
+ });
311501
+ }
311502
+ catch (err) {
311503
+ const stderr = err?.stderr?.toString() || '';
311504
+ throw new Error(`Failed to compile .rego files to WASM:\n${stderr}\n` +
311505
+ 'Ensure your .rego files are valid and the `opa` CLI is installed.');
311506
+ }
311507
+ // Extract policy.wasm from the tar.gz bundle
311508
+ // OPA bundles are tar.gz with /policy.wasm inside
311509
+ try {
311510
+ (0, child_process_1.execFileSync)('tar', ['-xzf', bundleTar, '-C', cacheDir, '/policy.wasm'], {
311511
+ stdio: 'pipe',
311512
+ });
311513
+ const extractedWasm = path.join(cacheDir, 'policy.wasm');
311514
+ if (fs.existsSync(extractedWasm)) {
311515
+ // Move to cache-key named file
311516
+ fs.renameSync(extractedWasm, cachedWasm);
311517
+ }
311518
+ }
311519
+ catch {
311520
+ // Some tar implementations don't like leading /
311521
+ try {
311522
+ (0, child_process_1.execFileSync)('tar', ['-xzf', bundleTar, '-C', cacheDir, 'policy.wasm'], {
311523
+ stdio: 'pipe',
311524
+ });
311525
+ const extractedWasm = path.join(cacheDir, 'policy.wasm');
311526
+ if (fs.existsSync(extractedWasm)) {
311527
+ fs.renameSync(extractedWasm, cachedWasm);
311528
+ }
311529
+ }
311530
+ catch (err2) {
311531
+ throw new Error(`Failed to extract policy.wasm from OPA bundle: ${err2?.message || err2}`);
311532
+ }
311533
+ }
311534
+ // Clean up tar
311535
+ try {
311536
+ fs.unlinkSync(bundleTar);
311537
+ }
311538
+ catch { }
311539
+ if (!fs.existsSync(cachedWasm)) {
311540
+ throw new Error('OPA build succeeded but policy.wasm was not found in the bundle');
311541
+ }
311542
+ return fs.readFileSync(cachedWasm);
311543
+ }
311544
+ }
311545
+ exports.OpaCompiler = OpaCompiler;
311546
+
311547
+
311548
+ /***/ }),
311549
+
311550
+ /***/ 44693:
311551
+ /***/ ((__unused_webpack_module, exports) => {
311552
+
311553
+ "use strict";
311554
+
311555
+ /**
311556
+ * Copyright (c) ProbeLabs. All rights reserved.
311557
+ * Licensed under the Elastic License 2.0; you may not use this file except
311558
+ * in compliance with the Elastic License 2.0.
311559
+ */
311560
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
311561
+ exports.OpaHttpEvaluator = void 0;
311562
+ /**
311563
+ * OPA HTTP Evaluator - evaluates policies via an external OPA server's REST API.
311564
+ *
311565
+ * Uses the built-in `fetch` API (Node 18+), so no extra dependencies are needed.
311566
+ */
311567
+ class OpaHttpEvaluator {
311568
+ baseUrl;
311569
+ timeout;
311570
+ constructor(baseUrl, timeout = 5000) {
311571
+ // Validate URL format and protocol
311572
+ let parsed;
311573
+ try {
311574
+ parsed = new URL(baseUrl);
311575
+ }
311576
+ catch {
311577
+ throw new Error(`OPA HTTP evaluator: invalid URL: ${baseUrl}`);
311578
+ }
311579
+ if (!['http:', 'https:'].includes(parsed.protocol)) {
311580
+ throw new Error(`OPA HTTP evaluator: url must use http:// or https:// protocol, got: ${baseUrl}`);
311581
+ }
311582
+ // Block cloud metadata, loopback, link-local, and private network addresses
311583
+ const hostname = parsed.hostname;
311584
+ if (this.isBlockedHostname(hostname)) {
311585
+ throw new Error(`OPA HTTP evaluator: url must not point to internal, loopback, or private network addresses`);
311586
+ }
311587
+ // Normalize: strip trailing slash
311588
+ this.baseUrl = baseUrl.replace(/\/+$/, '');
311589
+ this.timeout = timeout;
311590
+ }
311591
+ /**
311592
+ * Check if a hostname is blocked due to SSRF concerns.
311593
+ *
311594
+ * Blocks:
311595
+ * - Loopback addresses (127.x.x.x, localhost, 0.0.0.0, ::1)
311596
+ * - Link-local addresses (169.254.x.x)
311597
+ * - Private networks (10.x.x.x, 172.16-31.x.x, 192.168.x.x)
311598
+ * - IPv6 unique local addresses (fd00::/8)
311599
+ * - Cloud metadata services (*.internal)
311600
+ */
311601
+ isBlockedHostname(hostname) {
311602
+ if (!hostname)
311603
+ return true; // block empty hostnames
311604
+ // Normalize hostname: lowercase and remove brackets for IPv6
311605
+ const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, '');
311606
+ // Block .internal domains (cloud metadata services)
311607
+ if (normalized === 'metadata.google.internal' || normalized.endsWith('.internal')) {
311608
+ return true;
311609
+ }
311610
+ // Block localhost variants
311611
+ if (normalized === 'localhost' || normalized === 'localhost.localdomain') {
311612
+ return true;
311613
+ }
311614
+ // Block IPv6 loopback
311615
+ if (normalized === '::1' || normalized === '0:0:0:0:0:0:0:1') {
311616
+ return true;
311617
+ }
311618
+ // Check IPv4 patterns
311619
+ const ipv4Pattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
311620
+ const ipv4Match = normalized.match(ipv4Pattern);
311621
+ if (ipv4Match) {
311622
+ const octets = ipv4Match.slice(1, 5).map(Number);
311623
+ // Validate octets are in range [0, 255]
311624
+ if (octets.some(octet => octet > 255)) {
311625
+ return false;
311626
+ }
311627
+ const [a, b] = octets;
311628
+ // Block loopback: 127.0.0.0/8
311629
+ if (a === 127) {
311630
+ return true;
311631
+ }
311632
+ // Block 0.0.0.0/8 (this host)
311633
+ if (a === 0) {
311634
+ return true;
311635
+ }
311636
+ // Block link-local: 169.254.0.0/16
311637
+ if (a === 169 && b === 254) {
311638
+ return true;
311639
+ }
311640
+ // Block private networks
311641
+ // 10.0.0.0/8
311642
+ if (a === 10) {
311643
+ return true;
311644
+ }
311645
+ // 172.16.0.0/12 (172.16.x.x through 172.31.x.x)
311646
+ if (a === 172 && b >= 16 && b <= 31) {
311647
+ return true;
311648
+ }
311649
+ // 192.168.0.0/16
311650
+ if (a === 192 && b === 168) {
311651
+ return true;
311652
+ }
311653
+ }
311654
+ // Check IPv6 patterns
311655
+ // Block unique local addresses: fd00::/8
311656
+ if (normalized.startsWith('fd') || normalized.startsWith('fc')) {
311657
+ return true;
311658
+ }
311659
+ // Block link-local: fe80::/10
311660
+ if (normalized.startsWith('fe80:')) {
311661
+ return true;
311662
+ }
311663
+ return false;
311664
+ }
311665
+ /**
311666
+ * Evaluate a policy rule against an input document via OPA REST API.
311667
+ *
311668
+ * @param input - The input document to evaluate
311669
+ * @param rulePath - OPA rule path (e.g., 'visor/check/execute')
311670
+ * @returns The result object from OPA, or undefined on error
311671
+ */
311672
+ async evaluate(input, rulePath) {
311673
+ // OPA Data API: POST /v1/data/<path>
311674
+ const encodedPath = rulePath
311675
+ .split('/')
311676
+ .map(s => encodeURIComponent(s))
311677
+ .join('/');
311678
+ const url = `${this.baseUrl}/v1/data/${encodedPath}`;
311679
+ const controller = new AbortController();
311680
+ const timer = setTimeout(() => controller.abort(), this.timeout);
311681
+ try {
311682
+ const response = await fetch(url, {
311683
+ method: 'POST',
311684
+ headers: { 'Content-Type': 'application/json' },
311685
+ body: JSON.stringify({ input }),
311686
+ signal: controller.signal,
311687
+ });
311688
+ if (!response.ok) {
311689
+ throw new Error(`OPA HTTP ${response.status}: ${response.statusText}`);
311690
+ }
311691
+ let body;
311692
+ try {
311693
+ body = await response.json();
311694
+ }
311695
+ catch (jsonErr) {
311696
+ throw new Error(`OPA HTTP evaluator: failed to parse JSON response: ${jsonErr instanceof Error ? jsonErr.message : String(jsonErr)}`);
311697
+ }
311698
+ // OPA returns { result: { ... } }
311699
+ return body?.result;
311700
+ }
311701
+ finally {
311702
+ clearTimeout(timer);
311703
+ }
311704
+ }
311705
+ async shutdown() {
311706
+ // No persistent connections to close
311707
+ }
311708
+ }
311709
+ exports.OpaHttpEvaluator = OpaHttpEvaluator;
311710
+
311711
+
311712
+ /***/ }),
311713
+
311714
+ /***/ 39530:
311715
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
311716
+
311717
+ "use strict";
311718
+
311719
+ /**
311720
+ * Copyright (c) ProbeLabs. All rights reserved.
311721
+ * Licensed under the Elastic License 2.0; you may not use this file except
311722
+ * in compliance with the Elastic License 2.0.
311723
+ */
311724
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
311725
+ exports.OpaPolicyEngine = void 0;
311726
+ const opa_wasm_evaluator_1 = __nccwpck_require__(8613);
311727
+ const opa_http_evaluator_1 = __nccwpck_require__(44693);
311728
+ const policy_input_builder_1 = __nccwpck_require__(17117);
311729
+ /**
311730
+ * Enterprise OPA Policy Engine.
311731
+ *
311732
+ * Wraps both WASM (local) and HTTP (remote) OPA evaluators behind the
311733
+ * OSS PolicyEngine interface. All OPA input building and role resolution
311734
+ * is handled internally — the OSS call sites pass only plain types.
311735
+ */
311736
+ class OpaPolicyEngine {
311737
+ evaluator = null;
311738
+ fallback;
311739
+ timeout;
311740
+ config;
311741
+ inputBuilder = null;
311742
+ logger = null;
311743
+ constructor(config) {
311744
+ this.config = config;
311745
+ this.fallback = config.fallback || 'deny';
311746
+ this.timeout = config.timeout || 5000;
311747
+ }
311748
+ async initialize(config) {
311749
+ // Resolve logger once at initialization
311750
+ try {
311751
+ this.logger = (__nccwpck_require__(86999).logger);
311752
+ }
311753
+ catch {
311754
+ // logger not available in this context
311755
+ }
311756
+ // Build actor/repo context from environment (available at engine init time)
311757
+ const actor = {
311758
+ authorAssociation: process.env.VISOR_AUTHOR_ASSOCIATION,
311759
+ login: process.env.VISOR_AUTHOR_LOGIN || process.env.GITHUB_ACTOR,
311760
+ isLocalMode: !process.env.GITHUB_ACTIONS,
311761
+ };
311762
+ const repo = {
311763
+ owner: process.env.GITHUB_REPOSITORY_OWNER,
311764
+ name: process.env.GITHUB_REPOSITORY?.split('/')[1],
311765
+ branch: process.env.GITHUB_HEAD_REF,
311766
+ baseBranch: process.env.GITHUB_BASE_REF,
311767
+ event: process.env.GITHUB_EVENT_NAME,
311768
+ };
311769
+ const prNum = process.env.GITHUB_PR_NUMBER
311770
+ ? parseInt(process.env.GITHUB_PR_NUMBER, 10)
311771
+ : undefined;
311772
+ const pullRequest = {
311773
+ number: prNum !== undefined && Number.isFinite(prNum) ? prNum : undefined,
311774
+ };
311775
+ this.inputBuilder = new policy_input_builder_1.PolicyInputBuilder(config, actor, repo, pullRequest);
311776
+ if (config.engine === 'local') {
311777
+ if (!config.rules) {
311778
+ throw new Error('OPA local mode requires `policy.rules` path to .wasm or .rego files');
311779
+ }
311780
+ const wasm = new opa_wasm_evaluator_1.OpaWasmEvaluator();
311781
+ await wasm.initialize(config.rules);
311782
+ if (config.data) {
311783
+ wasm.loadData(config.data);
311784
+ }
311785
+ this.evaluator = wasm;
311786
+ }
311787
+ else if (config.engine === 'remote') {
311788
+ if (!config.url) {
311789
+ throw new Error('OPA remote mode requires `policy.url` pointing to OPA server');
311790
+ }
311791
+ this.evaluator = new opa_http_evaluator_1.OpaHttpEvaluator(config.url, this.timeout);
311792
+ }
311793
+ else {
311794
+ this.evaluator = null;
311795
+ }
311796
+ }
311797
+ /**
311798
+ * Update actor/repo/PR context (e.g., after PR info becomes available).
311799
+ * Called by the enterprise loader when engine context is enriched.
311800
+ */
311801
+ setActorContext(actor, repo, pullRequest) {
311802
+ this.inputBuilder = new policy_input_builder_1.PolicyInputBuilder(this.config, actor, repo, pullRequest);
311803
+ }
311804
+ async evaluateCheckExecution(checkId, checkConfig) {
311805
+ if (!this.evaluator || !this.inputBuilder)
311806
+ return { allowed: true };
311807
+ const cfg = checkConfig && typeof checkConfig === 'object'
311808
+ ? checkConfig
311809
+ : {};
311810
+ const policyOverride = cfg.policy;
311811
+ const input = this.inputBuilder.forCheckExecution({
311812
+ id: checkId,
311813
+ type: cfg.type || 'ai',
311814
+ group: cfg.group,
311815
+ tags: cfg.tags,
311816
+ criticality: cfg.criticality,
311817
+ sandbox: cfg.sandbox,
311818
+ policy: policyOverride,
311819
+ });
311820
+ return this.doEvaluate(input, this.resolveRulePath('check.execute', policyOverride?.rule));
311821
+ }
311822
+ async evaluateToolInvocation(serverName, methodName, transport) {
311823
+ if (!this.evaluator || !this.inputBuilder)
311824
+ return { allowed: true };
311825
+ const input = this.inputBuilder.forToolInvocation(serverName, methodName, transport);
311826
+ return this.doEvaluate(input, 'visor/tool/invoke');
311827
+ }
311828
+ async evaluateCapabilities(checkId, capabilities) {
311829
+ if (!this.evaluator || !this.inputBuilder)
311830
+ return { allowed: true };
311831
+ const input = this.inputBuilder.forCapabilityResolve(checkId, capabilities);
311832
+ return this.doEvaluate(input, 'visor/capability/resolve');
311833
+ }
311834
+ async shutdown() {
311835
+ if (this.evaluator && 'shutdown' in this.evaluator) {
311836
+ await this.evaluator.shutdown();
311837
+ }
311838
+ this.evaluator = null;
311839
+ this.inputBuilder = null;
311840
+ }
311841
+ resolveRulePath(defaultScope, override) {
311842
+ if (override) {
311843
+ return override.startsWith('visor/') ? override : `visor/${override}`;
311844
+ }
311845
+ return `visor/${defaultScope.replace(/\./g, '/')}`;
311846
+ }
311847
+ async doEvaluate(input, rulePath) {
311848
+ try {
311849
+ this.logger?.debug(`[PolicyEngine] Evaluating ${rulePath}`, JSON.stringify(input));
311850
+ let timer;
311851
+ const timeoutPromise = new Promise((_resolve, reject) => {
311852
+ timer = setTimeout(() => reject(new Error('policy evaluation timeout')), this.timeout);
311853
+ });
311854
+ try {
311855
+ const result = await Promise.race([this.rawEvaluate(input, rulePath), timeoutPromise]);
311856
+ const decision = this.parseDecision(result);
311857
+ // In warn mode, override denied decisions to allowed but flag as warn
311858
+ if (!decision.allowed && this.fallback === 'warn') {
311859
+ decision.allowed = true;
311860
+ decision.warn = true;
311861
+ decision.reason = `audit: ${decision.reason || 'policy denied'}`;
311862
+ }
311863
+ this.logger?.debug(`[PolicyEngine] Decision for ${rulePath}: allowed=${decision.allowed}, warn=${decision.warn || false}, reason=${decision.reason || 'none'}`);
311864
+ return decision;
311865
+ }
311866
+ finally {
311867
+ if (timer)
311868
+ clearTimeout(timer);
311869
+ }
311870
+ }
311871
+ catch (err) {
311872
+ const msg = err instanceof Error ? err.message : String(err);
311873
+ this.logger?.warn(`[PolicyEngine] Evaluation failed for ${rulePath}: ${msg}`);
311874
+ return {
311875
+ allowed: this.fallback === 'allow' || this.fallback === 'warn',
311876
+ warn: this.fallback === 'warn' ? true : undefined,
311877
+ reason: `policy evaluation failed, fallback=${this.fallback}`,
311878
+ };
311879
+ }
311880
+ }
311881
+ async rawEvaluate(input, rulePath) {
311882
+ if (this.evaluator instanceof opa_wasm_evaluator_1.OpaWasmEvaluator) {
311883
+ const result = await this.evaluator.evaluate(input);
311884
+ // WASM compiled with `-e visor` entrypoint returns the full visor package tree.
311885
+ // Navigate to the specific rule subtree using rulePath segments.
311886
+ // e.g., 'visor/check/execute' → result.check.execute
311887
+ return this.navigateWasmResult(result, rulePath);
311888
+ }
311889
+ return this.evaluator.evaluate(input, rulePath);
311890
+ }
311891
+ /**
311892
+ * Navigate nested OPA WASM result tree to reach the specific rule's output.
311893
+ * The WASM entrypoint `-e visor` means the result root IS the visor package,
311894
+ * so we strip the `visor/` prefix and walk the remaining segments.
311895
+ */
311896
+ navigateWasmResult(result, rulePath) {
311897
+ if (!result || typeof result !== 'object')
311898
+ return result;
311899
+ // Strip the 'visor/' prefix (matches our compilation entrypoint)
311900
+ const segments = rulePath.replace(/^visor\//, '').split('/');
311901
+ let current = result;
311902
+ for (const seg of segments) {
311903
+ if (current && typeof current === 'object' && seg in current) {
311904
+ current = current[seg];
311905
+ }
311906
+ else {
311907
+ return undefined; // path not found in result tree
311908
+ }
311909
+ }
311910
+ return current;
311911
+ }
311912
+ parseDecision(result) {
311913
+ if (result === undefined || result === null) {
311914
+ return {
311915
+ allowed: this.fallback === 'allow' || this.fallback === 'warn',
311916
+ warn: this.fallback === 'warn' ? true : undefined,
311917
+ reason: this.fallback === 'warn' ? 'audit: no policy result' : 'no policy result',
311918
+ };
311919
+ }
311920
+ const allowed = result.allowed !== false;
311921
+ const decision = {
311922
+ allowed,
311923
+ reason: result.reason,
311924
+ };
311925
+ if (result.capabilities) {
311926
+ decision.capabilities = result.capabilities;
311927
+ }
311928
+ return decision;
311929
+ }
311930
+ }
311931
+ exports.OpaPolicyEngine = OpaPolicyEngine;
311932
+
311933
+
311934
+ /***/ }),
311935
+
311936
+ /***/ 8613:
311937
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
311938
+
311939
+ "use strict";
311940
+
311941
+ /**
311942
+ * Copyright (c) ProbeLabs. All rights reserved.
311943
+ * Licensed under the Elastic License 2.0; you may not use this file except
311944
+ * in compliance with the Elastic License 2.0.
311945
+ */
311946
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
311947
+ if (k2 === undefined) k2 = k;
311948
+ var desc = Object.getOwnPropertyDescriptor(m, k);
311949
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
311950
+ desc = { enumerable: true, get: function() { return m[k]; } };
311951
+ }
311952
+ Object.defineProperty(o, k2, desc);
311953
+ }) : (function(o, m, k, k2) {
311954
+ if (k2 === undefined) k2 = k;
311955
+ o[k2] = m[k];
311956
+ }));
311957
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
311958
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
311959
+ }) : function(o, v) {
311960
+ o["default"] = v;
311961
+ });
311962
+ var __importStar = (this && this.__importStar) || (function () {
311963
+ var ownKeys = function(o) {
311964
+ ownKeys = Object.getOwnPropertyNames || function (o) {
311965
+ var ar = [];
311966
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
311967
+ return ar;
311968
+ };
311969
+ return ownKeys(o);
311970
+ };
311971
+ return function (mod) {
311972
+ if (mod && mod.__esModule) return mod;
311973
+ var result = {};
311974
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
311975
+ __setModuleDefault(result, mod);
311976
+ return result;
311977
+ };
311978
+ })();
311979
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
311980
+ exports.OpaWasmEvaluator = void 0;
311981
+ const fs = __importStar(__nccwpck_require__(79896));
311982
+ const path = __importStar(__nccwpck_require__(16928));
311983
+ const opa_compiler_1 = __nccwpck_require__(628);
311984
+ /**
311985
+ * OPA WASM Evaluator - loads and evaluates OPA policies locally.
311986
+ *
311987
+ * Supports three input formats:
311988
+ * 1. Pre-compiled `.wasm` bundle — loaded directly (fastest startup)
311989
+ * 2. `.rego` files or directory — auto-compiled to WASM via `opa build` CLI
311990
+ * 3. Directory with `policy.wasm` inside — loaded directly
311991
+ *
311992
+ * Compilation and caching of .rego files is delegated to {@link OpaCompiler}.
311993
+ *
311994
+ * Requires:
311995
+ * - `@open-policy-agent/opa-wasm` npm package (optional dep)
311996
+ * - `opa` CLI on PATH (only when auto-compiling .rego files)
311997
+ */
311998
+ class OpaWasmEvaluator {
311999
+ policy = null;
312000
+ dataDocument = {};
312001
+ compiler = new opa_compiler_1.OpaCompiler();
312002
+ async initialize(rulesPath) {
312003
+ const paths = Array.isArray(rulesPath) ? rulesPath : [rulesPath];
312004
+ const wasmBytes = await this.compiler.resolveWasmBytes(paths);
312005
+ try {
312006
+ // Use createRequire to load the optional dep at runtime without ncc bundling it.
312007
+ // `new Function('id', 'return require(id)')` fails in ncc bundles because
312008
+ // `require` is not in the `new Function` scope. `createRequire` works correctly
312009
+ // because it creates a real Node.js require rooted at the given path.
312010
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
312011
+ const { createRequire } = __nccwpck_require__(73339);
312012
+ const runtimeRequire = createRequire(__filename);
312013
+ const opaWasm = runtimeRequire('@open-policy-agent/opa-wasm');
312014
+ const loadPolicy = opaWasm.loadPolicy || opaWasm.default?.loadPolicy;
312015
+ if (!loadPolicy) {
312016
+ throw new Error('loadPolicy not found in @open-policy-agent/opa-wasm');
312017
+ }
312018
+ this.policy = await loadPolicy(wasmBytes);
312019
+ }
312020
+ catch (err) {
312021
+ if (err?.code === 'MODULE_NOT_FOUND' || err?.code === 'ERR_MODULE_NOT_FOUND') {
312022
+ throw new Error('OPA WASM evaluator requires @open-policy-agent/opa-wasm. ' +
312023
+ 'Install it with: npm install @open-policy-agent/opa-wasm');
312024
+ }
312025
+ throw err;
312026
+ }
312027
+ }
312028
+ /**
312029
+ * Load external data from a JSON file to use as the OPA data document.
312030
+ * The loaded data will be passed to `policy.setData()` during evaluation,
312031
+ * making it available in Rego via `data.<key>`.
312032
+ */
312033
+ loadData(dataPath) {
312034
+ const resolved = path.resolve(dataPath);
312035
+ if (path.normalize(resolved).includes('..')) {
312036
+ throw new Error(`Data path contains traversal sequences: ${dataPath}`);
312037
+ }
312038
+ if (!fs.existsSync(resolved)) {
312039
+ throw new Error(`OPA data file not found: ${resolved}`);
312040
+ }
312041
+ const stat = fs.statSync(resolved);
312042
+ if (stat.size > 10 * 1024 * 1024) {
312043
+ throw new Error(`OPA data file exceeds 10MB limit: ${resolved} (${stat.size} bytes)`);
312044
+ }
312045
+ const raw = fs.readFileSync(resolved, 'utf-8');
312046
+ try {
312047
+ const parsed = JSON.parse(raw);
312048
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
312049
+ throw new Error('OPA data file must contain a JSON object (not an array or primitive)');
312050
+ }
312051
+ this.dataDocument = parsed;
312052
+ }
312053
+ catch (err) {
312054
+ if (err.message.startsWith('OPA data file must')) {
312055
+ throw err;
312056
+ }
312057
+ throw new Error(`Failed to parse OPA data file ${resolved}: ${err.message}`);
312058
+ }
312059
+ }
312060
+ async evaluate(input) {
312061
+ if (!this.policy) {
312062
+ throw new Error('OPA WASM evaluator not initialized');
312063
+ }
312064
+ this.policy.setData(this.dataDocument);
312065
+ const resultSet = this.policy.evaluate(input);
312066
+ if (Array.isArray(resultSet) && resultSet.length > 0) {
312067
+ return resultSet[0].result;
312068
+ }
312069
+ return undefined;
312070
+ }
312071
+ async shutdown() {
312072
+ if (this.policy) {
312073
+ // opa-wasm policy objects may have a close/free method for WASM cleanup
312074
+ if (typeof this.policy.close === 'function') {
312075
+ try {
312076
+ this.policy.close();
312077
+ }
312078
+ catch { }
312079
+ }
312080
+ else if (typeof this.policy.free === 'function') {
312081
+ try {
312082
+ this.policy.free();
312083
+ }
312084
+ catch { }
312085
+ }
312086
+ }
312087
+ this.policy = null;
312088
+ }
312089
+ }
312090
+ exports.OpaWasmEvaluator = OpaWasmEvaluator;
312091
+
312092
+
312093
+ /***/ }),
312094
+
312095
+ /***/ 17117:
312096
+ /***/ ((__unused_webpack_module, exports) => {
312097
+
312098
+ "use strict";
312099
+
312100
+ /**
312101
+ * Copyright (c) ProbeLabs. All rights reserved.
312102
+ * Licensed under the Elastic License 2.0; you may not use this file except
312103
+ * in compliance with the Elastic License 2.0.
312104
+ */
312105
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
312106
+ exports.PolicyInputBuilder = void 0;
312107
+ /**
312108
+ * Builds OPA-compatible input documents from engine context.
312109
+ *
312110
+ * Resolves actor roles from the `policy.roles` config section by matching
312111
+ * the actor's authorAssociation and login against role definitions.
312112
+ */
312113
+ class PolicyInputBuilder {
312114
+ roles;
312115
+ actor;
312116
+ repository;
312117
+ pullRequest;
312118
+ constructor(policyConfig, actor, repository, pullRequest) {
312119
+ this.roles = policyConfig.roles || {};
312120
+ this.actor = actor;
312121
+ this.repository = repository;
312122
+ this.pullRequest = pullRequest;
312123
+ }
312124
+ /** Resolve which roles apply to the current actor. */
312125
+ resolveRoles() {
312126
+ const matched = [];
312127
+ for (const [roleName, roleConfig] of Object.entries(this.roles)) {
312128
+ let identityMatch = false;
312129
+ if (roleConfig.author_association &&
312130
+ this.actor.authorAssociation &&
312131
+ roleConfig.author_association.includes(this.actor.authorAssociation)) {
312132
+ identityMatch = true;
312133
+ }
312134
+ if (!identityMatch &&
312135
+ roleConfig.users &&
312136
+ this.actor.login &&
312137
+ roleConfig.users.includes(this.actor.login)) {
312138
+ identityMatch = true;
312139
+ }
312140
+ // Slack user ID match
312141
+ if (!identityMatch &&
312142
+ roleConfig.slack_users &&
312143
+ this.actor.slack?.userId &&
312144
+ roleConfig.slack_users.includes(this.actor.slack.userId)) {
312145
+ identityMatch = true;
312146
+ }
312147
+ // Email match (case-insensitive)
312148
+ if (!identityMatch && roleConfig.emails && this.actor.slack?.email) {
312149
+ const actorEmail = this.actor.slack.email.toLowerCase();
312150
+ if (roleConfig.emails.some(e => e.toLowerCase() === actorEmail)) {
312151
+ identityMatch = true;
312152
+ }
312153
+ }
312154
+ // Note: teams-based role resolution requires GitHub API access (read:org scope)
312155
+ // and is not yet implemented. If configured, the role will not match via teams.
312156
+ if (!identityMatch)
312157
+ continue;
312158
+ // slack_channels gate: if set, the role only applies when triggered from one of these channels
312159
+ if (roleConfig.slack_channels && roleConfig.slack_channels.length > 0) {
312160
+ if (!this.actor.slack?.channelId ||
312161
+ !roleConfig.slack_channels.includes(this.actor.slack.channelId)) {
312162
+ continue;
312163
+ }
312164
+ }
312165
+ matched.push(roleName);
312166
+ }
312167
+ return matched;
312168
+ }
312169
+ buildActor() {
312170
+ return {
312171
+ authorAssociation: this.actor.authorAssociation,
312172
+ login: this.actor.login,
312173
+ roles: this.resolveRoles(),
312174
+ isLocalMode: this.actor.isLocalMode,
312175
+ ...(this.actor.slack && { slack: this.actor.slack }),
312176
+ };
312177
+ }
312178
+ forCheckExecution(check) {
312179
+ return {
312180
+ scope: 'check.execute',
312181
+ check: {
312182
+ id: check.id,
312183
+ type: check.type,
312184
+ group: check.group,
312185
+ tags: check.tags,
312186
+ criticality: check.criticality,
312187
+ sandbox: check.sandbox,
312188
+ policy: check.policy,
312189
+ },
312190
+ actor: this.buildActor(),
312191
+ repository: this.repository,
312192
+ pullRequest: this.pullRequest,
312193
+ };
312194
+ }
312195
+ forToolInvocation(serverName, methodName, transport) {
312196
+ return {
312197
+ scope: 'tool.invoke',
312198
+ tool: { serverName, methodName, transport },
312199
+ actor: this.buildActor(),
312200
+ repository: this.repository,
312201
+ pullRequest: this.pullRequest,
312202
+ };
312203
+ }
312204
+ forCapabilityResolve(checkId, capabilities) {
312205
+ return {
312206
+ scope: 'capability.resolve',
312207
+ check: { id: checkId, type: 'ai' },
312208
+ capability: capabilities,
312209
+ actor: this.buildActor(),
312210
+ repository: this.repository,
312211
+ pullRequest: this.pullRequest,
312212
+ };
312213
+ }
312214
+ }
312215
+ exports.PolicyInputBuilder = PolicyInputBuilder;
312216
+
312217
+
312218
+ /***/ }),
312219
+
312220
+ /***/ 63737:
312221
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
312222
+
312223
+ "use strict";
312224
+
312225
+ /**
312226
+ * Copyright (c) ProbeLabs. All rights reserved.
312227
+ * Licensed under the Elastic License 2.0; you may not use this file except
312228
+ * in compliance with the Elastic License 2.0.
312229
+ */
312230
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
312231
+ if (k2 === undefined) k2 = k;
312232
+ var desc = Object.getOwnPropertyDescriptor(m, k);
312233
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
312234
+ desc = { enumerable: true, get: function() { return m[k]; } };
312235
+ }
312236
+ Object.defineProperty(o, k2, desc);
312237
+ }) : (function(o, m, k, k2) {
312238
+ if (k2 === undefined) k2 = k;
312239
+ o[k2] = m[k];
312240
+ }));
312241
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
312242
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
312243
+ }) : function(o, v) {
312244
+ o["default"] = v;
312245
+ });
312246
+ var __importStar = (this && this.__importStar) || (function () {
312247
+ var ownKeys = function(o) {
312248
+ ownKeys = Object.getOwnPropertyNames || function (o) {
312249
+ var ar = [];
312250
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
312251
+ return ar;
312252
+ };
312253
+ return ownKeys(o);
312254
+ };
312255
+ return function (mod) {
312256
+ if (mod && mod.__esModule) return mod;
312257
+ var result = {};
312258
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
312259
+ __setModuleDefault(result, mod);
312260
+ return result;
312261
+ };
312262
+ })();
312263
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
312264
+ exports.KnexStoreBackend = void 0;
312265
+ /**
312266
+ * Knex-backed schedule store for PostgreSQL, MySQL, and MSSQL (Enterprise)
312267
+ *
312268
+ * Uses Knex query builder for database-agnostic SQL. Same schema as SQLite backend
312269
+ * but with real distributed locking via row-level claims (claimed_by/claimed_at/lock_token).
312270
+ */
312271
+ const fs = __importStar(__nccwpck_require__(79896));
312272
+ const path = __importStar(__nccwpck_require__(16928));
312273
+ const uuid_1 = __nccwpck_require__(31914);
312274
+ const logger_1 = __nccwpck_require__(86999);
312275
+ function toNum(val) {
312276
+ if (val === null || val === undefined)
312277
+ return undefined;
312278
+ return typeof val === 'string' ? parseInt(val, 10) : val;
312279
+ }
312280
+ function safeJsonParse(value) {
312281
+ if (!value)
312282
+ return undefined;
312283
+ try {
312284
+ return JSON.parse(value);
312285
+ }
312286
+ catch {
312287
+ return undefined;
312288
+ }
312289
+ }
312290
+ function fromTriggerRow(row) {
312291
+ return {
312292
+ id: row.id,
312293
+ creatorId: row.creator_id,
312294
+ creatorContext: row.creator_context ?? undefined,
312295
+ creatorName: row.creator_name ?? undefined,
312296
+ description: row.description ?? undefined,
312297
+ channels: safeJsonParse(row.channels),
312298
+ fromUsers: safeJsonParse(row.from_users),
312299
+ fromBots: row.from_bots === true || row.from_bots === 1,
312300
+ contains: safeJsonParse(row.contains),
312301
+ matchPattern: row.match_pattern ?? undefined,
312302
+ threads: row.threads,
312303
+ workflow: row.workflow,
312304
+ inputs: safeJsonParse(row.inputs),
312305
+ outputContext: safeJsonParse(row.output_context),
312306
+ status: row.status,
312307
+ enabled: row.enabled === true || row.enabled === 1,
312308
+ createdAt: toNum(row.created_at),
312309
+ };
312310
+ }
312311
+ function toTriggerInsertRow(trigger) {
312312
+ return {
312313
+ id: trigger.id,
312314
+ creator_id: trigger.creatorId,
312315
+ creator_context: trigger.creatorContext ?? null,
312316
+ creator_name: trigger.creatorName ?? null,
312317
+ description: trigger.description ?? null,
312318
+ channels: trigger.channels ? JSON.stringify(trigger.channels) : null,
312319
+ from_users: trigger.fromUsers ? JSON.stringify(trigger.fromUsers) : null,
312320
+ from_bots: trigger.fromBots,
312321
+ contains: trigger.contains ? JSON.stringify(trigger.contains) : null,
312322
+ match_pattern: trigger.matchPattern ?? null,
312323
+ threads: trigger.threads,
312324
+ workflow: trigger.workflow,
312325
+ inputs: trigger.inputs ? JSON.stringify(trigger.inputs) : null,
312326
+ output_context: trigger.outputContext ? JSON.stringify(trigger.outputContext) : null,
312327
+ status: trigger.status,
312328
+ enabled: trigger.enabled,
312329
+ created_at: trigger.createdAt,
312330
+ };
312331
+ }
312332
+ function fromDbRow(row) {
312333
+ return {
312334
+ id: row.id,
312335
+ creatorId: row.creator_id,
312336
+ creatorContext: row.creator_context ?? undefined,
312337
+ creatorName: row.creator_name ?? undefined,
312338
+ timezone: row.timezone,
312339
+ schedule: row.schedule_expr,
312340
+ runAt: toNum(row.run_at),
312341
+ isRecurring: row.is_recurring === true || row.is_recurring === 1,
312342
+ originalExpression: row.original_expression,
312343
+ workflow: row.workflow ?? undefined,
312344
+ workflowInputs: safeJsonParse(row.workflow_inputs),
312345
+ outputContext: safeJsonParse(row.output_context),
312346
+ status: row.status,
312347
+ createdAt: toNum(row.created_at),
312348
+ lastRunAt: toNum(row.last_run_at),
312349
+ nextRunAt: toNum(row.next_run_at),
312350
+ runCount: row.run_count,
312351
+ failureCount: row.failure_count,
312352
+ lastError: row.last_error ?? undefined,
312353
+ previousResponse: row.previous_response ?? undefined,
312354
+ };
312355
+ }
312356
+ function toInsertRow(schedule) {
312357
+ return {
312358
+ id: schedule.id,
312359
+ creator_id: schedule.creatorId,
312360
+ creator_context: schedule.creatorContext ?? null,
312361
+ creator_name: schedule.creatorName ?? null,
312362
+ timezone: schedule.timezone,
312363
+ schedule_expr: schedule.schedule,
312364
+ run_at: schedule.runAt ?? null,
312365
+ is_recurring: schedule.isRecurring,
312366
+ original_expression: schedule.originalExpression,
312367
+ workflow: schedule.workflow ?? null,
312368
+ workflow_inputs: schedule.workflowInputs ? JSON.stringify(schedule.workflowInputs) : null,
312369
+ output_context: schedule.outputContext ? JSON.stringify(schedule.outputContext) : null,
312370
+ status: schedule.status,
312371
+ created_at: schedule.createdAt,
312372
+ last_run_at: schedule.lastRunAt ?? null,
312373
+ next_run_at: schedule.nextRunAt ?? null,
312374
+ run_count: schedule.runCount,
312375
+ failure_count: schedule.failureCount,
312376
+ last_error: schedule.lastError ?? null,
312377
+ previous_response: schedule.previousResponse ?? null,
312378
+ };
312379
+ }
312380
+ /**
312381
+ * Enterprise Knex-backed store for PostgreSQL, MySQL, and MSSQL
312382
+ */
312383
+ class KnexStoreBackend {
312384
+ knex = null;
312385
+ driver;
312386
+ connection;
312387
+ constructor(driver, storageConfig, _haConfig) {
312388
+ this.driver = driver;
312389
+ this.connection = (storageConfig.connection || {});
312390
+ }
312391
+ async initialize() {
312392
+ // Load knex dynamically
312393
+ const { createRequire } = __nccwpck_require__(73339);
312394
+ const runtimeRequire = createRequire(__filename);
312395
+ let knexFactory;
312396
+ try {
312397
+ knexFactory = runtimeRequire('knex');
312398
+ }
312399
+ catch (err) {
312400
+ const code = err?.code;
312401
+ if (code === 'MODULE_NOT_FOUND' || code === 'ERR_MODULE_NOT_FOUND') {
312402
+ throw new Error('knex is required for PostgreSQL/MySQL/MSSQL schedule storage. ' +
312403
+ 'Install it with: npm install knex');
312404
+ }
312405
+ throw err;
312406
+ }
312407
+ const clientMap = {
312408
+ postgresql: 'pg',
312409
+ mysql: 'mysql2',
312410
+ mssql: 'tedious',
312411
+ };
312412
+ const client = clientMap[this.driver];
312413
+ // Build connection config
312414
+ let connection;
312415
+ if (this.connection.connection_string) {
312416
+ connection = this.connection.connection_string;
312417
+ }
312418
+ else if (this.driver === 'mssql') {
312419
+ connection = this.buildMssqlConnection();
312420
+ }
312421
+ else {
312422
+ connection = this.buildStandardConnection();
312423
+ }
312424
+ this.knex = knexFactory({
312425
+ client,
312426
+ connection,
312427
+ pool: {
312428
+ min: this.connection.pool?.min ?? 0,
312429
+ max: this.connection.pool?.max ?? 10,
312430
+ },
312431
+ });
312432
+ // Run schema migration
312433
+ await this.migrateSchema();
312434
+ logger_1.logger.info(`[KnexStore] Initialized (${this.driver})`);
312435
+ }
312436
+ buildStandardConnection() {
312437
+ return {
312438
+ host: this.connection.host || 'localhost',
312439
+ port: this.connection.port,
312440
+ database: this.connection.database || 'visor',
312441
+ user: this.connection.user,
312442
+ password: this.connection.password,
312443
+ ssl: this.resolveSslConfig(),
312444
+ };
312445
+ }
312446
+ buildMssqlConnection() {
312447
+ const ssl = this.connection.ssl;
312448
+ const sslEnabled = ssl === true || (typeof ssl === 'object' && ssl.enabled !== false);
312449
+ return {
312450
+ server: this.connection.host || 'localhost',
312451
+ port: this.connection.port,
312452
+ database: this.connection.database || 'visor',
312453
+ user: this.connection.user,
312454
+ password: this.connection.password,
312455
+ options: {
312456
+ encrypt: sslEnabled,
312457
+ trustServerCertificate: typeof ssl === 'object' ? ssl.reject_unauthorized === false : !sslEnabled,
312458
+ },
312459
+ };
312460
+ }
312461
+ resolveSslConfig() {
312462
+ const ssl = this.connection.ssl;
312463
+ if (ssl === false || ssl === undefined)
312464
+ return false;
312465
+ if (ssl === true)
312466
+ return { rejectUnauthorized: true };
312467
+ // Object config
312468
+ if (ssl.enabled === false)
312469
+ return false;
312470
+ const result = {
312471
+ rejectUnauthorized: ssl.reject_unauthorized !== false,
312472
+ };
312473
+ if (ssl.ca) {
312474
+ const caPath = this.validateSslPath(ssl.ca, 'CA certificate');
312475
+ result.ca = fs.readFileSync(caPath, 'utf8');
312476
+ }
312477
+ if (ssl.cert) {
312478
+ const certPath = this.validateSslPath(ssl.cert, 'client certificate');
312479
+ result.cert = fs.readFileSync(certPath, 'utf8');
312480
+ }
312481
+ if (ssl.key) {
312482
+ const keyPath = this.validateSslPath(ssl.key, 'client key');
312483
+ result.key = fs.readFileSync(keyPath, 'utf8');
312484
+ }
312485
+ return result;
312486
+ }
312487
+ validateSslPath(filePath, label) {
312488
+ const resolved = path.resolve(filePath);
312489
+ if (resolved !== path.normalize(resolved)) {
312490
+ throw new Error(`SSL ${label} path contains invalid sequences: ${filePath}`);
312491
+ }
312492
+ if (!fs.existsSync(resolved)) {
312493
+ throw new Error(`SSL ${label} not found: ${filePath}`);
312494
+ }
312495
+ return resolved;
312496
+ }
312497
+ async shutdown() {
312498
+ if (this.knex) {
312499
+ await this.knex.destroy();
312500
+ this.knex = null;
312501
+ }
312502
+ }
312503
+ async migrateSchema() {
312504
+ const knex = this.getKnex();
312505
+ const exists = await knex.schema.hasTable('schedules');
312506
+ if (!exists) {
312507
+ await knex.schema.createTable('schedules', table => {
312508
+ table.string('id', 36).primary();
312509
+ table.string('creator_id', 255).notNullable().index();
312510
+ table.string('creator_context', 255);
312511
+ table.string('creator_name', 255);
312512
+ table.string('timezone', 64).notNullable().defaultTo('UTC');
312513
+ table.string('schedule_expr', 255);
312514
+ table.bigInteger('run_at');
312515
+ table.boolean('is_recurring').notNullable();
312516
+ table.text('original_expression');
312517
+ table.string('workflow', 255);
312518
+ table.text('workflow_inputs');
312519
+ table.text('output_context');
312520
+ table.string('status', 20).notNullable().index();
312521
+ table.bigInteger('created_at').notNullable();
312522
+ table.bigInteger('last_run_at');
312523
+ table.bigInteger('next_run_at');
312524
+ table.integer('run_count').notNullable().defaultTo(0);
312525
+ table.integer('failure_count').notNullable().defaultTo(0);
312526
+ table.text('last_error');
312527
+ table.text('previous_response');
312528
+ table.index(['status', 'next_run_at']);
312529
+ });
312530
+ }
312531
+ // Create message_triggers table
312532
+ const triggersExist = await knex.schema.hasTable('message_triggers');
312533
+ if (!triggersExist) {
312534
+ await knex.schema.createTable('message_triggers', table => {
312535
+ table.string('id', 36).primary();
312536
+ table.string('creator_id', 255).notNullable().index();
312537
+ table.string('creator_context', 255);
312538
+ table.string('creator_name', 255);
312539
+ table.text('description');
312540
+ table.text('channels'); // JSON array
312541
+ table.text('from_users'); // JSON array
312542
+ table.boolean('from_bots').notNullable().defaultTo(false);
312543
+ table.text('contains'); // JSON array
312544
+ table.text('match_pattern');
312545
+ table.string('threads', 20).notNullable().defaultTo('any');
312546
+ table.string('workflow', 255).notNullable();
312547
+ table.text('inputs'); // JSON
312548
+ table.text('output_context'); // JSON
312549
+ table.string('status', 20).notNullable().defaultTo('active').index();
312550
+ table.boolean('enabled').notNullable().defaultTo(true);
312551
+ table.bigInteger('created_at').notNullable();
312552
+ });
312553
+ }
312554
+ // Create scheduler_locks table for distributed locking
312555
+ const locksExist = await knex.schema.hasTable('scheduler_locks');
312556
+ if (!locksExist) {
312557
+ await knex.schema.createTable('scheduler_locks', table => {
312558
+ table.string('lock_id', 255).primary();
312559
+ table.string('node_id', 255).notNullable();
312560
+ table.string('lock_token', 36).notNullable();
312561
+ table.bigInteger('acquired_at').notNullable();
312562
+ table.bigInteger('expires_at').notNullable();
312563
+ });
312564
+ }
312565
+ }
312566
+ getKnex() {
312567
+ if (!this.knex) {
312568
+ throw new Error('[KnexStore] Not initialized. Call initialize() first.');
312569
+ }
312570
+ return this.knex;
312571
+ }
312572
+ // --- CRUD ---
312573
+ async create(schedule) {
312574
+ const knex = this.getKnex();
312575
+ const newSchedule = {
312576
+ ...schedule,
312577
+ id: (0, uuid_1.v4)(),
312578
+ createdAt: Date.now(),
312579
+ runCount: 0,
312580
+ failureCount: 0,
312581
+ status: 'active',
312582
+ };
312583
+ await knex('schedules').insert(toInsertRow(newSchedule));
312584
+ logger_1.logger.info(`[KnexStore] Created schedule ${newSchedule.id} for user ${newSchedule.creatorId}`);
312585
+ return newSchedule;
312586
+ }
312587
+ async importSchedule(schedule) {
312588
+ const knex = this.getKnex();
312589
+ const existing = await knex('schedules').where('id', schedule.id).first();
312590
+ if (existing)
312591
+ return; // Already imported (idempotent)
312592
+ await knex('schedules').insert(toInsertRow(schedule));
312593
+ }
312594
+ async get(id) {
312595
+ const knex = this.getKnex();
312596
+ const row = await knex('schedules').where('id', id).first();
312597
+ return row ? fromDbRow(row) : undefined;
312598
+ }
312599
+ async update(id, patch) {
312600
+ const knex = this.getKnex();
312601
+ const existing = await knex('schedules').where('id', id).first();
312602
+ if (!existing)
312603
+ return undefined;
312604
+ const current = fromDbRow(existing);
312605
+ const updated = { ...current, ...patch, id: current.id };
312606
+ const row = toInsertRow(updated);
312607
+ // Remove id from update (PK cannot change)
312608
+ delete row.id;
312609
+ await knex('schedules').where('id', id).update(row);
312610
+ return updated;
312611
+ }
312612
+ async delete(id) {
312613
+ const knex = this.getKnex();
312614
+ const deleted = await knex('schedules').where('id', id).del();
312615
+ if (deleted > 0) {
312616
+ logger_1.logger.info(`[KnexStore] Deleted schedule ${id}`);
312617
+ return true;
312618
+ }
312619
+ return false;
312620
+ }
312621
+ // --- Queries ---
312622
+ async getByCreator(creatorId) {
312623
+ const knex = this.getKnex();
312624
+ const rows = await knex('schedules').where('creator_id', creatorId);
312625
+ return rows.map((r) => fromDbRow(r));
312626
+ }
312627
+ async getActiveSchedules() {
312628
+ const knex = this.getKnex();
312629
+ const rows = await knex('schedules').where('status', 'active');
312630
+ return rows.map((r) => fromDbRow(r));
312631
+ }
312632
+ async getDueSchedules(now) {
312633
+ const ts = now ?? Date.now();
312634
+ const knex = this.getKnex();
312635
+ // MSSQL uses 1/0 for booleans
312636
+ const bFalse = this.driver === 'mssql' ? 0 : false;
312637
+ const bTrue = this.driver === 'mssql' ? 1 : true;
312638
+ const rows = await knex('schedules')
312639
+ .where('status', 'active')
312640
+ .andWhere(function () {
312641
+ this.where(function () {
312642
+ this.where('is_recurring', bFalse)
312643
+ .whereNotNull('run_at')
312644
+ .where('run_at', '<=', ts);
312645
+ }).orWhere(function () {
312646
+ this.where('is_recurring', bTrue)
312647
+ .whereNotNull('next_run_at')
312648
+ .where('next_run_at', '<=', ts);
312649
+ });
312650
+ });
312651
+ return rows.map((r) => fromDbRow(r));
312652
+ }
312653
+ async findByWorkflow(creatorId, workflowName) {
312654
+ const knex = this.getKnex();
312655
+ const escaped = workflowName.toLowerCase().replace(/[%_\\]/g, '\\$&');
312656
+ const pattern = `%${escaped}%`;
312657
+ const rows = await knex('schedules')
312658
+ .where('creator_id', creatorId)
312659
+ .where('status', 'active')
312660
+ .whereRaw("LOWER(workflow) LIKE ? ESCAPE '\\'", [pattern]);
312661
+ return rows.map((r) => fromDbRow(r));
312662
+ }
312663
+ async getAll() {
312664
+ const knex = this.getKnex();
312665
+ const rows = await knex('schedules');
312666
+ return rows.map((r) => fromDbRow(r));
312667
+ }
312668
+ async getStats() {
312669
+ const knex = this.getKnex();
312670
+ // MSSQL uses 1/0 for booleans; PostgreSQL/MySQL accept both true/1
312671
+ const boolTrue = this.driver === 'mssql' ? '1' : 'true';
312672
+ const boolFalse = this.driver === 'mssql' ? '0' : 'false';
312673
+ const result = await knex('schedules')
312674
+ .select(knex.raw('COUNT(*) as total'), knex.raw("SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active"), knex.raw("SUM(CASE WHEN status = 'paused' THEN 1 ELSE 0 END) as paused"), knex.raw("SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed"), knex.raw("SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed"), knex.raw(`SUM(CASE WHEN is_recurring = ${boolTrue} THEN 1 ELSE 0 END) as recurring`), knex.raw(`SUM(CASE WHEN is_recurring = ${boolFalse} THEN 1 ELSE 0 END) as one_time`))
312675
+ .first();
312676
+ return {
312677
+ total: Number(result.total) || 0,
312678
+ active: Number(result.active) || 0,
312679
+ paused: Number(result.paused) || 0,
312680
+ completed: Number(result.completed) || 0,
312681
+ failed: Number(result.failed) || 0,
312682
+ recurring: Number(result.recurring) || 0,
312683
+ oneTime: Number(result.one_time) || 0,
312684
+ };
312685
+ }
312686
+ async validateLimits(creatorId, isRecurring, limits) {
312687
+ const knex = this.getKnex();
312688
+ if (limits.maxGlobal) {
312689
+ const result = await knex('schedules').count('* as cnt').first();
312690
+ if (Number(result?.cnt) >= limits.maxGlobal) {
312691
+ throw new Error(`Global schedule limit reached (${limits.maxGlobal})`);
312692
+ }
312693
+ }
312694
+ if (limits.maxPerUser) {
312695
+ const result = await knex('schedules')
312696
+ .where('creator_id', creatorId)
312697
+ .count('* as cnt')
312698
+ .first();
312699
+ if (Number(result?.cnt) >= limits.maxPerUser) {
312700
+ throw new Error(`You have reached the maximum number of schedules (${limits.maxPerUser})`);
312701
+ }
312702
+ }
312703
+ if (isRecurring && limits.maxRecurringPerUser) {
312704
+ const bTrue = this.driver === 'mssql' ? 1 : true;
312705
+ const result = await knex('schedules')
312706
+ .where('creator_id', creatorId)
312707
+ .where('is_recurring', bTrue)
312708
+ .count('* as cnt')
312709
+ .first();
312710
+ if (Number(result?.cnt) >= limits.maxRecurringPerUser) {
312711
+ throw new Error(`You have reached the maximum number of recurring schedules (${limits.maxRecurringPerUser})`);
312712
+ }
312713
+ }
312714
+ }
312715
+ // --- HA Distributed Locking (via scheduler_locks table) ---
312716
+ async tryAcquireLock(lockId, nodeId, ttlSeconds) {
312717
+ const knex = this.getKnex();
312718
+ const now = Date.now();
312719
+ const expiresAt = now + ttlSeconds * 1000;
312720
+ const token = (0, uuid_1.v4)();
312721
+ // Step 1: Try to claim an existing expired lock
312722
+ const updated = await knex('scheduler_locks')
312723
+ .where('lock_id', lockId)
312724
+ .where('expires_at', '<', now)
312725
+ .update({
312726
+ node_id: nodeId,
312727
+ lock_token: token,
312728
+ acquired_at: now,
312729
+ expires_at: expiresAt,
312730
+ });
312731
+ if (updated > 0)
312732
+ return token;
312733
+ // Step 2: Try to INSERT a new lock row
312734
+ try {
312735
+ await knex('scheduler_locks').insert({
312736
+ lock_id: lockId,
312737
+ node_id: nodeId,
312738
+ lock_token: token,
312739
+ acquired_at: now,
312740
+ expires_at: expiresAt,
312741
+ });
312742
+ return token;
312743
+ }
312744
+ catch {
312745
+ // Unique constraint violation — another node holds the lock
312746
+ return null;
312747
+ }
312748
+ }
312749
+ async releaseLock(lockId, lockToken) {
312750
+ const knex = this.getKnex();
312751
+ await knex('scheduler_locks').where('lock_id', lockId).where('lock_token', lockToken).del();
312752
+ }
312753
+ async renewLock(lockId, lockToken, ttlSeconds) {
312754
+ const knex = this.getKnex();
312755
+ const now = Date.now();
312756
+ const expiresAt = now + ttlSeconds * 1000;
312757
+ const updated = await knex('scheduler_locks')
312758
+ .where('lock_id', lockId)
312759
+ .where('lock_token', lockToken)
312760
+ .update({ acquired_at: now, expires_at: expiresAt });
312761
+ return updated > 0;
312762
+ }
312763
+ async flush() {
312764
+ // No-op for server-based backends
312765
+ }
312766
+ // --- Message Trigger CRUD ---
312767
+ async createTrigger(trigger) {
312768
+ const knex = this.getKnex();
312769
+ const newTrigger = {
312770
+ ...trigger,
312771
+ id: (0, uuid_1.v4)(),
312772
+ createdAt: Date.now(),
312773
+ };
312774
+ await knex('message_triggers').insert(toTriggerInsertRow(newTrigger));
312775
+ logger_1.logger.info(`[KnexStore] Created trigger ${newTrigger.id} for user ${newTrigger.creatorId}`);
312776
+ return newTrigger;
312777
+ }
312778
+ async getTrigger(id) {
312779
+ const knex = this.getKnex();
312780
+ const row = await knex('message_triggers').where('id', id).first();
312781
+ return row ? fromTriggerRow(row) : undefined;
312782
+ }
312783
+ async updateTrigger(id, patch) {
312784
+ const knex = this.getKnex();
312785
+ const existing = await knex('message_triggers').where('id', id).first();
312786
+ if (!existing)
312787
+ return undefined;
312788
+ const current = fromTriggerRow(existing);
312789
+ const updated = {
312790
+ ...current,
312791
+ ...patch,
312792
+ id: current.id,
312793
+ createdAt: current.createdAt,
312794
+ };
312795
+ const row = toTriggerInsertRow(updated);
312796
+ delete row.id;
312797
+ await knex('message_triggers').where('id', id).update(row);
312798
+ return updated;
312799
+ }
312800
+ async deleteTrigger(id) {
312801
+ const knex = this.getKnex();
312802
+ const deleted = await knex('message_triggers').where('id', id).del();
312803
+ if (deleted > 0) {
312804
+ logger_1.logger.info(`[KnexStore] Deleted trigger ${id}`);
312805
+ return true;
312806
+ }
312807
+ return false;
312808
+ }
312809
+ async getTriggersByCreator(creatorId) {
312810
+ const knex = this.getKnex();
312811
+ const rows = await knex('message_triggers').where('creator_id', creatorId);
312812
+ return rows.map((r) => fromTriggerRow(r));
312813
+ }
312814
+ async getActiveTriggers() {
312815
+ const knex = this.getKnex();
312816
+ const rows = await knex('message_triggers')
312817
+ .where('status', 'active')
312818
+ .where('enabled', this.driver === 'mssql' ? 1 : true);
312819
+ return rows.map((r) => fromTriggerRow(r));
312820
+ }
312821
+ }
312822
+ exports.KnexStoreBackend = KnexStoreBackend;
312823
+
312824
+
311021
312825
  /***/ }),
311022
312826
 
311023
312827
  /***/ 83864:
@@ -314274,6 +316078,22 @@ exports.configSchema = {
314274
316078
  $ref: '#/definitions/SlackConfig',
314275
316079
  description: 'Slack configuration',
314276
316080
  },
316081
+ telegram: {
316082
+ $ref: '#/definitions/TelegramConfig',
316083
+ description: 'Telegram bot configuration',
316084
+ },
316085
+ email: {
316086
+ $ref: '#/definitions/EmailConfig',
316087
+ description: 'Email integration configuration',
316088
+ },
316089
+ whatsapp: {
316090
+ $ref: '#/definitions/WhatsAppConfig',
316091
+ description: 'WhatsApp bot configuration',
316092
+ },
316093
+ teams: {
316094
+ $ref: '#/definitions/TeamsConfig',
316095
+ description: 'Microsoft Teams bot configuration',
316096
+ },
314277
316097
  scheduler: {
314278
316098
  $ref: '#/definitions/SchedulerConfig',
314279
316099
  description: 'Scheduler configuration for scheduled workflow execution',
@@ -315047,7 +316867,7 @@ exports.configSchema = {
315047
316867
  description: 'Arguments/inputs for the workflow',
315048
316868
  },
315049
316869
  overrides: {
315050
- $ref: '#/definitions/Record%3Cstring%2CPartial%3Cinterface-src_types_config.ts-13844-28438-src_types_config.ts-0-56400%3E%3E',
316870
+ $ref: '#/definitions/Record%3Cstring%2CPartial%3Cinterface-src_types_config.ts-14017-28611-src_types_config.ts-0-56833%3E%3E',
315051
316871
  description: 'Override specific step configurations in the workflow',
315052
316872
  },
315053
316873
  output_mapping: {
@@ -315063,7 +316883,7 @@ exports.configSchema = {
315063
316883
  description: 'Config file path - alternative to workflow ID (loads a Visor config file as workflow)',
315064
316884
  },
315065
316885
  workflow_overrides: {
315066
- $ref: '#/definitions/Record%3Cstring%2CPartial%3Cinterface-src_types_config.ts-13844-28438-src_types_config.ts-0-56400%3E%3E',
316886
+ $ref: '#/definitions/Record%3Cstring%2CPartial%3Cinterface-src_types_config.ts-14017-28611-src_types_config.ts-0-56833%3E%3E',
315067
316887
  description: 'Alias for overrides - workflow step overrides (backward compatibility)',
315068
316888
  },
315069
316889
  ref: {
@@ -315248,6 +317068,10 @@ exports.configSchema = {
315248
317068
  'schedule',
315249
317069
  'webhook_received',
315250
317070
  'slack_message',
317071
+ 'telegram_message',
317072
+ 'email_message',
317073
+ 'whatsapp_message',
317074
+ 'teams_message',
315251
317075
  ],
315252
317076
  description: 'Valid event triggers for checks',
315253
317077
  },
@@ -315761,7 +317585,7 @@ exports.configSchema = {
315761
317585
  description: 'Custom output name (defaults to workflow name)',
315762
317586
  },
315763
317587
  overrides: {
315764
- $ref: '#/definitions/Record%3Cstring%2CPartial%3Cinterface-src_types_config.ts-13844-28438-src_types_config.ts-0-56400%3E%3E',
317588
+ $ref: '#/definitions/Record%3Cstring%2CPartial%3Cinterface-src_types_config.ts-14017-28611-src_types_config.ts-0-56833%3E%3E',
315765
317589
  description: 'Step overrides',
315766
317590
  },
315767
317591
  output_mapping: {
@@ -315776,13 +317600,13 @@ exports.configSchema = {
315776
317600
  '^x-': {},
315777
317601
  },
315778
317602
  },
315779
- 'Record<string,Partial<interface-src_types_config.ts-13844-28438-src_types_config.ts-0-56400>>': {
317603
+ 'Record<string,Partial<interface-src_types_config.ts-14017-28611-src_types_config.ts-0-56833>>': {
315780
317604
  type: 'object',
315781
317605
  additionalProperties: {
315782
- $ref: '#/definitions/Partial%3Cinterface-src_types_config.ts-13844-28438-src_types_config.ts-0-56400%3E',
317606
+ $ref: '#/definitions/Partial%3Cinterface-src_types_config.ts-14017-28611-src_types_config.ts-0-56833%3E',
315783
317607
  },
315784
317608
  },
315785
- 'Partial<interface-src_types_config.ts-13844-28438-src_types_config.ts-0-56400>': {
317609
+ 'Partial<interface-src_types_config.ts-14017-28611-src_types_config.ts-0-56833>': {
315786
317610
  type: 'object',
315787
317611
  additionalProperties: false,
315788
317612
  },
@@ -316641,6 +318465,260 @@ exports.configSchema = {
316641
318465
  '^x-': {},
316642
318466
  },
316643
318467
  },
318468
+ TelegramConfig: {
318469
+ type: 'object',
318470
+ properties: {
318471
+ bot_token: {
318472
+ type: 'string',
318473
+ description: 'Bot token from',
318474
+ },
318475
+ polling_timeout: {
318476
+ type: 'number',
318477
+ description: 'Polling timeout in seconds for getUpdates (default: 30)',
318478
+ },
318479
+ chat_allowlist: {
318480
+ type: 'array',
318481
+ items: {
318482
+ type: ['string', 'number'],
318483
+ },
318484
+ description: 'Chat/group allowlist - numeric chat IDs that the bot responds in',
318485
+ },
318486
+ require_mention: {
318487
+ type: 'boolean',
318488
+ description: 'In groups, only respond when',
318489
+ },
318490
+ workflow: {
318491
+ type: 'string',
318492
+ description: 'Workflow to run when a message is received',
318493
+ },
318494
+ },
318495
+ additionalProperties: false,
318496
+ patternProperties: {
318497
+ '^x-': {},
318498
+ },
318499
+ },
318500
+ EmailConfig: {
318501
+ type: 'object',
318502
+ properties: {
318503
+ receive: {
318504
+ type: 'object',
318505
+ properties: {
318506
+ type: {
318507
+ type: 'string',
318508
+ enum: ['imap', 'resend'],
318509
+ description: "Backend type: 'imap' (universal) or 'resend' (managed webhook)",
318510
+ },
318511
+ host: {
318512
+ type: 'string',
318513
+ description: 'IMAP server hostname',
318514
+ },
318515
+ port: {
318516
+ type: 'number',
318517
+ description: 'IMAP server port (default: 993)',
318518
+ },
318519
+ auth: {
318520
+ type: 'object',
318521
+ properties: {
318522
+ user: {
318523
+ type: 'string',
318524
+ },
318525
+ pass: {
318526
+ type: 'string',
318527
+ },
318528
+ },
318529
+ additionalProperties: false,
318530
+ description: 'IMAP auth credentials',
318531
+ patternProperties: {
318532
+ '^x-': {},
318533
+ },
318534
+ },
318535
+ secure: {
318536
+ type: 'boolean',
318537
+ description: 'Use TLS (default: true)',
318538
+ },
318539
+ poll_interval: {
318540
+ type: 'number',
318541
+ description: 'Polling interval in seconds when IDLE not available (default: 30)',
318542
+ },
318543
+ folder: {
318544
+ type: 'string',
318545
+ description: "IMAP folder to monitor (default: 'INBOX')",
318546
+ },
318547
+ mark_read: {
318548
+ type: 'boolean',
318549
+ description: 'Mark processed messages as read (default: true)',
318550
+ },
318551
+ api_key: {
318552
+ type: 'string',
318553
+ description: "Resend API key (for type: 'resend')",
318554
+ },
318555
+ webhook_secret: {
318556
+ type: 'string',
318557
+ description: 'Resend webhook secret for signature verification',
318558
+ },
318559
+ },
318560
+ additionalProperties: false,
318561
+ description: 'Receive backend configuration',
318562
+ patternProperties: {
318563
+ '^x-': {},
318564
+ },
318565
+ },
318566
+ send: {
318567
+ type: 'object',
318568
+ properties: {
318569
+ type: {
318570
+ type: 'string',
318571
+ enum: ['smtp', 'resend'],
318572
+ description: "Backend type: 'smtp' (universal) or 'resend' (managed API)",
318573
+ },
318574
+ host: {
318575
+ type: 'string',
318576
+ description: 'SMTP server hostname',
318577
+ },
318578
+ port: {
318579
+ type: 'number',
318580
+ description: 'SMTP server port (default: 587)',
318581
+ },
318582
+ auth: {
318583
+ type: 'object',
318584
+ properties: {
318585
+ user: {
318586
+ type: 'string',
318587
+ },
318588
+ pass: {
318589
+ type: 'string',
318590
+ },
318591
+ },
318592
+ additionalProperties: false,
318593
+ description: 'SMTP auth credentials',
318594
+ patternProperties: {
318595
+ '^x-': {},
318596
+ },
318597
+ },
318598
+ secure: {
318599
+ type: 'boolean',
318600
+ description: 'Use TLS (default: true)',
318601
+ },
318602
+ from: {
318603
+ type: 'string',
318604
+ description: 'Default sender address (e.g., "Bot <bot@example.com>")',
318605
+ },
318606
+ api_key: {
318607
+ type: 'string',
318608
+ description: "Resend API key (for type: 'resend')",
318609
+ },
318610
+ },
318611
+ additionalProperties: false,
318612
+ description: 'Send backend configuration',
318613
+ patternProperties: {
318614
+ '^x-': {},
318615
+ },
318616
+ },
318617
+ allowlist: {
318618
+ type: 'array',
318619
+ items: {
318620
+ type: 'string',
318621
+ },
318622
+ description: 'Only process emails from these senders',
318623
+ },
318624
+ workflow: {
318625
+ type: 'string',
318626
+ description: 'Workflow to run when an email is received',
318627
+ },
318628
+ },
318629
+ additionalProperties: false,
318630
+ patternProperties: {
318631
+ '^x-': {},
318632
+ },
318633
+ },
318634
+ WhatsAppConfig: {
318635
+ type: 'object',
318636
+ properties: {
318637
+ access_token: {
318638
+ type: 'string',
318639
+ description: 'WhatsApp Cloud API access token (or WHATSAPP_ACCESS_TOKEN env var)',
318640
+ },
318641
+ phone_number_id: {
318642
+ type: 'string',
318643
+ description: 'Phone Number ID from Meta Business Suite (or WHATSAPP_PHONE_NUMBER_ID env var)',
318644
+ },
318645
+ app_secret: {
318646
+ type: 'string',
318647
+ description: 'Meta App Secret for webhook signature verification (or WHATSAPP_APP_SECRET env var)',
318648
+ },
318649
+ verify_token: {
318650
+ type: 'string',
318651
+ description: 'Verify token for webhook subscription challenge (or WHATSAPP_VERIFY_TOKEN env var)',
318652
+ },
318653
+ api_version: {
318654
+ type: 'string',
318655
+ description: "Graph API version (default: 'v21.0')",
318656
+ },
318657
+ port: {
318658
+ type: 'number',
318659
+ description: 'Port for webhook HTTP server (default: 8443)',
318660
+ },
318661
+ host: {
318662
+ type: 'string',
318663
+ description: "Host for webhook HTTP server (default: '0.0.0.0')",
318664
+ },
318665
+ phone_allowlist: {
318666
+ type: 'array',
318667
+ items: {
318668
+ type: 'string',
318669
+ },
318670
+ description: 'Phone number allowlist — only respond to these numbers',
318671
+ },
318672
+ workflow: {
318673
+ type: 'string',
318674
+ description: 'Workflow to run when a message is received',
318675
+ },
318676
+ },
318677
+ additionalProperties: false,
318678
+ patternProperties: {
318679
+ '^x-': {},
318680
+ },
318681
+ },
318682
+ TeamsConfig: {
318683
+ type: 'object',
318684
+ properties: {
318685
+ app_id: {
318686
+ type: 'string',
318687
+ description: 'Azure AD App (client) ID (or TEAMS_APP_ID env var)',
318688
+ },
318689
+ app_password: {
318690
+ type: 'string',
318691
+ description: 'Azure AD App client secret (or TEAMS_APP_PASSWORD env var)',
318692
+ },
318693
+ tenant_id: {
318694
+ type: 'string',
318695
+ description: 'Azure AD Tenant ID for single-tenant apps (or TEAMS_TENANT_ID env var)',
318696
+ },
318697
+ port: {
318698
+ type: 'number',
318699
+ description: 'Port for webhook HTTP server (default: 3978)',
318700
+ },
318701
+ host: {
318702
+ type: 'string',
318703
+ description: "Host for webhook HTTP server (default: '0.0.0.0')",
318704
+ },
318705
+ user_allowlist: {
318706
+ type: 'array',
318707
+ items: {
318708
+ type: 'string',
318709
+ },
318710
+ description: 'User ID allowlist — only respond to these AAD user IDs',
318711
+ },
318712
+ workflow: {
318713
+ type: 'string',
318714
+ description: 'Workflow to run when a message is received',
318715
+ },
318716
+ },
318717
+ additionalProperties: false,
318718
+ patternProperties: {
318719
+ '^x-': {},
318720
+ },
318721
+ },
316644
318722
  SchedulerConfig: {
316645
318723
  type: 'object',
316646
318724
  properties: {
@@ -323257,6 +325335,35 @@ class OutputFormatters {
323257
325335
  exports.OutputFormatters = OutputFormatters;
323258
325336
 
323259
325337
 
325338
+ /***/ }),
325339
+
325340
+ /***/ 93866:
325341
+ /***/ ((__unused_webpack_module, exports) => {
325342
+
325343
+ "use strict";
325344
+
325345
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
325346
+ exports.DefaultPolicyEngine = void 0;
325347
+ /**
325348
+ * Default (no-op) policy engine — always allows everything.
325349
+ * Used when no enterprise license is present or policy is disabled.
325350
+ */
325351
+ class DefaultPolicyEngine {
325352
+ async initialize(_config) { }
325353
+ async evaluateCheckExecution(_checkId, _checkConfig) {
325354
+ return { allowed: true };
325355
+ }
325356
+ async evaluateToolInvocation(_serverName, _methodName, _transport) {
325357
+ return { allowed: true };
325358
+ }
325359
+ async evaluateCapabilities(_checkId, _capabilities) {
325360
+ return { allowed: true };
325361
+ }
325362
+ async shutdown() { }
325363
+ }
325364
+ exports.DefaultPolicyEngine = DefaultPolicyEngine;
325365
+
325366
+
323260
325367
  /***/ }),
323261
325368
 
323262
325369
  /***/ 96611:
@@ -346248,7 +348355,7 @@ class StateMachineExecutionEngine {
346248
348355
  try {
346249
348356
  logger_1.logger.debug(`[PolicyEngine] Loading enterprise policy engine (engine=${configWithTagFilter.policy.engine})`);
346250
348357
  // @ts-ignore — enterprise/ may not exist in OSS builds (caught at runtime)
346251
- const { loadEnterprisePolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(7065)));
348358
+ const { loadEnterprisePolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(87068)));
346252
348359
  context.policyEngine = await loadEnterprisePolicyEngine(configWithTagFilter.policy);
346253
348360
  logger_1.logger.debug(`[PolicyEngine] Initialized: ${context.policyEngine?.constructor?.name || 'unknown'}`);
346254
348361
  }
@@ -357681,7 +359788,12 @@ exports.getTestMetricsSnapshot = getTestMetricsSnapshot;
357681
359788
  exports.resetTestMetricsSnapshot = resetTestMetricsSnapshot;
357682
359789
  const lazy_otel_1 = __nccwpck_require__(21084);
357683
359790
  let initialized = false;
357684
- const meter = lazy_otel_1.metrics.getMeter('visor');
359791
+ // Lazy meter: acquired inside ensureInstruments() so that the MeterProvider
359792
+ // registered by NodeSDK (in initTelemetry) is available. Acquiring at
359793
+ // module-load time would return a no-op meter because the SDK hasn't started.
359794
+ function getMeter() {
359795
+ return lazy_otel_1.metrics.getMeter('visor');
359796
+ }
357685
359797
  // Test helpers (enabled with VISOR_TEST_METRICS=true)
357686
359798
  const TEST_ENABLED = process.env.VISOR_TEST_METRICS === 'true';
357687
359799
  const TEST_SNAPSHOT = { fail_if_triggered: 0 };
@@ -357701,47 +359813,47 @@ function ensureInstruments() {
357701
359813
  if (initialized)
357702
359814
  return;
357703
359815
  try {
357704
- checkDurationHist = meter.createHistogram('visor.check.duration_ms', {
359816
+ checkDurationHist = getMeter().createHistogram('visor.check.duration_ms', {
357705
359817
  description: 'Duration of a check execution in milliseconds',
357706
359818
  unit: 'ms',
357707
359819
  });
357708
- providerDurationHist = meter.createHistogram('visor.provider.duration_ms', {
359820
+ providerDurationHist = getMeter().createHistogram('visor.provider.duration_ms', {
357709
359821
  description: 'Duration of provider execution in milliseconds',
357710
359822
  unit: 'ms',
357711
359823
  });
357712
- foreachDurationHist = meter.createHistogram('visor.foreach.item.duration_ms', {
359824
+ foreachDurationHist = getMeter().createHistogram('visor.foreach.item.duration_ms', {
357713
359825
  description: 'Duration of a forEach item execution in milliseconds',
357714
359826
  unit: 'ms',
357715
359827
  });
357716
- issuesCounter = meter.createCounter('visor.check.issues', {
359828
+ issuesCounter = getMeter().createCounter('visor.check.issues', {
357717
359829
  description: 'Number of issues produced by checks',
357718
359830
  unit: '1',
357719
359831
  });
357720
- activeChecks = meter.createUpDownCounter('visor.run.active_checks', {
359832
+ activeChecks = getMeter().createUpDownCounter('visor.run.active_checks', {
357721
359833
  description: 'Number of checks actively running',
357722
359834
  unit: '1',
357723
359835
  });
357724
- failIfCounter = meter.createCounter('visor.fail_if.triggered', {
359836
+ failIfCounter = getMeter().createCounter('visor.fail_if.triggered', {
357725
359837
  description: 'Number of times fail_if condition triggered',
357726
359838
  unit: '1',
357727
359839
  });
357728
- diagramBlocks = meter.createCounter('visor.diagram.blocks', {
359840
+ diagramBlocks = getMeter().createCounter('visor.diagram.blocks', {
357729
359841
  description: 'Number of Mermaid diagram blocks emitted',
357730
359842
  unit: '1',
357731
359843
  });
357732
- runCounter = meter.createCounter('visor.run.total', {
359844
+ runCounter = getMeter().createCounter('visor.run.total', {
357733
359845
  description: 'Total number of visor runs (workflow executions)',
357734
359846
  unit: '1',
357735
359847
  });
357736
- runDurationHist = meter.createHistogram('visor.run.duration_ms', {
359848
+ runDurationHist = getMeter().createHistogram('visor.run.duration_ms', {
357737
359849
  description: 'Duration of a complete visor run in milliseconds',
357738
359850
  unit: 'ms',
357739
359851
  });
357740
- aiCallCounter = meter.createCounter('visor.ai_call.total', {
359852
+ aiCallCounter = getMeter().createCounter('visor.ai_call.total', {
357741
359853
  description: 'Total number of AI provider calls',
357742
359854
  unit: '1',
357743
359855
  });
357744
- runAiCallsHist = meter.createHistogram('visor.run.ai_calls', {
359856
+ runAiCallsHist = getMeter().createHistogram('visor.run.ai_calls', {
357745
359857
  description: 'Number of AI calls per visor run',
357746
359858
  unit: '1',
357747
359859
  });
@@ -357982,7 +360094,7 @@ async function initTelemetry(opts = {}) {
357982
360094
  const path = __nccwpck_require__(16928);
357983
360095
  const outDir = opts.file?.dir ||
357984
360096
  process.env.VISOR_TRACE_DIR ||
357985
- __nccwpck_require__.ab + "traces";
360097
+ path.join(process.cwd(), 'output', 'traces');
357986
360098
  fs.mkdirSync(outDir, { recursive: true });
357987
360099
  const ts = new Date().toISOString().replace(/[:.]/g, '-');
357988
360100
  process.env.VISOR_FALLBACK_TRACE_FILE = path.join(outDir, `run-${ts}.ndjson`);
@@ -358232,7 +360344,7 @@ async function shutdownTelemetry() {
358232
360344
  if (process.env.VISOR_TRACE_REPORT === 'true') {
358233
360345
  const fs = __nccwpck_require__(79896);
358234
360346
  const path = __nccwpck_require__(16928);
358235
- const outDir = process.env.VISOR_TRACE_DIR || __nccwpck_require__.ab + "traces";
360347
+ const outDir = process.env.VISOR_TRACE_DIR || path.join(process.cwd(), 'output', 'traces');
358236
360348
  if (!fs.existsSync(outDir))
358237
360349
  fs.mkdirSync(outDir, { recursive: true });
358238
360350
  const ts = new Date().toISOString().replace(/[:.]/g, '-');
@@ -358783,7 +360895,7 @@ function __getOrCreateNdjsonPath() {
358783
360895
  fs.mkdirSync(dir, { recursive: true });
358784
360896
  return __ndjsonPath;
358785
360897
  }
358786
- const outDir = process.env.VISOR_TRACE_DIR || __nccwpck_require__.ab + "traces";
360898
+ const outDir = process.env.VISOR_TRACE_DIR || path.join(process.cwd(), 'output', 'traces');
358787
360899
  if (!fs.existsSync(outDir))
358788
360900
  fs.mkdirSync(outDir, { recursive: true });
358789
360901
  if (!__ndjsonPath) {
@@ -374709,22 +376821,6 @@ class WorkflowRegistry {
374709
376821
  exports.WorkflowRegistry = WorkflowRegistry;
374710
376822
 
374711
376823
 
374712
- /***/ }),
374713
-
374714
- /***/ 7065:
374715
- /***/ ((module) => {
374716
-
374717
- module.exports = eval("require")("./enterprise/loader");
374718
-
374719
-
374720
- /***/ }),
374721
-
374722
- /***/ 71370:
374723
- /***/ ((module) => {
374724
-
374725
- module.exports = eval("require")("./enterprise/policy/policy-input-builder");
374726
-
374727
-
374728
376824
  /***/ }),
374729
376825
 
374730
376826
  /***/ 18327:
@@ -448808,13 +450904,13 @@ function categorizeError(error40) {
448808
450904
  if (lowerMessage.includes("path does not exist") || lowerMessage.includes("no such file or directory") || errorCode === "enoent") {
448809
450905
  return new PathError(message, {
448810
450906
  originalError: error40,
448811
- suggestion: "The specified path does not exist. Please verify the path or use a different directory."
450907
+ suggestion: "The specified path does not exist. Use the listFiles tool to check the correct directory structure, then retry with a valid path."
448812
450908
  });
448813
450909
  }
448814
450910
  if (lowerMessage.includes("not a directory") || errorCode === "enotdir") {
448815
450911
  return new PathError(message, {
448816
450912
  originalError: error40,
448817
- suggestion: "The path is not a directory. Please provide a valid directory path."
450913
+ suggestion: "The path is not a directory. Use the listFiles tool to find the correct directory, then retry."
448818
450914
  });
448819
450915
  }
448820
450916
  if (lowerMessage.includes("permission denied") || errorCode === "eacces") {
@@ -449070,7 +451166,7 @@ async function validateCwdPath(inputPath, defaultPath = process.cwd()) {
449070
451166
  }
449071
451167
  if (error40.code === "ENOENT") {
449072
451168
  throw new PathError(`Path does not exist: ${normalizedPath}`, {
449073
- suggestion: "The specified path does not exist. Please verify the path is correct or use a different directory.",
451169
+ suggestion: "The specified path does not exist. Use the listFiles tool to check the correct directory structure, then retry with a valid path.",
449074
451170
  details: { path: normalizedPath }
449075
451171
  });
449076
451172
  }
@@ -530061,6 +532157,9 @@ var require_utils2 = __commonJS({
530061
532157
  sandboxGlobal
530062
532158
  };
530063
532159
  context.prototypeWhitelist.set(Object.getPrototypeOf([][Symbol.iterator]()), /* @__PURE__ */ new Set());
532160
+ context.prototypeWhitelist.set(Object.getPrototypeOf(""[Symbol.iterator]()), /* @__PURE__ */ new Set());
532161
+ context.prototypeWhitelist.set(Object.getPrototypeOf((/* @__PURE__ */ new Set())[Symbol.iterator]()), /* @__PURE__ */ new Set());
532162
+ context.prototypeWhitelist.set(Object.getPrototypeOf((/* @__PURE__ */ new Map())[Symbol.iterator]()), /* @__PURE__ */ new Set());
530064
532163
  return context;
530065
532164
  }
530066
532165
  function createExecContext(sandbox, executionTree, evalContext) {
@@ -531199,6 +533298,18 @@ var require_executor = __commonJS({
531199
533298
  a = void 0;
531200
533299
  }
531201
533300
  }
533301
+ if (op === 29 && !a) {
533302
+ done(void 0, a);
533303
+ return;
533304
+ }
533305
+ if (op === 30 && a) {
533306
+ done(void 0, a);
533307
+ return;
533308
+ }
533309
+ if (op === 85 && a !== null && a !== void 0) {
533310
+ done(void 0, a);
533311
+ return;
533312
+ }
531202
533313
  let bobj;
531203
533314
  try {
531204
533315
  let ad;
@@ -531261,6 +533372,18 @@ var require_executor = __commonJS({
531261
533372
  a = void 0;
531262
533373
  }
531263
533374
  }
533375
+ if (op === 29 && !a) {
533376
+ done(void 0, a);
533377
+ return;
533378
+ }
533379
+ if (op === 30 && a) {
533380
+ done(void 0, a);
533381
+ return;
533382
+ }
533383
+ if (op === 85 && a !== null && a !== void 0) {
533384
+ done(void 0, a);
533385
+ return;
533386
+ }
531264
533387
  let bobj;
531265
533388
  try {
531266
533389
  bobj = syncDone((d) => execSync(ticks, tree[2], scope, context, d, inLoopOrSwitch)).result;
@@ -544899,7 +547022,7 @@ var init_ProbeAgent = __esm({
544899
547022
  if (limiter && result.textStream) {
544900
547023
  const originalStream = result.textStream;
544901
547024
  const debug = this.debug;
544902
- result.textStream = (async function* () {
547025
+ const wrappedStream = (async function* () {
544903
547026
  try {
544904
547027
  for await (const chunk of originalStream) {
544905
547028
  yield chunk;
@@ -544912,6 +547035,13 @@ var init_ProbeAgent = __esm({
544912
547035
  }
544913
547036
  }
544914
547037
  })();
547038
+ return new Proxy(result, {
547039
+ get(target, prop) {
547040
+ if (prop === "textStream") return wrappedStream;
547041
+ const value = target[prop];
547042
+ return typeof value === "function" ? value.bind(target) : value;
547043
+ }
547044
+ });
544915
547045
  } else if (limiter) {
544916
547046
  limiter.release(null);
544917
547047
  }
@@ -546565,6 +548695,21 @@ You are working with a workspace. Available paths: ${workspaceDesc}
546565
548695
  }
546566
548696
  }
546567
548697
  }
548698
+ if (steps.length >= 3) {
548699
+ const last3 = steps.slice(-3);
548700
+ const allErrors = last3.every(
548701
+ (s) => s.toolResults?.length > 0 && s.toolResults.every((tr) => {
548702
+ const r = typeof tr.result === "string" ? tr.result : "";
548703
+ return r.includes("<error ") || r.includes("does not exist");
548704
+ })
548705
+ );
548706
+ if (allErrors) {
548707
+ if (this.debug) {
548708
+ console.log(`[DEBUG] prepareStep: 3 consecutive tool errors, forcing toolChoice=none`);
548709
+ }
548710
+ return { toolChoice: "none" };
548711
+ }
548712
+ }
546568
548713
  const lastStep = steps[steps.length - 1];
546569
548714
  const modelJustStopped = lastStep?.finishReason === "stop" && (!lastStep?.toolCalls || lastStep.toolCalls.length === 0);
546570
548715
  if (modelJustStopped) {
@@ -546593,7 +548738,8 @@ Here is the result to review:
546593
548738
  ${resultToReview}
546594
548739
  </result>
546595
548740
 
546596
- Double-check your response based on the criteria above. If everything looks good, respond with your previous answer exactly as-is. If something needs to be fixed or is missing, do it now, then respond with the COMPLETE updated answer (everything you did in total, not just the fix).`;
548741
+ IMPORTANT: First review ALL completed work in the conversation above before taking any action.
548742
+ Double-check your response based on the criteria above. If everything looks good, respond with your previous answer exactly as-is. If your text has inaccuracies, fix the text. Only call a tool if you find a genuinely MISSING action \u2014 NEVER redo work that was already completed successfully. Respond with the COMPLETE corrected answer.`;
546597
548743
  return {
546598
548744
  userMessage: completionPromptMessage,
546599
548745
  toolChoice: "none"
@@ -546752,7 +548898,8 @@ Here is the result to review:
546752
548898
  ${finalResult}
546753
548899
  </result>
546754
548900
 
546755
- Double-check your response based on the criteria above. If everything looks good, respond with your previous answer exactly as-is. If something needs to be fixed or is missing, do it now, then respond with the COMPLETE updated answer (everything you did in total, not just the fix).`;
548901
+ IMPORTANT: First review ALL completed work in the conversation above before taking any action.
548902
+ Double-check your response based on the criteria above. If everything looks good, respond with your previous answer exactly as-is. If your text has inaccuracies, fix the text. Only call a tool if you find a genuinely MISSING action \u2014 NEVER redo work that was already completed successfully. Respond with the COMPLETE corrected answer.`;
546756
548903
  currentMessages.push({ role: "user", content: completionPromptMessage });
546757
548904
  const completionStreamOptions = {
546758
548905
  model: this.provider ? this.provider(this.model) : this.model,
@@ -548778,7 +550925,11 @@ var init_vercel = __esm({
548778
550925
  return result;
548779
550926
  } catch (error40) {
548780
550927
  console.error("Error executing search command:", error40);
548781
- return formatErrorForAI(error40);
550928
+ const formatted = formatErrorForAI(error40);
550929
+ if (error40.category === "path_error" || error40.message?.includes("does not exist")) {
550930
+ return formatted + "\n\nThe path does not exist. Use the listFiles tool to verify the correct directory structure before retrying. If the workspace itself is gone, output your final answer with whatever information you have.";
550931
+ }
550932
+ return formatted;
548782
550933
  }
548783
550934
  }
548784
550935
  try {
@@ -608036,7 +610187,7 @@ module.exports = /*#__PURE__*/JSON.parse('["aaa","aarp","abb","abbott","abbvie",
608036
610187
  /***/ ((module) => {
608037
610188
 
608038
610189
  "use strict";
608039
- module.exports = /*#__PURE__*/JSON.parse('{"name":"@probelabs/visor","version":"0.1.173","main":"dist/index.js","bin":{"visor":"./dist/index.js"},"exports":{".":{"require":"./dist/index.js","import":"./dist/index.js"},"./sdk":{"types":"./dist/sdk/sdk.d.ts","import":"./dist/sdk/sdk.mjs","require":"./dist/sdk/sdk.js"},"./cli":{"require":"./dist/index.js"}},"files":["dist/","defaults/","action.yml","README.md","LICENSE"],"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"scripts":{"build:cli":"ncc build src/index.ts -o dist && cp -r defaults dist/ && cp -r output dist/ && cp -r docs dist/ && cp -r examples dist/ && cp -r src/debug-visualizer/ui dist/debug-visualizer/ && node scripts/inject-version.js && echo \'#!/usr/bin/env node\' | cat - dist/index.js > temp && mv temp dist/index.js && chmod +x dist/index.js","build:sdk":"tsup src/sdk.ts --dts --sourcemap --format esm,cjs --out-dir dist/sdk","build":"./scripts/build-oss.sh","build:ee":"npm run build:cli && npm run build:sdk","test":"jest && npm run test:yaml","test:unit":"jest","prepublishOnly":"npm run build","test:watch":"jest --watch","test:coverage":"jest --coverage","test:ee":"jest --testPathPatterns=\'tests/ee\' --testPathIgnorePatterns=\'/node_modules/\' --no-coverage","test:manual:bash":"RUN_MANUAL_TESTS=true jest tests/manual/bash-config-manual.test.ts","lint":"eslint src tests --ext .ts","lint:fix":"eslint src tests --ext .ts --fix","format":"prettier --write src tests","format:check":"prettier --check src tests","clean":"","clean:traces":"node scripts/clean-traces.js","prebuild":"npm run clean && node scripts/generate-config-schema.js","pretest":"npm run clean:traces && node scripts/generate-config-schema.js && npm run build:cli","pretest:unit":"npm run clean:traces && node scripts/generate-config-schema.js && npm run build:cli","test:with-build":"npm run build:cli && jest","test:yaml":"node dist/index.js test --progress compact","test:yaml:parallel":"node dist/index.js test --progress compact --max-parallel 4","prepare":"husky","pre-commit":"lint-staged","deploy:site":"cd site && npx wrangler pages deploy . --project-name=visor-site --commit-dirty=true","deploy:worker":"npx wrangler deploy","deploy":"npm run deploy:site && npm run deploy:worker","publish:ee":"./scripts/publish-ee.sh","release":"./scripts/release.sh","release:patch":"./scripts/release.sh patch","release:minor":"./scripts/release.sh minor","release:major":"./scripts/release.sh major","release:prerelease":"./scripts/release.sh prerelease","docs:validate":"node scripts/validate-readme-links.js","workshop:setup":"npm install -D reveal-md@6.1.2","workshop:serve":"cd workshop && reveal-md slides.md -w","workshop:export":"reveal-md workshop/slides.md --static workshop/build","workshop:pdf":"reveal-md workshop/slides.md --print workshop/Visor-Workshop.pdf --print-size letter","workshop:pdf:ci":"reveal-md workshop/slides.md --print workshop/Visor-Workshop.pdf --print-size letter --puppeteer-launch-args=\\"--no-sandbox --disable-dev-shm-usage\\"","workshop:pdf:a4":"reveal-md workshop/slides.md --print workshop/Visor-Workshop-A4.pdf --print-size A4","workshop:build":"npm run workshop:export && npm run workshop:pdf","simulate:issue":"TS_NODE_TRANSPILE_ONLY=1 ts-node scripts/simulate-gh-run.ts --event issues --action opened --debug","simulate:comment":"TS_NODE_TRANSPILE_ONLY=1 ts-node scripts/simulate-gh-run.ts --event issue_comment --action created --debug"},"keywords":["code-review","ai","github-action","cli","pr-review","visor"],"author":"Probe Labs","license":"MIT","description":"AI workflow engine for code review, assistants, and automation — orchestrate checks, MCP tools, and AI providers with YAML-driven pipelines","repository":{"type":"git","url":"git+https://github.com/probelabs/visor.git"},"bugs":{"url":"https://github.com/probelabs/visor/issues"},"homepage":"https://github.com/probelabs/visor#readme","dependencies":{"@actions/core":"^1.11.1","@apidevtools/swagger-parser":"^12.1.0","@grammyjs/runner":"^2.0.3","@modelcontextprotocol/sdk":"^1.25.3","@nyariv/sandboxjs":"github:probelabs/SandboxJS#23c4bb611f7d05f3cb8c523917b5f57103e48108","@octokit/action":"^8.0.2","@octokit/auth-app":"^8.1.0","@octokit/core":"^7.0.3","@octokit/rest":"^22.0.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.203.0","@opentelemetry/core":"^1.30.1","@opentelemetry/exporter-logs-otlp-http":"^0.203.0","@opentelemetry/exporter-metrics-otlp-http":"^0.203.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.203.0","@opentelemetry/exporter-trace-otlp-http":"^0.203.0","@opentelemetry/instrumentation":"^0.203.0","@opentelemetry/resources":"^1.30.1","@opentelemetry/sdk-logs":"^0.203.0","@opentelemetry/sdk-metrics":"^1.30.1","@opentelemetry/sdk-node":"^0.203.0","@opentelemetry/sdk-trace-base":"^1.30.1","@opentelemetry/semantic-conventions":"^1.30.1","@probelabs/probe":"^0.6.0-rc290","@types/commander":"^2.12.0","@types/uuid":"^10.0.0","acorn":"^8.16.0","acorn-walk":"^8.3.5","ajv":"^8.17.1","ajv-formats":"^3.0.1","better-sqlite3":"^11.0.0","blessed":"^0.1.81","botbuilder":"^4.23.3","botframework-connector":"^4.23.3","cli-table3":"^0.6.5","commander":"^14.0.0","deepmerge":"^4.3.1","dotenv":"^17.2.3","grammy":"^1.41.1","ignore":"^7.0.5","imapflow":"^1.2.12","js-yaml":"^4.1.0","jsonpath-plus":"^10.4.0","liquidjs":"^10.21.1","mailparser":"^3.9.3","minimatch":"^10.2.2","node-cron":"^3.0.3","nodemailer":"^8.0.1","open":"^9.1.0","resend":"^6.9.3","simple-git":"^3.28.0","uuid":"^11.1.0","ws":"^8.18.3"},"optionalDependencies":{"@anthropic/claude-code-sdk":"npm:null@*","@open-policy-agent/opa-wasm":"^1.10.0","knex":"^3.1.0","mysql2":"^3.11.0","pg":"^8.13.0","tedious":"^19.0.0"},"devDependencies":{"@eslint/js":"^9.34.0","@kie/act-js":"^2.6.2","@kie/mock-github":"^2.0.1","@swc/core":"^1.13.2","@swc/jest":"^0.2.37","@types/better-sqlite3":"^7.6.0","@types/blessed":"^0.1.27","@types/jest":"^30.0.0","@types/js-yaml":"^4.0.9","@types/mailparser":"^3.4.6","@types/node":"^24.3.0","@types/node-cron":"^3.0.11","@types/nodemailer":"^7.0.11","@types/ws":"^8.18.1","@typescript-eslint/eslint-plugin":"^8.42.0","@typescript-eslint/parser":"^8.42.0","@vercel/ncc":"^0.38.4","eslint":"^9.34.0","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.4","husky":"^9.1.7","jest":"^30.1.3","lint-staged":"^16.1.6","prettier":"^3.6.2","reveal-md":"^6.1.2","ts-json-schema-generator":"^1.5.1","ts-node":"^10.9.2","tsup":"^8.5.0","typescript":"^5.9.2","wrangler":"^3.0.0"},"peerDependenciesMeta":{"@anthropic/claude-code-sdk":{"optional":true}},"directories":{"test":"tests"},"lint-staged":{"src/**/*.{ts,js}":["eslint --fix","prettier --write"],"tests/**/*.{ts,js}":["eslint --fix","prettier --write"],"*.{json,md,yml,yaml}":["prettier --write"]}}');
610190
+ module.exports = /*#__PURE__*/JSON.parse('{"name":"@probelabs/visor","version":"0.1.42","main":"dist/index.js","bin":{"visor":"./dist/index.js"},"exports":{".":{"require":"./dist/index.js","import":"./dist/index.js"},"./sdk":{"types":"./dist/sdk/sdk.d.ts","import":"./dist/sdk/sdk.mjs","require":"./dist/sdk/sdk.js"},"./cli":{"require":"./dist/index.js"}},"files":["dist/","defaults/","action.yml","README.md","LICENSE"],"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"scripts":{"build:cli":"ncc build src/index.ts -o dist && cp -r defaults dist/ && cp -r output dist/ && cp -r docs dist/ && cp -r examples dist/ && cp -r src/debug-visualizer/ui dist/debug-visualizer/ && node scripts/inject-version.js && echo \'#!/usr/bin/env node\' | cat - dist/index.js > temp && mv temp dist/index.js && chmod +x dist/index.js","build:sdk":"tsup src/sdk.ts --dts --sourcemap --format esm,cjs --out-dir dist/sdk","build":"./scripts/build-oss.sh","build:ee":"npm run build:cli && npm run build:sdk","test":"jest && npm run test:yaml","test:unit":"jest","prepublishOnly":"npm run build","test:watch":"jest --watch","test:coverage":"jest --coverage","test:ee":"jest --testPathPatterns=\'tests/ee\' --testPathIgnorePatterns=\'/node_modules/\' --no-coverage","test:manual:bash":"RUN_MANUAL_TESTS=true jest tests/manual/bash-config-manual.test.ts","lint":"eslint src tests --ext .ts","lint:fix":"eslint src tests --ext .ts --fix","format":"prettier --write src tests","format:check":"prettier --check src tests","clean":"","clean:traces":"node scripts/clean-traces.js","prebuild":"npm run clean && node scripts/generate-config-schema.js","pretest":"npm run clean:traces && node scripts/generate-config-schema.js && npm run build:cli","pretest:unit":"npm run clean:traces && node scripts/generate-config-schema.js && npm run build:cli","test:with-build":"npm run build:cli && jest","test:yaml":"node dist/index.js test --progress compact","test:yaml:parallel":"node dist/index.js test --progress compact --max-parallel 4","prepare":"husky","pre-commit":"lint-staged","deploy:site":"cd site && npx wrangler pages deploy . --project-name=visor-site --commit-dirty=true","deploy:worker":"npx wrangler deploy","deploy":"npm run deploy:site && npm run deploy:worker","publish:ee":"./scripts/publish-ee.sh","release":"./scripts/release.sh","release:patch":"./scripts/release.sh patch","release:minor":"./scripts/release.sh minor","release:major":"./scripts/release.sh major","release:prerelease":"./scripts/release.sh prerelease","docs:validate":"node scripts/validate-readme-links.js","workshop:setup":"npm install -D reveal-md@6.1.2","workshop:serve":"cd workshop && reveal-md slides.md -w","workshop:export":"reveal-md workshop/slides.md --static workshop/build","workshop:pdf":"reveal-md workshop/slides.md --print workshop/Visor-Workshop.pdf --print-size letter","workshop:pdf:ci":"reveal-md workshop/slides.md --print workshop/Visor-Workshop.pdf --print-size letter --puppeteer-launch-args=\\"--no-sandbox --disable-dev-shm-usage\\"","workshop:pdf:a4":"reveal-md workshop/slides.md --print workshop/Visor-Workshop-A4.pdf --print-size A4","workshop:build":"npm run workshop:export && npm run workshop:pdf","simulate:issue":"TS_NODE_TRANSPILE_ONLY=1 ts-node scripts/simulate-gh-run.ts --event issues --action opened --debug","simulate:comment":"TS_NODE_TRANSPILE_ONLY=1 ts-node scripts/simulate-gh-run.ts --event issue_comment --action created --debug"},"keywords":["code-review","ai","github-action","cli","pr-review","visor"],"author":"Probe Labs","license":"MIT","description":"AI workflow engine for code review, assistants, and automation — orchestrate checks, MCP tools, and AI providers with YAML-driven pipelines","repository":{"type":"git","url":"git+https://github.com/probelabs/visor.git"},"bugs":{"url":"https://github.com/probelabs/visor/issues"},"homepage":"https://github.com/probelabs/visor#readme","dependencies":{"@actions/core":"^1.11.1","@apidevtools/swagger-parser":"^12.1.0","@grammyjs/runner":"^2.0.3","@modelcontextprotocol/sdk":"^1.25.3","@nyariv/sandboxjs":"github:probelabs/SandboxJS#23c4bb611f7d05f3cb8c523917b5f57103e48108","@octokit/action":"^8.0.2","@octokit/auth-app":"^8.1.0","@octokit/core":"^7.0.3","@octokit/rest":"^22.0.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.203.0","@opentelemetry/core":"^1.30.1","@opentelemetry/exporter-logs-otlp-http":"^0.203.0","@opentelemetry/exporter-metrics-otlp-http":"^0.203.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.203.0","@opentelemetry/exporter-trace-otlp-http":"^0.203.0","@opentelemetry/instrumentation":"^0.203.0","@opentelemetry/resources":"^1.30.1","@opentelemetry/sdk-logs":"^0.203.0","@opentelemetry/sdk-metrics":"^1.30.1","@opentelemetry/sdk-node":"^0.203.0","@opentelemetry/sdk-trace-base":"^1.30.1","@opentelemetry/semantic-conventions":"^1.30.1","@probelabs/probe":"^0.6.0-rc291","@types/commander":"^2.12.0","@types/uuid":"^10.0.0","acorn":"^8.16.0","acorn-walk":"^8.3.5","ajv":"^8.17.1","ajv-formats":"^3.0.1","better-sqlite3":"^11.0.0","blessed":"^0.1.81","botbuilder":"^4.23.3","botframework-connector":"^4.23.3","cli-table3":"^0.6.5","commander":"^14.0.0","deepmerge":"^4.3.1","dotenv":"^17.2.3","grammy":"^1.41.1","ignore":"^7.0.5","imapflow":"^1.2.12","js-yaml":"^4.1.0","jsonpath-plus":"^10.4.0","liquidjs":"^10.21.1","mailparser":"^3.9.3","minimatch":"^10.2.2","node-cron":"^3.0.3","nodemailer":"^8.0.1","open":"^9.1.0","resend":"^6.9.3","simple-git":"^3.28.0","uuid":"^11.1.0","ws":"^8.18.3"},"optionalDependencies":{"@anthropic/claude-code-sdk":"npm:null@*","@open-policy-agent/opa-wasm":"^1.10.0","knex":"^3.1.0","mysql2":"^3.11.0","pg":"^8.13.0","tedious":"^19.0.0"},"devDependencies":{"@eslint/js":"^9.34.0","@kie/act-js":"^2.6.2","@kie/mock-github":"^2.0.1","@swc/core":"^1.13.2","@swc/jest":"^0.2.37","@types/better-sqlite3":"^7.6.0","@types/blessed":"^0.1.27","@types/jest":"^30.0.0","@types/js-yaml":"^4.0.9","@types/mailparser":"^3.4.6","@types/node":"^24.3.0","@types/node-cron":"^3.0.11","@types/nodemailer":"^7.0.11","@types/ws":"^8.18.1","@typescript-eslint/eslint-plugin":"^8.42.0","@typescript-eslint/parser":"^8.42.0","@vercel/ncc":"^0.38.4","eslint":"^9.34.0","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.4","husky":"^9.1.7","jest":"^30.1.3","lint-staged":"^16.1.6","prettier":"^3.6.2","reveal-md":"^6.1.2","ts-json-schema-generator":"^1.5.1","ts-node":"^10.9.2","tsup":"^8.5.0","typescript":"^5.9.2","wrangler":"^3.0.0"},"peerDependenciesMeta":{"@anthropic/claude-code-sdk":{"optional":true}},"directories":{"test":"tests"},"lint-staged":{"src/**/*.{ts,js}":["eslint --fix","prettier --write"],"tests/**/*.{ts,js}":["eslint --fix","prettier --write"],"*.{json,md,yml,yaml}":["prettier --write"]}}');
608040
610191
 
608041
610192
  /***/ })
608042
610193