@probelabs/visor 0.1.147-ee → 0.1.148

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 (98) hide show
  1. package/dist/frontends/github-frontend.d.ts +2 -1
  2. package/dist/frontends/github-frontend.d.ts.map +1 -1
  3. package/dist/index.js +747 -1831
  4. package/dist/output/traces/run-2026-03-02T18-32-11-359Z.ndjson +138 -0
  5. package/dist/output/traces/run-2026-03-02T18-32-55-702Z.ndjson +1442 -0
  6. package/dist/providers/ai-check-provider.d.ts.map +1 -1
  7. package/dist/scheduler/schedule-tool.d.ts.map +1 -1
  8. package/dist/scheduler/scheduler.d.ts +5 -0
  9. package/dist/scheduler/scheduler.d.ts.map +1 -1
  10. package/dist/sdk/{check-provider-registry-LBYIKFYM.mjs → check-provider-registry-35BPTY4W.mjs} +5 -6
  11. package/dist/sdk/{check-provider-registry-SCPM6DIT.mjs → check-provider-registry-DVQDGTOE.mjs} +5 -6
  12. package/dist/sdk/check-provider-registry-KHPY6LB4.mjs +29 -0
  13. package/dist/sdk/{chunk-4F5UVWAN.mjs → chunk-62TNF5PJ.mjs} +2 -2
  14. package/dist/sdk/{chunk-4F5UVWAN.mjs.map → chunk-62TNF5PJ.mjs.map} +1 -1
  15. package/dist/sdk/{chunk-PNZH3JSI.mjs → chunk-6N6JRWCW.mjs} +2743 -277
  16. package/dist/sdk/chunk-6N6JRWCW.mjs.map +1 -0
  17. package/dist/sdk/{chunk-FBJ7MC7R.mjs → chunk-AYQE4JCU.mjs} +3 -3
  18. package/dist/sdk/chunk-CISJ6DJW.mjs +1502 -0
  19. package/dist/sdk/chunk-CISJ6DJW.mjs.map +1 -0
  20. package/dist/sdk/chunk-EGUHXVWS.mjs +443 -0
  21. package/dist/sdk/chunk-EGUHXVWS.mjs.map +1 -0
  22. package/dist/sdk/{chunk-EWGX7LI7.mjs → chunk-H4AYMOAT.mjs} +2742 -276
  23. package/dist/sdk/chunk-H4AYMOAT.mjs.map +1 -0
  24. package/dist/sdk/chunk-IF2UD2KS.mjs +43159 -0
  25. package/dist/sdk/chunk-IF2UD2KS.mjs.map +1 -0
  26. package/dist/sdk/{chunk-V2QW6ECX.mjs → chunk-RJLJUTSU.mjs} +2 -2
  27. package/dist/sdk/chunk-S2YO4ZE3.mjs +739 -0
  28. package/dist/sdk/chunk-S2YO4ZE3.mjs.map +1 -0
  29. package/dist/sdk/{failure-condition-evaluator-FHNZL2US.mjs → failure-condition-evaluator-I6QWFKV3.mjs} +3 -3
  30. package/dist/sdk/failure-condition-evaluator-IVCTD4BZ.mjs +17 -0
  31. package/dist/sdk/{github-frontend-47EU2HBY.mjs → github-frontend-2MC77L7F.mjs} +16 -4
  32. package/dist/sdk/github-frontend-2MC77L7F.mjs.map +1 -0
  33. package/dist/sdk/github-frontend-DFT5G32K.mjs +1368 -0
  34. package/dist/sdk/github-frontend-DFT5G32K.mjs.map +1 -0
  35. package/dist/sdk/{host-GVR4UGZ3.mjs → host-4F6I3ZXN.mjs} +2 -2
  36. package/dist/sdk/{host-KGN5OIAM.mjs → host-H7IX4GBK.mjs} +2 -2
  37. package/dist/sdk/{routing-CZ36LVVS.mjs → routing-LU5PAREW.mjs} +4 -4
  38. package/dist/sdk/routing-UT3BXBXH.mjs +25 -0
  39. package/dist/sdk/schedule-tool-CONR4VW3.mjs +35 -0
  40. package/dist/sdk/schedule-tool-K3GQXCBN.mjs +35 -0
  41. package/dist/sdk/schedule-tool-SBXAEBDD.mjs +35 -0
  42. package/dist/sdk/{schedule-tool-handler-KFYNV7HL.mjs → schedule-tool-handler-GFQCJAVZ.mjs} +5 -6
  43. package/dist/sdk/schedule-tool-handler-GFQCJAVZ.mjs.map +1 -0
  44. package/dist/sdk/{schedule-tool-handler-E7XHMU5G.mjs → schedule-tool-handler-R7PG3VMR.mjs} +5 -6
  45. package/dist/sdk/schedule-tool-handler-R7PG3VMR.mjs.map +1 -0
  46. package/dist/sdk/schedule-tool-handler-YUC6CAXX.mjs +39 -0
  47. package/dist/sdk/schedule-tool-handler-YUC6CAXX.mjs.map +1 -0
  48. package/dist/sdk/sdk.js +1573 -1629
  49. package/dist/sdk/sdk.js.map +1 -1
  50. package/dist/sdk/sdk.mjs +4 -5
  51. package/dist/sdk/sdk.mjs.map +1 -1
  52. package/dist/sdk/{trace-helpers-EHDZ42HH.mjs → trace-helpers-6ROJR7N3.mjs} +2 -2
  53. package/dist/sdk/trace-helpers-6ROJR7N3.mjs.map +1 -0
  54. package/dist/sdk/trace-helpers-J463EU4B.mjs +25 -0
  55. package/dist/sdk/trace-helpers-J463EU4B.mjs.map +1 -0
  56. package/dist/sdk/{workflow-check-provider-5453TW65.mjs → workflow-check-provider-DYSO3PML.mjs} +5 -6
  57. package/dist/sdk/workflow-check-provider-DYSO3PML.mjs.map +1 -0
  58. package/dist/sdk/{workflow-check-provider-BSUSPFOF.mjs → workflow-check-provider-FIFFQDQU.mjs} +5 -6
  59. package/dist/sdk/workflow-check-provider-FIFFQDQU.mjs.map +1 -0
  60. package/dist/sdk/workflow-check-provider-GJNGTS3F.mjs +29 -0
  61. package/dist/sdk/workflow-check-provider-GJNGTS3F.mjs.map +1 -0
  62. package/dist/state-machine/context/build-engine-context.d.ts.map +1 -1
  63. package/dist/traces/run-2026-03-02T18-32-11-359Z.ndjson +138 -0
  64. package/dist/traces/run-2026-03-02T18-32-55-702Z.ndjson +1442 -0
  65. package/dist/utils/tool-resolver.d.ts.map +1 -1
  66. package/dist/utils/workspace-manager.d.ts +31 -8
  67. package/dist/utils/workspace-manager.d.ts.map +1 -1
  68. package/dist/utils/worktree-manager.d.ts +6 -0
  69. package/dist/utils/worktree-manager.d.ts.map +1 -1
  70. package/package.json +2 -2
  71. package/dist/sdk/chunk-EWGX7LI7.mjs.map +0 -1
  72. package/dist/sdk/chunk-PNZH3JSI.mjs.map +0 -1
  73. package/dist/sdk/chunk-XKCER23W.mjs +0 -1490
  74. package/dist/sdk/chunk-XKCER23W.mjs.map +0 -1
  75. package/dist/sdk/github-frontend-47EU2HBY.mjs.map +0 -1
  76. package/dist/sdk/knex-store-HPXJILBL.mjs +0 -411
  77. package/dist/sdk/knex-store-HPXJILBL.mjs.map +0 -1
  78. package/dist/sdk/loader-YSRMVXC3.mjs +0 -89
  79. package/dist/sdk/loader-YSRMVXC3.mjs.map +0 -1
  80. package/dist/sdk/opa-policy-engine-S2S2ULEI.mjs +0 -655
  81. package/dist/sdk/opa-policy-engine-S2S2ULEI.mjs.map +0 -1
  82. package/dist/sdk/schedule-tool-2COUUTF7.mjs +0 -18
  83. package/dist/sdk/validator-XTZJZZJH.mjs +0 -134
  84. package/dist/sdk/validator-XTZJZZJH.mjs.map +0 -1
  85. /package/dist/sdk/{check-provider-registry-LBYIKFYM.mjs.map → check-provider-registry-35BPTY4W.mjs.map} +0 -0
  86. /package/dist/sdk/{check-provider-registry-SCPM6DIT.mjs.map → check-provider-registry-DVQDGTOE.mjs.map} +0 -0
  87. /package/dist/sdk/{failure-condition-evaluator-FHNZL2US.mjs.map → check-provider-registry-KHPY6LB4.mjs.map} +0 -0
  88. /package/dist/sdk/{chunk-FBJ7MC7R.mjs.map → chunk-AYQE4JCU.mjs.map} +0 -0
  89. /package/dist/sdk/{chunk-V2QW6ECX.mjs.map → chunk-RJLJUTSU.mjs.map} +0 -0
  90. /package/dist/sdk/{routing-CZ36LVVS.mjs.map → failure-condition-evaluator-I6QWFKV3.mjs.map} +0 -0
  91. /package/dist/sdk/{schedule-tool-2COUUTF7.mjs.map → failure-condition-evaluator-IVCTD4BZ.mjs.map} +0 -0
  92. /package/dist/sdk/{host-GVR4UGZ3.mjs.map → host-4F6I3ZXN.mjs.map} +0 -0
  93. /package/dist/sdk/{host-KGN5OIAM.mjs.map → host-H7IX4GBK.mjs.map} +0 -0
  94. /package/dist/sdk/{schedule-tool-handler-E7XHMU5G.mjs.map → routing-LU5PAREW.mjs.map} +0 -0
  95. /package/dist/sdk/{schedule-tool-handler-KFYNV7HL.mjs.map → routing-UT3BXBXH.mjs.map} +0 -0
  96. /package/dist/sdk/{trace-helpers-EHDZ42HH.mjs.map → schedule-tool-CONR4VW3.mjs.map} +0 -0
  97. /package/dist/sdk/{workflow-check-provider-5453TW65.mjs.map → schedule-tool-K3GQXCBN.mjs.map} +0 -0
  98. /package/dist/sdk/{workflow-check-provider-BSUSPFOF.mjs.map → schedule-tool-SBXAEBDD.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.147';
3
- process.env.PROBE_VERSION = '0.6.0-rc262';
4
- process.env.VISOR_COMMIT_SHA = '986bd9df126dcf4c0564d12701994e4bad407897';
5
- process.env.VISOR_COMMIT_SHORT = '986bd9d';
2
+ process.env.VISOR_VERSION = '0.1.148';
3
+ process.env.PROBE_VERSION = '0.6.0-rc264';
4
+ process.env.VISOR_COMMIT_SHA = '8d09da19e112d8649810da46458aa77d3f034fc6';
5
+ process.env.VISOR_COMMIT_SHORT = '8d09da19';
6
6
  /******/ (() => { // webpackBootstrap
7
7
  /******/ var __webpack_modules__ = ({
8
8
 
@@ -161193,7 +161193,7 @@ async function handleDumpPolicyInput(checkId, argv) {
161193
161193
  let PolicyInputBuilder;
161194
161194
  try {
161195
161195
  // @ts-ignore — enterprise/ may not exist in OSS builds (caught at runtime)
161196
- const mod = await Promise.resolve().then(() => __importStar(__nccwpck_require__(17117)));
161196
+ const mod = await Promise.resolve().then(() => __importStar(__nccwpck_require__(71370)));
161197
161197
  PolicyInputBuilder = mod.PolicyInputBuilder;
161198
161198
  }
161199
161199
  catch {
@@ -167035,1690 +167035,6 @@ class DependencyResolver {
167035
167035
  exports.DependencyResolver = DependencyResolver;
167036
167036
 
167037
167037
 
167038
- /***/ }),
167039
-
167040
- /***/ 50069:
167041
- /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
167042
-
167043
- "use strict";
167044
-
167045
- /**
167046
- * Copyright (c) ProbeLabs. All rights reserved.
167047
- * Licensed under the Elastic License 2.0; you may not use this file except
167048
- * in compliance with the Elastic License 2.0.
167049
- */
167050
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
167051
- if (k2 === undefined) k2 = k;
167052
- var desc = Object.getOwnPropertyDescriptor(m, k);
167053
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
167054
- desc = { enumerable: true, get: function() { return m[k]; } };
167055
- }
167056
- Object.defineProperty(o, k2, desc);
167057
- }) : (function(o, m, k, k2) {
167058
- if (k2 === undefined) k2 = k;
167059
- o[k2] = m[k];
167060
- }));
167061
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
167062
- Object.defineProperty(o, "default", { enumerable: true, value: v });
167063
- }) : function(o, v) {
167064
- o["default"] = v;
167065
- });
167066
- var __importStar = (this && this.__importStar) || (function () {
167067
- var ownKeys = function(o) {
167068
- ownKeys = Object.getOwnPropertyNames || function (o) {
167069
- var ar = [];
167070
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
167071
- return ar;
167072
- };
167073
- return ownKeys(o);
167074
- };
167075
- return function (mod) {
167076
- if (mod && mod.__esModule) return mod;
167077
- var result = {};
167078
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
167079
- __setModuleDefault(result, mod);
167080
- return result;
167081
- };
167082
- })();
167083
- Object.defineProperty(exports, "__esModule", ({ value: true }));
167084
- exports.LicenseValidator = void 0;
167085
- const crypto = __importStar(__nccwpck_require__(76982));
167086
- const fs = __importStar(__nccwpck_require__(79896));
167087
- const path = __importStar(__nccwpck_require__(16928));
167088
- class LicenseValidator {
167089
- /** Ed25519 public key for license verification (PEM format). */
167090
- static PUBLIC_KEY = '-----BEGIN PUBLIC KEY-----\n' +
167091
- 'MCowBQYDK2VwAyEAI/Zd08EFmgIdrDm/HXd0l3/5GBt7R1PrdvhdmEXhJlU=\n' +
167092
- '-----END PUBLIC KEY-----\n';
167093
- cache = null;
167094
- static CACHE_TTL = 5 * 60 * 1000; // 5 minutes
167095
- static GRACE_PERIOD = 72 * 3600 * 1000; // 72 hours after expiry
167096
- /**
167097
- * Load and validate license from environment or file.
167098
- *
167099
- * Resolution order:
167100
- * 1. VISOR_LICENSE env var (JWT string)
167101
- * 2. VISOR_LICENSE_FILE env var (path to file)
167102
- * 3. .visor-license in project root (cwd)
167103
- * 4. .visor-license in ~/.config/visor/
167104
- */
167105
- async loadAndValidate() {
167106
- // Return cached result if still fresh
167107
- if (this.cache && Date.now() - this.cache.validatedAt < LicenseValidator.CACHE_TTL) {
167108
- return this.cache.payload;
167109
- }
167110
- const token = this.resolveToken();
167111
- if (!token)
167112
- return null;
167113
- const payload = this.verifyAndDecode(token);
167114
- if (!payload)
167115
- return null;
167116
- this.cache = { payload, validatedAt: Date.now() };
167117
- return payload;
167118
- }
167119
- /** Check if a specific feature is licensed */
167120
- hasFeature(feature) {
167121
- if (!this.cache)
167122
- return false;
167123
- return this.cache.payload.features.includes(feature);
167124
- }
167125
- /** Check if license is valid (with grace period) */
167126
- isValid() {
167127
- if (!this.cache)
167128
- return false;
167129
- const now = Date.now();
167130
- const expiryMs = this.cache.payload.exp * 1000;
167131
- return now < expiryMs + LicenseValidator.GRACE_PERIOD;
167132
- }
167133
- /** Check if the license is within its grace period (expired but still valid) */
167134
- isInGracePeriod() {
167135
- if (!this.cache)
167136
- return false;
167137
- const now = Date.now();
167138
- const expiryMs = this.cache.payload.exp * 1000;
167139
- return now >= expiryMs && now < expiryMs + LicenseValidator.GRACE_PERIOD;
167140
- }
167141
- resolveToken() {
167142
- // 1. Direct env var
167143
- if (process.env.VISOR_LICENSE) {
167144
- return process.env.VISOR_LICENSE.trim();
167145
- }
167146
- // 2. File path from env (validate against path traversal)
167147
- if (process.env.VISOR_LICENSE_FILE) {
167148
- // path.resolve() produces an absolute path with all '..' segments resolved,
167149
- // so a separate resolved.includes('..') check is unnecessary.
167150
- const resolved = path.resolve(process.env.VISOR_LICENSE_FILE);
167151
- const home = process.env.HOME || process.env.USERPROFILE || '';
167152
- const allowedPrefixes = [path.normalize(process.cwd())];
167153
- if (home)
167154
- allowedPrefixes.push(path.normalize(path.join(home, '.config', 'visor')));
167155
- // Resolve symlinks so an attacker cannot create a symlink inside an
167156
- // allowed prefix that points to an arbitrary file outside it.
167157
- let realPath;
167158
- try {
167159
- realPath = fs.realpathSync(resolved);
167160
- }
167161
- catch {
167162
- return null; // File doesn't exist or isn't accessible
167163
- }
167164
- const isSafe = allowedPrefixes.some(prefix => realPath === prefix || realPath.startsWith(prefix + path.sep));
167165
- if (!isSafe)
167166
- return null;
167167
- return this.readFile(realPath);
167168
- }
167169
- // 3. .visor-license in cwd
167170
- const cwdPath = path.join(process.cwd(), '.visor-license');
167171
- const cwdToken = this.readFile(cwdPath);
167172
- if (cwdToken)
167173
- return cwdToken;
167174
- // 4. ~/.config/visor/.visor-license
167175
- const home = process.env.HOME || process.env.USERPROFILE || '';
167176
- if (home) {
167177
- const configPath = path.join(home, '.config', 'visor', '.visor-license');
167178
- const configToken = this.readFile(configPath);
167179
- if (configToken)
167180
- return configToken;
167181
- }
167182
- return null;
167183
- }
167184
- readFile(filePath) {
167185
- try {
167186
- return fs.readFileSync(filePath, 'utf-8').trim();
167187
- }
167188
- catch {
167189
- return null;
167190
- }
167191
- }
167192
- verifyAndDecode(token) {
167193
- try {
167194
- const parts = token.split('.');
167195
- if (parts.length !== 3)
167196
- return null;
167197
- const [headerB64, payloadB64, signatureB64] = parts;
167198
- // Decode header to verify algorithm
167199
- const header = JSON.parse(Buffer.from(headerB64, 'base64url').toString());
167200
- if (header.alg !== 'EdDSA')
167201
- return null;
167202
- // Verify signature
167203
- const data = `${headerB64}.${payloadB64}`;
167204
- const signature = Buffer.from(signatureB64, 'base64url');
167205
- const publicKey = crypto.createPublicKey(LicenseValidator.PUBLIC_KEY);
167206
- // Validate that the loaded public key is actually Ed25519 (OID 1.3.101.112).
167207
- // This prevents algorithm-confusion attacks if the embedded key were ever
167208
- // swapped to a different type.
167209
- if (publicKey.asymmetricKeyType !== 'ed25519') {
167210
- return null;
167211
- }
167212
- // Ed25519 verification: algorithm must be null because EdDSA performs its
167213
- // own internal hashing (SHA-512) — passing a digest algorithm here would
167214
- // cause Node.js to throw. The key type is validated above.
167215
- const isValid = crypto.verify(null, Buffer.from(data), publicKey, signature);
167216
- if (!isValid)
167217
- return null;
167218
- // Decode payload
167219
- const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString());
167220
- // Validate required fields
167221
- if (!payload.org ||
167222
- !Array.isArray(payload.features) ||
167223
- typeof payload.exp !== 'number' ||
167224
- typeof payload.iat !== 'number' ||
167225
- !payload.sub) {
167226
- return null;
167227
- }
167228
- // Check expiry (with grace period)
167229
- const now = Date.now();
167230
- const expiryMs = payload.exp * 1000;
167231
- if (now >= expiryMs + LicenseValidator.GRACE_PERIOD) {
167232
- return null;
167233
- }
167234
- return payload;
167235
- }
167236
- catch {
167237
- return null;
167238
- }
167239
- }
167240
- }
167241
- exports.LicenseValidator = LicenseValidator;
167242
-
167243
-
167244
- /***/ }),
167245
-
167246
- /***/ 87068:
167247
- /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
167248
-
167249
- "use strict";
167250
-
167251
- /**
167252
- * Copyright (c) ProbeLabs. All rights reserved.
167253
- * Licensed under the Elastic License 2.0; you may not use this file except
167254
- * in compliance with the Elastic License 2.0.
167255
- */
167256
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
167257
- if (k2 === undefined) k2 = k;
167258
- var desc = Object.getOwnPropertyDescriptor(m, k);
167259
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
167260
- desc = { enumerable: true, get: function() { return m[k]; } };
167261
- }
167262
- Object.defineProperty(o, k2, desc);
167263
- }) : (function(o, m, k, k2) {
167264
- if (k2 === undefined) k2 = k;
167265
- o[k2] = m[k];
167266
- }));
167267
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
167268
- Object.defineProperty(o, "default", { enumerable: true, value: v });
167269
- }) : function(o, v) {
167270
- o["default"] = v;
167271
- });
167272
- var __importStar = (this && this.__importStar) || (function () {
167273
- var ownKeys = function(o) {
167274
- ownKeys = Object.getOwnPropertyNames || function (o) {
167275
- var ar = [];
167276
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
167277
- return ar;
167278
- };
167279
- return ownKeys(o);
167280
- };
167281
- return function (mod) {
167282
- if (mod && mod.__esModule) return mod;
167283
- var result = {};
167284
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
167285
- __setModuleDefault(result, mod);
167286
- return result;
167287
- };
167288
- })();
167289
- Object.defineProperty(exports, "__esModule", ({ value: true }));
167290
- exports.loadEnterprisePolicyEngine = loadEnterprisePolicyEngine;
167291
- exports.loadEnterpriseStoreBackend = loadEnterpriseStoreBackend;
167292
- const default_engine_1 = __nccwpck_require__(93866);
167293
- /**
167294
- * Load the enterprise policy engine if licensed, otherwise return the default no-op engine.
167295
- *
167296
- * This is the sole import boundary between OSS and enterprise code. Core code
167297
- * must only import from this module (via dynamic `await import()`), never from
167298
- * individual enterprise submodules.
167299
- */
167300
- async function loadEnterprisePolicyEngine(config) {
167301
- try {
167302
- const { LicenseValidator } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(50069)));
167303
- const validator = new LicenseValidator();
167304
- const license = await validator.loadAndValidate();
167305
- if (!license || !validator.hasFeature('policy')) {
167306
- return new default_engine_1.DefaultPolicyEngine();
167307
- }
167308
- if (validator.isInGracePeriod()) {
167309
- // eslint-disable-next-line no-console
167310
- console.warn('[visor:enterprise] License has expired but is within the 72-hour grace period. ' +
167311
- 'Please renew your license.');
167312
- }
167313
- const { OpaPolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(39530)));
167314
- const engine = new OpaPolicyEngine(config);
167315
- await engine.initialize(config);
167316
- return engine;
167317
- }
167318
- catch (err) {
167319
- // Enterprise code not available or initialization failed
167320
- const msg = err instanceof Error ? err.message : String(err);
167321
- try {
167322
- const { logger } = __nccwpck_require__(86999);
167323
- logger.warn(`[PolicyEngine] Enterprise policy init failed, falling back to default: ${msg}`);
167324
- }
167325
- catch {
167326
- // silent
167327
- }
167328
- return new default_engine_1.DefaultPolicyEngine();
167329
- }
167330
- }
167331
- /**
167332
- * Load the enterprise schedule store backend if licensed.
167333
- *
167334
- * @param driver Database driver ('postgresql', 'mysql', or 'mssql')
167335
- * @param storageConfig Storage configuration with connection details
167336
- * @param haConfig Optional HA configuration
167337
- * @throws Error if enterprise license is not available or missing 'scheduler-sql' feature
167338
- */
167339
- async function loadEnterpriseStoreBackend(driver, storageConfig, haConfig) {
167340
- const { LicenseValidator } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(50069)));
167341
- const validator = new LicenseValidator();
167342
- const license = await validator.loadAndValidate();
167343
- if (!license || !validator.hasFeature('scheduler-sql')) {
167344
- throw new Error(`The ${driver} schedule storage driver requires a Visor Enterprise license ` +
167345
- `with the 'scheduler-sql' feature. Please upgrade or use driver: 'sqlite' (default).`);
167346
- }
167347
- if (validator.isInGracePeriod()) {
167348
- // eslint-disable-next-line no-console
167349
- console.warn('[visor:enterprise] License has expired but is within the 72-hour grace period. ' +
167350
- 'Please renew your license.');
167351
- }
167352
- const { KnexStoreBackend } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(63737)));
167353
- return new KnexStoreBackend(driver, storageConfig, haConfig);
167354
- }
167355
-
167356
-
167357
- /***/ }),
167358
-
167359
- /***/ 628:
167360
- /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
167361
-
167362
- "use strict";
167363
-
167364
- /**
167365
- * Copyright (c) ProbeLabs. All rights reserved.
167366
- * Licensed under the Elastic License 2.0; you may not use this file except
167367
- * in compliance with the Elastic License 2.0.
167368
- */
167369
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
167370
- if (k2 === undefined) k2 = k;
167371
- var desc = Object.getOwnPropertyDescriptor(m, k);
167372
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
167373
- desc = { enumerable: true, get: function() { return m[k]; } };
167374
- }
167375
- Object.defineProperty(o, k2, desc);
167376
- }) : (function(o, m, k, k2) {
167377
- if (k2 === undefined) k2 = k;
167378
- o[k2] = m[k];
167379
- }));
167380
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
167381
- Object.defineProperty(o, "default", { enumerable: true, value: v });
167382
- }) : function(o, v) {
167383
- o["default"] = v;
167384
- });
167385
- var __importStar = (this && this.__importStar) || (function () {
167386
- var ownKeys = function(o) {
167387
- ownKeys = Object.getOwnPropertyNames || function (o) {
167388
- var ar = [];
167389
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
167390
- return ar;
167391
- };
167392
- return ownKeys(o);
167393
- };
167394
- return function (mod) {
167395
- if (mod && mod.__esModule) return mod;
167396
- var result = {};
167397
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
167398
- __setModuleDefault(result, mod);
167399
- return result;
167400
- };
167401
- })();
167402
- Object.defineProperty(exports, "__esModule", ({ value: true }));
167403
- exports.OpaCompiler = void 0;
167404
- const fs = __importStar(__nccwpck_require__(79896));
167405
- const path = __importStar(__nccwpck_require__(16928));
167406
- const os = __importStar(__nccwpck_require__(70857));
167407
- const crypto = __importStar(__nccwpck_require__(76982));
167408
- const child_process_1 = __nccwpck_require__(35317);
167409
- /**
167410
- * OPA Rego Compiler - compiles .rego policy files to WASM bundles using the `opa` CLI.
167411
- *
167412
- * Handles:
167413
- * - Resolving input paths to WASM bytes (direct .wasm, directory with policy.wasm, or .rego files)
167414
- * - Compiling .rego files to WASM via `opa build`
167415
- * - Caching compiled bundles based on content hashes
167416
- * - Extracting policy.wasm from OPA tar.gz bundles
167417
- *
167418
- * Requires:
167419
- * - `opa` CLI on PATH (only when auto-compiling .rego files)
167420
- */
167421
- class OpaCompiler {
167422
- static CACHE_DIR = path.join(os.tmpdir(), 'visor-opa-cache');
167423
- /**
167424
- * Resolve the input paths to WASM bytes.
167425
- *
167426
- * Strategy:
167427
- * 1. If any path is a .wasm file, read it directly
167428
- * 2. If a directory contains policy.wasm, read it
167429
- * 3. Otherwise, collect all .rego files and auto-compile via `opa build`
167430
- */
167431
- async resolveWasmBytes(paths) {
167432
- // Collect .rego files and check for existing .wasm
167433
- const regoFiles = [];
167434
- for (const p of paths) {
167435
- const resolved = path.resolve(p);
167436
- // Reject paths containing '..' after resolution (path traversal)
167437
- if (path.normalize(resolved).includes('..')) {
167438
- throw new Error(`Policy path contains traversal sequences: ${p}`);
167439
- }
167440
- // Direct .wasm file
167441
- if (resolved.endsWith('.wasm') && fs.existsSync(resolved)) {
167442
- return fs.readFileSync(resolved);
167443
- }
167444
- if (!fs.existsSync(resolved))
167445
- continue;
167446
- const stat = fs.statSync(resolved);
167447
- if (stat.isDirectory()) {
167448
- // Check for pre-compiled policy.wasm in directory
167449
- const wasmCandidate = path.join(resolved, 'policy.wasm');
167450
- if (fs.existsSync(wasmCandidate)) {
167451
- return fs.readFileSync(wasmCandidate);
167452
- }
167453
- // Collect all .rego files from directory
167454
- const files = fs.readdirSync(resolved);
167455
- for (const f of files) {
167456
- if (f.endsWith('.rego')) {
167457
- regoFiles.push(path.join(resolved, f));
167458
- }
167459
- }
167460
- }
167461
- else if (resolved.endsWith('.rego')) {
167462
- regoFiles.push(resolved);
167463
- }
167464
- }
167465
- if (regoFiles.length === 0) {
167466
- throw new Error(`OPA WASM evaluator: no .wasm bundle or .rego files found in: ${paths.join(', ')}`);
167467
- }
167468
- // Auto-compile .rego -> .wasm
167469
- return this.compileRego(regoFiles);
167470
- }
167471
- /**
167472
- * Auto-compile .rego files to a WASM bundle using the `opa` CLI.
167473
- *
167474
- * Caches the compiled bundle based on a content hash of all input .rego files
167475
- * so subsequent runs skip compilation if policies haven't changed.
167476
- */
167477
- compileRego(regoFiles) {
167478
- // Check that `opa` CLI is available
167479
- try {
167480
- (0, child_process_1.execFileSync)('opa', ['version'], { stdio: 'pipe' });
167481
- }
167482
- catch {
167483
- throw new Error('OPA CLI (`opa`) not found on PATH. Install it from https://www.openpolicyagent.org/docs/latest/#running-opa\n' +
167484
- 'Or pre-compile your .rego files: opa build -t wasm -e visor -o bundle.tar.gz ' +
167485
- regoFiles.join(' '));
167486
- }
167487
- // Compute content hash for cache key
167488
- const hash = crypto.createHash('sha256');
167489
- for (const f of regoFiles.sort()) {
167490
- hash.update(fs.readFileSync(f));
167491
- hash.update(f); // include filename for disambiguation
167492
- }
167493
- const cacheKey = hash.digest('hex').slice(0, 16);
167494
- const cacheDir = OpaCompiler.CACHE_DIR;
167495
- const cachedWasm = path.join(cacheDir, `${cacheKey}.wasm`);
167496
- // Return cached bundle if still valid
167497
- if (fs.existsSync(cachedWasm)) {
167498
- return fs.readFileSync(cachedWasm);
167499
- }
167500
- // Compile to WASM via opa build
167501
- fs.mkdirSync(cacheDir, { recursive: true });
167502
- const bundleTar = path.join(cacheDir, `${cacheKey}-bundle.tar.gz`);
167503
- try {
167504
- const args = [
167505
- 'build',
167506
- '-t',
167507
- 'wasm',
167508
- '-e',
167509
- 'visor', // entrypoint: the visor package tree
167510
- '-o',
167511
- bundleTar,
167512
- ...regoFiles,
167513
- ];
167514
- (0, child_process_1.execFileSync)('opa', args, {
167515
- stdio: 'pipe',
167516
- timeout: 30000,
167517
- });
167518
- }
167519
- catch (err) {
167520
- const stderr = err?.stderr?.toString() || '';
167521
- throw new Error(`Failed to compile .rego files to WASM:\n${stderr}\n` +
167522
- 'Ensure your .rego files are valid and the `opa` CLI is installed.');
167523
- }
167524
- // Extract policy.wasm from the tar.gz bundle
167525
- // OPA bundles are tar.gz with /policy.wasm inside
167526
- try {
167527
- (0, child_process_1.execFileSync)('tar', ['-xzf', bundleTar, '-C', cacheDir, '/policy.wasm'], {
167528
- stdio: 'pipe',
167529
- });
167530
- const extractedWasm = path.join(cacheDir, 'policy.wasm');
167531
- if (fs.existsSync(extractedWasm)) {
167532
- // Move to cache-key named file
167533
- fs.renameSync(extractedWasm, cachedWasm);
167534
- }
167535
- }
167536
- catch {
167537
- // Some tar implementations don't like leading /
167538
- try {
167539
- (0, child_process_1.execFileSync)('tar', ['-xzf', bundleTar, '-C', cacheDir, 'policy.wasm'], {
167540
- stdio: 'pipe',
167541
- });
167542
- const extractedWasm = path.join(cacheDir, 'policy.wasm');
167543
- if (fs.existsSync(extractedWasm)) {
167544
- fs.renameSync(extractedWasm, cachedWasm);
167545
- }
167546
- }
167547
- catch (err2) {
167548
- throw new Error(`Failed to extract policy.wasm from OPA bundle: ${err2?.message || err2}`);
167549
- }
167550
- }
167551
- // Clean up tar
167552
- try {
167553
- fs.unlinkSync(bundleTar);
167554
- }
167555
- catch { }
167556
- if (!fs.existsSync(cachedWasm)) {
167557
- throw new Error('OPA build succeeded but policy.wasm was not found in the bundle');
167558
- }
167559
- return fs.readFileSync(cachedWasm);
167560
- }
167561
- }
167562
- exports.OpaCompiler = OpaCompiler;
167563
-
167564
-
167565
- /***/ }),
167566
-
167567
- /***/ 44693:
167568
- /***/ ((__unused_webpack_module, exports) => {
167569
-
167570
- "use strict";
167571
-
167572
- /**
167573
- * Copyright (c) ProbeLabs. All rights reserved.
167574
- * Licensed under the Elastic License 2.0; you may not use this file except
167575
- * in compliance with the Elastic License 2.0.
167576
- */
167577
- Object.defineProperty(exports, "__esModule", ({ value: true }));
167578
- exports.OpaHttpEvaluator = void 0;
167579
- /**
167580
- * OPA HTTP Evaluator - evaluates policies via an external OPA server's REST API.
167581
- *
167582
- * Uses the built-in `fetch` API (Node 18+), so no extra dependencies are needed.
167583
- */
167584
- class OpaHttpEvaluator {
167585
- baseUrl;
167586
- timeout;
167587
- constructor(baseUrl, timeout = 5000) {
167588
- // Validate URL format and protocol
167589
- let parsed;
167590
- try {
167591
- parsed = new URL(baseUrl);
167592
- }
167593
- catch {
167594
- throw new Error(`OPA HTTP evaluator: invalid URL: ${baseUrl}`);
167595
- }
167596
- if (!['http:', 'https:'].includes(parsed.protocol)) {
167597
- throw new Error(`OPA HTTP evaluator: url must use http:// or https:// protocol, got: ${baseUrl}`);
167598
- }
167599
- // Block cloud metadata, loopback, link-local, and private network addresses
167600
- const hostname = parsed.hostname;
167601
- if (this.isBlockedHostname(hostname)) {
167602
- throw new Error(`OPA HTTP evaluator: url must not point to internal, loopback, or private network addresses`);
167603
- }
167604
- // Normalize: strip trailing slash
167605
- this.baseUrl = baseUrl.replace(/\/+$/, '');
167606
- this.timeout = timeout;
167607
- }
167608
- /**
167609
- * Check if a hostname is blocked due to SSRF concerns.
167610
- *
167611
- * Blocks:
167612
- * - Loopback addresses (127.x.x.x, localhost, 0.0.0.0, ::1)
167613
- * - Link-local addresses (169.254.x.x)
167614
- * - Private networks (10.x.x.x, 172.16-31.x.x, 192.168.x.x)
167615
- * - IPv6 unique local addresses (fd00::/8)
167616
- * - Cloud metadata services (*.internal)
167617
- */
167618
- isBlockedHostname(hostname) {
167619
- if (!hostname)
167620
- return true; // block empty hostnames
167621
- // Normalize hostname: lowercase and remove brackets for IPv6
167622
- const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, '');
167623
- // Block .internal domains (cloud metadata services)
167624
- if (normalized === 'metadata.google.internal' || normalized.endsWith('.internal')) {
167625
- return true;
167626
- }
167627
- // Block localhost variants
167628
- if (normalized === 'localhost' || normalized === 'localhost.localdomain') {
167629
- return true;
167630
- }
167631
- // Block IPv6 loopback
167632
- if (normalized === '::1' || normalized === '0:0:0:0:0:0:0:1') {
167633
- return true;
167634
- }
167635
- // Check IPv4 patterns
167636
- const ipv4Pattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
167637
- const ipv4Match = normalized.match(ipv4Pattern);
167638
- if (ipv4Match) {
167639
- const octets = ipv4Match.slice(1, 5).map(Number);
167640
- // Validate octets are in range [0, 255]
167641
- if (octets.some(octet => octet > 255)) {
167642
- return false;
167643
- }
167644
- const [a, b] = octets;
167645
- // Block loopback: 127.0.0.0/8
167646
- if (a === 127) {
167647
- return true;
167648
- }
167649
- // Block 0.0.0.0/8 (this host)
167650
- if (a === 0) {
167651
- return true;
167652
- }
167653
- // Block link-local: 169.254.0.0/16
167654
- if (a === 169 && b === 254) {
167655
- return true;
167656
- }
167657
- // Block private networks
167658
- // 10.0.0.0/8
167659
- if (a === 10) {
167660
- return true;
167661
- }
167662
- // 172.16.0.0/12 (172.16.x.x through 172.31.x.x)
167663
- if (a === 172 && b >= 16 && b <= 31) {
167664
- return true;
167665
- }
167666
- // 192.168.0.0/16
167667
- if (a === 192 && b === 168) {
167668
- return true;
167669
- }
167670
- }
167671
- // Check IPv6 patterns
167672
- // Block unique local addresses: fd00::/8
167673
- if (normalized.startsWith('fd') || normalized.startsWith('fc')) {
167674
- return true;
167675
- }
167676
- // Block link-local: fe80::/10
167677
- if (normalized.startsWith('fe80:')) {
167678
- return true;
167679
- }
167680
- return false;
167681
- }
167682
- /**
167683
- * Evaluate a policy rule against an input document via OPA REST API.
167684
- *
167685
- * @param input - The input document to evaluate
167686
- * @param rulePath - OPA rule path (e.g., 'visor/check/execute')
167687
- * @returns The result object from OPA, or undefined on error
167688
- */
167689
- async evaluate(input, rulePath) {
167690
- // OPA Data API: POST /v1/data/<path>
167691
- const encodedPath = rulePath
167692
- .split('/')
167693
- .map(s => encodeURIComponent(s))
167694
- .join('/');
167695
- const url = `${this.baseUrl}/v1/data/${encodedPath}`;
167696
- const controller = new AbortController();
167697
- const timer = setTimeout(() => controller.abort(), this.timeout);
167698
- try {
167699
- const response = await fetch(url, {
167700
- method: 'POST',
167701
- headers: { 'Content-Type': 'application/json' },
167702
- body: JSON.stringify({ input }),
167703
- signal: controller.signal,
167704
- });
167705
- if (!response.ok) {
167706
- throw new Error(`OPA HTTP ${response.status}: ${response.statusText}`);
167707
- }
167708
- let body;
167709
- try {
167710
- body = await response.json();
167711
- }
167712
- catch (jsonErr) {
167713
- throw new Error(`OPA HTTP evaluator: failed to parse JSON response: ${jsonErr instanceof Error ? jsonErr.message : String(jsonErr)}`);
167714
- }
167715
- // OPA returns { result: { ... } }
167716
- return body?.result;
167717
- }
167718
- finally {
167719
- clearTimeout(timer);
167720
- }
167721
- }
167722
- async shutdown() {
167723
- // No persistent connections to close
167724
- }
167725
- }
167726
- exports.OpaHttpEvaluator = OpaHttpEvaluator;
167727
-
167728
-
167729
- /***/ }),
167730
-
167731
- /***/ 39530:
167732
- /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
167733
-
167734
- "use strict";
167735
-
167736
- /**
167737
- * Copyright (c) ProbeLabs. All rights reserved.
167738
- * Licensed under the Elastic License 2.0; you may not use this file except
167739
- * in compliance with the Elastic License 2.0.
167740
- */
167741
- Object.defineProperty(exports, "__esModule", ({ value: true }));
167742
- exports.OpaPolicyEngine = void 0;
167743
- const opa_wasm_evaluator_1 = __nccwpck_require__(8613);
167744
- const opa_http_evaluator_1 = __nccwpck_require__(44693);
167745
- const policy_input_builder_1 = __nccwpck_require__(17117);
167746
- /**
167747
- * Enterprise OPA Policy Engine.
167748
- *
167749
- * Wraps both WASM (local) and HTTP (remote) OPA evaluators behind the
167750
- * OSS PolicyEngine interface. All OPA input building and role resolution
167751
- * is handled internally — the OSS call sites pass only plain types.
167752
- */
167753
- class OpaPolicyEngine {
167754
- evaluator = null;
167755
- fallback;
167756
- timeout;
167757
- config;
167758
- inputBuilder = null;
167759
- logger = null;
167760
- constructor(config) {
167761
- this.config = config;
167762
- this.fallback = config.fallback || 'deny';
167763
- this.timeout = config.timeout || 5000;
167764
- }
167765
- async initialize(config) {
167766
- // Resolve logger once at initialization
167767
- try {
167768
- this.logger = (__nccwpck_require__(86999).logger);
167769
- }
167770
- catch {
167771
- // logger not available in this context
167772
- }
167773
- // Build actor/repo context from environment (available at engine init time)
167774
- const actor = {
167775
- authorAssociation: process.env.VISOR_AUTHOR_ASSOCIATION,
167776
- login: process.env.VISOR_AUTHOR_LOGIN || process.env.GITHUB_ACTOR,
167777
- isLocalMode: !process.env.GITHUB_ACTIONS,
167778
- };
167779
- const repo = {
167780
- owner: process.env.GITHUB_REPOSITORY_OWNER,
167781
- name: process.env.GITHUB_REPOSITORY?.split('/')[1],
167782
- branch: process.env.GITHUB_HEAD_REF,
167783
- baseBranch: process.env.GITHUB_BASE_REF,
167784
- event: process.env.GITHUB_EVENT_NAME,
167785
- };
167786
- const prNum = process.env.GITHUB_PR_NUMBER
167787
- ? parseInt(process.env.GITHUB_PR_NUMBER, 10)
167788
- : undefined;
167789
- const pullRequest = {
167790
- number: prNum !== undefined && Number.isFinite(prNum) ? prNum : undefined,
167791
- };
167792
- this.inputBuilder = new policy_input_builder_1.PolicyInputBuilder(config, actor, repo, pullRequest);
167793
- if (config.engine === 'local') {
167794
- if (!config.rules) {
167795
- throw new Error('OPA local mode requires `policy.rules` path to .wasm or .rego files');
167796
- }
167797
- const wasm = new opa_wasm_evaluator_1.OpaWasmEvaluator();
167798
- await wasm.initialize(config.rules);
167799
- if (config.data) {
167800
- wasm.loadData(config.data);
167801
- }
167802
- this.evaluator = wasm;
167803
- }
167804
- else if (config.engine === 'remote') {
167805
- if (!config.url) {
167806
- throw new Error('OPA remote mode requires `policy.url` pointing to OPA server');
167807
- }
167808
- this.evaluator = new opa_http_evaluator_1.OpaHttpEvaluator(config.url, this.timeout);
167809
- }
167810
- else {
167811
- this.evaluator = null;
167812
- }
167813
- }
167814
- /**
167815
- * Update actor/repo/PR context (e.g., after PR info becomes available).
167816
- * Called by the enterprise loader when engine context is enriched.
167817
- */
167818
- setActorContext(actor, repo, pullRequest) {
167819
- this.inputBuilder = new policy_input_builder_1.PolicyInputBuilder(this.config, actor, repo, pullRequest);
167820
- }
167821
- async evaluateCheckExecution(checkId, checkConfig) {
167822
- if (!this.evaluator || !this.inputBuilder)
167823
- return { allowed: true };
167824
- const cfg = checkConfig && typeof checkConfig === 'object'
167825
- ? checkConfig
167826
- : {};
167827
- const policyOverride = cfg.policy;
167828
- const input = this.inputBuilder.forCheckExecution({
167829
- id: checkId,
167830
- type: cfg.type || 'ai',
167831
- group: cfg.group,
167832
- tags: cfg.tags,
167833
- criticality: cfg.criticality,
167834
- sandbox: cfg.sandbox,
167835
- policy: policyOverride,
167836
- });
167837
- return this.doEvaluate(input, this.resolveRulePath('check.execute', policyOverride?.rule));
167838
- }
167839
- async evaluateToolInvocation(serverName, methodName, transport) {
167840
- if (!this.evaluator || !this.inputBuilder)
167841
- return { allowed: true };
167842
- const input = this.inputBuilder.forToolInvocation(serverName, methodName, transport);
167843
- return this.doEvaluate(input, 'visor/tool/invoke');
167844
- }
167845
- async evaluateCapabilities(checkId, capabilities) {
167846
- if (!this.evaluator || !this.inputBuilder)
167847
- return { allowed: true };
167848
- const input = this.inputBuilder.forCapabilityResolve(checkId, capabilities);
167849
- return this.doEvaluate(input, 'visor/capability/resolve');
167850
- }
167851
- async shutdown() {
167852
- if (this.evaluator && 'shutdown' in this.evaluator) {
167853
- await this.evaluator.shutdown();
167854
- }
167855
- this.evaluator = null;
167856
- this.inputBuilder = null;
167857
- }
167858
- resolveRulePath(defaultScope, override) {
167859
- if (override) {
167860
- return override.startsWith('visor/') ? override : `visor/${override}`;
167861
- }
167862
- return `visor/${defaultScope.replace(/\./g, '/')}`;
167863
- }
167864
- async doEvaluate(input, rulePath) {
167865
- try {
167866
- this.logger?.debug(`[PolicyEngine] Evaluating ${rulePath}`, JSON.stringify(input));
167867
- let timer;
167868
- const timeoutPromise = new Promise((_resolve, reject) => {
167869
- timer = setTimeout(() => reject(new Error('policy evaluation timeout')), this.timeout);
167870
- });
167871
- try {
167872
- const result = await Promise.race([this.rawEvaluate(input, rulePath), timeoutPromise]);
167873
- const decision = this.parseDecision(result);
167874
- // In warn mode, override denied decisions to allowed but flag as warn
167875
- if (!decision.allowed && this.fallback === 'warn') {
167876
- decision.allowed = true;
167877
- decision.warn = true;
167878
- decision.reason = `audit: ${decision.reason || 'policy denied'}`;
167879
- }
167880
- this.logger?.debug(`[PolicyEngine] Decision for ${rulePath}: allowed=${decision.allowed}, warn=${decision.warn || false}, reason=${decision.reason || 'none'}`);
167881
- return decision;
167882
- }
167883
- finally {
167884
- if (timer)
167885
- clearTimeout(timer);
167886
- }
167887
- }
167888
- catch (err) {
167889
- const msg = err instanceof Error ? err.message : String(err);
167890
- this.logger?.warn(`[PolicyEngine] Evaluation failed for ${rulePath}: ${msg}`);
167891
- return {
167892
- allowed: this.fallback === 'allow' || this.fallback === 'warn',
167893
- warn: this.fallback === 'warn' ? true : undefined,
167894
- reason: `policy evaluation failed, fallback=${this.fallback}`,
167895
- };
167896
- }
167897
- }
167898
- async rawEvaluate(input, rulePath) {
167899
- if (this.evaluator instanceof opa_wasm_evaluator_1.OpaWasmEvaluator) {
167900
- const result = await this.evaluator.evaluate(input);
167901
- // WASM compiled with `-e visor` entrypoint returns the full visor package tree.
167902
- // Navigate to the specific rule subtree using rulePath segments.
167903
- // e.g., 'visor/check/execute' → result.check.execute
167904
- return this.navigateWasmResult(result, rulePath);
167905
- }
167906
- return this.evaluator.evaluate(input, rulePath);
167907
- }
167908
- /**
167909
- * Navigate nested OPA WASM result tree to reach the specific rule's output.
167910
- * The WASM entrypoint `-e visor` means the result root IS the visor package,
167911
- * so we strip the `visor/` prefix and walk the remaining segments.
167912
- */
167913
- navigateWasmResult(result, rulePath) {
167914
- if (!result || typeof result !== 'object')
167915
- return result;
167916
- // Strip the 'visor/' prefix (matches our compilation entrypoint)
167917
- const segments = rulePath.replace(/^visor\//, '').split('/');
167918
- let current = result;
167919
- for (const seg of segments) {
167920
- if (current && typeof current === 'object' && seg in current) {
167921
- current = current[seg];
167922
- }
167923
- else {
167924
- return undefined; // path not found in result tree
167925
- }
167926
- }
167927
- return current;
167928
- }
167929
- parseDecision(result) {
167930
- if (result === undefined || result === null) {
167931
- return {
167932
- allowed: this.fallback === 'allow' || this.fallback === 'warn',
167933
- warn: this.fallback === 'warn' ? true : undefined,
167934
- reason: this.fallback === 'warn' ? 'audit: no policy result' : 'no policy result',
167935
- };
167936
- }
167937
- const allowed = result.allowed !== false;
167938
- const decision = {
167939
- allowed,
167940
- reason: result.reason,
167941
- };
167942
- if (result.capabilities) {
167943
- decision.capabilities = result.capabilities;
167944
- }
167945
- return decision;
167946
- }
167947
- }
167948
- exports.OpaPolicyEngine = OpaPolicyEngine;
167949
-
167950
-
167951
- /***/ }),
167952
-
167953
- /***/ 8613:
167954
- /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
167955
-
167956
- "use strict";
167957
-
167958
- /**
167959
- * Copyright (c) ProbeLabs. All rights reserved.
167960
- * Licensed under the Elastic License 2.0; you may not use this file except
167961
- * in compliance with the Elastic License 2.0.
167962
- */
167963
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
167964
- if (k2 === undefined) k2 = k;
167965
- var desc = Object.getOwnPropertyDescriptor(m, k);
167966
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
167967
- desc = { enumerable: true, get: function() { return m[k]; } };
167968
- }
167969
- Object.defineProperty(o, k2, desc);
167970
- }) : (function(o, m, k, k2) {
167971
- if (k2 === undefined) k2 = k;
167972
- o[k2] = m[k];
167973
- }));
167974
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
167975
- Object.defineProperty(o, "default", { enumerable: true, value: v });
167976
- }) : function(o, v) {
167977
- o["default"] = v;
167978
- });
167979
- var __importStar = (this && this.__importStar) || (function () {
167980
- var ownKeys = function(o) {
167981
- ownKeys = Object.getOwnPropertyNames || function (o) {
167982
- var ar = [];
167983
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
167984
- return ar;
167985
- };
167986
- return ownKeys(o);
167987
- };
167988
- return function (mod) {
167989
- if (mod && mod.__esModule) return mod;
167990
- var result = {};
167991
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
167992
- __setModuleDefault(result, mod);
167993
- return result;
167994
- };
167995
- })();
167996
- Object.defineProperty(exports, "__esModule", ({ value: true }));
167997
- exports.OpaWasmEvaluator = void 0;
167998
- const fs = __importStar(__nccwpck_require__(79896));
167999
- const path = __importStar(__nccwpck_require__(16928));
168000
- const opa_compiler_1 = __nccwpck_require__(628);
168001
- /**
168002
- * OPA WASM Evaluator - loads and evaluates OPA policies locally.
168003
- *
168004
- * Supports three input formats:
168005
- * 1. Pre-compiled `.wasm` bundle — loaded directly (fastest startup)
168006
- * 2. `.rego` files or directory — auto-compiled to WASM via `opa build` CLI
168007
- * 3. Directory with `policy.wasm` inside — loaded directly
168008
- *
168009
- * Compilation and caching of .rego files is delegated to {@link OpaCompiler}.
168010
- *
168011
- * Requires:
168012
- * - `@open-policy-agent/opa-wasm` npm package (optional dep)
168013
- * - `opa` CLI on PATH (only when auto-compiling .rego files)
168014
- */
168015
- class OpaWasmEvaluator {
168016
- policy = null;
168017
- dataDocument = {};
168018
- compiler = new opa_compiler_1.OpaCompiler();
168019
- async initialize(rulesPath) {
168020
- const paths = Array.isArray(rulesPath) ? rulesPath : [rulesPath];
168021
- const wasmBytes = await this.compiler.resolveWasmBytes(paths);
168022
- try {
168023
- // Use createRequire to load the optional dep at runtime without ncc bundling it.
168024
- // `new Function('id', 'return require(id)')` fails in ncc bundles because
168025
- // `require` is not in the `new Function` scope. `createRequire` works correctly
168026
- // because it creates a real Node.js require rooted at the given path.
168027
- // eslint-disable-next-line @typescript-eslint/no-var-requires
168028
- const { createRequire } = __nccwpck_require__(73339);
168029
- const runtimeRequire = createRequire(__filename);
168030
- const opaWasm = runtimeRequire('@open-policy-agent/opa-wasm');
168031
- const loadPolicy = opaWasm.loadPolicy || opaWasm.default?.loadPolicy;
168032
- if (!loadPolicy) {
168033
- throw new Error('loadPolicy not found in @open-policy-agent/opa-wasm');
168034
- }
168035
- this.policy = await loadPolicy(wasmBytes);
168036
- }
168037
- catch (err) {
168038
- if (err?.code === 'MODULE_NOT_FOUND' || err?.code === 'ERR_MODULE_NOT_FOUND') {
168039
- throw new Error('OPA WASM evaluator requires @open-policy-agent/opa-wasm. ' +
168040
- 'Install it with: npm install @open-policy-agent/opa-wasm');
168041
- }
168042
- throw err;
168043
- }
168044
- }
168045
- /**
168046
- * Load external data from a JSON file to use as the OPA data document.
168047
- * The loaded data will be passed to `policy.setData()` during evaluation,
168048
- * making it available in Rego via `data.<key>`.
168049
- */
168050
- loadData(dataPath) {
168051
- const resolved = path.resolve(dataPath);
168052
- if (path.normalize(resolved).includes('..')) {
168053
- throw new Error(`Data path contains traversal sequences: ${dataPath}`);
168054
- }
168055
- if (!fs.existsSync(resolved)) {
168056
- throw new Error(`OPA data file not found: ${resolved}`);
168057
- }
168058
- const stat = fs.statSync(resolved);
168059
- if (stat.size > 10 * 1024 * 1024) {
168060
- throw new Error(`OPA data file exceeds 10MB limit: ${resolved} (${stat.size} bytes)`);
168061
- }
168062
- const raw = fs.readFileSync(resolved, 'utf-8');
168063
- try {
168064
- const parsed = JSON.parse(raw);
168065
- if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
168066
- throw new Error('OPA data file must contain a JSON object (not an array or primitive)');
168067
- }
168068
- this.dataDocument = parsed;
168069
- }
168070
- catch (err) {
168071
- if (err.message.startsWith('OPA data file must')) {
168072
- throw err;
168073
- }
168074
- throw new Error(`Failed to parse OPA data file ${resolved}: ${err.message}`);
168075
- }
168076
- }
168077
- async evaluate(input) {
168078
- if (!this.policy) {
168079
- throw new Error('OPA WASM evaluator not initialized');
168080
- }
168081
- this.policy.setData(this.dataDocument);
168082
- const resultSet = this.policy.evaluate(input);
168083
- if (Array.isArray(resultSet) && resultSet.length > 0) {
168084
- return resultSet[0].result;
168085
- }
168086
- return undefined;
168087
- }
168088
- async shutdown() {
168089
- if (this.policy) {
168090
- // opa-wasm policy objects may have a close/free method for WASM cleanup
168091
- if (typeof this.policy.close === 'function') {
168092
- try {
168093
- this.policy.close();
168094
- }
168095
- catch { }
168096
- }
168097
- else if (typeof this.policy.free === 'function') {
168098
- try {
168099
- this.policy.free();
168100
- }
168101
- catch { }
168102
- }
168103
- }
168104
- this.policy = null;
168105
- }
168106
- }
168107
- exports.OpaWasmEvaluator = OpaWasmEvaluator;
168108
-
168109
-
168110
- /***/ }),
168111
-
168112
- /***/ 17117:
168113
- /***/ ((__unused_webpack_module, exports) => {
168114
-
168115
- "use strict";
168116
-
168117
- /**
168118
- * Copyright (c) ProbeLabs. All rights reserved.
168119
- * Licensed under the Elastic License 2.0; you may not use this file except
168120
- * in compliance with the Elastic License 2.0.
168121
- */
168122
- Object.defineProperty(exports, "__esModule", ({ value: true }));
168123
- exports.PolicyInputBuilder = void 0;
168124
- /**
168125
- * Builds OPA-compatible input documents from engine context.
168126
- *
168127
- * Resolves actor roles from the `policy.roles` config section by matching
168128
- * the actor's authorAssociation and login against role definitions.
168129
- */
168130
- class PolicyInputBuilder {
168131
- roles;
168132
- actor;
168133
- repository;
168134
- pullRequest;
168135
- constructor(policyConfig, actor, repository, pullRequest) {
168136
- this.roles = policyConfig.roles || {};
168137
- this.actor = actor;
168138
- this.repository = repository;
168139
- this.pullRequest = pullRequest;
168140
- }
168141
- /** Resolve which roles apply to the current actor. */
168142
- resolveRoles() {
168143
- const matched = [];
168144
- for (const [roleName, roleConfig] of Object.entries(this.roles)) {
168145
- let identityMatch = false;
168146
- if (roleConfig.author_association &&
168147
- this.actor.authorAssociation &&
168148
- roleConfig.author_association.includes(this.actor.authorAssociation)) {
168149
- identityMatch = true;
168150
- }
168151
- if (!identityMatch &&
168152
- roleConfig.users &&
168153
- this.actor.login &&
168154
- roleConfig.users.includes(this.actor.login)) {
168155
- identityMatch = true;
168156
- }
168157
- // Slack user ID match
168158
- if (!identityMatch &&
168159
- roleConfig.slack_users &&
168160
- this.actor.slack?.userId &&
168161
- roleConfig.slack_users.includes(this.actor.slack.userId)) {
168162
- identityMatch = true;
168163
- }
168164
- // Email match (case-insensitive)
168165
- if (!identityMatch && roleConfig.emails && this.actor.slack?.email) {
168166
- const actorEmail = this.actor.slack.email.toLowerCase();
168167
- if (roleConfig.emails.some(e => e.toLowerCase() === actorEmail)) {
168168
- identityMatch = true;
168169
- }
168170
- }
168171
- // Note: teams-based role resolution requires GitHub API access (read:org scope)
168172
- // and is not yet implemented. If configured, the role will not match via teams.
168173
- if (!identityMatch)
168174
- continue;
168175
- // slack_channels gate: if set, the role only applies when triggered from one of these channels
168176
- if (roleConfig.slack_channels && roleConfig.slack_channels.length > 0) {
168177
- if (!this.actor.slack?.channelId ||
168178
- !roleConfig.slack_channels.includes(this.actor.slack.channelId)) {
168179
- continue;
168180
- }
168181
- }
168182
- matched.push(roleName);
168183
- }
168184
- return matched;
168185
- }
168186
- buildActor() {
168187
- return {
168188
- authorAssociation: this.actor.authorAssociation,
168189
- login: this.actor.login,
168190
- roles: this.resolveRoles(),
168191
- isLocalMode: this.actor.isLocalMode,
168192
- ...(this.actor.slack && { slack: this.actor.slack }),
168193
- };
168194
- }
168195
- forCheckExecution(check) {
168196
- return {
168197
- scope: 'check.execute',
168198
- check: {
168199
- id: check.id,
168200
- type: check.type,
168201
- group: check.group,
168202
- tags: check.tags,
168203
- criticality: check.criticality,
168204
- sandbox: check.sandbox,
168205
- policy: check.policy,
168206
- },
168207
- actor: this.buildActor(),
168208
- repository: this.repository,
168209
- pullRequest: this.pullRequest,
168210
- };
168211
- }
168212
- forToolInvocation(serverName, methodName, transport) {
168213
- return {
168214
- scope: 'tool.invoke',
168215
- tool: { serverName, methodName, transport },
168216
- actor: this.buildActor(),
168217
- repository: this.repository,
168218
- pullRequest: this.pullRequest,
168219
- };
168220
- }
168221
- forCapabilityResolve(checkId, capabilities) {
168222
- return {
168223
- scope: 'capability.resolve',
168224
- check: { id: checkId, type: 'ai' },
168225
- capability: capabilities,
168226
- actor: this.buildActor(),
168227
- repository: this.repository,
168228
- pullRequest: this.pullRequest,
168229
- };
168230
- }
168231
- }
168232
- exports.PolicyInputBuilder = PolicyInputBuilder;
168233
-
168234
-
168235
- /***/ }),
168236
-
168237
- /***/ 63737:
168238
- /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
168239
-
168240
- "use strict";
168241
-
168242
- /**
168243
- * Copyright (c) ProbeLabs. All rights reserved.
168244
- * Licensed under the Elastic License 2.0; you may not use this file except
168245
- * in compliance with the Elastic License 2.0.
168246
- */
168247
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
168248
- if (k2 === undefined) k2 = k;
168249
- var desc = Object.getOwnPropertyDescriptor(m, k);
168250
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
168251
- desc = { enumerable: true, get: function() { return m[k]; } };
168252
- }
168253
- Object.defineProperty(o, k2, desc);
168254
- }) : (function(o, m, k, k2) {
168255
- if (k2 === undefined) k2 = k;
168256
- o[k2] = m[k];
168257
- }));
168258
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
168259
- Object.defineProperty(o, "default", { enumerable: true, value: v });
168260
- }) : function(o, v) {
168261
- o["default"] = v;
168262
- });
168263
- var __importStar = (this && this.__importStar) || (function () {
168264
- var ownKeys = function(o) {
168265
- ownKeys = Object.getOwnPropertyNames || function (o) {
168266
- var ar = [];
168267
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
168268
- return ar;
168269
- };
168270
- return ownKeys(o);
168271
- };
168272
- return function (mod) {
168273
- if (mod && mod.__esModule) return mod;
168274
- var result = {};
168275
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
168276
- __setModuleDefault(result, mod);
168277
- return result;
168278
- };
168279
- })();
168280
- Object.defineProperty(exports, "__esModule", ({ value: true }));
168281
- exports.KnexStoreBackend = void 0;
168282
- /**
168283
- * Knex-backed schedule store for PostgreSQL, MySQL, and MSSQL (Enterprise)
168284
- *
168285
- * Uses Knex query builder for database-agnostic SQL. Same schema as SQLite backend
168286
- * but with real distributed locking via row-level claims (claimed_by/claimed_at/lock_token).
168287
- */
168288
- const fs = __importStar(__nccwpck_require__(79896));
168289
- const path = __importStar(__nccwpck_require__(16928));
168290
- const uuid_1 = __nccwpck_require__(31914);
168291
- const logger_1 = __nccwpck_require__(86999);
168292
- function toNum(val) {
168293
- if (val === null || val === undefined)
168294
- return undefined;
168295
- return typeof val === 'string' ? parseInt(val, 10) : val;
168296
- }
168297
- function safeJsonParse(value) {
168298
- if (!value)
168299
- return undefined;
168300
- try {
168301
- return JSON.parse(value);
168302
- }
168303
- catch {
168304
- return undefined;
168305
- }
168306
- }
168307
- function fromDbRow(row) {
168308
- return {
168309
- id: row.id,
168310
- creatorId: row.creator_id,
168311
- creatorContext: row.creator_context ?? undefined,
168312
- creatorName: row.creator_name ?? undefined,
168313
- timezone: row.timezone,
168314
- schedule: row.schedule_expr,
168315
- runAt: toNum(row.run_at),
168316
- isRecurring: row.is_recurring === true || row.is_recurring === 1,
168317
- originalExpression: row.original_expression,
168318
- workflow: row.workflow ?? undefined,
168319
- workflowInputs: safeJsonParse(row.workflow_inputs),
168320
- outputContext: safeJsonParse(row.output_context),
168321
- status: row.status,
168322
- createdAt: toNum(row.created_at),
168323
- lastRunAt: toNum(row.last_run_at),
168324
- nextRunAt: toNum(row.next_run_at),
168325
- runCount: row.run_count,
168326
- failureCount: row.failure_count,
168327
- lastError: row.last_error ?? undefined,
168328
- previousResponse: row.previous_response ?? undefined,
168329
- };
168330
- }
168331
- function toInsertRow(schedule) {
168332
- return {
168333
- id: schedule.id,
168334
- creator_id: schedule.creatorId,
168335
- creator_context: schedule.creatorContext ?? null,
168336
- creator_name: schedule.creatorName ?? null,
168337
- timezone: schedule.timezone,
168338
- schedule_expr: schedule.schedule,
168339
- run_at: schedule.runAt ?? null,
168340
- is_recurring: schedule.isRecurring,
168341
- original_expression: schedule.originalExpression,
168342
- workflow: schedule.workflow ?? null,
168343
- workflow_inputs: schedule.workflowInputs ? JSON.stringify(schedule.workflowInputs) : null,
168344
- output_context: schedule.outputContext ? JSON.stringify(schedule.outputContext) : null,
168345
- status: schedule.status,
168346
- created_at: schedule.createdAt,
168347
- last_run_at: schedule.lastRunAt ?? null,
168348
- next_run_at: schedule.nextRunAt ?? null,
168349
- run_count: schedule.runCount,
168350
- failure_count: schedule.failureCount,
168351
- last_error: schedule.lastError ?? null,
168352
- previous_response: schedule.previousResponse ?? null,
168353
- };
168354
- }
168355
- /**
168356
- * Enterprise Knex-backed store for PostgreSQL, MySQL, and MSSQL
168357
- */
168358
- class KnexStoreBackend {
168359
- knex = null;
168360
- driver;
168361
- connection;
168362
- constructor(driver, storageConfig, _haConfig) {
168363
- this.driver = driver;
168364
- this.connection = (storageConfig.connection || {});
168365
- }
168366
- async initialize() {
168367
- // Load knex dynamically
168368
- const { createRequire } = __nccwpck_require__(73339);
168369
- const runtimeRequire = createRequire(__filename);
168370
- let knexFactory;
168371
- try {
168372
- knexFactory = runtimeRequire('knex');
168373
- }
168374
- catch (err) {
168375
- const code = err?.code;
168376
- if (code === 'MODULE_NOT_FOUND' || code === 'ERR_MODULE_NOT_FOUND') {
168377
- throw new Error('knex is required for PostgreSQL/MySQL/MSSQL schedule storage. ' +
168378
- 'Install it with: npm install knex');
168379
- }
168380
- throw err;
168381
- }
168382
- const clientMap = {
168383
- postgresql: 'pg',
168384
- mysql: 'mysql2',
168385
- mssql: 'tedious',
168386
- };
168387
- const client = clientMap[this.driver];
168388
- // Build connection config
168389
- let connection;
168390
- if (this.connection.connection_string) {
168391
- connection = this.connection.connection_string;
168392
- }
168393
- else if (this.driver === 'mssql') {
168394
- connection = this.buildMssqlConnection();
168395
- }
168396
- else {
168397
- connection = this.buildStandardConnection();
168398
- }
168399
- this.knex = knexFactory({
168400
- client,
168401
- connection,
168402
- pool: {
168403
- min: this.connection.pool?.min ?? 0,
168404
- max: this.connection.pool?.max ?? 10,
168405
- },
168406
- });
168407
- // Run schema migration
168408
- await this.migrateSchema();
168409
- logger_1.logger.info(`[KnexStore] Initialized (${this.driver})`);
168410
- }
168411
- buildStandardConnection() {
168412
- return {
168413
- host: this.connection.host || 'localhost',
168414
- port: this.connection.port,
168415
- database: this.connection.database || 'visor',
168416
- user: this.connection.user,
168417
- password: this.connection.password,
168418
- ssl: this.resolveSslConfig(),
168419
- };
168420
- }
168421
- buildMssqlConnection() {
168422
- const ssl = this.connection.ssl;
168423
- const sslEnabled = ssl === true || (typeof ssl === 'object' && ssl.enabled !== false);
168424
- return {
168425
- server: this.connection.host || 'localhost',
168426
- port: this.connection.port,
168427
- database: this.connection.database || 'visor',
168428
- user: this.connection.user,
168429
- password: this.connection.password,
168430
- options: {
168431
- encrypt: sslEnabled,
168432
- trustServerCertificate: typeof ssl === 'object' ? ssl.reject_unauthorized === false : !sslEnabled,
168433
- },
168434
- };
168435
- }
168436
- resolveSslConfig() {
168437
- const ssl = this.connection.ssl;
168438
- if (ssl === false || ssl === undefined)
168439
- return false;
168440
- if (ssl === true)
168441
- return { rejectUnauthorized: true };
168442
- // Object config
168443
- if (ssl.enabled === false)
168444
- return false;
168445
- const result = {
168446
- rejectUnauthorized: ssl.reject_unauthorized !== false,
168447
- };
168448
- if (ssl.ca) {
168449
- const caPath = this.validateSslPath(ssl.ca, 'CA certificate');
168450
- result.ca = fs.readFileSync(caPath, 'utf8');
168451
- }
168452
- if (ssl.cert) {
168453
- const certPath = this.validateSslPath(ssl.cert, 'client certificate');
168454
- result.cert = fs.readFileSync(certPath, 'utf8');
168455
- }
168456
- if (ssl.key) {
168457
- const keyPath = this.validateSslPath(ssl.key, 'client key');
168458
- result.key = fs.readFileSync(keyPath, 'utf8');
168459
- }
168460
- return result;
168461
- }
168462
- validateSslPath(filePath, label) {
168463
- const resolved = path.resolve(filePath);
168464
- if (resolved !== path.normalize(resolved)) {
168465
- throw new Error(`SSL ${label} path contains invalid sequences: ${filePath}`);
168466
- }
168467
- if (!fs.existsSync(resolved)) {
168468
- throw new Error(`SSL ${label} not found: ${filePath}`);
168469
- }
168470
- return resolved;
168471
- }
168472
- async shutdown() {
168473
- if (this.knex) {
168474
- await this.knex.destroy();
168475
- this.knex = null;
168476
- }
168477
- }
168478
- async migrateSchema() {
168479
- const knex = this.getKnex();
168480
- const exists = await knex.schema.hasTable('schedules');
168481
- if (!exists) {
168482
- await knex.schema.createTable('schedules', table => {
168483
- table.string('id', 36).primary();
168484
- table.string('creator_id', 255).notNullable().index();
168485
- table.string('creator_context', 255);
168486
- table.string('creator_name', 255);
168487
- table.string('timezone', 64).notNullable().defaultTo('UTC');
168488
- table.string('schedule_expr', 255);
168489
- table.bigInteger('run_at');
168490
- table.boolean('is_recurring').notNullable();
168491
- table.text('original_expression');
168492
- table.string('workflow', 255);
168493
- table.text('workflow_inputs');
168494
- table.text('output_context');
168495
- table.string('status', 20).notNullable().index();
168496
- table.bigInteger('created_at').notNullable();
168497
- table.bigInteger('last_run_at');
168498
- table.bigInteger('next_run_at');
168499
- table.integer('run_count').notNullable().defaultTo(0);
168500
- table.integer('failure_count').notNullable().defaultTo(0);
168501
- table.text('last_error');
168502
- table.text('previous_response');
168503
- table.index(['status', 'next_run_at']);
168504
- });
168505
- }
168506
- // Create scheduler_locks table for distributed locking
168507
- const locksExist = await knex.schema.hasTable('scheduler_locks');
168508
- if (!locksExist) {
168509
- await knex.schema.createTable('scheduler_locks', table => {
168510
- table.string('lock_id', 255).primary();
168511
- table.string('node_id', 255).notNullable();
168512
- table.string('lock_token', 36).notNullable();
168513
- table.bigInteger('acquired_at').notNullable();
168514
- table.bigInteger('expires_at').notNullable();
168515
- });
168516
- }
168517
- }
168518
- getKnex() {
168519
- if (!this.knex) {
168520
- throw new Error('[KnexStore] Not initialized. Call initialize() first.');
168521
- }
168522
- return this.knex;
168523
- }
168524
- // --- CRUD ---
168525
- async create(schedule) {
168526
- const knex = this.getKnex();
168527
- const newSchedule = {
168528
- ...schedule,
168529
- id: (0, uuid_1.v4)(),
168530
- createdAt: Date.now(),
168531
- runCount: 0,
168532
- failureCount: 0,
168533
- status: 'active',
168534
- };
168535
- await knex('schedules').insert(toInsertRow(newSchedule));
168536
- logger_1.logger.info(`[KnexStore] Created schedule ${newSchedule.id} for user ${newSchedule.creatorId}`);
168537
- return newSchedule;
168538
- }
168539
- async importSchedule(schedule) {
168540
- const knex = this.getKnex();
168541
- const existing = await knex('schedules').where('id', schedule.id).first();
168542
- if (existing)
168543
- return; // Already imported (idempotent)
168544
- await knex('schedules').insert(toInsertRow(schedule));
168545
- }
168546
- async get(id) {
168547
- const knex = this.getKnex();
168548
- const row = await knex('schedules').where('id', id).first();
168549
- return row ? fromDbRow(row) : undefined;
168550
- }
168551
- async update(id, patch) {
168552
- const knex = this.getKnex();
168553
- const existing = await knex('schedules').where('id', id).first();
168554
- if (!existing)
168555
- return undefined;
168556
- const current = fromDbRow(existing);
168557
- const updated = { ...current, ...patch, id: current.id };
168558
- const row = toInsertRow(updated);
168559
- // Remove id from update (PK cannot change)
168560
- delete row.id;
168561
- await knex('schedules').where('id', id).update(row);
168562
- return updated;
168563
- }
168564
- async delete(id) {
168565
- const knex = this.getKnex();
168566
- const deleted = await knex('schedules').where('id', id).del();
168567
- if (deleted > 0) {
168568
- logger_1.logger.info(`[KnexStore] Deleted schedule ${id}`);
168569
- return true;
168570
- }
168571
- return false;
168572
- }
168573
- // --- Queries ---
168574
- async getByCreator(creatorId) {
168575
- const knex = this.getKnex();
168576
- const rows = await knex('schedules').where('creator_id', creatorId);
168577
- return rows.map((r) => fromDbRow(r));
168578
- }
168579
- async getActiveSchedules() {
168580
- const knex = this.getKnex();
168581
- const rows = await knex('schedules').where('status', 'active');
168582
- return rows.map((r) => fromDbRow(r));
168583
- }
168584
- async getDueSchedules(now) {
168585
- const ts = now ?? Date.now();
168586
- const knex = this.getKnex();
168587
- // MSSQL uses 1/0 for booleans
168588
- const bFalse = this.driver === 'mssql' ? 0 : false;
168589
- const bTrue = this.driver === 'mssql' ? 1 : true;
168590
- const rows = await knex('schedules')
168591
- .where('status', 'active')
168592
- .andWhere(function () {
168593
- this.where(function () {
168594
- this.where('is_recurring', bFalse)
168595
- .whereNotNull('run_at')
168596
- .where('run_at', '<=', ts);
168597
- }).orWhere(function () {
168598
- this.where('is_recurring', bTrue)
168599
- .whereNotNull('next_run_at')
168600
- .where('next_run_at', '<=', ts);
168601
- });
168602
- });
168603
- return rows.map((r) => fromDbRow(r));
168604
- }
168605
- async findByWorkflow(creatorId, workflowName) {
168606
- const knex = this.getKnex();
168607
- const escaped = workflowName.toLowerCase().replace(/[%_\\]/g, '\\$&');
168608
- const pattern = `%${escaped}%`;
168609
- const rows = await knex('schedules')
168610
- .where('creator_id', creatorId)
168611
- .where('status', 'active')
168612
- .whereRaw("LOWER(workflow) LIKE ? ESCAPE '\\'", [pattern]);
168613
- return rows.map((r) => fromDbRow(r));
168614
- }
168615
- async getAll() {
168616
- const knex = this.getKnex();
168617
- const rows = await knex('schedules');
168618
- return rows.map((r) => fromDbRow(r));
168619
- }
168620
- async getStats() {
168621
- const knex = this.getKnex();
168622
- // MSSQL uses 1/0 for booleans; PostgreSQL/MySQL accept both true/1
168623
- const boolTrue = this.driver === 'mssql' ? '1' : 'true';
168624
- const boolFalse = this.driver === 'mssql' ? '0' : 'false';
168625
- const result = await knex('schedules')
168626
- .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`))
168627
- .first();
168628
- return {
168629
- total: Number(result.total) || 0,
168630
- active: Number(result.active) || 0,
168631
- paused: Number(result.paused) || 0,
168632
- completed: Number(result.completed) || 0,
168633
- failed: Number(result.failed) || 0,
168634
- recurring: Number(result.recurring) || 0,
168635
- oneTime: Number(result.one_time) || 0,
168636
- };
168637
- }
168638
- async validateLimits(creatorId, isRecurring, limits) {
168639
- const knex = this.getKnex();
168640
- if (limits.maxGlobal) {
168641
- const result = await knex('schedules').count('* as cnt').first();
168642
- if (Number(result?.cnt) >= limits.maxGlobal) {
168643
- throw new Error(`Global schedule limit reached (${limits.maxGlobal})`);
168644
- }
168645
- }
168646
- if (limits.maxPerUser) {
168647
- const result = await knex('schedules')
168648
- .where('creator_id', creatorId)
168649
- .count('* as cnt')
168650
- .first();
168651
- if (Number(result?.cnt) >= limits.maxPerUser) {
168652
- throw new Error(`You have reached the maximum number of schedules (${limits.maxPerUser})`);
168653
- }
168654
- }
168655
- if (isRecurring && limits.maxRecurringPerUser) {
168656
- const bTrue = this.driver === 'mssql' ? 1 : true;
168657
- const result = await knex('schedules')
168658
- .where('creator_id', creatorId)
168659
- .where('is_recurring', bTrue)
168660
- .count('* as cnt')
168661
- .first();
168662
- if (Number(result?.cnt) >= limits.maxRecurringPerUser) {
168663
- throw new Error(`You have reached the maximum number of recurring schedules (${limits.maxRecurringPerUser})`);
168664
- }
168665
- }
168666
- }
168667
- // --- HA Distributed Locking (via scheduler_locks table) ---
168668
- async tryAcquireLock(lockId, nodeId, ttlSeconds) {
168669
- const knex = this.getKnex();
168670
- const now = Date.now();
168671
- const expiresAt = now + ttlSeconds * 1000;
168672
- const token = (0, uuid_1.v4)();
168673
- // Step 1: Try to claim an existing expired lock
168674
- const updated = await knex('scheduler_locks')
168675
- .where('lock_id', lockId)
168676
- .where('expires_at', '<', now)
168677
- .update({
168678
- node_id: nodeId,
168679
- lock_token: token,
168680
- acquired_at: now,
168681
- expires_at: expiresAt,
168682
- });
168683
- if (updated > 0)
168684
- return token;
168685
- // Step 2: Try to INSERT a new lock row
168686
- try {
168687
- await knex('scheduler_locks').insert({
168688
- lock_id: lockId,
168689
- node_id: nodeId,
168690
- lock_token: token,
168691
- acquired_at: now,
168692
- expires_at: expiresAt,
168693
- });
168694
- return token;
168695
- }
168696
- catch {
168697
- // Unique constraint violation — another node holds the lock
168698
- return null;
168699
- }
168700
- }
168701
- async releaseLock(lockId, lockToken) {
168702
- const knex = this.getKnex();
168703
- await knex('scheduler_locks').where('lock_id', lockId).where('lock_token', lockToken).del();
168704
- }
168705
- async renewLock(lockId, lockToken, ttlSeconds) {
168706
- const knex = this.getKnex();
168707
- const now = Date.now();
168708
- const expiresAt = now + ttlSeconds * 1000;
168709
- const updated = await knex('scheduler_locks')
168710
- .where('lock_id', lockId)
168711
- .where('lock_token', lockToken)
168712
- .update({ acquired_at: now, expires_at: expiresAt });
168713
- return updated > 0;
168714
- }
168715
- async flush() {
168716
- // No-op for server-based backends
168717
- }
168718
- }
168719
- exports.KnexStoreBackend = KnexStoreBackend;
168720
-
168721
-
168722
167038
  /***/ }),
168723
167039
 
168724
167040
  /***/ 83864:
@@ -169587,6 +167903,7 @@ class GitHubFrontend {
169587
167903
  minUpdateDelayMs = 1000; // Minimum delay between updates (public for testing)
169588
167904
  // Cache of created GitHub comment IDs per group to handle API eventual consistency
169589
167905
  createdCommentGithubIds = new Map();
167906
+ _stopped = false;
169590
167907
  start(ctx) {
169591
167908
  const log = ctx.logger;
169592
167909
  const bus = ctx.eventBus;
@@ -169714,10 +168031,23 @@ class GitHubFrontend {
169714
168031
  }
169715
168032
  }));
169716
168033
  }
169717
- stop() {
168034
+ async stop() {
168035
+ this._stopped = true;
169718
168036
  for (const s of this.subs)
169719
168037
  s.unsubscribe();
169720
168038
  this.subs = [];
168039
+ if (this._timer) {
168040
+ clearTimeout(this._timer);
168041
+ this._timer = null;
168042
+ }
168043
+ this._pendingIds.clear();
168044
+ // Drain any in-flight updateGroupedComment operations so callers that
168045
+ // await stop() (e.g. FrontendsHost.stopAll) are guaranteed no async
168046
+ // work leaks after stop resolves.
168047
+ const pending = Array.from(this.updateLocks.values());
168048
+ if (pending.length > 0) {
168049
+ await Promise.allSettled(pending);
168050
+ }
169721
168051
  }
169722
168052
  async buildFullBody(ctx, group) {
169723
168053
  const header = this.renderThreadHeader(ctx, group);
@@ -169808,6 +168138,8 @@ ${end}`);
169808
168138
  */
169809
168139
  async performGroupedCommentUpdate(ctx, comments, group, changedIds) {
169810
168140
  try {
168141
+ if (this._stopped)
168142
+ return;
169811
168143
  if (!ctx.run.repo || !ctx.run.pr)
169812
168144
  return;
169813
168145
  // Check if PR comments are enabled (default to true if not specified)
@@ -179538,35 +177870,6 @@ class OutputFormatters {
179538
177870
  exports.OutputFormatters = OutputFormatters;
179539
177871
 
179540
177872
 
179541
- /***/ }),
179542
-
179543
- /***/ 93866:
179544
- /***/ ((__unused_webpack_module, exports) => {
179545
-
179546
- "use strict";
179547
-
179548
- Object.defineProperty(exports, "__esModule", ({ value: true }));
179549
- exports.DefaultPolicyEngine = void 0;
179550
- /**
179551
- * Default (no-op) policy engine — always allows everything.
179552
- * Used when no enterprise license is present or policy is disabled.
179553
- */
179554
- class DefaultPolicyEngine {
179555
- async initialize(_config) { }
179556
- async evaluateCheckExecution(_checkId, _checkConfig) {
179557
- return { allowed: true };
179558
- }
179559
- async evaluateToolInvocation(_serverName, _methodName, _transport) {
179560
- return { allowed: true };
179561
- }
179562
- async evaluateCapabilities(_checkId, _capabilities) {
179563
- return { allowed: true };
179564
- }
179565
- async shutdown() { }
179566
- }
179567
- exports.DefaultPolicyEngine = DefaultPolicyEngine;
179568
-
179569
-
179570
177873
  /***/ }),
179571
177874
 
179572
177875
  /***/ 96611:
@@ -181187,12 +179490,53 @@ class AICheckProvider extends check_provider_interface_1.CheckProvider {
181187
179490
  if (Object.keys(dynamicServers).length > 0) {
181188
179491
  Object.assign(mcpServers, dynamicServers);
181189
179492
  }
179493
+ // Emit telemetry for tool setup diagnostics
179494
+ try {
179495
+ const span = lazy_otel_1.trace.getSpan(lazy_otel_1.context.active());
179496
+ if (span) {
179497
+ span.addEvent('tool_setup.mcp_servers_js', {
179498
+ 'tool_setup.server_count': Object.keys(dynamicServers).length,
179499
+ 'tool_setup.server_names': Object.keys(dynamicServers).join(','),
179500
+ 'tool_setup.workflow_entries': Object.entries(dynamicServers)
179501
+ .filter(([, cfg]) => cfg?.workflow)
179502
+ .map(([name, cfg]) => `${name}→${cfg.workflow}`)
179503
+ .join(','),
179504
+ });
179505
+ }
179506
+ }
179507
+ catch { }
181190
179508
  }
181191
179509
  catch (error) {
181192
- logger_1.logger.error(`[AICheckProvider] Failed to evaluate ai_mcp_servers_js: ${error instanceof Error ? error.message : 'Unknown error'}`);
179510
+ const errMsg = error instanceof Error ? error.message : 'Unknown error';
179511
+ logger_1.logger.error(`[AICheckProvider] Failed to evaluate ai_mcp_servers_js: ${errMsg}`);
179512
+ // Emit telemetry for the failure
179513
+ try {
179514
+ const span = lazy_otel_1.trace.getSpan(lazy_otel_1.context.active());
179515
+ if (span) {
179516
+ span.addEvent('tool_setup.mcp_servers_js_error', {
179517
+ 'tool_setup.error': errMsg,
179518
+ });
179519
+ }
179520
+ }
179521
+ catch { }
181193
179522
  // Continue without dynamic servers
181194
179523
  }
181195
179524
  }
179525
+ else if (mcpServersJsExpr && !_dependencyResults) {
179526
+ // Expression exists but no dependency results — this means the check has no dependencies
179527
+ // or the dependency results map was empty/undefined
179528
+ try {
179529
+ const span = lazy_otel_1.trace.getSpan(lazy_otel_1.context.active());
179530
+ if (span) {
179531
+ span.addEvent('tool_setup.mcp_servers_js_skipped', {
179532
+ 'tool_setup.reason': 'no_dependency_results',
179533
+ 'tool_setup.has_expr': true,
179534
+ 'tool_setup.has_deps': false,
179535
+ });
179536
+ }
179537
+ }
179538
+ catch { }
179539
+ }
181196
179540
  // 5. Resolve environment variable placeholders in MCP server env configs
181197
179541
  // Supports ${VAR} and ${{ env.VAR }} syntax
181198
179542
  for (const serverConfig of Object.values(mcpServers)) {
@@ -181345,6 +179689,28 @@ class AICheckProvider extends check_provider_interface_1.CheckProvider {
181345
179689
  try {
181346
179690
  // Load custom tools from global config (supports workflows and custom tools)
181347
179691
  const customTools = this.loadCustomTools(customToolsToLoad, config);
179692
+ // Emit telemetry for tool resolution results
179693
+ try {
179694
+ const span = lazy_otel_1.trace.getSpan(lazy_otel_1.context.active());
179695
+ if (span) {
179696
+ const requestedNames = customToolsToLoad.map(item => typeof item === 'string'
179697
+ ? item
179698
+ : `${item.name || item.workflow}(wf:${item.workflow})`);
179699
+ span.addEvent('tool_setup.resolution', {
179700
+ 'tool_setup.requested_count': customToolsToLoad.length,
179701
+ 'tool_setup.requested_names': requestedNames.join(','),
179702
+ 'tool_setup.resolved_count': customTools.size,
179703
+ 'tool_setup.resolved_names': Array.from(customTools.keys()).join(','),
179704
+ 'tool_setup.missing_count': customToolsToLoad.length - customTools.size,
179705
+ });
179706
+ }
179707
+ }
179708
+ catch { }
179709
+ if (customToolsToLoad.length > 0 && customTools.size === 0) {
179710
+ logger_1.logger.warn(`[AICheckProvider] All ${customToolsToLoad.length} custom tools failed to resolve! ` +
179711
+ `Requested: ${customToolsToLoad.map(item => (typeof item === 'string' ? item : item.workflow)).join(', ')}. ` +
179712
+ `AI will have no workflow tools available.`);
179713
+ }
181348
179714
  // Add schedule tool if enabled (via ai_mcp_servers { tool: 'schedule' } or enable_scheduler)
181349
179715
  if (scheduleToolEnabled) {
181350
179716
  const scheduleTool = (0, schedule_tool_1.getScheduleToolDefinition)();
@@ -181382,10 +179748,36 @@ class AICheckProvider extends check_provider_interface_1.CheckProvider {
181382
179748
  }
181383
179749
  }
181384
179750
  catch (error) {
181385
- logger_1.logger.error(`[AICheckProvider] Failed to start custom tools SSE server '${customToolsServerName}': ${error instanceof Error ? error.message : 'Unknown error'}`);
179751
+ const errMsg = error instanceof Error ? error.message : 'Unknown error';
179752
+ logger_1.logger.error(`[AICheckProvider] Failed to start custom tools SSE server '${customToolsServerName}': ${errMsg}`);
179753
+ // Emit telemetry for SSE server failure
179754
+ try {
179755
+ const span = lazy_otel_1.trace.getSpan(lazy_otel_1.context.active());
179756
+ if (span) {
179757
+ span.addEvent('tool_setup.sse_server_error', {
179758
+ 'tool_setup.error': errMsg,
179759
+ 'tool_setup.server_name': customToolsServerName || '',
179760
+ });
179761
+ }
179762
+ }
179763
+ catch { }
181386
179764
  // Continue without custom tools
181387
179765
  }
181388
179766
  }
179767
+ // Emit final tool setup summary telemetry
179768
+ try {
179769
+ const span = lazy_otel_1.trace.getSpan(lazy_otel_1.context.active());
179770
+ if (span) {
179771
+ const finalServerNames = Object.keys(mcpServers);
179772
+ span.addEvent('tool_setup.final', {
179773
+ 'tool_setup.final_server_count': finalServerNames.length,
179774
+ 'tool_setup.final_server_names': finalServerNames.join(','),
179775
+ 'tool_setup.has_custom_tools_server': !!customToolsServer,
179776
+ 'tool_setup.tools_disabled': !!config.ai?.disableTools,
179777
+ });
179778
+ }
179779
+ }
179780
+ catch { }
181389
179781
  // Pass MCP server config directly to AI service (unless tools are disabled)
181390
179782
  if (Object.keys(mcpServers).length > 0 && !config.ai?.disableTools) {
181391
179783
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -193932,6 +192324,11 @@ async function handleCancel(positional, flags) {
193932
192324
  process.exit(1);
193933
192325
  }
193934
192326
  await store.deleteAsync(schedule.id);
192327
+ // Also cancel the in-memory job (cron or timeout) so it doesn't fire
192328
+ const scheduler = (0, scheduler_1.getScheduler)();
192329
+ if (scheduler) {
192330
+ scheduler.cancelSchedule(schedule.id);
192331
+ }
193935
192332
  console.log('Schedule cancelled successfully!');
193936
192333
  console.log();
193937
192334
  console.log(` ID: ${schedule.id.substring(0, 8)}`);
@@ -194839,6 +193236,7 @@ exports.isScheduleTool = isScheduleTool;
194839
193236
  exports.buildScheduleToolContext = buildScheduleToolContext;
194840
193237
  const schedule_store_1 = __nccwpck_require__(27336);
194841
193238
  const schedule_parser_1 = __nccwpck_require__(48478);
193239
+ const scheduler_1 = __nccwpck_require__(28404);
194842
193240
  const logger_1 = __nccwpck_require__(86999);
194843
193241
  /**
194844
193242
  * Simple glob-style pattern matching for workflow names
@@ -195259,8 +193657,13 @@ async function handleCancel(args, context, store) {
195259
193657
  error: 'You can only cancel your own schedules.',
195260
193658
  };
195261
193659
  }
195262
- // Delete the schedule
193660
+ // Delete the schedule from DB
195263
193661
  await store.deleteAsync(schedule.id);
193662
+ // Also cancel the in-memory job (cron or timeout) so it doesn't fire
193663
+ const scheduler = (0, scheduler_1.getScheduler)();
193664
+ if (scheduler) {
193665
+ scheduler.cancelSchedule(schedule.id);
193666
+ }
195264
193667
  logger_1.logger.info(`[ScheduleTool] Cancelled schedule ${schedule.id} for user ${context.userId}`);
195265
193668
  return {
195266
193669
  success: true,
@@ -195718,6 +194121,27 @@ class Scheduler {
195718
194121
  getStore() {
195719
194122
  return this.store;
195720
194123
  }
194124
+ /**
194125
+ * Cancel a schedule's in-memory job (cron or timeout).
194126
+ * Called after deleting from DB to ensure the job doesn't fire again.
194127
+ */
194128
+ cancelSchedule(scheduleId) {
194129
+ // Stop cron job if it exists
194130
+ const cronJob = this.cronJobs.get(scheduleId);
194131
+ if (cronJob) {
194132
+ cronJob.stop();
194133
+ this.cronJobs.delete(scheduleId);
194134
+ logger_1.logger.debug(`[Scheduler] Cancelled cron job for schedule ${scheduleId}`);
194135
+ return;
194136
+ }
194137
+ // Clear timeout if it exists
194138
+ const timeout = this.oneTimeTimeouts.get(scheduleId);
194139
+ if (timeout) {
194140
+ clearTimeout(timeout);
194141
+ this.oneTimeTimeouts.delete(scheduleId);
194142
+ logger_1.logger.debug(`[Scheduler] Cancelled timeout for schedule ${scheduleId}`);
194143
+ }
194144
+ }
195721
194145
  /**
195722
194146
  * Start the scheduler
195723
194147
  */
@@ -196098,6 +194522,26 @@ class Scheduler {
196098
194522
  * Execute a scheduled workflow
196099
194523
  */
196100
194524
  async executeSchedule(schedule) {
194525
+ // DB freshness check: verify the schedule still exists and is active.
194526
+ // This prevents execution of cancelled or paused schedules when the
194527
+ // in-memory job fires after a DB-only cancellation.
194528
+ // Note: This is a single indexed primary-key lookup (<1ms for SQLite),
194529
+ // and only runs for user-created schedules (static cron jobs use
194530
+ // executeStaticCronJob instead), so the overhead is negligible
194531
+ // compared to the workflow execution that follows.
194532
+ try {
194533
+ const fresh = await this.store.getAsync(schedule.id);
194534
+ if (!fresh || fresh.status !== 'active') {
194535
+ logger_1.logger.info(`[Scheduler] Schedule ${schedule.id} is no longer active (${fresh ? fresh.status : 'deleted'}), skipping execution`);
194536
+ // Clean up the in-memory job since the schedule is gone/inactive
194537
+ this.cancelSchedule(schedule.id);
194538
+ return;
194539
+ }
194540
+ }
194541
+ catch {
194542
+ // If we can't check the DB, log and proceed (don't block execution on DB errors)
194543
+ logger_1.logger.warn(`[Scheduler] Could not verify schedule ${schedule.id} freshness, proceeding with execution`);
194544
+ }
196101
194545
  const description = schedule.workflow || 'reminder';
196102
194546
  logger_1.logger.info(`[Scheduler] Executing schedule ${schedule.id}: ${description}`);
196103
194547
  const startTime = Date.now();
@@ -200234,7 +198678,7 @@ class StateMachineExecutionEngine {
200234
198678
  try {
200235
198679
  logger_1.logger.debug(`[PolicyEngine] Loading enterprise policy engine (engine=${configWithTagFilter.policy.engine})`);
200236
198680
  // @ts-ignore — enterprise/ may not exist in OSS builds (caught at runtime)
200237
- const { loadEnterprisePolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(87068)));
198681
+ const { loadEnterprisePolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(7065)));
200238
198682
  context.policyEngine = await loadEnterprisePolicyEngine(configWithTagFilter.policy);
200239
198683
  logger_1.logger.debug(`[PolicyEngine] Initialized: ${context.policyEngine?.constructor?.name || 'unknown'}`);
200240
198684
  }
@@ -201330,6 +199774,13 @@ async function initializeWorkspace(context) {
201330
199774
  process.env.VISOR_WORKSPACE_MAIN_PROJECT = info.mainProjectPath;
201331
199775
  process.env.VISOR_WORKSPACE_MAIN_PROJECT_NAME = info.mainProjectName;
201332
199776
  process.env.VISOR_ORIGINAL_WORKDIR = originalPath;
199777
+ // Prevent git from walking above the workspace base path.
199778
+ // Without this, git commands in workspace subdirectories can discover
199779
+ // a rogue .git in a parent directory (e.g. /tmp/.git) and leak
199780
+ // operations across all workspaces.
199781
+ const basePath = workspaceConfig?.base_path || process.env.VISOR_WORKSPACE_PATH || '/tmp/visor-workspaces';
199782
+ const existing = process.env.GIT_CEILING_DIRECTORIES;
199783
+ process.env.GIT_CEILING_DIRECTORIES = existing ? `${existing}:${basePath}` : basePath;
201333
199784
  }
201334
199785
  catch { }
201335
199786
  logger_1.logger.info(`[Workspace] Initialized workspace: ${info.workspacePath}`);
@@ -210498,7 +208949,7 @@ async function initTelemetry(opts = {}) {
210498
208949
  const path = __nccwpck_require__(16928);
210499
208950
  const outDir = opts.file?.dir ||
210500
208951
  process.env.VISOR_TRACE_DIR ||
210501
- path.join(process.cwd(), 'output', 'traces');
208952
+ __nccwpck_require__.ab + "traces";
210502
208953
  fs.mkdirSync(outDir, { recursive: true });
210503
208954
  const ts = new Date().toISOString().replace(/[:.]/g, '-');
210504
208955
  process.env.VISOR_FALLBACK_TRACE_FILE = path.join(outDir, `run-${ts}.ndjson`);
@@ -210703,7 +209154,7 @@ async function shutdownTelemetry() {
210703
209154
  if (process.env.VISOR_TRACE_REPORT === 'true') {
210704
209155
  const fs = __nccwpck_require__(79896);
210705
209156
  const path = __nccwpck_require__(16928);
210706
- const outDir = process.env.VISOR_TRACE_DIR || path.join(process.cwd(), 'output', 'traces');
209157
+ const outDir = process.env.VISOR_TRACE_DIR || __nccwpck_require__.ab + "traces";
210707
209158
  if (!fs.existsSync(outDir))
210708
209159
  fs.mkdirSync(outDir, { recursive: true });
210709
209160
  const ts = new Date().toISOString().replace(/[:.]/g, '-');
@@ -211202,7 +209653,7 @@ function __getOrCreateNdjsonPath() {
211202
209653
  fs.mkdirSync(dir, { recursive: true });
211203
209654
  return __ndjsonPath;
211204
209655
  }
211205
- const outDir = process.env.VISOR_TRACE_DIR || path.join(process.cwd(), 'output', 'traces');
209656
+ const outDir = process.env.VISOR_TRACE_DIR || __nccwpck_require__.ab + "traces";
211206
209657
  if (!fs.existsSync(outDir))
211207
209658
  fs.mkdirSync(outDir, { recursive: true });
211208
209659
  if (!__ndjsonPath) {
@@ -222335,6 +220786,7 @@ function buildProviderTemplateContext(prInfo, dependencyResults, memoryStore, ou
222335
220786
  Object.defineProperty(exports, "__esModule", ({ value: true }));
222336
220787
  exports.resolveTools = resolveTools;
222337
220788
  const workflow_tool_executor_1 = __nccwpck_require__(30236);
220789
+ const workflow_registry_1 = __nccwpck_require__(82824);
222338
220790
  const logger_1 = __nccwpck_require__(86999);
222339
220791
  /**
222340
220792
  * Resolve tool items to CustomToolDefinition instances.
@@ -222345,6 +220797,13 @@ const logger_1 = __nccwpck_require__(86999);
222345
220797
  */
222346
220798
  function resolveTools(toolItems, globalTools, logPrefix = '[ToolResolver]') {
222347
220799
  const tools = new Map();
220800
+ // Log registry state once for debugging workflow resolution failures
220801
+ const registry = workflow_registry_1.WorkflowRegistry.getInstance();
220802
+ const registeredWorkflows = registry.list().map(w => w.id);
220803
+ if (toolItems.some(item => typeof item !== 'string' && (0, workflow_tool_executor_1.isWorkflowToolReference)(item))) {
220804
+ logger_1.logger.info(`${logPrefix} Resolving ${toolItems.length} tool items. ` +
220805
+ `WorkflowRegistry has ${registeredWorkflows.length} workflows: [${registeredWorkflows.join(', ')}]`);
220806
+ }
222348
220807
  for (const item of toolItems) {
222349
220808
  // First, try to resolve as a workflow tool
222350
220809
  const workflowTool = (0, workflow_tool_executor_1.resolveWorkflowToolFromItem)(item);
@@ -222364,7 +220823,8 @@ function resolveTools(toolItems, globalTools, logPrefix = '[ToolResolver]') {
222364
220823
  logger_1.logger.warn(`${logPrefix} Tool '${item}' not found in global tools or workflow registry`);
222365
220824
  }
222366
220825
  else if ((0, workflow_tool_executor_1.isWorkflowToolReference)(item)) {
222367
- logger_1.logger.warn(`${logPrefix} Workflow '${item.workflow}' referenced but not found in registry`);
220826
+ logger_1.logger.warn(`${logPrefix} Workflow '${item.workflow}' referenced but not found in registry. ` +
220827
+ `Available: [${registeredWorkflows.join(', ')}]`);
222368
220828
  }
222369
220829
  }
222370
220830
  if (tools.size === 0 && toolItems.length > 0 && !globalTools) {
@@ -222741,6 +221201,10 @@ class WorkspaceManager {
222741
221201
  catch { }
222742
221202
  await this.createMainProjectWorktree(mainProjectPath);
222743
221203
  }
221204
+ else {
221205
+ // Worktree exists and is valid — update to latest upstream and clean
221206
+ await this.refreshWorktreeToUpstream(mainProjectPath);
221207
+ }
222744
221208
  }
222745
221209
  else {
222746
221210
  await this.createMainProjectWorktree(mainProjectPath);
@@ -222956,32 +221420,129 @@ class WorkspaceManager {
222956
221420
  return cleaned;
222957
221421
  }
222958
221422
  /**
222959
- * Create worktree for the main project
222960
- *
222961
- * visor-disable: architecture - Not using WorktreeManager here because:
222962
- * 1. WorktreeManager expects remote URLs and clones to bare repos first
222963
- * 2. This operates on the LOCAL repo we're already in (no cloning needed)
222964
- * 3. Adding a "local mode" to WorktreeManager would add complexity for minimal benefit
222965
- * The git commands here are simpler (just rev-parse + worktree add) vs WorktreeManager's
222966
- * full clone/bare-repo/fetch/worktree pipeline.
221423
+ * visor-disable: architecture - The helpers below (resolveUpstreamRef,
221424
+ * fetchAndResolveUpstream, resetAndCleanWorktree, refreshWorktreeToUpstream)
221425
+ * are NOT duplicates of WorktreeManager's fetchRef/getCommitShaForRef/cleanWorktree.
221426
+ * WorktreeManager operates on BARE repo caches cloned from remote URLs, while
221427
+ * WorkspaceManager operates on the LOCAL working repo the user already has checked out.
221428
+ * The git commands differ (e.g. `fetch origin --prune` vs `fetch origin <ref>:<ref>`)
221429
+ * and sharing code would require adding a "local mode" to WorktreeManager for no benefit.
222967
221430
  */
222968
- async createMainProjectWorktree(targetPath) {
222969
- logger_1.logger.debug(`Creating main project worktree: ${targetPath}`);
222970
- // Get current HEAD
222971
- const headResult = await command_executor_1.commandExecutor.execute(`git -C ${shellEscape(this.originalPath)} rev-parse HEAD`, {
222972
- timeout: 10000,
222973
- });
221431
+ /**
221432
+ * Resolve the upstream default branch ref.
221433
+ * Tries origin/HEAD (symbolic), then origin/main, then origin/master.
221434
+ * Falls back to local HEAD if no remote is configured.
221435
+ */
221436
+ async resolveUpstreamRef() {
221437
+ const esc = shellEscape(this.originalPath);
221438
+ // First, try to resolve origin/HEAD (follows the remote's default branch)
221439
+ const symbolicResult = await command_executor_1.commandExecutor.execute(`git -C ${esc} symbolic-ref refs/remotes/origin/HEAD 2>/dev/null`, { timeout: 10000 });
221440
+ if (symbolicResult.exitCode === 0 && symbolicResult.stdout.trim()) {
221441
+ // Returns something like "refs/remotes/origin/main"
221442
+ const ref = symbolicResult.stdout.trim().replace('refs/remotes/', '');
221443
+ logger_1.logger.debug(`[Workspace] Resolved upstream default branch via origin/HEAD: ${ref}`);
221444
+ return ref;
221445
+ }
221446
+ // Try origin/main
221447
+ const mainResult = await command_executor_1.commandExecutor.execute(`git -C ${esc} rev-parse --verify origin/main 2>/dev/null`, { timeout: 10000 });
221448
+ if (mainResult.exitCode === 0) {
221449
+ logger_1.logger.debug(`[Workspace] Using origin/main as upstream ref`);
221450
+ return 'origin/main';
221451
+ }
221452
+ // Try origin/master
221453
+ const masterResult = await command_executor_1.commandExecutor.execute(`git -C ${esc} rev-parse --verify origin/master 2>/dev/null`, { timeout: 10000 });
221454
+ if (masterResult.exitCode === 0) {
221455
+ logger_1.logger.debug(`[Workspace] Using origin/master as upstream ref`);
221456
+ return 'origin/master';
221457
+ }
221458
+ // Fallback: no remote configured, use local HEAD
221459
+ logger_1.logger.warn(`[Workspace] No upstream remote found, falling back to local HEAD`);
221460
+ return 'HEAD';
221461
+ }
221462
+ /**
221463
+ * Fetch latest from origin, resolve the upstream default branch, and return
221464
+ * both the ref name and the resolved commit SHA.
221465
+ */
221466
+ async fetchAndResolveUpstream() {
221467
+ // Fetch latest from origin
221468
+ logger_1.logger.debug(`[Workspace] Fetching latest from origin`);
221469
+ const fetchResult = await command_executor_1.commandExecutor.execute(`git -C ${shellEscape(this.originalPath)} fetch origin --prune 2>&1`, { timeout: 120000 });
221470
+ if (fetchResult.exitCode !== 0) {
221471
+ logger_1.logger.warn(`[Workspace] fetch origin failed (will use cached refs): ${fetchResult.stderr}`);
221472
+ }
221473
+ // Resolve the upstream ref
221474
+ const upstreamRef = await this.resolveUpstreamRef();
221475
+ // Get the commit SHA for the upstream ref
221476
+ const shaResult = await command_executor_1.commandExecutor.execute(`git -C ${shellEscape(this.originalPath)} rev-parse ${shellEscape(upstreamRef)}`, { timeout: 10000 });
221477
+ if (shaResult.exitCode === 0) {
221478
+ return { upstreamRef, targetSha: shaResult.stdout.trim() };
221479
+ }
221480
+ // Upstream ref unresolvable — fall back to local HEAD
221481
+ logger_1.logger.warn(`[Workspace] Could not resolve ${upstreamRef} (${shaResult.stderr.trim()}), falling back to HEAD`);
221482
+ const headResult = await command_executor_1.commandExecutor.execute(`git -C ${shellEscape(this.originalPath)} rev-parse HEAD`, { timeout: 10000 });
222974
221483
  if (headResult.exitCode !== 0) {
222975
- throw new Error(`Failed to get HEAD: ${headResult.stderr}`);
221484
+ throw new Error(`Repository has no commits — cannot create worktree: ${headResult.stderr}`);
221485
+ }
221486
+ return { upstreamRef: 'HEAD', targetSha: headResult.stdout.trim() };
221487
+ }
221488
+ /**
221489
+ * Reset a worktree to a specific commit and clean all modifications.
221490
+ */
221491
+ async resetAndCleanWorktree(worktreePath, targetSha) {
221492
+ const escapedPath = shellEscape(worktreePath);
221493
+ const escapedSha = shellEscape(targetSha);
221494
+ const resetResult = await command_executor_1.commandExecutor.execute(`git -C ${escapedPath} reset --hard ${escapedSha}`, { timeout: 10000 });
221495
+ if (resetResult.exitCode !== 0) {
221496
+ logger_1.logger.warn(`[Workspace] reset --hard failed: ${resetResult.stderr}`);
221497
+ }
221498
+ const cleanResult = await command_executor_1.commandExecutor.execute(`git -C ${escapedPath} clean -fdx`, {
221499
+ timeout: 30000,
221500
+ });
221501
+ if (cleanResult.exitCode !== 0) {
221502
+ logger_1.logger.warn(`[Workspace] clean -fdx failed: ${cleanResult.stderr}`);
221503
+ }
221504
+ }
221505
+ /**
221506
+ * Refresh an existing worktree to the latest upstream default branch
221507
+ * and ensure it has no modified or untracked files.
221508
+ */
221509
+ async refreshWorktreeToUpstream(worktreePath) {
221510
+ logger_1.logger.info(`[Workspace] Refreshing worktree to latest upstream: ${worktreePath}`);
221511
+ try {
221512
+ const { upstreamRef, targetSha } = await this.fetchAndResolveUpstream();
221513
+ // Point worktree to the upstream commit
221514
+ const checkoutResult = await command_executor_1.commandExecutor.execute(`git -C ${shellEscape(worktreePath)} checkout --detach ${shellEscape(targetSha)}`, { timeout: 30000 });
221515
+ if (checkoutResult.exitCode !== 0) {
221516
+ logger_1.logger.warn(`[Workspace] checkout --detach failed (worktree stays at current commit): ${checkoutResult.stderr}`);
221517
+ // Still clean even if checkout failed — the worktree is valid, just at old commit
221518
+ await this.resetAndCleanWorktree(worktreePath, 'HEAD');
221519
+ return;
221520
+ }
221521
+ // Reset and clean
221522
+ await this.resetAndCleanWorktree(worktreePath, targetSha);
221523
+ logger_1.logger.info(`[Workspace] Worktree updated to ${upstreamRef} (${targetSha.slice(0, 8)})`);
221524
+ }
221525
+ catch (error) {
221526
+ // Best-effort: a stale worktree is better than failing initialization entirely
221527
+ logger_1.logger.warn(`[Workspace] Failed to refresh worktree (continuing with stale state): ${error}`);
222976
221528
  }
222977
- const headRef = headResult.stdout.trim();
222978
- // Create worktree using detached HEAD to avoid branch conflicts
222979
- const createCmd = `git -C ${shellEscape(this.originalPath)} worktree add --detach ${shellEscape(targetPath)} ${shellEscape(headRef)}`;
221529
+ }
221530
+ /**
221531
+ * Create worktree for the main project.
221532
+ * See visor-disable comment above resolveUpstreamRef for why this doesn't use WorktreeManager.
221533
+ */
221534
+ async createMainProjectWorktree(targetPath) {
221535
+ logger_1.logger.debug(`Creating main project worktree: ${targetPath}`);
221536
+ const { upstreamRef, targetSha } = await this.fetchAndResolveUpstream();
221537
+ // Create worktree using detached HEAD at the upstream commit
221538
+ const createCmd = `git -C ${shellEscape(this.originalPath)} worktree add --detach ${shellEscape(targetPath)} ${shellEscape(targetSha)}`;
222980
221539
  const result = await command_executor_1.commandExecutor.execute(createCmd, { timeout: 60000 });
222981
221540
  if (result.exitCode !== 0) {
222982
221541
  throw new Error(`Failed to create main project worktree: ${result.stderr}`);
222983
221542
  }
222984
- logger_1.logger.debug(`Created main project worktree at ${targetPath}`);
221543
+ // Clean (shouldn't be needed in a fresh worktree, but defense in depth)
221544
+ await this.resetAndCleanWorktree(targetPath, targetSha);
221545
+ logger_1.logger.info(`Created main project worktree at ${targetPath} (${upstreamRef} -> ${targetSha.slice(0, 8)})`);
222985
221546
  }
222986
221547
  /**
222987
221548
  * Remove main project worktree
@@ -223663,27 +222224,52 @@ class WorktreeManager {
223663
222224
  fs.rmSync(worktree_path, { recursive: true, force: true });
223664
222225
  }
223665
222226
  }
222227
+ // Clean up sibling metadata file
222228
+ const metadataPath = this.getMetadataPath(worktree_path);
222229
+ try {
222230
+ if (fs.existsSync(metadataPath)) {
222231
+ fs.unlinkSync(metadataPath);
222232
+ }
222233
+ }
222234
+ catch {
222235
+ // best-effort cleanup
222236
+ }
223666
222237
  // Remove from active list
223667
222238
  this.activeWorktrees.delete(worktreeId);
223668
222239
  logger_1.logger.info(`Successfully removed worktree: ${worktreeId}`);
223669
222240
  }
222241
+ /**
222242
+ * Get the metadata file path for a worktree.
222243
+ * Stored as a sibling file OUTSIDE the worktree to avoid being committed
222244
+ * when agents run `git add .` inside the checked-out repo.
222245
+ */
222246
+ getMetadataPath(worktreePath) {
222247
+ return worktreePath.replace(/\/?$/, '') + '.metadata.json';
222248
+ }
223670
222249
  /**
223671
222250
  * Save worktree metadata
223672
222251
  */
223673
222252
  async saveMetadata(worktreePath, metadata) {
223674
- const metadataPath = path.join(worktreePath, '.visor-metadata.json');
222253
+ const metadataPath = this.getMetadataPath(worktreePath);
223675
222254
  fs.writeFileSync(metadataPath, JSON.stringify(metadata, null, 2), 'utf8');
223676
222255
  }
223677
222256
  /**
223678
222257
  * Load worktree metadata
223679
222258
  */
223680
222259
  async loadMetadata(worktreePath) {
223681
- const metadataPath = path.join(worktreePath, '.visor-metadata.json');
223682
- if (!fs.existsSync(metadataPath)) {
222260
+ const metadataPath = this.getMetadataPath(worktreePath);
222261
+ // Also check legacy location (inside worktree) for backwards compatibility
222262
+ const legacyPath = path.join(worktreePath, '.visor-metadata.json');
222263
+ const pathToRead = fs.existsSync(metadataPath)
222264
+ ? metadataPath
222265
+ : fs.existsSync(legacyPath)
222266
+ ? legacyPath
222267
+ : null;
222268
+ if (!pathToRead) {
223683
222269
  return null;
223684
222270
  }
223685
222271
  try {
223686
- const content = fs.readFileSync(metadataPath, 'utf8');
222272
+ const content = fs.readFileSync(pathToRead, 'utf8');
223687
222273
  return JSON.parse(content);
223688
222274
  }
223689
222275
  catch (error) {
@@ -224755,6 +223341,22 @@ class WorkflowRegistry {
224755
223341
  exports.WorkflowRegistry = WorkflowRegistry;
224756
223342
 
224757
223343
 
223344
+ /***/ }),
223345
+
223346
+ /***/ 7065:
223347
+ /***/ ((module) => {
223348
+
223349
+ module.exports = eval("require")("./enterprise/loader");
223350
+
223351
+
223352
+ /***/ }),
223353
+
223354
+ /***/ 71370:
223355
+ /***/ ((module) => {
223356
+
223357
+ module.exports = eval("require")("./enterprise/policy/policy-input-builder");
223358
+
223359
+
224758
223360
  /***/ }),
224759
223361
 
224760
223362
  /***/ 18327:
@@ -266426,7 +265028,7 @@ var require_package2 = __commonJS({
266426
265028
  module2.exports = {
266427
265029
  name: "@aws-sdk/client-bedrock-runtime",
266428
265030
  description: "AWS SDK for JavaScript Bedrock Runtime Client for Node.js, Browser and React Native",
266429
- version: "3.999.0",
265031
+ version: "3.1000.0",
266430
265032
  scripts: {
266431
265033
  build: "concurrently 'yarn:build:types' 'yarn:build:es' && yarn build:cjs",
266432
265034
  "build:cjs": "node ../../scripts/compilation/inline client-bedrock-runtime",
@@ -266437,7 +265039,11 @@ var require_package2 = __commonJS({
266437
265039
  clean: "premove dist-cjs dist-es dist-types tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo",
266438
265040
  "extract:docs": "api-extractor run --local",
266439
265041
  "generate:client": "node ../../scripts/generate-clients/single-service --solo bedrock-runtime",
266440
- "test:index": "tsc --noEmit ./test/index-types.ts && node ./test/index-objects.spec.mjs"
265042
+ test: "yarn g:vitest run --passWithNoTests",
265043
+ "test:index": "tsc --noEmit ./test/index-types.ts && node ./test/index-objects.spec.mjs",
265044
+ "test:integration": "yarn g:vitest run --passWithNoTests -c vitest.config.integ.mts",
265045
+ "test:integration:watch": "yarn g:vitest run --passWithNoTests -c vitest.config.integ.mts",
265046
+ "test:watch": "yarn g:vitest watch --passWithNoTests"
266441
265047
  },
266442
265048
  main: "./dist-cjs/index.js",
266443
265049
  types: "./dist-types/index.d.ts",
@@ -266456,7 +265062,7 @@ var require_package2 = __commonJS({
266456
265062
  "@aws-sdk/middleware-user-agent": "^3.972.15",
266457
265063
  "@aws-sdk/middleware-websocket": "^3.972.10",
266458
265064
  "@aws-sdk/region-config-resolver": "^3.972.6",
266459
- "@aws-sdk/token-providers": "3.999.0",
265065
+ "@aws-sdk/token-providers": "3.1000.0",
266460
265066
  "@aws-sdk/types": "^3.973.4",
266461
265067
  "@aws-sdk/util-endpoints": "^3.996.3",
266462
265068
  "@aws-sdk/util-user-agent-browser": "^3.972.6",
@@ -266493,12 +265099,14 @@ var require_package2 = __commonJS({
266493
265099
  tslib: "^2.6.2"
266494
265100
  },
266495
265101
  devDependencies: {
265102
+ "@smithy/snapshot-testing": "^1.0.7",
266496
265103
  "@tsconfig/node20": "20.1.8",
266497
265104
  "@types/node": "^20.14.8",
266498
265105
  concurrently: "7.0.0",
266499
265106
  "downlevel-dts": "0.10.1",
266500
265107
  premove: "4.0.0",
266501
- typescript: "~5.8.3"
265108
+ typescript: "~5.8.3",
265109
+ vitest: "^4.0.17"
266502
265110
  },
266503
265111
  engines: {
266504
265112
  node: ">=20.0.0"
@@ -268500,9 +267108,9 @@ var init_sso_oidc = __esm({
268500
267108
  }
268501
267109
  });
268502
267110
 
268503
- // node_modules/@aws-sdk/token-providers/dist-cjs/index.js
267111
+ // node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-cjs/index.js
268504
267112
  var require_dist_cjs56 = __commonJS({
268505
- "node_modules/@aws-sdk/token-providers/dist-cjs/index.js"(exports2) {
267113
+ "node_modules/@aws-sdk/credential-provider-sso/node_modules/@aws-sdk/token-providers/dist-cjs/index.js"(exports2) {
268506
267114
  "use strict";
268507
267115
  var client = (init_client(), __toCommonJS(client_exports));
268508
267116
  var httpAuthSchemes = (init_httpAuthSchemes2(), __toCommonJS(httpAuthSchemes_exports));
@@ -272335,8 +270943,155 @@ var require_dist_cjs63 = __commonJS({
272335
270943
  }
272336
270944
  });
272337
270945
 
272338
- // node_modules/@smithy/eventstream-serde-node/dist-cjs/index.js
270946
+ // node_modules/@aws-sdk/token-providers/dist-cjs/index.js
272339
270947
  var require_dist_cjs64 = __commonJS({
270948
+ "node_modules/@aws-sdk/token-providers/dist-cjs/index.js"(exports2) {
270949
+ "use strict";
270950
+ var client = (init_client(), __toCommonJS(client_exports));
270951
+ var httpAuthSchemes = (init_httpAuthSchemes2(), __toCommonJS(httpAuthSchemes_exports));
270952
+ var propertyProvider = require_dist_cjs24();
270953
+ var sharedIniFileLoader = require_dist_cjs42();
270954
+ var node_fs = __nccwpck_require__(73024);
270955
+ var fromEnvSigningName = ({ logger: logger2, signingName } = {}) => async () => {
270956
+ logger2?.debug?.("@aws-sdk/token-providers - fromEnvSigningName");
270957
+ if (!signingName) {
270958
+ throw new propertyProvider.TokenProviderError("Please pass 'signingName' to compute environment variable key", { logger: logger2 });
270959
+ }
270960
+ const bearerTokenKey = httpAuthSchemes.getBearerTokenEnvKey(signingName);
270961
+ if (!(bearerTokenKey in process.env)) {
270962
+ throw new propertyProvider.TokenProviderError(`Token not present in '${bearerTokenKey}' environment variable`, { logger: logger2 });
270963
+ }
270964
+ const token = { token: process.env[bearerTokenKey] };
270965
+ client.setTokenFeature(token, "BEARER_SERVICE_ENV_VARS", "3");
270966
+ return token;
270967
+ };
270968
+ var EXPIRE_WINDOW_MS = 5 * 60 * 1e3;
270969
+ var REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`;
270970
+ var getSsoOidcClient = async (ssoRegion, init = {}, callerClientConfig) => {
270971
+ const { SSOOIDCClient: SSOOIDCClient2 } = await Promise.resolve().then(() => (init_sso_oidc(), sso_oidc_exports));
270972
+ const coalesce = (prop) => init.clientConfig?.[prop] ?? init.parentClientConfig?.[prop] ?? callerClientConfig?.[prop];
270973
+ const ssoOidcClient = new SSOOIDCClient2(Object.assign({}, init.clientConfig ?? {}, {
270974
+ region: ssoRegion ?? init.clientConfig?.region,
270975
+ logger: coalesce("logger"),
270976
+ userAgentAppId: coalesce("userAgentAppId")
270977
+ }));
270978
+ return ssoOidcClient;
270979
+ };
270980
+ var getNewSsoOidcToken = async (ssoToken, ssoRegion, init = {}, callerClientConfig) => {
270981
+ const { CreateTokenCommand: CreateTokenCommand2 } = await Promise.resolve().then(() => (init_sso_oidc(), sso_oidc_exports));
270982
+ const ssoOidcClient = await getSsoOidcClient(ssoRegion, init, callerClientConfig);
270983
+ return ssoOidcClient.send(new CreateTokenCommand2({
270984
+ clientId: ssoToken.clientId,
270985
+ clientSecret: ssoToken.clientSecret,
270986
+ refreshToken: ssoToken.refreshToken,
270987
+ grantType: "refresh_token"
270988
+ }));
270989
+ };
270990
+ var validateTokenExpiry = (token) => {
270991
+ if (token.expiration && token.expiration.getTime() < Date.now()) {
270992
+ throw new propertyProvider.TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false);
270993
+ }
270994
+ };
270995
+ var validateTokenKey = (key, value, forRefresh = false) => {
270996
+ if (typeof value === "undefined") {
270997
+ throw new propertyProvider.TokenProviderError(`Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`, false);
270998
+ }
270999
+ };
271000
+ var { writeFile: writeFile2 } = node_fs.promises;
271001
+ var writeSSOTokenToFile = (id, ssoToken) => {
271002
+ const tokenFilepath = sharedIniFileLoader.getSSOTokenFilepath(id);
271003
+ const tokenString = JSON.stringify(ssoToken, null, 2);
271004
+ return writeFile2(tokenFilepath, tokenString);
271005
+ };
271006
+ var lastRefreshAttemptTime = /* @__PURE__ */ new Date(0);
271007
+ var fromSso = (init = {}) => async ({ callerClientConfig } = {}) => {
271008
+ init.logger?.debug("@aws-sdk/token-providers - fromSso");
271009
+ const profiles = await sharedIniFileLoader.parseKnownFiles(init);
271010
+ const profileName = sharedIniFileLoader.getProfileName({
271011
+ profile: init.profile ?? callerClientConfig?.profile
271012
+ });
271013
+ const profile = profiles[profileName];
271014
+ if (!profile) {
271015
+ throw new propertyProvider.TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false);
271016
+ } else if (!profile["sso_session"]) {
271017
+ throw new propertyProvider.TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`);
271018
+ }
271019
+ const ssoSessionName = profile["sso_session"];
271020
+ const ssoSessions = await sharedIniFileLoader.loadSsoSessionData(init);
271021
+ const ssoSession = ssoSessions[ssoSessionName];
271022
+ if (!ssoSession) {
271023
+ throw new propertyProvider.TokenProviderError(`Sso session '${ssoSessionName}' could not be found in shared credentials file.`, false);
271024
+ }
271025
+ for (const ssoSessionRequiredKey of ["sso_start_url", "sso_region"]) {
271026
+ if (!ssoSession[ssoSessionRequiredKey]) {
271027
+ throw new propertyProvider.TokenProviderError(`Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`, false);
271028
+ }
271029
+ }
271030
+ ssoSession["sso_start_url"];
271031
+ const ssoRegion = ssoSession["sso_region"];
271032
+ let ssoToken;
271033
+ try {
271034
+ ssoToken = await sharedIniFileLoader.getSSOTokenFromFile(ssoSessionName);
271035
+ } catch (e5) {
271036
+ throw new propertyProvider.TokenProviderError(`The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, false);
271037
+ }
271038
+ validateTokenKey("accessToken", ssoToken.accessToken);
271039
+ validateTokenKey("expiresAt", ssoToken.expiresAt);
271040
+ const { accessToken, expiresAt } = ssoToken;
271041
+ const existingToken = { token: accessToken, expiration: new Date(expiresAt) };
271042
+ if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) {
271043
+ return existingToken;
271044
+ }
271045
+ if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1e3) {
271046
+ validateTokenExpiry(existingToken);
271047
+ return existingToken;
271048
+ }
271049
+ validateTokenKey("clientId", ssoToken.clientId, true);
271050
+ validateTokenKey("clientSecret", ssoToken.clientSecret, true);
271051
+ validateTokenKey("refreshToken", ssoToken.refreshToken, true);
271052
+ try {
271053
+ lastRefreshAttemptTime.setTime(Date.now());
271054
+ const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init, callerClientConfig);
271055
+ validateTokenKey("accessToken", newSsoOidcToken.accessToken);
271056
+ validateTokenKey("expiresIn", newSsoOidcToken.expiresIn);
271057
+ const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1e3);
271058
+ try {
271059
+ await writeSSOTokenToFile(ssoSessionName, {
271060
+ ...ssoToken,
271061
+ accessToken: newSsoOidcToken.accessToken,
271062
+ expiresAt: newTokenExpiration.toISOString(),
271063
+ refreshToken: newSsoOidcToken.refreshToken
271064
+ });
271065
+ } catch (error2) {
271066
+ }
271067
+ return {
271068
+ token: newSsoOidcToken.accessToken,
271069
+ expiration: newTokenExpiration
271070
+ };
271071
+ } catch (error2) {
271072
+ validateTokenExpiry(existingToken);
271073
+ return existingToken;
271074
+ }
271075
+ };
271076
+ var fromStatic = ({ token, logger: logger2 }) => async () => {
271077
+ logger2?.debug("@aws-sdk/token-providers - fromStatic");
271078
+ if (!token || !token.token) {
271079
+ throw new propertyProvider.TokenProviderError(`Please pass a valid token to fromStatic`, false);
271080
+ }
271081
+ return token;
271082
+ };
271083
+ var nodeProvider = (init = {}) => propertyProvider.memoize(propertyProvider.chain(fromSso(init), async () => {
271084
+ throw new propertyProvider.TokenProviderError("Could not load token from any providers", false);
271085
+ }), (token) => token.expiration !== void 0 && token.expiration.getTime() - Date.now() < 3e5, (token) => token.expiration !== void 0);
271086
+ exports2.fromEnvSigningName = fromEnvSigningName;
271087
+ exports2.fromSso = fromSso;
271088
+ exports2.fromStatic = fromStatic;
271089
+ exports2.nodeProvider = nodeProvider;
271090
+ }
271091
+ });
271092
+
271093
+ // node_modules/@smithy/eventstream-serde-node/dist-cjs/index.js
271094
+ var require_dist_cjs65 = __commonJS({
272340
271095
  "node_modules/@smithy/eventstream-serde-node/dist-cjs/index.js"(exports2) {
272341
271096
  "use strict";
272342
271097
  var eventstreamSerdeUniversal = require_dist_cjs35();
@@ -275018,11 +273773,11 @@ var require_runtimeConfig = __commonJS({
275018
273773
  var core_1 = (init_dist_es2(), __toCommonJS(dist_es_exports2));
275019
273774
  var credential_provider_node_1 = require_dist_cjs62();
275020
273775
  var eventstream_handler_node_1 = require_dist_cjs63();
275021
- var token_providers_1 = require_dist_cjs56();
273776
+ var token_providers_1 = require_dist_cjs64();
275022
273777
  var util_user_agent_node_1 = require_dist_cjs51();
275023
273778
  var config_resolver_1 = require_dist_cjs39();
275024
273779
  var core_2 = (init_dist_es(), __toCommonJS(dist_es_exports));
275025
- var eventstream_serde_node_1 = require_dist_cjs64();
273780
+ var eventstream_serde_node_1 = require_dist_cjs65();
275026
273781
  var hash_node_1 = require_dist_cjs52();
275027
273782
  var middleware_retry_1 = require_dist_cjs47();
275028
273783
  var node_config_provider_1 = require_dist_cjs43();
@@ -275094,7 +273849,7 @@ var require_runtimeConfig = __commonJS({
275094
273849
  });
275095
273850
 
275096
273851
  // node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/index.js
275097
- var require_dist_cjs65 = __commonJS({
273852
+ var require_dist_cjs66 = __commonJS({
275098
273853
  "node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/index.js"(exports2) {
275099
273854
  "use strict";
275100
273855
  var middlewareEventstream = require_dist_cjs3();
@@ -275939,13 +274694,13 @@ var import_client_bedrock_runtime, import_client_bedrock_runtime2, import_client
275939
274694
  var init_dist3 = __esm({
275940
274695
  "node_modules/@ai-sdk/amazon-bedrock/dist/index.mjs"() {
275941
274696
  init_dist2();
275942
- import_client_bedrock_runtime = __toESM(require_dist_cjs65(), 1);
274697
+ import_client_bedrock_runtime = __toESM(require_dist_cjs66(), 1);
275943
274698
  init_dist();
275944
- import_client_bedrock_runtime2 = __toESM(require_dist_cjs65(), 1);
274699
+ import_client_bedrock_runtime2 = __toESM(require_dist_cjs66(), 1);
275945
274700
  init_dist();
275946
274701
  init_dist();
275947
274702
  init_dist2();
275948
- import_client_bedrock_runtime3 = __toESM(require_dist_cjs65(), 1);
274703
+ import_client_bedrock_runtime3 = __toESM(require_dist_cjs66(), 1);
275949
274704
  generateFileId = createIdGenerator({ prefix: "file", size: 16 });
275950
274705
  BedrockChatLanguageModel = class {
275951
274706
  constructor(modelId, settings, config) {
@@ -299113,7 +297868,6 @@ var init_reg_exp = __esm({
299113
297868
  // node_modules/chevrotain/lib/src/scan/lexer.js
299114
297869
  function analyzeTokenTypes(tokenTypes, options) {
299115
297870
  options = defaults_default(options, {
299116
- useSticky: SUPPORT_STICKY,
299117
297871
  debug: false,
299118
297872
  safeMode: false,
299119
297873
  positionTracking: "full",
@@ -299162,7 +297916,7 @@ function analyzeTokenTypes(tokenTypes, options) {
299162
297916
  ], regExpSource[1])) {
299163
297917
  return regExpSource[1];
299164
297918
  } else {
299165
- return options.useSticky ? addStickyFlag(currPattern) : addStartOfInput(currPattern);
297919
+ return addStickyFlag(currPattern);
299166
297920
  }
299167
297921
  } else if (isFunction_default(currPattern)) {
299168
297922
  hasCustom = true;
@@ -299176,7 +297930,7 @@ function analyzeTokenTypes(tokenTypes, options) {
299176
297930
  } else {
299177
297931
  const escapedRegExpString = currPattern.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
299178
297932
  const wrappedRegExp = new RegExp(escapedRegExpString);
299179
- return options.useSticky ? addStickyFlag(wrappedRegExp) : addStartOfInput(wrappedRegExp);
297933
+ return addStickyFlag(wrappedRegExp);
299180
297934
  }
299181
297935
  } else {
299182
297936
  throw Error("non exhaustive match");
@@ -299580,10 +298334,6 @@ function noMetaChar(regExp) {
299580
298334
  function usesLookAheadOrBehind(regExp) {
299581
298335
  return /(\(\?=)|(\(\?!)|(\(\?<=)|(\(\?<!)/.test(regExp.source);
299582
298336
  }
299583
- function addStartOfInput(pattern) {
299584
- const flags = pattern.ignoreCase ? "i" : "";
299585
- return new RegExp(`^(?:${pattern.source})`, flags);
299586
- }
299587
298337
  function addStickyFlag(pattern) {
299588
298338
  const flags = pattern.ignoreCase ? "iy" : "y";
299589
298339
  return new RegExp(`${pattern.source}`, flags);
@@ -299772,7 +298522,7 @@ function initCharCodeToOptimizedIndexMap() {
299772
298522
  }
299773
298523
  }
299774
298524
  }
299775
- var PATTERN, DEFAULT_MODE, MODES, SUPPORT_STICKY, end_of_input, start_of_input, LineTerminatorOptimizedTester, minOptimizationVal, charCodeToOptimizedIdxMap;
298525
+ var PATTERN, DEFAULT_MODE, MODES, end_of_input, start_of_input, LineTerminatorOptimizedTester, minOptimizationVal, charCodeToOptimizedIdxMap;
299776
298526
  var init_lexer = __esm({
299777
298527
  "node_modules/chevrotain/lib/src/scan/lexer.js"() {
299778
298528
  init_api3();
@@ -299784,7 +298534,6 @@ var init_lexer = __esm({
299784
298534
  PATTERN = "PATTERN";
299785
298535
  DEFAULT_MODE = "defaultMode";
299786
298536
  MODES = "modes";
299787
- SUPPORT_STICKY = typeof new RegExp("(?:)").sticky === "boolean";
299788
298537
  end_of_input = /[^\\][$]/;
299789
298538
  start_of_input = /[^\\[][\^]|^\^/;
299790
298539
  LineTerminatorOptimizedTester = {
@@ -300100,13 +298849,6 @@ var init_lexer_public = __esm({
300100
298849
  PRINT_WARNING(warningDescriptor.message);
300101
298850
  });
300102
298851
  this.TRACE_INIT("Choosing sub-methods implementations", () => {
300103
- if (SUPPORT_STICKY) {
300104
- this.chopInput = identity_default;
300105
- this.match = this.matchWithTest;
300106
- } else {
300107
- this.updateLastIndex = noop_default;
300108
- this.match = this.matchWithExec;
300109
- }
300110
298852
  if (hasOnlySingleMode) {
300111
298853
  this.handleModes = noop_default;
300112
298854
  }
@@ -300169,7 +298911,7 @@ var init_lexer_public = __esm({
300169
298911
  // this method also used quite a bit of `!` none null assertions because it is too optimized
300170
298912
  // for `tsc` to always understand it is "safe"
300171
298913
  tokenizeInternal(text, initialMode) {
300172
- let i5, j5, k5, matchAltImage, longerAlt, matchedImage, payload2, altPayload, imageLength, group, tokType, newToken, errLength, droppedChar, msg, match2;
298914
+ let i5, j5, k5, matchAltImage, longerAlt, matchedImage, payload2, altPayload, imageLength, group, tokType, newToken, errLength, msg, match2;
300173
298915
  const orgText = text;
300174
298916
  const orgLength = orgText.length;
300175
298917
  let offset2 = 0;
@@ -300188,19 +298930,7 @@ var init_lexer_public = __esm({
300188
298930
  const modeStack = [];
300189
298931
  const emptyArray = [];
300190
298932
  Object.freeze(emptyArray);
300191
- let getPossiblePatterns;
300192
- function getPossiblePatternsSlow() {
300193
- return patternIdxToConfig;
300194
- }
300195
- function getPossiblePatternsOptimized(charCode) {
300196
- const optimizedCharIdx = charCodeToOptimizedIndex(charCode);
300197
- const possiblePatterns = currCharCodeToPatternIdxToConfig[optimizedCharIdx];
300198
- if (possiblePatterns === void 0) {
300199
- return emptyArray;
300200
- } else {
300201
- return possiblePatterns;
300202
- }
300203
- }
298933
+ let isOptimizedMode = false;
300204
298934
  const pop_mode = (popToken) => {
300205
298935
  if (modeStack.length === 1 && // if we have both a POP_MODE and a PUSH_MODE this is in-fact a "transition"
300206
298936
  // So no error should occur.
@@ -300221,9 +298951,9 @@ var init_lexer_public = __esm({
300221
298951
  currModePatternsLength = patternIdxToConfig.length;
300222
298952
  const modeCanBeOptimized = this.canModeBeOptimized[newMode] && this.config.safeMode === false;
300223
298953
  if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) {
300224
- getPossiblePatterns = getPossiblePatternsOptimized;
298954
+ isOptimizedMode = true;
300225
298955
  } else {
300226
- getPossiblePatterns = getPossiblePatternsSlow;
298956
+ isOptimizedMode = false;
300227
298957
  }
300228
298958
  }
300229
298959
  };
@@ -300235,9 +298965,9 @@ var init_lexer_public = __esm({
300235
298965
  currModePatternsLength = patternIdxToConfig.length;
300236
298966
  const modeCanBeOptimized = this.canModeBeOptimized[newMode] && this.config.safeMode === false;
300237
298967
  if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) {
300238
- getPossiblePatterns = getPossiblePatternsOptimized;
298968
+ isOptimizedMode = true;
300239
298969
  } else {
300240
- getPossiblePatterns = getPossiblePatternsSlow;
298970
+ isOptimizedMode = false;
300241
298971
  }
300242
298972
  }
300243
298973
  push_mode.call(this, initialMode);
@@ -300245,8 +298975,16 @@ var init_lexer_public = __esm({
300245
298975
  const recoveryEnabled = this.config.recoveryEnabled;
300246
298976
  while (offset2 < orgLength) {
300247
298977
  matchedImage = null;
298978
+ imageLength = -1;
300248
298979
  const nextCharCode = orgText.charCodeAt(offset2);
300249
- const chosenPatternIdxToConfig = getPossiblePatterns(nextCharCode);
298980
+ let chosenPatternIdxToConfig;
298981
+ if (isOptimizedMode) {
298982
+ const optimizedCharIdx = charCodeToOptimizedIndex(nextCharCode);
298983
+ const possiblePatterns = currCharCodeToPatternIdxToConfig[optimizedCharIdx];
298984
+ chosenPatternIdxToConfig = possiblePatterns !== void 0 ? possiblePatterns : emptyArray;
298985
+ } else {
298986
+ chosenPatternIdxToConfig = patternIdxToConfig;
298987
+ }
300250
298988
  const chosenPatternsLength = chosenPatternIdxToConfig.length;
300251
298989
  for (i5 = 0; i5 < chosenPatternsLength; i5++) {
300252
298990
  currConfig = chosenPatternIdxToConfig[i5];
@@ -300255,12 +298993,14 @@ var init_lexer_public = __esm({
300255
298993
  const singleCharCode = currConfig.short;
300256
298994
  if (singleCharCode !== false) {
300257
298995
  if (nextCharCode === singleCharCode) {
298996
+ imageLength = 1;
300258
298997
  matchedImage = currPattern;
300259
298998
  }
300260
298999
  } else if (currConfig.isCustom === true) {
300261
299000
  match2 = currPattern.exec(orgText, offset2, matchedTokens, groups);
300262
299001
  if (match2 !== null) {
300263
299002
  matchedImage = match2[0];
299003
+ imageLength = matchedImage.length;
300264
299004
  if (match2.payload !== void 0) {
300265
299005
  payload2 = match2.payload;
300266
299006
  }
@@ -300268,12 +299008,13 @@ var init_lexer_public = __esm({
300268
299008
  matchedImage = null;
300269
299009
  }
300270
299010
  } else {
300271
- this.updateLastIndex(currPattern, offset2);
300272
- matchedImage = this.match(currPattern, text, offset2);
299011
+ currPattern.lastIndex = offset2;
299012
+ imageLength = this.matchLength(currPattern, text, offset2);
300273
299013
  }
300274
- if (matchedImage !== null) {
299014
+ if (imageLength !== -1) {
300275
299015
  longerAlt = currConfig.longerAlt;
300276
299016
  if (longerAlt !== void 0) {
299017
+ matchedImage = text.substring(offset2, offset2 + imageLength);
300277
299018
  const longerAltLength = longerAlt.length;
300278
299019
  for (k5 = 0; k5 < longerAltLength; k5++) {
300279
299020
  const longerAltConfig = patternIdxToConfig[longerAlt[k5]];
@@ -300290,11 +299031,12 @@ var init_lexer_public = __esm({
300290
299031
  matchAltImage = null;
300291
299032
  }
300292
299033
  } else {
300293
- this.updateLastIndex(longerAltPattern, offset2);
299034
+ longerAltPattern.lastIndex = offset2;
300294
299035
  matchAltImage = this.match(longerAltPattern, text, offset2);
300295
299036
  }
300296
299037
  if (matchAltImage && matchAltImage.length > matchedImage.length) {
300297
299038
  matchedImage = matchAltImage;
299039
+ imageLength = matchAltImage.length;
300298
299040
  payload2 = altPayload;
300299
299041
  currConfig = longerAltConfig;
300300
299042
  break;
@@ -300304,10 +299046,10 @@ var init_lexer_public = __esm({
300304
299046
  break;
300305
299047
  }
300306
299048
  }
300307
- if (matchedImage !== null) {
300308
- imageLength = matchedImage.length;
299049
+ if (imageLength !== -1) {
300309
299050
  group = currConfig.group;
300310
299051
  if (group !== void 0) {
299052
+ matchedImage = matchedImage !== null ? matchedImage : text.substring(offset2, offset2 + imageLength);
300311
299053
  tokType = currConfig.tokenTypeIdx;
300312
299054
  newToken = this.createTokenInstance(matchedImage, offset2, tokType, currConfig.tokenType, line, column, imageLength);
300313
299055
  this.handlePayload(newToken, payload2);
@@ -300317,15 +299059,13 @@ var init_lexer_public = __esm({
300317
299059
  groups[group].push(newToken);
300318
299060
  }
300319
299061
  }
300320
- text = this.chopInput(text, imageLength);
300321
- offset2 = offset2 + imageLength;
300322
- column = this.computeNewColumn(column, imageLength);
300323
299062
  if (trackLines === true && currConfig.canLineTerminator === true) {
300324
299063
  let numOfLTsInMatch = 0;
300325
299064
  let foundTerminator;
300326
299065
  let lastLTEndOffset;
300327
299066
  lineTerminatorPattern.lastIndex = 0;
300328
299067
  do {
299068
+ matchedImage = matchedImage !== null ? matchedImage : text.substring(offset2, offset2 + imageLength);
300329
299069
  foundTerminator = lineTerminatorPattern.test(matchedImage);
300330
299070
  if (foundTerminator === true) {
300331
299071
  lastLTEndOffset = lineTerminatorPattern.lastIndex - 1;
@@ -300336,8 +299076,13 @@ var init_lexer_public = __esm({
300336
299076
  line = line + numOfLTsInMatch;
300337
299077
  column = imageLength - lastLTEndOffset;
300338
299078
  this.updateTokenEndLineColumnLocation(newToken, group, lastLTEndOffset, numOfLTsInMatch, line, column, imageLength);
299079
+ } else {
299080
+ column = this.computeNewColumn(column, imageLength);
300339
299081
  }
299082
+ } else {
299083
+ column = this.computeNewColumn(column, imageLength);
300340
299084
  }
299085
+ offset2 = offset2 + imageLength;
300341
299086
  this.handleModes(currConfig, pop_mode, push_mode, newToken);
300342
299087
  } else {
300343
299088
  const errorStartOffset = offset2;
@@ -300345,7 +299090,6 @@ var init_lexer_public = __esm({
300345
299090
  const errorColumn = column;
300346
299091
  let foundResyncPoint = recoveryEnabled === false;
300347
299092
  while (foundResyncPoint === false && offset2 < orgLength) {
300348
- text = this.chopInput(text, 1);
300349
299093
  offset2++;
300350
299094
  for (j5 = 0; j5 < currModePatternsLength; j5++) {
300351
299095
  const currConfig2 = patternIdxToConfig[j5];
@@ -300358,7 +299102,7 @@ var init_lexer_public = __esm({
300358
299102
  } else if (currConfig2.isCustom === true) {
300359
299103
  foundResyncPoint = currPattern.exec(orgText, offset2, matchedTokens, groups) !== null;
300360
299104
  } else {
300361
- this.updateLastIndex(currPattern, offset2);
299105
+ currPattern.lastIndex = offset2;
300362
299106
  foundResyncPoint = currPattern.exec(text) !== null;
300363
299107
  }
300364
299108
  if (foundResyncPoint === true) {
@@ -300401,12 +299145,6 @@ var init_lexer_public = __esm({
300401
299145
  push_mode.call(this, config.push);
300402
299146
  }
300403
299147
  }
300404
- chopInput(text, length) {
300405
- return text.substring(length);
300406
- }
300407
- updateLastIndex(regExp, newLastIndex) {
300408
- regExp.lastIndex = newLastIndex;
300409
- }
300410
299148
  // TODO: decrease this under 600 characters? inspect stripping comments option in TSC compiler
300411
299149
  updateTokenEndLineColumnLocation(newToken, group, lastLTIdx, numOfLTsInMatch, line, column, imageLength) {
300412
299150
  let lastCharIsLT, fixForEndingInLT;
@@ -300469,16 +299207,19 @@ var init_lexer_public = __esm({
300469
299207
  token.payload = payload2;
300470
299208
  }
300471
299209
  }
300472
- matchWithTest(pattern, text, offset2) {
299210
+ match(pattern, text, offset2) {
300473
299211
  const found = pattern.test(text);
300474
299212
  if (found === true) {
300475
299213
  return text.substring(offset2, pattern.lastIndex);
300476
299214
  }
300477
299215
  return null;
300478
299216
  }
300479
- matchWithExec(pattern, text) {
300480
- const regExpArray = pattern.exec(text);
300481
- return regExpArray !== null ? regExpArray[0] : null;
299217
+ matchLength(pattern, text, offset2) {
299218
+ const found = pattern.test(text);
299219
+ if (found === true) {
299220
+ return pattern.lastIndex - offset2;
299221
+ }
299222
+ return -1;
300482
299223
  }
300483
299224
  };
300484
299225
  Lexer.SKIPPED = "This marks a skipped Token pattern, this means each token identified by it will be consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.";
@@ -300670,12 +299411,20 @@ For Further details.`;
300670
299411
  return errMsg;
300671
299412
  },
300672
299413
  buildAlternationAmbiguityError(options) {
300673
- const pathMsg = map_default(options.prefixPath, (currtok) => tokenLabel2(currtok)).join(", ");
300674
299414
  const occurrence = options.alternation.idx === 0 ? "" : options.alternation.idx;
299415
+ const isEmptyPath = options.prefixPath.length === 0;
300675
299416
  let currMessage = `Ambiguous Alternatives Detected: <${options.ambiguityIndices.join(" ,")}> in <OR${occurrence}> inside <${options.topLevelRule.name}> Rule,
300676
- <${pathMsg}> may appears as a prefix path in all these alternatives.
300677
299417
  `;
300678
- currMessage = currMessage + `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES
299418
+ if (isEmptyPath) {
299419
+ currMessage += `These alternatives are all empty (match no tokens), making them indistinguishable.
299420
+ Only the last alternative may be empty.
299421
+ `;
299422
+ } else {
299423
+ const pathMsg = map_default(options.prefixPath, (currtok) => tokenLabel2(currtok)).join(", ");
299424
+ currMessage += `<${pathMsg}> may appears as a prefix path in all these alternatives.
299425
+ `;
299426
+ }
299427
+ currMessage += `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES
300679
299428
  For Further details.`;
300680
299429
  return currMessage;
300681
299430
  },
@@ -329914,12 +328663,31 @@ function cleanSchemaResponse(response) {
329914
328663
  const closeChar = openChar === "{" ? "}" : "]";
329915
328664
  let bracketCount = 1;
329916
328665
  let endIndex = startIndex + 1;
328666
+ let inString = false;
328667
+ let escapeNext = false;
329917
328668
  while (endIndex < trimmed.length && bracketCount > 0) {
329918
328669
  const char = trimmed[endIndex];
329919
- if (char === openChar) {
329920
- bracketCount++;
329921
- } else if (char === closeChar) {
329922
- bracketCount--;
328670
+ if (escapeNext) {
328671
+ escapeNext = false;
328672
+ endIndex++;
328673
+ continue;
328674
+ }
328675
+ if (char === "\\" && inString) {
328676
+ escapeNext = true;
328677
+ endIndex++;
328678
+ continue;
328679
+ }
328680
+ if (char === '"') {
328681
+ inString = !inString;
328682
+ endIndex++;
328683
+ continue;
328684
+ }
328685
+ if (!inString) {
328686
+ if (char === openChar) {
328687
+ bracketCount++;
328688
+ } else if (char === closeChar) {
328689
+ bracketCount--;
328690
+ }
329923
328691
  }
329924
328692
  endIndex++;
329925
328693
  }
@@ -352300,6 +351068,122 @@ var init_bashPermissions = __esm({
352300
351068
  });
352301
351069
 
352302
351070
  // src/agent/bashExecutor.js
351071
+ function splitCommandComponents(command) {
351072
+ const parts = [];
351073
+ let current2 = "";
351074
+ let inQuote = false;
351075
+ let quoteChar = "";
351076
+ for (let i5 = 0; i5 < command.length; i5++) {
351077
+ const c5 = command[i5];
351078
+ const next = command[i5 + 1] || "";
351079
+ if (c5 === "\\" && !inQuote) {
351080
+ current2 += c5 + next;
351081
+ i5++;
351082
+ continue;
351083
+ }
351084
+ if (inQuote && quoteChar === '"' && c5 === "\\" && next) {
351085
+ current2 += c5 + next;
351086
+ i5++;
351087
+ continue;
351088
+ }
351089
+ if (!inQuote && (c5 === '"' || c5 === "'")) {
351090
+ inQuote = true;
351091
+ quoteChar = c5;
351092
+ current2 += c5;
351093
+ continue;
351094
+ }
351095
+ if (inQuote && c5 === quoteChar) {
351096
+ inQuote = false;
351097
+ current2 += c5;
351098
+ continue;
351099
+ }
351100
+ if (!inQuote) {
351101
+ if (c5 === "&" && next === "&" || c5 === "|" && next === "|") {
351102
+ if (current2.trim()) parts.push(current2.trim());
351103
+ current2 = "";
351104
+ i5++;
351105
+ continue;
351106
+ }
351107
+ if (c5 === "|" || c5 === ";") {
351108
+ if (current2.trim()) parts.push(current2.trim());
351109
+ current2 = "";
351110
+ continue;
351111
+ }
351112
+ }
351113
+ current2 += c5;
351114
+ }
351115
+ if (current2.trim()) parts.push(current2.trim());
351116
+ return parts;
351117
+ }
351118
+ function checkSingleCommandInteractive(command) {
351119
+ let effective = command.trim();
351120
+ while (/^\w+=\S*\s/.test(effective)) {
351121
+ effective = effective.replace(/^\w+=\S*\s+/, "");
351122
+ }
351123
+ const parts = effective.split(/\s+/);
351124
+ const base2 = parts[0];
351125
+ const args = parts.slice(1);
351126
+ if (["vi", "vim", "nvim", "nano", "emacs", "pico", "joe", "mcedit"].includes(base2)) {
351127
+ return `'${base2}' is an interactive editor and cannot run without a terminal. Use non-interactive file manipulation commands instead.`;
351128
+ }
351129
+ if (["less", "more"].includes(base2)) {
351130
+ return `'${base2}' is an interactive pager. Use 'cat', 'head', or 'tail' instead.`;
351131
+ }
351132
+ if (base2 === "git") {
351133
+ const sub = args[0];
351134
+ if (sub === "commit") {
351135
+ const hasNonInteractiveFlag = args.some(
351136
+ (a5) => a5 === "-m" || a5.startsWith("--message") || a5 === "-C" || a5 === "-c" || a5.startsWith("--fixup") || a5.startsWith("--squash") || a5 === "--allow-empty-message" || a5 === "--no-edit"
351137
+ );
351138
+ if (!hasNonInteractiveFlag) {
351139
+ return `Interactive command: 'git commit' opens an editor for the commit message. Use 'git commit -m "your message"' instead.`;
351140
+ }
351141
+ }
351142
+ if (sub === "rebase" && (args.includes("--continue") || args.includes("--skip"))) {
351143
+ return "Interactive command: 'git rebase --continue' opens an editor. Set environment variable GIT_EDITOR=true to accept default messages, e.g. pass env: {GIT_EDITOR: 'true'} or prepend GIT_EDITOR=true to the command.";
351144
+ }
351145
+ if (sub === "rebase" && (args.includes("-i") || args.includes("--interactive"))) {
351146
+ return "Interactive command: 'git rebase -i' requires an interactive editor. Interactive rebase cannot run without a terminal.";
351147
+ }
351148
+ if (sub === "merge" && !args.includes("--no-edit") && !args.includes("--no-commit") && !args.includes("--ff-only")) {
351149
+ return "Interactive command: 'git merge' may open an editor for the merge commit message. Add '--no-edit' to accept the default message.";
351150
+ }
351151
+ if (sub === "cherry-pick" && !args.includes("--no-edit")) {
351152
+ return "Interactive command: 'git cherry-pick' may open an editor. Add '--no-edit' to accept the default message.";
351153
+ }
351154
+ if (sub === "revert" && !args.includes("--no-edit")) {
351155
+ return "Interactive command: 'git revert' opens an editor. Add '--no-edit' to accept the default message.";
351156
+ }
351157
+ if (sub === "tag" && args.includes("-a") && !args.some((a5) => a5 === "-m" || a5.startsWith("--message"))) {
351158
+ return `Interactive command: 'git tag -a' opens an editor for the tag message. Use 'git tag -a <name> -m "message"' instead.`;
351159
+ }
351160
+ if (sub === "add" && (args.includes("-i") || args.includes("--interactive") || args.includes("-p") || args.includes("--patch"))) {
351161
+ return "Interactive command: 'git add -i/-p' requires interactive input. Use 'git add <files>' to stage specific files instead.";
351162
+ }
351163
+ }
351164
+ if (["python", "python3", "node", "irb", "ghci", "lua", "R", "ruby"].includes(base2) && args.length === 0) {
351165
+ return `Interactive command: '${base2}' without arguments starts an interactive REPL. Provide a script file or use '-c'/'--eval' for inline code.`;
351166
+ }
351167
+ if (base2 === "mysql" && !args.some((a5) => a5 === "-e" || a5.startsWith("--execute"))) {
351168
+ return `Interactive command: 'mysql' without -e flag starts an interactive session. Use 'mysql -e "SQL QUERY"' instead.`;
351169
+ }
351170
+ if (base2 === "psql" && !args.some((a5) => a5 === "-c" || a5.startsWith("--command") || a5 === "-f" || a5.startsWith("--file"))) {
351171
+ return `Interactive command: 'psql' without -c flag starts an interactive session. Use 'psql -c "SQL QUERY"' instead.`;
351172
+ }
351173
+ if (["top", "htop", "btop", "nmon"].includes(base2)) {
351174
+ return `Interactive command: '${base2}' is an interactive TUI tool. Use 'ps aux' or 'top -b -n 1' for non-interactive process listing.`;
351175
+ }
351176
+ return null;
351177
+ }
351178
+ function checkInteractiveCommand(command) {
351179
+ if (!command || typeof command !== "string") return null;
351180
+ const components = splitCommandComponents(command.trim());
351181
+ for (const component of components) {
351182
+ const result = checkSingleCommandInteractive(component);
351183
+ if (result) return result;
351184
+ }
351185
+ return null;
351186
+ }
352303
351187
  async function executeBashCommand(command, options = {}) {
352304
351188
  const {
352305
351189
  workingDirectory = process.cwd(),
@@ -352329,6 +351213,24 @@ async function executeBashCommand(command, options = {}) {
352329
351213
  };
352330
351214
  }
352331
351215
  const startTime = Date.now();
351216
+ const interactiveError = checkInteractiveCommand(command);
351217
+ if (interactiveError) {
351218
+ if (debug) {
351219
+ console.log(`[BashExecutor] Blocked interactive command: "${command}"`);
351220
+ console.log(`[BashExecutor] Reason: ${interactiveError}`);
351221
+ }
351222
+ return {
351223
+ success: false,
351224
+ error: interactiveError,
351225
+ stdout: "",
351226
+ stderr: interactiveError,
351227
+ exitCode: 1,
351228
+ command,
351229
+ workingDirectory: cwd,
351230
+ duration: 0,
351231
+ interactive: true
351232
+ };
351233
+ }
352332
351234
  if (debug) {
352333
351235
  console.log(`[BashExecutor] Executing command: "${command}"`);
352334
351236
  console.log(`[BashExecutor] Working directory: "${cwd}"`);
@@ -352339,6 +351241,8 @@ async function executeBashCommand(command, options = {}) {
352339
351241
  ...process.env,
352340
351242
  ...env
352341
351243
  };
351244
+ if (!processEnv.GIT_EDITOR) processEnv.GIT_EDITOR = "true";
351245
+ if (!processEnv.GIT_TERMINAL_PROMPT) processEnv.GIT_TERMINAL_PROMPT = "0";
352342
351246
  const isComplex = isComplexCommand(command);
352343
351247
  let cmd, cmdArgs, useShell;
352344
351248
  if (isComplex) {
@@ -352373,20 +351277,32 @@ async function executeBashCommand(command, options = {}) {
352373
351277
  // stdin ignored, capture stdout/stderr
352374
351278
  shell: useShell,
352375
351279
  // false for security
351280
+ detached: true,
351281
+ // new session — no controlling terminal
352376
351282
  windowsHide: true
352377
351283
  });
352378
351284
  let stdout = "";
352379
351285
  let stderr = "";
352380
351286
  let killed = false;
352381
351287
  let timeoutHandle;
351288
+ const killProcessGroup = (signal) => {
351289
+ try {
351290
+ if (child.pid) process.kill(-child.pid, signal);
351291
+ } catch {
351292
+ try {
351293
+ child.kill(signal);
351294
+ } catch {
351295
+ }
351296
+ }
351297
+ };
352382
351298
  if (timeout > 0) {
352383
351299
  timeoutHandle = setTimeout(() => {
352384
351300
  if (!killed) {
352385
351301
  killed = true;
352386
- child.kill("SIGTERM");
351302
+ killProcessGroup("SIGTERM");
352387
351303
  setTimeout(() => {
352388
351304
  if (child.exitCode === null) {
352389
- child.kill("SIGKILL");
351305
+ killProcessGroup("SIGKILL");
352390
351306
  }
352391
351307
  }, 5e3);
352392
351308
  }
@@ -352399,7 +351315,7 @@ async function executeBashCommand(command, options = {}) {
352399
351315
  } else {
352400
351316
  if (!killed) {
352401
351317
  killed = true;
352402
- child.kill("SIGTERM");
351318
+ killProcessGroup("SIGTERM");
352403
351319
  }
352404
351320
  }
352405
351321
  });
@@ -352410,7 +351326,7 @@ async function executeBashCommand(command, options = {}) {
352410
351326
  } else {
352411
351327
  if (!killed) {
352412
351328
  killed = true;
352413
- child.kill("SIGTERM");
351329
+ killProcessGroup("SIGTERM");
352414
351330
  }
352415
351331
  }
352416
351332
  });
@@ -396950,7 +395866,7 @@ module.exports = /*#__PURE__*/JSON.parse('{"100":"Continue","101":"Switching Pro
396950
395866
  /***/ ((module) => {
396951
395867
 
396952
395868
  "use strict";
396953
- module.exports = /*#__PURE__*/JSON.parse('{"name":"@probelabs/visor","version":"0.1.42","main":"dist/index.js","bin":{"visor":"./dist/index.js"},"exports":{".":{"require":"./dist/index.js","import":"./dist/index.js"},"./sdk":{"types":"./dist/sdk/sdk.d.ts","import":"./dist/sdk/sdk.mjs","require":"./dist/sdk/sdk.js"},"./cli":{"require":"./dist/index.js"}},"files":["dist/","defaults/","action.yml","README.md","LICENSE"],"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"scripts":{"build:cli":"ncc build src/index.ts -o dist && cp -r defaults dist/ && cp -r output dist/ && cp -r docs dist/ && cp -r examples dist/ && cp -r src/debug-visualizer/ui dist/debug-visualizer/ && node scripts/inject-version.js && echo \'#!/usr/bin/env node\' | cat - dist/index.js > temp && mv temp dist/index.js && chmod +x dist/index.js","build:sdk":"tsup src/sdk.ts --dts --sourcemap --format esm,cjs --out-dir dist/sdk","build":"./scripts/build-oss.sh","build:ee":"npm run build:cli && npm run build:sdk","test":"jest && npm run test:yaml","test:unit":"jest","prepublishOnly":"npm run build","test:watch":"jest --watch","test:coverage":"jest --coverage","test:ee":"jest --testPathPatterns=\'tests/ee\' --testPathIgnorePatterns=\'/node_modules/\' --no-coverage","test:manual:bash":"RUN_MANUAL_TESTS=true jest tests/manual/bash-config-manual.test.ts","lint":"eslint src tests --ext .ts","lint:fix":"eslint src tests --ext .ts --fix","format":"prettier --write src tests","format:check":"prettier --check src tests","clean":"","clean:traces":"node scripts/clean-traces.js","prebuild":"npm run clean && node scripts/generate-config-schema.js","pretest":"npm run clean:traces && node scripts/generate-config-schema.js && npm run build:cli","pretest:unit":"npm run clean:traces && node scripts/generate-config-schema.js && npm run build:cli","test:with-build":"npm run build:cli && jest","test:yaml":"node dist/index.js test --progress compact","test:yaml:parallel":"node dist/index.js test --progress compact --max-parallel 4","prepare":"husky","pre-commit":"lint-staged","deploy:site":"cd site && npx wrangler pages deploy . --project-name=visor-site --commit-dirty=true","deploy:worker":"npx wrangler deploy","deploy":"npm run deploy:site && npm run deploy:worker","publish:ee":"./scripts/publish-ee.sh","release":"./scripts/release.sh","release:patch":"./scripts/release.sh patch","release:minor":"./scripts/release.sh minor","release:major":"./scripts/release.sh major","release:prerelease":"./scripts/release.sh prerelease","docs:validate":"node scripts/validate-readme-links.js","workshop:setup":"npm install -D reveal-md@6.1.2","workshop:serve":"cd workshop && reveal-md slides.md -w","workshop:export":"reveal-md workshop/slides.md --static workshop/build","workshop:pdf":"reveal-md workshop/slides.md --print workshop/Visor-Workshop.pdf --print-size letter","workshop:pdf:ci":"reveal-md workshop/slides.md --print workshop/Visor-Workshop.pdf --print-size letter --puppeteer-launch-args=\\"--no-sandbox --disable-dev-shm-usage\\"","workshop:pdf:a4":"reveal-md workshop/slides.md --print workshop/Visor-Workshop-A4.pdf --print-size A4","workshop:build":"npm run workshop:export && npm run workshop:pdf","simulate:issue":"TS_NODE_TRANSPILE_ONLY=1 ts-node scripts/simulate-gh-run.ts --event issues --action opened --debug","simulate:comment":"TS_NODE_TRANSPILE_ONLY=1 ts-node scripts/simulate-gh-run.ts --event issue_comment --action created --debug"},"keywords":["code-review","ai","github-action","cli","pr-review","visor"],"author":"Probe Labs","license":"MIT","description":"AI workflow engine for code review, assistants, and automation — orchestrate checks, MCP tools, and AI providers with YAML-driven pipelines","repository":{"type":"git","url":"git+https://github.com/probelabs/visor.git"},"bugs":{"url":"https://github.com/probelabs/visor/issues"},"homepage":"https://github.com/probelabs/visor#readme","dependencies":{"@actions/core":"^1.11.1","@apidevtools/swagger-parser":"^12.1.0","@modelcontextprotocol/sdk":"^1.25.3","@nyariv/sandboxjs":"github:probelabs/SandboxJS#f1c13b8eee98734a8ea024061eada4aa9a9ff2e9","@octokit/action":"^8.0.2","@octokit/auth-app":"^8.1.0","@octokit/core":"^7.0.3","@octokit/rest":"^22.0.0","@opentelemetry/api":"^1.9.0","@opentelemetry/core":"^1.30.1","@opentelemetry/exporter-trace-otlp-grpc":"^0.203.0","@opentelemetry/exporter-trace-otlp-http":"^0.203.0","@opentelemetry/instrumentation":"^0.203.0","@opentelemetry/resources":"^1.30.1","@opentelemetry/sdk-metrics":"^1.30.1","@opentelemetry/sdk-node":"^0.203.0","@opentelemetry/sdk-trace-base":"^1.30.1","@opentelemetry/semantic-conventions":"^1.30.1","@probelabs/probe":"^0.6.0-rc262","@types/commander":"^2.12.0","@types/uuid":"^10.0.0","acorn":"^8.16.0","acorn-walk":"^8.3.5","ajv":"^8.17.1","ajv-formats":"^3.0.1","better-sqlite3":"^11.0.0","blessed":"^0.1.81","cli-table3":"^0.6.5","commander":"^14.0.0","deepmerge":"^4.3.1","dotenv":"^17.2.3","ignore":"^7.0.5","js-yaml":"^4.1.0","jsonpath-plus":"^10.4.0","liquidjs":"^10.21.1","minimatch":"^10.2.2","node-cron":"^3.0.3","open":"^9.1.0","simple-git":"^3.28.0","uuid":"^11.1.0","ws":"^8.18.3"},"optionalDependencies":{"@anthropic/claude-code-sdk":"npm:null@*","@open-policy-agent/opa-wasm":"^1.10.0","knex":"^3.1.0","mysql2":"^3.11.0","pg":"^8.13.0","tedious":"^19.0.0"},"devDependencies":{"@eslint/js":"^9.34.0","@kie/act-js":"^2.6.2","@kie/mock-github":"^2.0.1","@swc/core":"^1.13.2","@swc/jest":"^0.2.37","@types/better-sqlite3":"^7.6.0","@types/blessed":"^0.1.27","@types/jest":"^30.0.0","@types/js-yaml":"^4.0.9","@types/node":"^24.3.0","@types/node-cron":"^3.0.11","@types/ws":"^8.18.1","@typescript-eslint/eslint-plugin":"^8.42.0","@typescript-eslint/parser":"^8.42.0","@vercel/ncc":"^0.38.4","eslint":"^9.34.0","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.4","husky":"^9.1.7","jest":"^30.1.3","lint-staged":"^16.1.6","prettier":"^3.6.2","reveal-md":"^6.1.2","ts-json-schema-generator":"^1.5.1","ts-node":"^10.9.2","tsup":"^8.5.0","typescript":"^5.9.2","wrangler":"^3.0.0"},"peerDependenciesMeta":{"@anthropic/claude-code-sdk":{"optional":true}},"directories":{"test":"tests"},"lint-staged":{"src/**/*.{ts,js}":["eslint --fix","prettier --write"],"tests/**/*.{ts,js}":["eslint --fix","prettier --write"],"*.{json,md,yml,yaml}":["prettier --write"]}}');
395869
+ module.exports = /*#__PURE__*/JSON.parse('{"name":"@probelabs/visor","version":"0.1.148","main":"dist/index.js","bin":{"visor":"./dist/index.js"},"exports":{".":{"require":"./dist/index.js","import":"./dist/index.js"},"./sdk":{"types":"./dist/sdk/sdk.d.ts","import":"./dist/sdk/sdk.mjs","require":"./dist/sdk/sdk.js"},"./cli":{"require":"./dist/index.js"}},"files":["dist/","defaults/","action.yml","README.md","LICENSE"],"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"scripts":{"build:cli":"ncc build src/index.ts -o dist && cp -r defaults dist/ && cp -r output dist/ && cp -r docs dist/ && cp -r examples dist/ && cp -r src/debug-visualizer/ui dist/debug-visualizer/ && node scripts/inject-version.js && echo \'#!/usr/bin/env node\' | cat - dist/index.js > temp && mv temp dist/index.js && chmod +x dist/index.js","build:sdk":"tsup src/sdk.ts --dts --sourcemap --format esm,cjs --out-dir dist/sdk","build":"./scripts/build-oss.sh","build:ee":"npm run build:cli && npm run build:sdk","test":"jest && npm run test:yaml","test:unit":"jest","prepublishOnly":"npm run build","test:watch":"jest --watch","test:coverage":"jest --coverage","test:ee":"jest --testPathPatterns=\'tests/ee\' --testPathIgnorePatterns=\'/node_modules/\' --no-coverage","test:manual:bash":"RUN_MANUAL_TESTS=true jest tests/manual/bash-config-manual.test.ts","lint":"eslint src tests --ext .ts","lint:fix":"eslint src tests --ext .ts --fix","format":"prettier --write src tests","format:check":"prettier --check src tests","clean":"","clean:traces":"node scripts/clean-traces.js","prebuild":"npm run clean && node scripts/generate-config-schema.js","pretest":"npm run clean:traces && node scripts/generate-config-schema.js && npm run build:cli","pretest:unit":"npm run clean:traces && node scripts/generate-config-schema.js && npm run build:cli","test:with-build":"npm run build:cli && jest","test:yaml":"node dist/index.js test --progress compact","test:yaml:parallel":"node dist/index.js test --progress compact --max-parallel 4","prepare":"husky","pre-commit":"lint-staged","deploy:site":"cd site && npx wrangler pages deploy . --project-name=visor-site --commit-dirty=true","deploy:worker":"npx wrangler deploy","deploy":"npm run deploy:site && npm run deploy:worker","publish:ee":"./scripts/publish-ee.sh","release":"./scripts/release.sh","release:patch":"./scripts/release.sh patch","release:minor":"./scripts/release.sh minor","release:major":"./scripts/release.sh major","release:prerelease":"./scripts/release.sh prerelease","docs:validate":"node scripts/validate-readme-links.js","workshop:setup":"npm install -D reveal-md@6.1.2","workshop:serve":"cd workshop && reveal-md slides.md -w","workshop:export":"reveal-md workshop/slides.md --static workshop/build","workshop:pdf":"reveal-md workshop/slides.md --print workshop/Visor-Workshop.pdf --print-size letter","workshop:pdf:ci":"reveal-md workshop/slides.md --print workshop/Visor-Workshop.pdf --print-size letter --puppeteer-launch-args=\\"--no-sandbox --disable-dev-shm-usage\\"","workshop:pdf:a4":"reveal-md workshop/slides.md --print workshop/Visor-Workshop-A4.pdf --print-size A4","workshop:build":"npm run workshop:export && npm run workshop:pdf","simulate:issue":"TS_NODE_TRANSPILE_ONLY=1 ts-node scripts/simulate-gh-run.ts --event issues --action opened --debug","simulate:comment":"TS_NODE_TRANSPILE_ONLY=1 ts-node scripts/simulate-gh-run.ts --event issue_comment --action created --debug"},"keywords":["code-review","ai","github-action","cli","pr-review","visor"],"author":"Probe Labs","license":"MIT","description":"AI workflow engine for code review, assistants, and automation — orchestrate checks, MCP tools, and AI providers with YAML-driven pipelines","repository":{"type":"git","url":"git+https://github.com/probelabs/visor.git"},"bugs":{"url":"https://github.com/probelabs/visor/issues"},"homepage":"https://github.com/probelabs/visor#readme","dependencies":{"@actions/core":"^1.11.1","@apidevtools/swagger-parser":"^12.1.0","@modelcontextprotocol/sdk":"^1.25.3","@nyariv/sandboxjs":"github:probelabs/SandboxJS#f1c13b8eee98734a8ea024061eada4aa9a9ff2e9","@octokit/action":"^8.0.2","@octokit/auth-app":"^8.1.0","@octokit/core":"^7.0.3","@octokit/rest":"^22.0.0","@opentelemetry/api":"^1.9.0","@opentelemetry/core":"^1.30.1","@opentelemetry/exporter-trace-otlp-grpc":"^0.203.0","@opentelemetry/exporter-trace-otlp-http":"^0.203.0","@opentelemetry/instrumentation":"^0.203.0","@opentelemetry/resources":"^1.30.1","@opentelemetry/sdk-metrics":"^1.30.1","@opentelemetry/sdk-node":"^0.203.0","@opentelemetry/sdk-trace-base":"^1.30.1","@opentelemetry/semantic-conventions":"^1.30.1","@probelabs/probe":"^0.6.0-rc264","@types/commander":"^2.12.0","@types/uuid":"^10.0.0","acorn":"^8.16.0","acorn-walk":"^8.3.5","ajv":"^8.17.1","ajv-formats":"^3.0.1","better-sqlite3":"^11.0.0","blessed":"^0.1.81","cli-table3":"^0.6.5","commander":"^14.0.0","deepmerge":"^4.3.1","dotenv":"^17.2.3","ignore":"^7.0.5","js-yaml":"^4.1.0","jsonpath-plus":"^10.4.0","liquidjs":"^10.21.1","minimatch":"^10.2.2","node-cron":"^3.0.3","open":"^9.1.0","simple-git":"^3.28.0","uuid":"^11.1.0","ws":"^8.18.3"},"optionalDependencies":{"@anthropic/claude-code-sdk":"npm:null@*","@open-policy-agent/opa-wasm":"^1.10.0","knex":"^3.1.0","mysql2":"^3.11.0","pg":"^8.13.0","tedious":"^19.0.0"},"devDependencies":{"@eslint/js":"^9.34.0","@kie/act-js":"^2.6.2","@kie/mock-github":"^2.0.1","@swc/core":"^1.13.2","@swc/jest":"^0.2.37","@types/better-sqlite3":"^7.6.0","@types/blessed":"^0.1.27","@types/jest":"^30.0.0","@types/js-yaml":"^4.0.9","@types/node":"^24.3.0","@types/node-cron":"^3.0.11","@types/ws":"^8.18.1","@typescript-eslint/eslint-plugin":"^8.42.0","@typescript-eslint/parser":"^8.42.0","@vercel/ncc":"^0.38.4","eslint":"^9.34.0","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.4","husky":"^9.1.7","jest":"^30.1.3","lint-staged":"^16.1.6","prettier":"^3.6.2","reveal-md":"^6.1.2","ts-json-schema-generator":"^1.5.1","ts-node":"^10.9.2","tsup":"^8.5.0","typescript":"^5.9.2","wrangler":"^3.0.0"},"peerDependenciesMeta":{"@anthropic/claude-code-sdk":{"optional":true}},"directories":{"test":"tests"},"lint-staged":{"src/**/*.{ts,js}":["eslint --fix","prettier --write"],"tests/**/*.{ts,js}":["eslint --fix","prettier --write"],"*.{json,md,yml,yaml}":["prettier --write"]}}');
396954
395870
 
396955
395871
  /***/ })
396956
395872