@probelabs/visor 0.1.171 → 0.1.172-ee

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/dist/agent-protocol/task-store.d.ts +8 -0
  2. package/dist/agent-protocol/task-store.d.ts.map +1 -1
  3. package/dist/agent-protocol/tasks-cli-handler.d.ts.map +1 -1
  4. package/dist/cli-main.d.ts.map +1 -1
  5. package/dist/index.js +2033 -99
  6. package/dist/sdk/{a2a-frontend-GUEGI5SX.mjs → a2a-frontend-N4VU3PHW.mjs} +36 -1
  7. package/dist/sdk/a2a-frontend-N4VU3PHW.mjs.map +1 -0
  8. package/dist/sdk/{check-provider-registry-YTI4PU5F.mjs → check-provider-registry-4KW2YPZW.mjs} +3 -3
  9. package/dist/sdk/{check-provider-registry-ZUU7KSKR.mjs → check-provider-registry-H5GQGT2X.mjs} +3 -3
  10. package/dist/sdk/{chunk-CXA3WUOB.mjs → chunk-CNZ7XHLN.mjs} +9 -9
  11. package/dist/sdk/{chunk-2VDUNKIP.mjs → chunk-ONN7TBQM.mjs} +14 -14
  12. package/dist/sdk/{chunk-XUQSI5SR.mjs.map → chunk-ONN7TBQM.mjs.map} +1 -1
  13. package/dist/sdk/{chunk-AVMMKGLQ.mjs → chunk-PDQTEBOJ.mjs} +18 -18
  14. package/dist/sdk/chunk-PDQTEBOJ.mjs.map +1 -0
  15. package/dist/sdk/{host-A7UNRBQU.mjs → host-DOJQVREK.mjs} +3 -3
  16. package/dist/sdk/{host-A4GGQVEN.mjs → host-YATAT2B4.mjs} +4 -4
  17. package/dist/sdk/knex-store-CRORFJE6.mjs +527 -0
  18. package/dist/sdk/knex-store-CRORFJE6.mjs.map +1 -0
  19. package/dist/sdk/loader-QMJFFST6.mjs +89 -0
  20. package/dist/sdk/loader-QMJFFST6.mjs.map +1 -0
  21. package/dist/sdk/opa-policy-engine-S2S2ULEI.mjs +655 -0
  22. package/dist/sdk/opa-policy-engine-S2S2ULEI.mjs.map +1 -0
  23. package/dist/sdk/{schedule-tool-DGVJDHJM.mjs → schedule-tool-HCJUIF4H.mjs} +3 -3
  24. package/dist/sdk/{schedule-tool-4MTFIHCA.mjs → schedule-tool-KUGCECKZ.mjs} +3 -3
  25. package/dist/sdk/{schedule-tool-handler-LMXQ4BZQ.mjs → schedule-tool-handler-DCMMLWLB.mjs} +3 -3
  26. package/dist/sdk/{schedule-tool-handler-XLCSBU3E.mjs → schedule-tool-handler-IZU43FC2.mjs} +3 -3
  27. package/dist/sdk/sdk.js +1700 -291
  28. package/dist/sdk/sdk.js.map +1 -1
  29. package/dist/sdk/sdk.mjs +5 -5
  30. package/dist/sdk/{slack-frontend-QO7LW5BH.mjs → slack-frontend-7T5UISCX.mjs} +2 -2
  31. package/dist/sdk/validator-XTZJZZJH.mjs +134 -0
  32. package/dist/sdk/validator-XTZJZZJH.mjs.map +1 -0
  33. package/dist/sdk/{workflow-check-provider-KQNLEQEY.mjs → workflow-check-provider-LO2X6XOJ.mjs} +3 -3
  34. package/dist/sdk/{workflow-check-provider-X5EMAJUZ.mjs → workflow-check-provider-O2SIH3PC.mjs} +3 -3
  35. package/dist/slack/markdown.d.ts.map +1 -1
  36. package/package.json +1 -1
  37. package/dist/output/traces/run-2026-03-08T07-55-35-120Z.ndjson +0 -138
  38. package/dist/output/traces/run-2026-03-08T07-56-13-035Z.ndjson +0 -2266
  39. package/dist/sdk/a2a-frontend-FGJ3UBHX.mjs +0 -1622
  40. package/dist/sdk/a2a-frontend-FGJ3UBHX.mjs.map +0 -1
  41. package/dist/sdk/a2a-frontend-GUEGI5SX.mjs.map +0 -1
  42. package/dist/sdk/check-provider-registry-PVTV5G5R.mjs +0 -30
  43. package/dist/sdk/chunk-2VDUNKIP.mjs.map +0 -1
  44. package/dist/sdk/chunk-6FDBLSGV.mjs +0 -739
  45. package/dist/sdk/chunk-6FDBLSGV.mjs.map +0 -1
  46. package/dist/sdk/chunk-AJK3FAA2.mjs +0 -1502
  47. package/dist/sdk/chunk-AJK3FAA2.mjs.map +0 -1
  48. package/dist/sdk/chunk-AVMMKGLQ.mjs.map +0 -1
  49. package/dist/sdk/chunk-O72J3ORS.mjs +0 -449
  50. package/dist/sdk/chunk-O72J3ORS.mjs.map +0 -1
  51. package/dist/sdk/chunk-XUQSI5SR.mjs +0 -44810
  52. package/dist/sdk/failure-condition-evaluator-EFMCQVAK.mjs +0 -18
  53. package/dist/sdk/github-frontend-XG55VJ4R.mjs +0 -1386
  54. package/dist/sdk/github-frontend-XG55VJ4R.mjs.map +0 -1
  55. package/dist/sdk/routing-BVEHVZHK.mjs +0 -26
  56. package/dist/sdk/schedule-tool-PHSF5U2B.mjs +0 -36
  57. package/dist/sdk/schedule-tool-handler-EFNCZNS7.mjs +0 -40
  58. package/dist/sdk/schedule-tool-handler-EFNCZNS7.mjs.map +0 -1
  59. package/dist/sdk/schedule-tool-handler-LMXQ4BZQ.mjs.map +0 -1
  60. package/dist/sdk/schedule-tool-handler-XLCSBU3E.mjs.map +0 -1
  61. package/dist/sdk/trace-helpers-P5L4COO4.mjs +0 -26
  62. package/dist/sdk/trace-helpers-P5L4COO4.mjs.map +0 -1
  63. package/dist/sdk/workflow-check-provider-KQNLEQEY.mjs.map +0 -1
  64. package/dist/sdk/workflow-check-provider-WLMTCFRA.mjs +0 -30
  65. package/dist/sdk/workflow-check-provider-WLMTCFRA.mjs.map +0 -1
  66. package/dist/sdk/workflow-check-provider-X5EMAJUZ.mjs.map +0 -1
  67. package/dist/traces/run-2026-03-08T07-55-35-120Z.ndjson +0 -138
  68. package/dist/traces/run-2026-03-08T07-56-13-035Z.ndjson +0 -2266
  69. /package/dist/sdk/{check-provider-registry-PVTV5G5R.mjs.map → check-provider-registry-4KW2YPZW.mjs.map} +0 -0
  70. /package/dist/sdk/{check-provider-registry-YTI4PU5F.mjs.map → check-provider-registry-H5GQGT2X.mjs.map} +0 -0
  71. /package/dist/sdk/{chunk-CXA3WUOB.mjs.map → chunk-CNZ7XHLN.mjs.map} +0 -0
  72. /package/dist/sdk/{host-A4GGQVEN.mjs.map → host-DOJQVREK.mjs.map} +0 -0
  73. /package/dist/sdk/{host-A7UNRBQU.mjs.map → host-YATAT2B4.mjs.map} +0 -0
  74. /package/dist/sdk/{check-provider-registry-ZUU7KSKR.mjs.map → schedule-tool-HCJUIF4H.mjs.map} +0 -0
  75. /package/dist/sdk/{failure-condition-evaluator-EFMCQVAK.mjs.map → schedule-tool-KUGCECKZ.mjs.map} +0 -0
  76. /package/dist/sdk/{routing-BVEHVZHK.mjs.map → schedule-tool-handler-DCMMLWLB.mjs.map} +0 -0
  77. /package/dist/sdk/{schedule-tool-4MTFIHCA.mjs.map → schedule-tool-handler-IZU43FC2.mjs.map} +0 -0
  78. /package/dist/sdk/{slack-frontend-QO7LW5BH.mjs.map → slack-frontend-7T5UISCX.mjs.map} +0 -0
  79. /package/dist/sdk/{schedule-tool-DGVJDHJM.mjs.map → workflow-check-provider-LO2X6XOJ.mjs.map} +0 -0
  80. /package/dist/sdk/{schedule-tool-PHSF5U2B.mjs.map → workflow-check-provider-O2SIH3PC.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.171';
2
+ process.env.VISOR_VERSION = '0.1.172';
3
3
  process.env.PROBE_VERSION = '0.6.0-rc290';
4
- process.env.VISOR_COMMIT_SHA = '12d9273ce614376592cf397b6c874dcbfa220b8b';
5
- process.env.VISOR_COMMIT_SHORT = '12d9273ce';
4
+ process.env.VISOR_COMMIT_SHA = 'eb6383c71ff3acd3d32816d705c29ca297eadddd';
5
+ process.env.VISOR_COMMIT_SHORT = 'eb6383c';
6
6
  /******/ (() => { // webpackBootstrap
7
7
  /******/ var __webpack_modules__ = ({
8
8
 
@@ -168069,6 +168069,16 @@ class SqliteTaskStore {
168069
168069
  conditions.push('workflow_id = ?');
168070
168070
  params.push(filter.workflowId);
168071
168071
  }
168072
+ if (filter.search) {
168073
+ // Escape SQL LIKE wildcards to prevent wildcard injection
168074
+ const escaped = filter.search.replace(/[%_\\]/g, '\\$&');
168075
+ conditions.push("request_message LIKE ? ESCAPE '\\'");
168076
+ params.push(`%${escaped}%`);
168077
+ }
168078
+ if (filter.claimedBy) {
168079
+ conditions.push('claimed_by = ?');
168080
+ params.push(filter.claimedBy);
168081
+ }
168072
168082
  const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
168073
168083
  return { where, params };
168074
168084
  }
@@ -168227,6 +168237,32 @@ class SqliteTaskStore {
168227
168237
  // -------------------------------------------------------------------------
168228
168238
  // Cleanup
168229
168239
  // -------------------------------------------------------------------------
168240
+ failStaleTasks(reason) {
168241
+ const db = this.getDb();
168242
+ const now = nowISO();
168243
+ const msg = reason || 'Process terminated while task was running';
168244
+ const statusMessage = JSON.stringify({
168245
+ message_id: crypto_1.default.randomUUID(),
168246
+ role: 'agent',
168247
+ parts: [{ text: msg }],
168248
+ });
168249
+ const result = db
168250
+ .prepare(`UPDATE agent_tasks
168251
+ SET state = 'failed', updated_at = ?, status_message = ?
168252
+ WHERE state = 'working'`)
168253
+ .run(now, statusMessage);
168254
+ return result.changes;
168255
+ }
168256
+ purgeOldTasks(olderThanMs) {
168257
+ const db = this.getDb();
168258
+ const cutoff = new Date(Date.now() - olderThanMs).toISOString();
168259
+ const result = db
168260
+ .prepare(`DELETE FROM agent_tasks
168261
+ WHERE state IN ('completed', 'failed', 'canceled', 'rejected')
168262
+ AND updated_at <= ?`)
168263
+ .run(cutoff);
168264
+ return result.changes;
168265
+ }
168230
168266
  deleteExpiredTasks() {
168231
168267
  const db = this.getDb();
168232
168268
  const now = nowISO();
@@ -168393,10 +168429,13 @@ exports.TaskStreamManager = TaskStreamManager;
168393
168429
  /***/ }),
168394
168430
 
168395
168431
  /***/ 5932:
168396
- /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
168432
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
168397
168433
 
168398
168434
  "use strict";
168399
168435
 
168436
+ var __importDefault = (this && this.__importDefault) || function (mod) {
168437
+ return (mod && mod.__esModule) ? mod : { "default": mod };
168438
+ };
168400
168439
  Object.defineProperty(exports, "__esModule", ({ value: true }));
168401
168440
  exports.handleTasksCommand = handleTasksCommand;
168402
168441
  /**
@@ -168409,6 +168448,7 @@ exports.handleTasksCommand = handleTasksCommand;
168409
168448
  * visor tasks cancel <task-id> - Cancel a task
168410
168449
  * visor tasks help - Show usage
168411
168450
  */
168451
+ const cli_table3_1 = __importDefault(__nccwpck_require__(25832));
168412
168452
  const logger_1 = __nccwpck_require__(86999);
168413
168453
  const instance_id_1 = __nccwpck_require__(89942);
168414
168454
  const task_store_1 = __nccwpck_require__(24711);
@@ -168478,9 +168518,19 @@ function buildFilter(flags) {
168478
168518
  if (typeof flags.state === 'string' && (0, state_transitions_1.isValidTaskState)(flags.state)) {
168479
168519
  filter.state = [flags.state];
168480
168520
  }
168521
+ else if (!flags.all) {
168522
+ // Default: show only active tasks (not completed history)
168523
+ filter.state = ['submitted', 'working', 'input_required', 'auth_required'];
168524
+ }
168481
168525
  if (typeof flags.agent === 'string') {
168482
168526
  filter.workflowId = flags.agent;
168483
168527
  }
168528
+ if (typeof flags.search === 'string') {
168529
+ filter.search = flags.search;
168530
+ }
168531
+ if (typeof flags.instance === 'string') {
168532
+ filter.claimedBy = flags.instance;
168533
+ }
168484
168534
  if (typeof flags.limit === 'string') {
168485
168535
  const n = parseInt(flags.limit, 10);
168486
168536
  if (!isNaN(n) && n > 0)
@@ -168504,30 +168554,59 @@ function formatMeta(meta) {
168504
168554
  parts.push(`sched:${meta.schedule_id}`);
168505
168555
  return parts.join(' ') || '-';
168506
168556
  }
168557
+ function stateColor(state) {
168558
+ switch (state) {
168559
+ case 'working':
168560
+ return '\x1b[33m' + state + '\x1b[0m'; // yellow
168561
+ case 'completed':
168562
+ return '\x1b[32m' + state + '\x1b[0m'; // green
168563
+ case 'failed':
168564
+ return '\x1b[31m' + state + '\x1b[0m'; // red
168565
+ case 'canceled':
168566
+ case 'rejected':
168567
+ return '\x1b[90m' + state + '\x1b[0m'; // grey
168568
+ case 'submitted':
168569
+ return '\x1b[36m' + state + '\x1b[0m'; // cyan
168570
+ case 'input_required':
168571
+ case 'auth_required':
168572
+ return '\x1b[35m' + state + '\x1b[0m'; // magenta
168573
+ default:
168574
+ return state;
168575
+ }
168576
+ }
168507
168577
  function formatTable(rows, total) {
168508
168578
  if (rows.length === 0)
168509
168579
  return 'No tasks found.';
168510
- const header = ['ID', 'Source', 'State', 'Workflow', 'Duration', 'Instance', 'Meta', 'Input'];
168511
- const data = rows.map(r => {
168580
+ const table = new cli_table3_1.default({
168581
+ head: ['ID', 'Source', 'State', 'Workflow', 'Duration', 'Instance', 'Meta', 'Input'],
168582
+ style: {
168583
+ head: ['cyan', 'bold'],
168584
+ border: ['grey'],
168585
+ },
168586
+ wordWrap: false,
168587
+ });
168588
+ for (const r of rows) {
168512
168589
  const duration = (0, state_transitions_1.isTerminalState)(r.state)
168513
168590
  ? formatDuration(r.created_at, r.updated_at)
168514
168591
  : formatDuration(r.claimed_at || r.created_at);
168515
- const instance = r.claimed_by || '-';
168516
- const workflow = r.workflow_id || '-';
168517
- const source = r.source || '-';
168518
- const meta = formatMeta(r.metadata);
168519
168592
  const input = r.request_message.length > 60
168520
168593
  ? r.request_message.slice(0, 57) + '...'
168521
168594
  : r.request_message || '-';
168522
- return [r.id.slice(0, 8), source, r.state, workflow, duration, instance, meta, input];
168523
- });
168524
- const widths = header.map((h, i) => Math.max(h.length, ...data.map(row => row[i].length)));
168525
- const sep = widths.map(w => '-'.repeat(w)).join(' ');
168526
- const fmt = (row) => row.map((cell, i) => cell.padEnd(widths[i])).join(' ');
168527
- const lines = [fmt(header), sep, ...data.map(fmt)];
168595
+ table.push([
168596
+ r.id.slice(0, 8),
168597
+ r.source || '-',
168598
+ stateColor(r.state),
168599
+ r.workflow_id || '-',
168600
+ duration,
168601
+ r.claimed_by || '-',
168602
+ formatMeta(r.metadata),
168603
+ input,
168604
+ ]);
168605
+ }
168606
+ let output = table.toString();
168528
168607
  if (total > rows.length)
168529
- lines.push(`\n(${total} total, showing ${rows.length})`);
168530
- return lines.join('\n');
168608
+ output += `\n(${total} total, showing ${rows.length})`;
168609
+ return output;
168531
168610
  }
168532
168611
  function formatMarkdown(rows, total) {
168533
168612
  if (rows.length === 0)
@@ -168565,15 +168644,16 @@ async function handleList(flags) {
168565
168644
  const render = async () => {
168566
168645
  await withTaskStore(async (store) => {
168567
168646
  const { rows, total } = store.listTasksRaw(filter);
168647
+ const activeOnly = !flags.all && !flags.state;
168568
168648
  if (output === 'json') {
168569
- console.log(JSON.stringify({ instance_id: instanceId, tasks: rows, total }, null, 2));
168649
+ console.log(JSON.stringify({ instance_id: instanceId, active_only: activeOnly, tasks: rows, total }, null, 2));
168570
168650
  }
168571
168651
  else if (output === 'markdown') {
168572
- console.log(`Instance: ${instanceId}\n`);
168652
+ console.log(`Instance: ${instanceId}${activeOnly ? ' (active tasks only, use --all for history)' : ''}\n`);
168573
168653
  console.log(formatMarkdown(rows, total));
168574
168654
  }
168575
168655
  else {
168576
- console.log(`Instance: ${instanceId}\n`);
168656
+ console.log(`Instance: ${instanceId}${activeOnly ? ' (active tasks only, use --all for history)' : ''}\n`);
168577
168657
  console.log(formatTable(rows, total));
168578
168658
  }
168579
168659
  });
@@ -168644,25 +168724,40 @@ async function handleStats(flags) {
168644
168724
  }, null, 2));
168645
168725
  return;
168646
168726
  }
168647
- console.log('Task State Summary');
168648
- console.log('------------------');
168727
+ const stateTable = new cli_table3_1.default({
168728
+ head: ['State', 'Count'],
168729
+ style: { head: ['cyan', 'bold'], border: ['grey'] },
168730
+ });
168649
168731
  for (const [state, count] of Object.entries(stateCounts)) {
168650
168732
  if (count > 0)
168651
- console.log(` ${state.padEnd(18)} ${count}`);
168733
+ stateTable.push([stateColor(state), String(count)]);
168652
168734
  }
168735
+ console.log('Task State Summary');
168736
+ console.log(stateTable.toString());
168653
168737
  if (Object.keys(agentCounts).length > 0) {
168654
- console.log('\nActive Tasks by Agent');
168655
- console.log('---------------------');
168738
+ const agentTable = new cli_table3_1.default({
168739
+ head: ['Workflow', 'Active Tasks'],
168740
+ style: { head: ['cyan', 'bold'], border: ['grey'] },
168741
+ });
168656
168742
  for (const [agent, count] of Object.entries(agentCounts)) {
168657
- console.log(` ${agent.padEnd(24)} ${count}`);
168743
+ agentTable.push([agent, String(count)]);
168658
168744
  }
168745
+ console.log('\nActive Tasks by Workflow');
168746
+ console.log(agentTable.toString());
168659
168747
  }
168660
- console.log(`\nActive workers: ${workerSet.size}`);
168748
+ console.log(`\nActive instances: ${workerSet.size}`);
168661
168749
  });
168662
168750
  }
168663
168751
  // ---------------------------------------------------------------------------
168664
168752
  // Subcommand: cancel
168665
168753
  // ---------------------------------------------------------------------------
168754
+ /**
168755
+ * Find a task by full ID or prefix match.
168756
+ */
168757
+ function findTaskByPrefix(store, prefix) {
168758
+ const { rows } = store.listTasksRaw({ limit: 500 });
168759
+ return rows.find(r => r.id === prefix || r.id.startsWith(prefix)) ?? null;
168760
+ }
168666
168761
  async function handleCancel(positional, _flags) {
168667
168762
  const taskId = positional[0];
168668
168763
  if (!taskId) {
@@ -168671,19 +168766,19 @@ async function handleCancel(positional, _flags) {
168671
168766
  return;
168672
168767
  }
168673
168768
  await withTaskStore(async (store) => {
168674
- const task = store.getTask(taskId);
168675
- if (!task) {
168769
+ const match = findTaskByPrefix(store, taskId);
168770
+ if (!match) {
168676
168771
  console.error(`Task not found: ${taskId}`);
168677
168772
  process.exitCode = 1;
168678
168773
  return;
168679
168774
  }
168680
- if ((0, state_transitions_1.isTerminalState)(task.status.state)) {
168681
- console.error(`Cannot cancel task in '${task.status.state}' state (already terminal)`);
168775
+ if ((0, state_transitions_1.isTerminalState)(match.state)) {
168776
+ console.error(`Cannot cancel task in '${match.state}' state (already terminal)`);
168682
168777
  process.exitCode = 1;
168683
168778
  return;
168684
168779
  }
168685
- store.updateTaskState(taskId, 'canceled');
168686
- console.log(`Task ${taskId.slice(0, 8)} canceled (was: ${task.status.state})`);
168780
+ store.updateTaskState(match.id, 'canceled');
168781
+ console.log(`Task ${match.id.slice(0, 8)} canceled (was: ${match.state})`);
168687
168782
  });
168688
168783
  }
168689
168784
  // ---------------------------------------------------------------------------
@@ -168698,9 +168793,7 @@ async function handleShow(positional, flags) {
168698
168793
  }
168699
168794
  const output = typeof flags.output === 'string' ? flags.output : 'table';
168700
168795
  await withTaskStore(async (store) => {
168701
- // Try to find by prefix match
168702
- const { rows } = store.listTasksRaw({ limit: 200 });
168703
- const match = rows.find(r => r.id.startsWith(taskId));
168796
+ const match = findTaskByPrefix(store, taskId);
168704
168797
  if (!match) {
168705
168798
  console.error(`Task not found: ${taskId}`);
168706
168799
  process.exitCode = 1;
@@ -168713,26 +168806,40 @@ async function handleShow(positional, flags) {
168713
168806
  const duration = (0, state_transitions_1.isTerminalState)(match.state)
168714
168807
  ? formatDuration(match.created_at, match.updated_at)
168715
168808
  : formatDuration(match.claimed_at || match.created_at);
168716
- console.log(`Task: ${match.id}`);
168717
- console.log(`State: ${match.state}`);
168718
- console.log(`Source: ${match.source}`);
168719
- console.log(`Workflow: ${match.workflow_id || '-'}`);
168720
- console.log(`Instance: ${match.claimed_by || '-'}`);
168721
- console.log(`Duration: ${duration}`);
168722
- console.log(`Created: ${match.created_at}`);
168723
- console.log(`Updated: ${match.updated_at}`);
168809
+ const detailTable = new cli_table3_1.default({
168810
+ style: { head: ['cyan', 'bold'], border: ['grey'] },
168811
+ wordWrap: false,
168812
+ });
168813
+ detailTable.push({ 'Task ID': match.id }, { State: stateColor(match.state) }, { Source: match.source }, { Workflow: match.workflow_id || '-' }, { Instance: match.claimed_by || '-' }, { Duration: duration }, { Created: match.created_at }, { Updated: match.updated_at });
168724
168814
  if (match.run_id)
168725
- console.log(`Run ID: ${match.run_id}`);
168726
- console.log(`Input: ${match.request_message}`);
168815
+ detailTable.push({ 'Run ID': match.run_id });
168816
+ detailTable.push({ Input: match.request_message });
168727
168817
  // Show metadata
168728
168818
  const meta = match.metadata;
168729
168819
  const metaKeys = Object.keys(meta).filter(k => k !== 'source');
168730
- if (metaKeys.length > 0) {
168731
- console.log(`\nMetadata:`);
168732
- for (const key of metaKeys) {
168733
- console.log(` ${key}: ${JSON.stringify(meta[key])}`);
168734
- }
168820
+ for (const key of metaKeys) {
168821
+ detailTable.push({ [key]: String(meta[key]) });
168735
168822
  }
168823
+ console.log(detailTable.toString());
168824
+ });
168825
+ }
168826
+ // ---------------------------------------------------------------------------
168827
+ // Subcommand: purge
168828
+ // ---------------------------------------------------------------------------
168829
+ async function handlePurge(flags) {
168830
+ const ageStr = typeof flags.age === 'string' ? flags.age : '7d';
168831
+ const match = ageStr.match(/^(\d+)([hdm])$/);
168832
+ if (!match) {
168833
+ console.error('Invalid --age format. Use e.g. 24h, 7d, 30d');
168834
+ process.exitCode = 1;
168835
+ return;
168836
+ }
168837
+ const value = parseInt(match[1], 10);
168838
+ const unit = match[2];
168839
+ const ms = unit === 'h' ? value * 3600_000 : unit === 'd' ? value * 86400_000 : value * 2592000_000;
168840
+ await withTaskStore(async (store) => {
168841
+ const deleted = store.purgeOldTasks(ms);
168842
+ console.log(`Purged ${deleted} terminal task(s) older than ${ageStr}.`);
168736
168843
  });
168737
168844
  }
168738
168845
  // ---------------------------------------------------------------------------
@@ -168746,28 +168853,33 @@ USAGE:
168746
168853
  visor tasks [command] [options]
168747
168854
 
168748
168855
  COMMANDS:
168749
- list List tasks (default)
168856
+ list List active tasks (default)
168750
168857
  show <task-id> Show task details (supports prefix match)
168751
168858
  stats Queue summary statistics
168752
168859
  cancel <task-id> Cancel a task
168860
+ purge [--age 7d] Delete old completed/failed tasks
168753
168861
  help Show this help
168754
168862
 
168755
168863
  OPTIONS:
168756
- --output <format> Output format: table (default), json, markdown
168864
+ --all Show all tasks including completed/failed history
168757
168865
  --state <state> Filter by state: submitted, working, completed, failed, canceled
168866
+ --search <text> Search tasks by input text
168867
+ --instance <id> Filter by visor instance ID
168758
168868
  --agent <workflow-id> Filter by agent/workflow
168759
168869
  --limit <n> Number of tasks to show (default: 20)
168870
+ --output <format> Output format: table (default), json, markdown
168760
168871
  --watch Refresh every 2 seconds
168761
168872
 
168762
168873
  EXAMPLES:
168763
- visor tasks List all tasks
168874
+ visor tasks List active tasks only
168875
+ visor tasks --all List all tasks including history
168876
+ visor tasks --state failed Show failed tasks
168877
+ visor tasks --search "auth" Search tasks by text
168764
168878
  visor tasks show abc123 Show full task details
168765
- visor tasks list --state working Show only working tasks
168766
- visor tasks list --agent security-review Show tasks for a specific agent
168767
- visor tasks list --output json JSON output
168768
168879
  visor tasks list --watch Live monitoring
168769
168880
  visor tasks stats Show queue statistics
168770
168881
  visor tasks cancel abc123 Cancel a task
168882
+ visor tasks purge --age 30d Delete tasks older than 30 days
168771
168883
  `);
168772
168884
  }
168773
168885
  // ---------------------------------------------------------------------------
@@ -168794,6 +168906,9 @@ async function handleTasksCommand(argv) {
168794
168906
  case 'cancel':
168795
168907
  await handleCancel(positional, flags);
168796
168908
  break;
168909
+ case 'purge':
168910
+ await handlePurge(flags);
168911
+ break;
168797
168912
  case 'help':
168798
168913
  printHelp();
168799
168914
  break;
@@ -171762,7 +171877,7 @@ async function handleDumpPolicyInput(checkId, argv) {
171762
171877
  let PolicyInputBuilder;
171763
171878
  try {
171764
171879
  // @ts-ignore — enterprise/ may not exist in OSS builds (caught at runtime)
171765
- const mod = await Promise.resolve().then(() => __importStar(__nccwpck_require__(71370)));
171880
+ const mod = await Promise.resolve().then(() => __importStar(__nccwpck_require__(17117)));
171766
171881
  PolicyInputBuilder = mod.PolicyInputBuilder;
171767
171882
  }
171768
171883
  catch {
@@ -172806,6 +172921,11 @@ async function main() {
172806
172921
  const { SqliteTaskStore } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(24711)));
172807
172922
  sharedTaskStore = new SqliteTaskStore();
172808
172923
  await sharedTaskStore.initialize();
172924
+ // Recover stale tasks from previous crashed runs
172925
+ const recovered = sharedTaskStore.failStaleTasks('Process terminated unexpectedly');
172926
+ if (recovered > 0) {
172927
+ logger_1.logger.info(`[TaskTracking] Recovered ${recovered} stale working task(s) → failed`);
172928
+ }
172809
172929
  logger_1.logger.info('[TaskTracking] Shared task store initialized');
172810
172930
  }
172811
172931
  catch (err) {
@@ -177791,6 +177911,1810 @@ class DependencyResolver {
177791
177911
  exports.DependencyResolver = DependencyResolver;
177792
177912
 
177793
177913
 
177914
+ /***/ }),
177915
+
177916
+ /***/ 50069:
177917
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
177918
+
177919
+ "use strict";
177920
+
177921
+ /**
177922
+ * Copyright (c) ProbeLabs. All rights reserved.
177923
+ * Licensed under the Elastic License 2.0; you may not use this file except
177924
+ * in compliance with the Elastic License 2.0.
177925
+ */
177926
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
177927
+ if (k2 === undefined) k2 = k;
177928
+ var desc = Object.getOwnPropertyDescriptor(m, k);
177929
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
177930
+ desc = { enumerable: true, get: function() { return m[k]; } };
177931
+ }
177932
+ Object.defineProperty(o, k2, desc);
177933
+ }) : (function(o, m, k, k2) {
177934
+ if (k2 === undefined) k2 = k;
177935
+ o[k2] = m[k];
177936
+ }));
177937
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
177938
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
177939
+ }) : function(o, v) {
177940
+ o["default"] = v;
177941
+ });
177942
+ var __importStar = (this && this.__importStar) || (function () {
177943
+ var ownKeys = function(o) {
177944
+ ownKeys = Object.getOwnPropertyNames || function (o) {
177945
+ var ar = [];
177946
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
177947
+ return ar;
177948
+ };
177949
+ return ownKeys(o);
177950
+ };
177951
+ return function (mod) {
177952
+ if (mod && mod.__esModule) return mod;
177953
+ var result = {};
177954
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
177955
+ __setModuleDefault(result, mod);
177956
+ return result;
177957
+ };
177958
+ })();
177959
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
177960
+ exports.LicenseValidator = void 0;
177961
+ const crypto = __importStar(__nccwpck_require__(76982));
177962
+ const fs = __importStar(__nccwpck_require__(79896));
177963
+ const path = __importStar(__nccwpck_require__(16928));
177964
+ class LicenseValidator {
177965
+ /** Ed25519 public key for license verification (PEM format). */
177966
+ static PUBLIC_KEY = '-----BEGIN PUBLIC KEY-----\n' +
177967
+ 'MCowBQYDK2VwAyEAI/Zd08EFmgIdrDm/HXd0l3/5GBt7R1PrdvhdmEXhJlU=\n' +
177968
+ '-----END PUBLIC KEY-----\n';
177969
+ cache = null;
177970
+ static CACHE_TTL = 5 * 60 * 1000; // 5 minutes
177971
+ static GRACE_PERIOD = 72 * 3600 * 1000; // 72 hours after expiry
177972
+ /**
177973
+ * Load and validate license from environment or file.
177974
+ *
177975
+ * Resolution order:
177976
+ * 1. VISOR_LICENSE env var (JWT string)
177977
+ * 2. VISOR_LICENSE_FILE env var (path to file)
177978
+ * 3. .visor-license in project root (cwd)
177979
+ * 4. .visor-license in ~/.config/visor/
177980
+ */
177981
+ async loadAndValidate() {
177982
+ // Return cached result if still fresh
177983
+ if (this.cache && Date.now() - this.cache.validatedAt < LicenseValidator.CACHE_TTL) {
177984
+ return this.cache.payload;
177985
+ }
177986
+ const token = this.resolveToken();
177987
+ if (!token)
177988
+ return null;
177989
+ const payload = this.verifyAndDecode(token);
177990
+ if (!payload)
177991
+ return null;
177992
+ this.cache = { payload, validatedAt: Date.now() };
177993
+ return payload;
177994
+ }
177995
+ /** Check if a specific feature is licensed */
177996
+ hasFeature(feature) {
177997
+ if (!this.cache)
177998
+ return false;
177999
+ return this.cache.payload.features.includes(feature);
178000
+ }
178001
+ /** Check if license is valid (with grace period) */
178002
+ isValid() {
178003
+ if (!this.cache)
178004
+ return false;
178005
+ const now = Date.now();
178006
+ const expiryMs = this.cache.payload.exp * 1000;
178007
+ return now < expiryMs + LicenseValidator.GRACE_PERIOD;
178008
+ }
178009
+ /** Check if the license is within its grace period (expired but still valid) */
178010
+ isInGracePeriod() {
178011
+ if (!this.cache)
178012
+ return false;
178013
+ const now = Date.now();
178014
+ const expiryMs = this.cache.payload.exp * 1000;
178015
+ return now >= expiryMs && now < expiryMs + LicenseValidator.GRACE_PERIOD;
178016
+ }
178017
+ resolveToken() {
178018
+ // 1. Direct env var
178019
+ if (process.env.VISOR_LICENSE) {
178020
+ return process.env.VISOR_LICENSE.trim();
178021
+ }
178022
+ // 2. File path from env (validate against path traversal)
178023
+ if (process.env.VISOR_LICENSE_FILE) {
178024
+ // path.resolve() produces an absolute path with all '..' segments resolved,
178025
+ // so a separate resolved.includes('..') check is unnecessary.
178026
+ const resolved = path.resolve(process.env.VISOR_LICENSE_FILE);
178027
+ const home = process.env.HOME || process.env.USERPROFILE || '';
178028
+ const allowedPrefixes = [path.normalize(process.cwd())];
178029
+ if (home)
178030
+ allowedPrefixes.push(path.normalize(path.join(home, '.config', 'visor')));
178031
+ // Resolve symlinks so an attacker cannot create a symlink inside an
178032
+ // allowed prefix that points to an arbitrary file outside it.
178033
+ let realPath;
178034
+ try {
178035
+ realPath = fs.realpathSync(resolved);
178036
+ }
178037
+ catch {
178038
+ return null; // File doesn't exist or isn't accessible
178039
+ }
178040
+ const isSafe = allowedPrefixes.some(prefix => realPath === prefix || realPath.startsWith(prefix + path.sep));
178041
+ if (!isSafe)
178042
+ return null;
178043
+ return this.readFile(realPath);
178044
+ }
178045
+ // 3. .visor-license in cwd
178046
+ const cwdPath = path.join(process.cwd(), '.visor-license');
178047
+ const cwdToken = this.readFile(cwdPath);
178048
+ if (cwdToken)
178049
+ return cwdToken;
178050
+ // 4. ~/.config/visor/.visor-license
178051
+ const home = process.env.HOME || process.env.USERPROFILE || '';
178052
+ if (home) {
178053
+ const configPath = path.join(home, '.config', 'visor', '.visor-license');
178054
+ const configToken = this.readFile(configPath);
178055
+ if (configToken)
178056
+ return configToken;
178057
+ }
178058
+ return null;
178059
+ }
178060
+ readFile(filePath) {
178061
+ try {
178062
+ return fs.readFileSync(filePath, 'utf-8').trim();
178063
+ }
178064
+ catch {
178065
+ return null;
178066
+ }
178067
+ }
178068
+ verifyAndDecode(token) {
178069
+ try {
178070
+ const parts = token.split('.');
178071
+ if (parts.length !== 3)
178072
+ return null;
178073
+ const [headerB64, payloadB64, signatureB64] = parts;
178074
+ // Decode header to verify algorithm
178075
+ const header = JSON.parse(Buffer.from(headerB64, 'base64url').toString());
178076
+ if (header.alg !== 'EdDSA')
178077
+ return null;
178078
+ // Verify signature
178079
+ const data = `${headerB64}.${payloadB64}`;
178080
+ const signature = Buffer.from(signatureB64, 'base64url');
178081
+ const publicKey = crypto.createPublicKey(LicenseValidator.PUBLIC_KEY);
178082
+ // Validate that the loaded public key is actually Ed25519 (OID 1.3.101.112).
178083
+ // This prevents algorithm-confusion attacks if the embedded key were ever
178084
+ // swapped to a different type.
178085
+ if (publicKey.asymmetricKeyType !== 'ed25519') {
178086
+ return null;
178087
+ }
178088
+ // Ed25519 verification: algorithm must be null because EdDSA performs its
178089
+ // own internal hashing (SHA-512) — passing a digest algorithm here would
178090
+ // cause Node.js to throw. The key type is validated above.
178091
+ const isValid = crypto.verify(null, Buffer.from(data), publicKey, signature);
178092
+ if (!isValid)
178093
+ return null;
178094
+ // Decode payload
178095
+ const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString());
178096
+ // Validate required fields
178097
+ if (!payload.org ||
178098
+ !Array.isArray(payload.features) ||
178099
+ typeof payload.exp !== 'number' ||
178100
+ typeof payload.iat !== 'number' ||
178101
+ !payload.sub) {
178102
+ return null;
178103
+ }
178104
+ // Check expiry (with grace period)
178105
+ const now = Date.now();
178106
+ const expiryMs = payload.exp * 1000;
178107
+ if (now >= expiryMs + LicenseValidator.GRACE_PERIOD) {
178108
+ return null;
178109
+ }
178110
+ return payload;
178111
+ }
178112
+ catch {
178113
+ return null;
178114
+ }
178115
+ }
178116
+ }
178117
+ exports.LicenseValidator = LicenseValidator;
178118
+
178119
+
178120
+ /***/ }),
178121
+
178122
+ /***/ 87068:
178123
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
178124
+
178125
+ "use strict";
178126
+
178127
+ /**
178128
+ * Copyright (c) ProbeLabs. All rights reserved.
178129
+ * Licensed under the Elastic License 2.0; you may not use this file except
178130
+ * in compliance with the Elastic License 2.0.
178131
+ */
178132
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
178133
+ if (k2 === undefined) k2 = k;
178134
+ var desc = Object.getOwnPropertyDescriptor(m, k);
178135
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
178136
+ desc = { enumerable: true, get: function() { return m[k]; } };
178137
+ }
178138
+ Object.defineProperty(o, k2, desc);
178139
+ }) : (function(o, m, k, k2) {
178140
+ if (k2 === undefined) k2 = k;
178141
+ o[k2] = m[k];
178142
+ }));
178143
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
178144
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
178145
+ }) : function(o, v) {
178146
+ o["default"] = v;
178147
+ });
178148
+ var __importStar = (this && this.__importStar) || (function () {
178149
+ var ownKeys = function(o) {
178150
+ ownKeys = Object.getOwnPropertyNames || function (o) {
178151
+ var ar = [];
178152
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
178153
+ return ar;
178154
+ };
178155
+ return ownKeys(o);
178156
+ };
178157
+ return function (mod) {
178158
+ if (mod && mod.__esModule) return mod;
178159
+ var result = {};
178160
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
178161
+ __setModuleDefault(result, mod);
178162
+ return result;
178163
+ };
178164
+ })();
178165
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
178166
+ exports.loadEnterprisePolicyEngine = loadEnterprisePolicyEngine;
178167
+ exports.loadEnterpriseStoreBackend = loadEnterpriseStoreBackend;
178168
+ const default_engine_1 = __nccwpck_require__(93866);
178169
+ /**
178170
+ * Load the enterprise policy engine if licensed, otherwise return the default no-op engine.
178171
+ *
178172
+ * This is the sole import boundary between OSS and enterprise code. Core code
178173
+ * must only import from this module (via dynamic `await import()`), never from
178174
+ * individual enterprise submodules.
178175
+ */
178176
+ async function loadEnterprisePolicyEngine(config) {
178177
+ try {
178178
+ const { LicenseValidator } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(50069)));
178179
+ const validator = new LicenseValidator();
178180
+ const license = await validator.loadAndValidate();
178181
+ if (!license || !validator.hasFeature('policy')) {
178182
+ return new default_engine_1.DefaultPolicyEngine();
178183
+ }
178184
+ if (validator.isInGracePeriod()) {
178185
+ // eslint-disable-next-line no-console
178186
+ console.warn('[visor:enterprise] License has expired but is within the 72-hour grace period. ' +
178187
+ 'Please renew your license.');
178188
+ }
178189
+ const { OpaPolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(39530)));
178190
+ const engine = new OpaPolicyEngine(config);
178191
+ await engine.initialize(config);
178192
+ return engine;
178193
+ }
178194
+ catch (err) {
178195
+ // Enterprise code not available or initialization failed
178196
+ const msg = err instanceof Error ? err.message : String(err);
178197
+ try {
178198
+ const { logger } = __nccwpck_require__(86999);
178199
+ logger.warn(`[PolicyEngine] Enterprise policy init failed, falling back to default: ${msg}`);
178200
+ }
178201
+ catch {
178202
+ // silent
178203
+ }
178204
+ return new default_engine_1.DefaultPolicyEngine();
178205
+ }
178206
+ }
178207
+ /**
178208
+ * Load the enterprise schedule store backend if licensed.
178209
+ *
178210
+ * @param driver Database driver ('postgresql', 'mysql', or 'mssql')
178211
+ * @param storageConfig Storage configuration with connection details
178212
+ * @param haConfig Optional HA configuration
178213
+ * @throws Error if enterprise license is not available or missing 'scheduler-sql' feature
178214
+ */
178215
+ async function loadEnterpriseStoreBackend(driver, storageConfig, haConfig) {
178216
+ const { LicenseValidator } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(50069)));
178217
+ const validator = new LicenseValidator();
178218
+ const license = await validator.loadAndValidate();
178219
+ if (!license || !validator.hasFeature('scheduler-sql')) {
178220
+ throw new Error(`The ${driver} schedule storage driver requires a Visor Enterprise license ` +
178221
+ `with the 'scheduler-sql' feature. Please upgrade or use driver: 'sqlite' (default).`);
178222
+ }
178223
+ if (validator.isInGracePeriod()) {
178224
+ // eslint-disable-next-line no-console
178225
+ console.warn('[visor:enterprise] License has expired but is within the 72-hour grace period. ' +
178226
+ 'Please renew your license.');
178227
+ }
178228
+ const { KnexStoreBackend } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(63737)));
178229
+ return new KnexStoreBackend(driver, storageConfig, haConfig);
178230
+ }
178231
+
178232
+
178233
+ /***/ }),
178234
+
178235
+ /***/ 628:
178236
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
178237
+
178238
+ "use strict";
178239
+
178240
+ /**
178241
+ * Copyright (c) ProbeLabs. All rights reserved.
178242
+ * Licensed under the Elastic License 2.0; you may not use this file except
178243
+ * in compliance with the Elastic License 2.0.
178244
+ */
178245
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
178246
+ if (k2 === undefined) k2 = k;
178247
+ var desc = Object.getOwnPropertyDescriptor(m, k);
178248
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
178249
+ desc = { enumerable: true, get: function() { return m[k]; } };
178250
+ }
178251
+ Object.defineProperty(o, k2, desc);
178252
+ }) : (function(o, m, k, k2) {
178253
+ if (k2 === undefined) k2 = k;
178254
+ o[k2] = m[k];
178255
+ }));
178256
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
178257
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
178258
+ }) : function(o, v) {
178259
+ o["default"] = v;
178260
+ });
178261
+ var __importStar = (this && this.__importStar) || (function () {
178262
+ var ownKeys = function(o) {
178263
+ ownKeys = Object.getOwnPropertyNames || function (o) {
178264
+ var ar = [];
178265
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
178266
+ return ar;
178267
+ };
178268
+ return ownKeys(o);
178269
+ };
178270
+ return function (mod) {
178271
+ if (mod && mod.__esModule) return mod;
178272
+ var result = {};
178273
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
178274
+ __setModuleDefault(result, mod);
178275
+ return result;
178276
+ };
178277
+ })();
178278
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
178279
+ exports.OpaCompiler = void 0;
178280
+ const fs = __importStar(__nccwpck_require__(79896));
178281
+ const path = __importStar(__nccwpck_require__(16928));
178282
+ const os = __importStar(__nccwpck_require__(70857));
178283
+ const crypto = __importStar(__nccwpck_require__(76982));
178284
+ const child_process_1 = __nccwpck_require__(35317);
178285
+ /**
178286
+ * OPA Rego Compiler - compiles .rego policy files to WASM bundles using the `opa` CLI.
178287
+ *
178288
+ * Handles:
178289
+ * - Resolving input paths to WASM bytes (direct .wasm, directory with policy.wasm, or .rego files)
178290
+ * - Compiling .rego files to WASM via `opa build`
178291
+ * - Caching compiled bundles based on content hashes
178292
+ * - Extracting policy.wasm from OPA tar.gz bundles
178293
+ *
178294
+ * Requires:
178295
+ * - `opa` CLI on PATH (only when auto-compiling .rego files)
178296
+ */
178297
+ class OpaCompiler {
178298
+ static CACHE_DIR = path.join(os.tmpdir(), 'visor-opa-cache');
178299
+ /**
178300
+ * Resolve the input paths to WASM bytes.
178301
+ *
178302
+ * Strategy:
178303
+ * 1. If any path is a .wasm file, read it directly
178304
+ * 2. If a directory contains policy.wasm, read it
178305
+ * 3. Otherwise, collect all .rego files and auto-compile via `opa build`
178306
+ */
178307
+ async resolveWasmBytes(paths) {
178308
+ // Collect .rego files and check for existing .wasm
178309
+ const regoFiles = [];
178310
+ for (const p of paths) {
178311
+ const resolved = path.resolve(p);
178312
+ // Reject paths containing '..' after resolution (path traversal)
178313
+ if (path.normalize(resolved).includes('..')) {
178314
+ throw new Error(`Policy path contains traversal sequences: ${p}`);
178315
+ }
178316
+ // Direct .wasm file
178317
+ if (resolved.endsWith('.wasm') && fs.existsSync(resolved)) {
178318
+ return fs.readFileSync(resolved);
178319
+ }
178320
+ if (!fs.existsSync(resolved))
178321
+ continue;
178322
+ const stat = fs.statSync(resolved);
178323
+ if (stat.isDirectory()) {
178324
+ // Check for pre-compiled policy.wasm in directory
178325
+ const wasmCandidate = path.join(resolved, 'policy.wasm');
178326
+ if (fs.existsSync(wasmCandidate)) {
178327
+ return fs.readFileSync(wasmCandidate);
178328
+ }
178329
+ // Collect all .rego files from directory
178330
+ const files = fs.readdirSync(resolved);
178331
+ for (const f of files) {
178332
+ if (f.endsWith('.rego')) {
178333
+ regoFiles.push(path.join(resolved, f));
178334
+ }
178335
+ }
178336
+ }
178337
+ else if (resolved.endsWith('.rego')) {
178338
+ regoFiles.push(resolved);
178339
+ }
178340
+ }
178341
+ if (regoFiles.length === 0) {
178342
+ throw new Error(`OPA WASM evaluator: no .wasm bundle or .rego files found in: ${paths.join(', ')}`);
178343
+ }
178344
+ // Auto-compile .rego -> .wasm
178345
+ return this.compileRego(regoFiles);
178346
+ }
178347
+ /**
178348
+ * Auto-compile .rego files to a WASM bundle using the `opa` CLI.
178349
+ *
178350
+ * Caches the compiled bundle based on a content hash of all input .rego files
178351
+ * so subsequent runs skip compilation if policies haven't changed.
178352
+ */
178353
+ compileRego(regoFiles) {
178354
+ // Check that `opa` CLI is available
178355
+ try {
178356
+ (0, child_process_1.execFileSync)('opa', ['version'], { stdio: 'pipe' });
178357
+ }
178358
+ catch {
178359
+ throw new Error('OPA CLI (`opa`) not found on PATH. Install it from https://www.openpolicyagent.org/docs/latest/#running-opa\n' +
178360
+ 'Or pre-compile your .rego files: opa build -t wasm -e visor -o bundle.tar.gz ' +
178361
+ regoFiles.join(' '));
178362
+ }
178363
+ // Compute content hash for cache key
178364
+ const hash = crypto.createHash('sha256');
178365
+ for (const f of regoFiles.sort()) {
178366
+ hash.update(fs.readFileSync(f));
178367
+ hash.update(f); // include filename for disambiguation
178368
+ }
178369
+ const cacheKey = hash.digest('hex').slice(0, 16);
178370
+ const cacheDir = OpaCompiler.CACHE_DIR;
178371
+ const cachedWasm = path.join(cacheDir, `${cacheKey}.wasm`);
178372
+ // Return cached bundle if still valid
178373
+ if (fs.existsSync(cachedWasm)) {
178374
+ return fs.readFileSync(cachedWasm);
178375
+ }
178376
+ // Compile to WASM via opa build
178377
+ fs.mkdirSync(cacheDir, { recursive: true });
178378
+ const bundleTar = path.join(cacheDir, `${cacheKey}-bundle.tar.gz`);
178379
+ try {
178380
+ const args = [
178381
+ 'build',
178382
+ '-t',
178383
+ 'wasm',
178384
+ '-e',
178385
+ 'visor', // entrypoint: the visor package tree
178386
+ '-o',
178387
+ bundleTar,
178388
+ ...regoFiles,
178389
+ ];
178390
+ (0, child_process_1.execFileSync)('opa', args, {
178391
+ stdio: 'pipe',
178392
+ timeout: 30000,
178393
+ });
178394
+ }
178395
+ catch (err) {
178396
+ const stderr = err?.stderr?.toString() || '';
178397
+ throw new Error(`Failed to compile .rego files to WASM:\n${stderr}\n` +
178398
+ 'Ensure your .rego files are valid and the `opa` CLI is installed.');
178399
+ }
178400
+ // Extract policy.wasm from the tar.gz bundle
178401
+ // OPA bundles are tar.gz with /policy.wasm inside
178402
+ try {
178403
+ (0, child_process_1.execFileSync)('tar', ['-xzf', bundleTar, '-C', cacheDir, '/policy.wasm'], {
178404
+ stdio: 'pipe',
178405
+ });
178406
+ const extractedWasm = path.join(cacheDir, 'policy.wasm');
178407
+ if (fs.existsSync(extractedWasm)) {
178408
+ // Move to cache-key named file
178409
+ fs.renameSync(extractedWasm, cachedWasm);
178410
+ }
178411
+ }
178412
+ catch {
178413
+ // Some tar implementations don't like leading /
178414
+ try {
178415
+ (0, child_process_1.execFileSync)('tar', ['-xzf', bundleTar, '-C', cacheDir, 'policy.wasm'], {
178416
+ stdio: 'pipe',
178417
+ });
178418
+ const extractedWasm = path.join(cacheDir, 'policy.wasm');
178419
+ if (fs.existsSync(extractedWasm)) {
178420
+ fs.renameSync(extractedWasm, cachedWasm);
178421
+ }
178422
+ }
178423
+ catch (err2) {
178424
+ throw new Error(`Failed to extract policy.wasm from OPA bundle: ${err2?.message || err2}`);
178425
+ }
178426
+ }
178427
+ // Clean up tar
178428
+ try {
178429
+ fs.unlinkSync(bundleTar);
178430
+ }
178431
+ catch { }
178432
+ if (!fs.existsSync(cachedWasm)) {
178433
+ throw new Error('OPA build succeeded but policy.wasm was not found in the bundle');
178434
+ }
178435
+ return fs.readFileSync(cachedWasm);
178436
+ }
178437
+ }
178438
+ exports.OpaCompiler = OpaCompiler;
178439
+
178440
+
178441
+ /***/ }),
178442
+
178443
+ /***/ 44693:
178444
+ /***/ ((__unused_webpack_module, exports) => {
178445
+
178446
+ "use strict";
178447
+
178448
+ /**
178449
+ * Copyright (c) ProbeLabs. All rights reserved.
178450
+ * Licensed under the Elastic License 2.0; you may not use this file except
178451
+ * in compliance with the Elastic License 2.0.
178452
+ */
178453
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
178454
+ exports.OpaHttpEvaluator = void 0;
178455
+ /**
178456
+ * OPA HTTP Evaluator - evaluates policies via an external OPA server's REST API.
178457
+ *
178458
+ * Uses the built-in `fetch` API (Node 18+), so no extra dependencies are needed.
178459
+ */
178460
+ class OpaHttpEvaluator {
178461
+ baseUrl;
178462
+ timeout;
178463
+ constructor(baseUrl, timeout = 5000) {
178464
+ // Validate URL format and protocol
178465
+ let parsed;
178466
+ try {
178467
+ parsed = new URL(baseUrl);
178468
+ }
178469
+ catch {
178470
+ throw new Error(`OPA HTTP evaluator: invalid URL: ${baseUrl}`);
178471
+ }
178472
+ if (!['http:', 'https:'].includes(parsed.protocol)) {
178473
+ throw new Error(`OPA HTTP evaluator: url must use http:// or https:// protocol, got: ${baseUrl}`);
178474
+ }
178475
+ // Block cloud metadata, loopback, link-local, and private network addresses
178476
+ const hostname = parsed.hostname;
178477
+ if (this.isBlockedHostname(hostname)) {
178478
+ throw new Error(`OPA HTTP evaluator: url must not point to internal, loopback, or private network addresses`);
178479
+ }
178480
+ // Normalize: strip trailing slash
178481
+ this.baseUrl = baseUrl.replace(/\/+$/, '');
178482
+ this.timeout = timeout;
178483
+ }
178484
+ /**
178485
+ * Check if a hostname is blocked due to SSRF concerns.
178486
+ *
178487
+ * Blocks:
178488
+ * - Loopback addresses (127.x.x.x, localhost, 0.0.0.0, ::1)
178489
+ * - Link-local addresses (169.254.x.x)
178490
+ * - Private networks (10.x.x.x, 172.16-31.x.x, 192.168.x.x)
178491
+ * - IPv6 unique local addresses (fd00::/8)
178492
+ * - Cloud metadata services (*.internal)
178493
+ */
178494
+ isBlockedHostname(hostname) {
178495
+ if (!hostname)
178496
+ return true; // block empty hostnames
178497
+ // Normalize hostname: lowercase and remove brackets for IPv6
178498
+ const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, '');
178499
+ // Block .internal domains (cloud metadata services)
178500
+ if (normalized === 'metadata.google.internal' || normalized.endsWith('.internal')) {
178501
+ return true;
178502
+ }
178503
+ // Block localhost variants
178504
+ if (normalized === 'localhost' || normalized === 'localhost.localdomain') {
178505
+ return true;
178506
+ }
178507
+ // Block IPv6 loopback
178508
+ if (normalized === '::1' || normalized === '0:0:0:0:0:0:0:1') {
178509
+ return true;
178510
+ }
178511
+ // Check IPv4 patterns
178512
+ const ipv4Pattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
178513
+ const ipv4Match = normalized.match(ipv4Pattern);
178514
+ if (ipv4Match) {
178515
+ const octets = ipv4Match.slice(1, 5).map(Number);
178516
+ // Validate octets are in range [0, 255]
178517
+ if (octets.some(octet => octet > 255)) {
178518
+ return false;
178519
+ }
178520
+ const [a, b] = octets;
178521
+ // Block loopback: 127.0.0.0/8
178522
+ if (a === 127) {
178523
+ return true;
178524
+ }
178525
+ // Block 0.0.0.0/8 (this host)
178526
+ if (a === 0) {
178527
+ return true;
178528
+ }
178529
+ // Block link-local: 169.254.0.0/16
178530
+ if (a === 169 && b === 254) {
178531
+ return true;
178532
+ }
178533
+ // Block private networks
178534
+ // 10.0.0.0/8
178535
+ if (a === 10) {
178536
+ return true;
178537
+ }
178538
+ // 172.16.0.0/12 (172.16.x.x through 172.31.x.x)
178539
+ if (a === 172 && b >= 16 && b <= 31) {
178540
+ return true;
178541
+ }
178542
+ // 192.168.0.0/16
178543
+ if (a === 192 && b === 168) {
178544
+ return true;
178545
+ }
178546
+ }
178547
+ // Check IPv6 patterns
178548
+ // Block unique local addresses: fd00::/8
178549
+ if (normalized.startsWith('fd') || normalized.startsWith('fc')) {
178550
+ return true;
178551
+ }
178552
+ // Block link-local: fe80::/10
178553
+ if (normalized.startsWith('fe80:')) {
178554
+ return true;
178555
+ }
178556
+ return false;
178557
+ }
178558
+ /**
178559
+ * Evaluate a policy rule against an input document via OPA REST API.
178560
+ *
178561
+ * @param input - The input document to evaluate
178562
+ * @param rulePath - OPA rule path (e.g., 'visor/check/execute')
178563
+ * @returns The result object from OPA, or undefined on error
178564
+ */
178565
+ async evaluate(input, rulePath) {
178566
+ // OPA Data API: POST /v1/data/<path>
178567
+ const encodedPath = rulePath
178568
+ .split('/')
178569
+ .map(s => encodeURIComponent(s))
178570
+ .join('/');
178571
+ const url = `${this.baseUrl}/v1/data/${encodedPath}`;
178572
+ const controller = new AbortController();
178573
+ const timer = setTimeout(() => controller.abort(), this.timeout);
178574
+ try {
178575
+ const response = await fetch(url, {
178576
+ method: 'POST',
178577
+ headers: { 'Content-Type': 'application/json' },
178578
+ body: JSON.stringify({ input }),
178579
+ signal: controller.signal,
178580
+ });
178581
+ if (!response.ok) {
178582
+ throw new Error(`OPA HTTP ${response.status}: ${response.statusText}`);
178583
+ }
178584
+ let body;
178585
+ try {
178586
+ body = await response.json();
178587
+ }
178588
+ catch (jsonErr) {
178589
+ throw new Error(`OPA HTTP evaluator: failed to parse JSON response: ${jsonErr instanceof Error ? jsonErr.message : String(jsonErr)}`);
178590
+ }
178591
+ // OPA returns { result: { ... } }
178592
+ return body?.result;
178593
+ }
178594
+ finally {
178595
+ clearTimeout(timer);
178596
+ }
178597
+ }
178598
+ async shutdown() {
178599
+ // No persistent connections to close
178600
+ }
178601
+ }
178602
+ exports.OpaHttpEvaluator = OpaHttpEvaluator;
178603
+
178604
+
178605
+ /***/ }),
178606
+
178607
+ /***/ 39530:
178608
+ /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
178609
+
178610
+ "use strict";
178611
+
178612
+ /**
178613
+ * Copyright (c) ProbeLabs. All rights reserved.
178614
+ * Licensed under the Elastic License 2.0; you may not use this file except
178615
+ * in compliance with the Elastic License 2.0.
178616
+ */
178617
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
178618
+ exports.OpaPolicyEngine = void 0;
178619
+ const opa_wasm_evaluator_1 = __nccwpck_require__(8613);
178620
+ const opa_http_evaluator_1 = __nccwpck_require__(44693);
178621
+ const policy_input_builder_1 = __nccwpck_require__(17117);
178622
+ /**
178623
+ * Enterprise OPA Policy Engine.
178624
+ *
178625
+ * Wraps both WASM (local) and HTTP (remote) OPA evaluators behind the
178626
+ * OSS PolicyEngine interface. All OPA input building and role resolution
178627
+ * is handled internally — the OSS call sites pass only plain types.
178628
+ */
178629
+ class OpaPolicyEngine {
178630
+ evaluator = null;
178631
+ fallback;
178632
+ timeout;
178633
+ config;
178634
+ inputBuilder = null;
178635
+ logger = null;
178636
+ constructor(config) {
178637
+ this.config = config;
178638
+ this.fallback = config.fallback || 'deny';
178639
+ this.timeout = config.timeout || 5000;
178640
+ }
178641
+ async initialize(config) {
178642
+ // Resolve logger once at initialization
178643
+ try {
178644
+ this.logger = (__nccwpck_require__(86999).logger);
178645
+ }
178646
+ catch {
178647
+ // logger not available in this context
178648
+ }
178649
+ // Build actor/repo context from environment (available at engine init time)
178650
+ const actor = {
178651
+ authorAssociation: process.env.VISOR_AUTHOR_ASSOCIATION,
178652
+ login: process.env.VISOR_AUTHOR_LOGIN || process.env.GITHUB_ACTOR,
178653
+ isLocalMode: !process.env.GITHUB_ACTIONS,
178654
+ };
178655
+ const repo = {
178656
+ owner: process.env.GITHUB_REPOSITORY_OWNER,
178657
+ name: process.env.GITHUB_REPOSITORY?.split('/')[1],
178658
+ branch: process.env.GITHUB_HEAD_REF,
178659
+ baseBranch: process.env.GITHUB_BASE_REF,
178660
+ event: process.env.GITHUB_EVENT_NAME,
178661
+ };
178662
+ const prNum = process.env.GITHUB_PR_NUMBER
178663
+ ? parseInt(process.env.GITHUB_PR_NUMBER, 10)
178664
+ : undefined;
178665
+ const pullRequest = {
178666
+ number: prNum !== undefined && Number.isFinite(prNum) ? prNum : undefined,
178667
+ };
178668
+ this.inputBuilder = new policy_input_builder_1.PolicyInputBuilder(config, actor, repo, pullRequest);
178669
+ if (config.engine === 'local') {
178670
+ if (!config.rules) {
178671
+ throw new Error('OPA local mode requires `policy.rules` path to .wasm or .rego files');
178672
+ }
178673
+ const wasm = new opa_wasm_evaluator_1.OpaWasmEvaluator();
178674
+ await wasm.initialize(config.rules);
178675
+ if (config.data) {
178676
+ wasm.loadData(config.data);
178677
+ }
178678
+ this.evaluator = wasm;
178679
+ }
178680
+ else if (config.engine === 'remote') {
178681
+ if (!config.url) {
178682
+ throw new Error('OPA remote mode requires `policy.url` pointing to OPA server');
178683
+ }
178684
+ this.evaluator = new opa_http_evaluator_1.OpaHttpEvaluator(config.url, this.timeout);
178685
+ }
178686
+ else {
178687
+ this.evaluator = null;
178688
+ }
178689
+ }
178690
+ /**
178691
+ * Update actor/repo/PR context (e.g., after PR info becomes available).
178692
+ * Called by the enterprise loader when engine context is enriched.
178693
+ */
178694
+ setActorContext(actor, repo, pullRequest) {
178695
+ this.inputBuilder = new policy_input_builder_1.PolicyInputBuilder(this.config, actor, repo, pullRequest);
178696
+ }
178697
+ async evaluateCheckExecution(checkId, checkConfig) {
178698
+ if (!this.evaluator || !this.inputBuilder)
178699
+ return { allowed: true };
178700
+ const cfg = checkConfig && typeof checkConfig === 'object'
178701
+ ? checkConfig
178702
+ : {};
178703
+ const policyOverride = cfg.policy;
178704
+ const input = this.inputBuilder.forCheckExecution({
178705
+ id: checkId,
178706
+ type: cfg.type || 'ai',
178707
+ group: cfg.group,
178708
+ tags: cfg.tags,
178709
+ criticality: cfg.criticality,
178710
+ sandbox: cfg.sandbox,
178711
+ policy: policyOverride,
178712
+ });
178713
+ return this.doEvaluate(input, this.resolveRulePath('check.execute', policyOverride?.rule));
178714
+ }
178715
+ async evaluateToolInvocation(serverName, methodName, transport) {
178716
+ if (!this.evaluator || !this.inputBuilder)
178717
+ return { allowed: true };
178718
+ const input = this.inputBuilder.forToolInvocation(serverName, methodName, transport);
178719
+ return this.doEvaluate(input, 'visor/tool/invoke');
178720
+ }
178721
+ async evaluateCapabilities(checkId, capabilities) {
178722
+ if (!this.evaluator || !this.inputBuilder)
178723
+ return { allowed: true };
178724
+ const input = this.inputBuilder.forCapabilityResolve(checkId, capabilities);
178725
+ return this.doEvaluate(input, 'visor/capability/resolve');
178726
+ }
178727
+ async shutdown() {
178728
+ if (this.evaluator && 'shutdown' in this.evaluator) {
178729
+ await this.evaluator.shutdown();
178730
+ }
178731
+ this.evaluator = null;
178732
+ this.inputBuilder = null;
178733
+ }
178734
+ resolveRulePath(defaultScope, override) {
178735
+ if (override) {
178736
+ return override.startsWith('visor/') ? override : `visor/${override}`;
178737
+ }
178738
+ return `visor/${defaultScope.replace(/\./g, '/')}`;
178739
+ }
178740
+ async doEvaluate(input, rulePath) {
178741
+ try {
178742
+ this.logger?.debug(`[PolicyEngine] Evaluating ${rulePath}`, JSON.stringify(input));
178743
+ let timer;
178744
+ const timeoutPromise = new Promise((_resolve, reject) => {
178745
+ timer = setTimeout(() => reject(new Error('policy evaluation timeout')), this.timeout);
178746
+ });
178747
+ try {
178748
+ const result = await Promise.race([this.rawEvaluate(input, rulePath), timeoutPromise]);
178749
+ const decision = this.parseDecision(result);
178750
+ // In warn mode, override denied decisions to allowed but flag as warn
178751
+ if (!decision.allowed && this.fallback === 'warn') {
178752
+ decision.allowed = true;
178753
+ decision.warn = true;
178754
+ decision.reason = `audit: ${decision.reason || 'policy denied'}`;
178755
+ }
178756
+ this.logger?.debug(`[PolicyEngine] Decision for ${rulePath}: allowed=${decision.allowed}, warn=${decision.warn || false}, reason=${decision.reason || 'none'}`);
178757
+ return decision;
178758
+ }
178759
+ finally {
178760
+ if (timer)
178761
+ clearTimeout(timer);
178762
+ }
178763
+ }
178764
+ catch (err) {
178765
+ const msg = err instanceof Error ? err.message : String(err);
178766
+ this.logger?.warn(`[PolicyEngine] Evaluation failed for ${rulePath}: ${msg}`);
178767
+ return {
178768
+ allowed: this.fallback === 'allow' || this.fallback === 'warn',
178769
+ warn: this.fallback === 'warn' ? true : undefined,
178770
+ reason: `policy evaluation failed, fallback=${this.fallback}`,
178771
+ };
178772
+ }
178773
+ }
178774
+ async rawEvaluate(input, rulePath) {
178775
+ if (this.evaluator instanceof opa_wasm_evaluator_1.OpaWasmEvaluator) {
178776
+ const result = await this.evaluator.evaluate(input);
178777
+ // WASM compiled with `-e visor` entrypoint returns the full visor package tree.
178778
+ // Navigate to the specific rule subtree using rulePath segments.
178779
+ // e.g., 'visor/check/execute' → result.check.execute
178780
+ return this.navigateWasmResult(result, rulePath);
178781
+ }
178782
+ return this.evaluator.evaluate(input, rulePath);
178783
+ }
178784
+ /**
178785
+ * Navigate nested OPA WASM result tree to reach the specific rule's output.
178786
+ * The WASM entrypoint `-e visor` means the result root IS the visor package,
178787
+ * so we strip the `visor/` prefix and walk the remaining segments.
178788
+ */
178789
+ navigateWasmResult(result, rulePath) {
178790
+ if (!result || typeof result !== 'object')
178791
+ return result;
178792
+ // Strip the 'visor/' prefix (matches our compilation entrypoint)
178793
+ const segments = rulePath.replace(/^visor\//, '').split('/');
178794
+ let current = result;
178795
+ for (const seg of segments) {
178796
+ if (current && typeof current === 'object' && seg in current) {
178797
+ current = current[seg];
178798
+ }
178799
+ else {
178800
+ return undefined; // path not found in result tree
178801
+ }
178802
+ }
178803
+ return current;
178804
+ }
178805
+ parseDecision(result) {
178806
+ if (result === undefined || result === null) {
178807
+ return {
178808
+ allowed: this.fallback === 'allow' || this.fallback === 'warn',
178809
+ warn: this.fallback === 'warn' ? true : undefined,
178810
+ reason: this.fallback === 'warn' ? 'audit: no policy result' : 'no policy result',
178811
+ };
178812
+ }
178813
+ const allowed = result.allowed !== false;
178814
+ const decision = {
178815
+ allowed,
178816
+ reason: result.reason,
178817
+ };
178818
+ if (result.capabilities) {
178819
+ decision.capabilities = result.capabilities;
178820
+ }
178821
+ return decision;
178822
+ }
178823
+ }
178824
+ exports.OpaPolicyEngine = OpaPolicyEngine;
178825
+
178826
+
178827
+ /***/ }),
178828
+
178829
+ /***/ 8613:
178830
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
178831
+
178832
+ "use strict";
178833
+
178834
+ /**
178835
+ * Copyright (c) ProbeLabs. All rights reserved.
178836
+ * Licensed under the Elastic License 2.0; you may not use this file except
178837
+ * in compliance with the Elastic License 2.0.
178838
+ */
178839
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
178840
+ if (k2 === undefined) k2 = k;
178841
+ var desc = Object.getOwnPropertyDescriptor(m, k);
178842
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
178843
+ desc = { enumerable: true, get: function() { return m[k]; } };
178844
+ }
178845
+ Object.defineProperty(o, k2, desc);
178846
+ }) : (function(o, m, k, k2) {
178847
+ if (k2 === undefined) k2 = k;
178848
+ o[k2] = m[k];
178849
+ }));
178850
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
178851
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
178852
+ }) : function(o, v) {
178853
+ o["default"] = v;
178854
+ });
178855
+ var __importStar = (this && this.__importStar) || (function () {
178856
+ var ownKeys = function(o) {
178857
+ ownKeys = Object.getOwnPropertyNames || function (o) {
178858
+ var ar = [];
178859
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
178860
+ return ar;
178861
+ };
178862
+ return ownKeys(o);
178863
+ };
178864
+ return function (mod) {
178865
+ if (mod && mod.__esModule) return mod;
178866
+ var result = {};
178867
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
178868
+ __setModuleDefault(result, mod);
178869
+ return result;
178870
+ };
178871
+ })();
178872
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
178873
+ exports.OpaWasmEvaluator = void 0;
178874
+ const fs = __importStar(__nccwpck_require__(79896));
178875
+ const path = __importStar(__nccwpck_require__(16928));
178876
+ const opa_compiler_1 = __nccwpck_require__(628);
178877
+ /**
178878
+ * OPA WASM Evaluator - loads and evaluates OPA policies locally.
178879
+ *
178880
+ * Supports three input formats:
178881
+ * 1. Pre-compiled `.wasm` bundle — loaded directly (fastest startup)
178882
+ * 2. `.rego` files or directory — auto-compiled to WASM via `opa build` CLI
178883
+ * 3. Directory with `policy.wasm` inside — loaded directly
178884
+ *
178885
+ * Compilation and caching of .rego files is delegated to {@link OpaCompiler}.
178886
+ *
178887
+ * Requires:
178888
+ * - `@open-policy-agent/opa-wasm` npm package (optional dep)
178889
+ * - `opa` CLI on PATH (only when auto-compiling .rego files)
178890
+ */
178891
+ class OpaWasmEvaluator {
178892
+ policy = null;
178893
+ dataDocument = {};
178894
+ compiler = new opa_compiler_1.OpaCompiler();
178895
+ async initialize(rulesPath) {
178896
+ const paths = Array.isArray(rulesPath) ? rulesPath : [rulesPath];
178897
+ const wasmBytes = await this.compiler.resolveWasmBytes(paths);
178898
+ try {
178899
+ // Use createRequire to load the optional dep at runtime without ncc bundling it.
178900
+ // `new Function('id', 'return require(id)')` fails in ncc bundles because
178901
+ // `require` is not in the `new Function` scope. `createRequire` works correctly
178902
+ // because it creates a real Node.js require rooted at the given path.
178903
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
178904
+ const { createRequire } = __nccwpck_require__(73339);
178905
+ const runtimeRequire = createRequire(__filename);
178906
+ const opaWasm = runtimeRequire('@open-policy-agent/opa-wasm');
178907
+ const loadPolicy = opaWasm.loadPolicy || opaWasm.default?.loadPolicy;
178908
+ if (!loadPolicy) {
178909
+ throw new Error('loadPolicy not found in @open-policy-agent/opa-wasm');
178910
+ }
178911
+ this.policy = await loadPolicy(wasmBytes);
178912
+ }
178913
+ catch (err) {
178914
+ if (err?.code === 'MODULE_NOT_FOUND' || err?.code === 'ERR_MODULE_NOT_FOUND') {
178915
+ throw new Error('OPA WASM evaluator requires @open-policy-agent/opa-wasm. ' +
178916
+ 'Install it with: npm install @open-policy-agent/opa-wasm');
178917
+ }
178918
+ throw err;
178919
+ }
178920
+ }
178921
+ /**
178922
+ * Load external data from a JSON file to use as the OPA data document.
178923
+ * The loaded data will be passed to `policy.setData()` during evaluation,
178924
+ * making it available in Rego via `data.<key>`.
178925
+ */
178926
+ loadData(dataPath) {
178927
+ const resolved = path.resolve(dataPath);
178928
+ if (path.normalize(resolved).includes('..')) {
178929
+ throw new Error(`Data path contains traversal sequences: ${dataPath}`);
178930
+ }
178931
+ if (!fs.existsSync(resolved)) {
178932
+ throw new Error(`OPA data file not found: ${resolved}`);
178933
+ }
178934
+ const stat = fs.statSync(resolved);
178935
+ if (stat.size > 10 * 1024 * 1024) {
178936
+ throw new Error(`OPA data file exceeds 10MB limit: ${resolved} (${stat.size} bytes)`);
178937
+ }
178938
+ const raw = fs.readFileSync(resolved, 'utf-8');
178939
+ try {
178940
+ const parsed = JSON.parse(raw);
178941
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
178942
+ throw new Error('OPA data file must contain a JSON object (not an array or primitive)');
178943
+ }
178944
+ this.dataDocument = parsed;
178945
+ }
178946
+ catch (err) {
178947
+ if (err.message.startsWith('OPA data file must')) {
178948
+ throw err;
178949
+ }
178950
+ throw new Error(`Failed to parse OPA data file ${resolved}: ${err.message}`);
178951
+ }
178952
+ }
178953
+ async evaluate(input) {
178954
+ if (!this.policy) {
178955
+ throw new Error('OPA WASM evaluator not initialized');
178956
+ }
178957
+ this.policy.setData(this.dataDocument);
178958
+ const resultSet = this.policy.evaluate(input);
178959
+ if (Array.isArray(resultSet) && resultSet.length > 0) {
178960
+ return resultSet[0].result;
178961
+ }
178962
+ return undefined;
178963
+ }
178964
+ async shutdown() {
178965
+ if (this.policy) {
178966
+ // opa-wasm policy objects may have a close/free method for WASM cleanup
178967
+ if (typeof this.policy.close === 'function') {
178968
+ try {
178969
+ this.policy.close();
178970
+ }
178971
+ catch { }
178972
+ }
178973
+ else if (typeof this.policy.free === 'function') {
178974
+ try {
178975
+ this.policy.free();
178976
+ }
178977
+ catch { }
178978
+ }
178979
+ }
178980
+ this.policy = null;
178981
+ }
178982
+ }
178983
+ exports.OpaWasmEvaluator = OpaWasmEvaluator;
178984
+
178985
+
178986
+ /***/ }),
178987
+
178988
+ /***/ 17117:
178989
+ /***/ ((__unused_webpack_module, exports) => {
178990
+
178991
+ "use strict";
178992
+
178993
+ /**
178994
+ * Copyright (c) ProbeLabs. All rights reserved.
178995
+ * Licensed under the Elastic License 2.0; you may not use this file except
178996
+ * in compliance with the Elastic License 2.0.
178997
+ */
178998
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
178999
+ exports.PolicyInputBuilder = void 0;
179000
+ /**
179001
+ * Builds OPA-compatible input documents from engine context.
179002
+ *
179003
+ * Resolves actor roles from the `policy.roles` config section by matching
179004
+ * the actor's authorAssociation and login against role definitions.
179005
+ */
179006
+ class PolicyInputBuilder {
179007
+ roles;
179008
+ actor;
179009
+ repository;
179010
+ pullRequest;
179011
+ constructor(policyConfig, actor, repository, pullRequest) {
179012
+ this.roles = policyConfig.roles || {};
179013
+ this.actor = actor;
179014
+ this.repository = repository;
179015
+ this.pullRequest = pullRequest;
179016
+ }
179017
+ /** Resolve which roles apply to the current actor. */
179018
+ resolveRoles() {
179019
+ const matched = [];
179020
+ for (const [roleName, roleConfig] of Object.entries(this.roles)) {
179021
+ let identityMatch = false;
179022
+ if (roleConfig.author_association &&
179023
+ this.actor.authorAssociation &&
179024
+ roleConfig.author_association.includes(this.actor.authorAssociation)) {
179025
+ identityMatch = true;
179026
+ }
179027
+ if (!identityMatch &&
179028
+ roleConfig.users &&
179029
+ this.actor.login &&
179030
+ roleConfig.users.includes(this.actor.login)) {
179031
+ identityMatch = true;
179032
+ }
179033
+ // Slack user ID match
179034
+ if (!identityMatch &&
179035
+ roleConfig.slack_users &&
179036
+ this.actor.slack?.userId &&
179037
+ roleConfig.slack_users.includes(this.actor.slack.userId)) {
179038
+ identityMatch = true;
179039
+ }
179040
+ // Email match (case-insensitive)
179041
+ if (!identityMatch && roleConfig.emails && this.actor.slack?.email) {
179042
+ const actorEmail = this.actor.slack.email.toLowerCase();
179043
+ if (roleConfig.emails.some(e => e.toLowerCase() === actorEmail)) {
179044
+ identityMatch = true;
179045
+ }
179046
+ }
179047
+ // Note: teams-based role resolution requires GitHub API access (read:org scope)
179048
+ // and is not yet implemented. If configured, the role will not match via teams.
179049
+ if (!identityMatch)
179050
+ continue;
179051
+ // slack_channels gate: if set, the role only applies when triggered from one of these channels
179052
+ if (roleConfig.slack_channels && roleConfig.slack_channels.length > 0) {
179053
+ if (!this.actor.slack?.channelId ||
179054
+ !roleConfig.slack_channels.includes(this.actor.slack.channelId)) {
179055
+ continue;
179056
+ }
179057
+ }
179058
+ matched.push(roleName);
179059
+ }
179060
+ return matched;
179061
+ }
179062
+ buildActor() {
179063
+ return {
179064
+ authorAssociation: this.actor.authorAssociation,
179065
+ login: this.actor.login,
179066
+ roles: this.resolveRoles(),
179067
+ isLocalMode: this.actor.isLocalMode,
179068
+ ...(this.actor.slack && { slack: this.actor.slack }),
179069
+ };
179070
+ }
179071
+ forCheckExecution(check) {
179072
+ return {
179073
+ scope: 'check.execute',
179074
+ check: {
179075
+ id: check.id,
179076
+ type: check.type,
179077
+ group: check.group,
179078
+ tags: check.tags,
179079
+ criticality: check.criticality,
179080
+ sandbox: check.sandbox,
179081
+ policy: check.policy,
179082
+ },
179083
+ actor: this.buildActor(),
179084
+ repository: this.repository,
179085
+ pullRequest: this.pullRequest,
179086
+ };
179087
+ }
179088
+ forToolInvocation(serverName, methodName, transport) {
179089
+ return {
179090
+ scope: 'tool.invoke',
179091
+ tool: { serverName, methodName, transport },
179092
+ actor: this.buildActor(),
179093
+ repository: this.repository,
179094
+ pullRequest: this.pullRequest,
179095
+ };
179096
+ }
179097
+ forCapabilityResolve(checkId, capabilities) {
179098
+ return {
179099
+ scope: 'capability.resolve',
179100
+ check: { id: checkId, type: 'ai' },
179101
+ capability: capabilities,
179102
+ actor: this.buildActor(),
179103
+ repository: this.repository,
179104
+ pullRequest: this.pullRequest,
179105
+ };
179106
+ }
179107
+ }
179108
+ exports.PolicyInputBuilder = PolicyInputBuilder;
179109
+
179110
+
179111
+ /***/ }),
179112
+
179113
+ /***/ 63737:
179114
+ /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
179115
+
179116
+ "use strict";
179117
+
179118
+ /**
179119
+ * Copyright (c) ProbeLabs. All rights reserved.
179120
+ * Licensed under the Elastic License 2.0; you may not use this file except
179121
+ * in compliance with the Elastic License 2.0.
179122
+ */
179123
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
179124
+ if (k2 === undefined) k2 = k;
179125
+ var desc = Object.getOwnPropertyDescriptor(m, k);
179126
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
179127
+ desc = { enumerable: true, get: function() { return m[k]; } };
179128
+ }
179129
+ Object.defineProperty(o, k2, desc);
179130
+ }) : (function(o, m, k, k2) {
179131
+ if (k2 === undefined) k2 = k;
179132
+ o[k2] = m[k];
179133
+ }));
179134
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
179135
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
179136
+ }) : function(o, v) {
179137
+ o["default"] = v;
179138
+ });
179139
+ var __importStar = (this && this.__importStar) || (function () {
179140
+ var ownKeys = function(o) {
179141
+ ownKeys = Object.getOwnPropertyNames || function (o) {
179142
+ var ar = [];
179143
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
179144
+ return ar;
179145
+ };
179146
+ return ownKeys(o);
179147
+ };
179148
+ return function (mod) {
179149
+ if (mod && mod.__esModule) return mod;
179150
+ var result = {};
179151
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
179152
+ __setModuleDefault(result, mod);
179153
+ return result;
179154
+ };
179155
+ })();
179156
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
179157
+ exports.KnexStoreBackend = void 0;
179158
+ /**
179159
+ * Knex-backed schedule store for PostgreSQL, MySQL, and MSSQL (Enterprise)
179160
+ *
179161
+ * Uses Knex query builder for database-agnostic SQL. Same schema as SQLite backend
179162
+ * but with real distributed locking via row-level claims (claimed_by/claimed_at/lock_token).
179163
+ */
179164
+ const fs = __importStar(__nccwpck_require__(79896));
179165
+ const path = __importStar(__nccwpck_require__(16928));
179166
+ const uuid_1 = __nccwpck_require__(31914);
179167
+ const logger_1 = __nccwpck_require__(86999);
179168
+ function toNum(val) {
179169
+ if (val === null || val === undefined)
179170
+ return undefined;
179171
+ return typeof val === 'string' ? parseInt(val, 10) : val;
179172
+ }
179173
+ function safeJsonParse(value) {
179174
+ if (!value)
179175
+ return undefined;
179176
+ try {
179177
+ return JSON.parse(value);
179178
+ }
179179
+ catch {
179180
+ return undefined;
179181
+ }
179182
+ }
179183
+ function fromTriggerRow(row) {
179184
+ return {
179185
+ id: row.id,
179186
+ creatorId: row.creator_id,
179187
+ creatorContext: row.creator_context ?? undefined,
179188
+ creatorName: row.creator_name ?? undefined,
179189
+ description: row.description ?? undefined,
179190
+ channels: safeJsonParse(row.channels),
179191
+ fromUsers: safeJsonParse(row.from_users),
179192
+ fromBots: row.from_bots === true || row.from_bots === 1,
179193
+ contains: safeJsonParse(row.contains),
179194
+ matchPattern: row.match_pattern ?? undefined,
179195
+ threads: row.threads,
179196
+ workflow: row.workflow,
179197
+ inputs: safeJsonParse(row.inputs),
179198
+ outputContext: safeJsonParse(row.output_context),
179199
+ status: row.status,
179200
+ enabled: row.enabled === true || row.enabled === 1,
179201
+ createdAt: toNum(row.created_at),
179202
+ };
179203
+ }
179204
+ function toTriggerInsertRow(trigger) {
179205
+ return {
179206
+ id: trigger.id,
179207
+ creator_id: trigger.creatorId,
179208
+ creator_context: trigger.creatorContext ?? null,
179209
+ creator_name: trigger.creatorName ?? null,
179210
+ description: trigger.description ?? null,
179211
+ channels: trigger.channels ? JSON.stringify(trigger.channels) : null,
179212
+ from_users: trigger.fromUsers ? JSON.stringify(trigger.fromUsers) : null,
179213
+ from_bots: trigger.fromBots,
179214
+ contains: trigger.contains ? JSON.stringify(trigger.contains) : null,
179215
+ match_pattern: trigger.matchPattern ?? null,
179216
+ threads: trigger.threads,
179217
+ workflow: trigger.workflow,
179218
+ inputs: trigger.inputs ? JSON.stringify(trigger.inputs) : null,
179219
+ output_context: trigger.outputContext ? JSON.stringify(trigger.outputContext) : null,
179220
+ status: trigger.status,
179221
+ enabled: trigger.enabled,
179222
+ created_at: trigger.createdAt,
179223
+ };
179224
+ }
179225
+ function fromDbRow(row) {
179226
+ return {
179227
+ id: row.id,
179228
+ creatorId: row.creator_id,
179229
+ creatorContext: row.creator_context ?? undefined,
179230
+ creatorName: row.creator_name ?? undefined,
179231
+ timezone: row.timezone,
179232
+ schedule: row.schedule_expr,
179233
+ runAt: toNum(row.run_at),
179234
+ isRecurring: row.is_recurring === true || row.is_recurring === 1,
179235
+ originalExpression: row.original_expression,
179236
+ workflow: row.workflow ?? undefined,
179237
+ workflowInputs: safeJsonParse(row.workflow_inputs),
179238
+ outputContext: safeJsonParse(row.output_context),
179239
+ status: row.status,
179240
+ createdAt: toNum(row.created_at),
179241
+ lastRunAt: toNum(row.last_run_at),
179242
+ nextRunAt: toNum(row.next_run_at),
179243
+ runCount: row.run_count,
179244
+ failureCount: row.failure_count,
179245
+ lastError: row.last_error ?? undefined,
179246
+ previousResponse: row.previous_response ?? undefined,
179247
+ };
179248
+ }
179249
+ function toInsertRow(schedule) {
179250
+ return {
179251
+ id: schedule.id,
179252
+ creator_id: schedule.creatorId,
179253
+ creator_context: schedule.creatorContext ?? null,
179254
+ creator_name: schedule.creatorName ?? null,
179255
+ timezone: schedule.timezone,
179256
+ schedule_expr: schedule.schedule,
179257
+ run_at: schedule.runAt ?? null,
179258
+ is_recurring: schedule.isRecurring,
179259
+ original_expression: schedule.originalExpression,
179260
+ workflow: schedule.workflow ?? null,
179261
+ workflow_inputs: schedule.workflowInputs ? JSON.stringify(schedule.workflowInputs) : null,
179262
+ output_context: schedule.outputContext ? JSON.stringify(schedule.outputContext) : null,
179263
+ status: schedule.status,
179264
+ created_at: schedule.createdAt,
179265
+ last_run_at: schedule.lastRunAt ?? null,
179266
+ next_run_at: schedule.nextRunAt ?? null,
179267
+ run_count: schedule.runCount,
179268
+ failure_count: schedule.failureCount,
179269
+ last_error: schedule.lastError ?? null,
179270
+ previous_response: schedule.previousResponse ?? null,
179271
+ };
179272
+ }
179273
+ /**
179274
+ * Enterprise Knex-backed store for PostgreSQL, MySQL, and MSSQL
179275
+ */
179276
+ class KnexStoreBackend {
179277
+ knex = null;
179278
+ driver;
179279
+ connection;
179280
+ constructor(driver, storageConfig, _haConfig) {
179281
+ this.driver = driver;
179282
+ this.connection = (storageConfig.connection || {});
179283
+ }
179284
+ async initialize() {
179285
+ // Load knex dynamically
179286
+ const { createRequire } = __nccwpck_require__(73339);
179287
+ const runtimeRequire = createRequire(__filename);
179288
+ let knexFactory;
179289
+ try {
179290
+ knexFactory = runtimeRequire('knex');
179291
+ }
179292
+ catch (err) {
179293
+ const code = err?.code;
179294
+ if (code === 'MODULE_NOT_FOUND' || code === 'ERR_MODULE_NOT_FOUND') {
179295
+ throw new Error('knex is required for PostgreSQL/MySQL/MSSQL schedule storage. ' +
179296
+ 'Install it with: npm install knex');
179297
+ }
179298
+ throw err;
179299
+ }
179300
+ const clientMap = {
179301
+ postgresql: 'pg',
179302
+ mysql: 'mysql2',
179303
+ mssql: 'tedious',
179304
+ };
179305
+ const client = clientMap[this.driver];
179306
+ // Build connection config
179307
+ let connection;
179308
+ if (this.connection.connection_string) {
179309
+ connection = this.connection.connection_string;
179310
+ }
179311
+ else if (this.driver === 'mssql') {
179312
+ connection = this.buildMssqlConnection();
179313
+ }
179314
+ else {
179315
+ connection = this.buildStandardConnection();
179316
+ }
179317
+ this.knex = knexFactory({
179318
+ client,
179319
+ connection,
179320
+ pool: {
179321
+ min: this.connection.pool?.min ?? 0,
179322
+ max: this.connection.pool?.max ?? 10,
179323
+ },
179324
+ });
179325
+ // Run schema migration
179326
+ await this.migrateSchema();
179327
+ logger_1.logger.info(`[KnexStore] Initialized (${this.driver})`);
179328
+ }
179329
+ buildStandardConnection() {
179330
+ return {
179331
+ host: this.connection.host || 'localhost',
179332
+ port: this.connection.port,
179333
+ database: this.connection.database || 'visor',
179334
+ user: this.connection.user,
179335
+ password: this.connection.password,
179336
+ ssl: this.resolveSslConfig(),
179337
+ };
179338
+ }
179339
+ buildMssqlConnection() {
179340
+ const ssl = this.connection.ssl;
179341
+ const sslEnabled = ssl === true || (typeof ssl === 'object' && ssl.enabled !== false);
179342
+ return {
179343
+ server: this.connection.host || 'localhost',
179344
+ port: this.connection.port,
179345
+ database: this.connection.database || 'visor',
179346
+ user: this.connection.user,
179347
+ password: this.connection.password,
179348
+ options: {
179349
+ encrypt: sslEnabled,
179350
+ trustServerCertificate: typeof ssl === 'object' ? ssl.reject_unauthorized === false : !sslEnabled,
179351
+ },
179352
+ };
179353
+ }
179354
+ resolveSslConfig() {
179355
+ const ssl = this.connection.ssl;
179356
+ if (ssl === false || ssl === undefined)
179357
+ return false;
179358
+ if (ssl === true)
179359
+ return { rejectUnauthorized: true };
179360
+ // Object config
179361
+ if (ssl.enabled === false)
179362
+ return false;
179363
+ const result = {
179364
+ rejectUnauthorized: ssl.reject_unauthorized !== false,
179365
+ };
179366
+ if (ssl.ca) {
179367
+ const caPath = this.validateSslPath(ssl.ca, 'CA certificate');
179368
+ result.ca = fs.readFileSync(caPath, 'utf8');
179369
+ }
179370
+ if (ssl.cert) {
179371
+ const certPath = this.validateSslPath(ssl.cert, 'client certificate');
179372
+ result.cert = fs.readFileSync(certPath, 'utf8');
179373
+ }
179374
+ if (ssl.key) {
179375
+ const keyPath = this.validateSslPath(ssl.key, 'client key');
179376
+ result.key = fs.readFileSync(keyPath, 'utf8');
179377
+ }
179378
+ return result;
179379
+ }
179380
+ validateSslPath(filePath, label) {
179381
+ const resolved = path.resolve(filePath);
179382
+ if (resolved !== path.normalize(resolved)) {
179383
+ throw new Error(`SSL ${label} path contains invalid sequences: ${filePath}`);
179384
+ }
179385
+ if (!fs.existsSync(resolved)) {
179386
+ throw new Error(`SSL ${label} not found: ${filePath}`);
179387
+ }
179388
+ return resolved;
179389
+ }
179390
+ async shutdown() {
179391
+ if (this.knex) {
179392
+ await this.knex.destroy();
179393
+ this.knex = null;
179394
+ }
179395
+ }
179396
+ async migrateSchema() {
179397
+ const knex = this.getKnex();
179398
+ const exists = await knex.schema.hasTable('schedules');
179399
+ if (!exists) {
179400
+ await knex.schema.createTable('schedules', table => {
179401
+ table.string('id', 36).primary();
179402
+ table.string('creator_id', 255).notNullable().index();
179403
+ table.string('creator_context', 255);
179404
+ table.string('creator_name', 255);
179405
+ table.string('timezone', 64).notNullable().defaultTo('UTC');
179406
+ table.string('schedule_expr', 255);
179407
+ table.bigInteger('run_at');
179408
+ table.boolean('is_recurring').notNullable();
179409
+ table.text('original_expression');
179410
+ table.string('workflow', 255);
179411
+ table.text('workflow_inputs');
179412
+ table.text('output_context');
179413
+ table.string('status', 20).notNullable().index();
179414
+ table.bigInteger('created_at').notNullable();
179415
+ table.bigInteger('last_run_at');
179416
+ table.bigInteger('next_run_at');
179417
+ table.integer('run_count').notNullable().defaultTo(0);
179418
+ table.integer('failure_count').notNullable().defaultTo(0);
179419
+ table.text('last_error');
179420
+ table.text('previous_response');
179421
+ table.index(['status', 'next_run_at']);
179422
+ });
179423
+ }
179424
+ // Create message_triggers table
179425
+ const triggersExist = await knex.schema.hasTable('message_triggers');
179426
+ if (!triggersExist) {
179427
+ await knex.schema.createTable('message_triggers', table => {
179428
+ table.string('id', 36).primary();
179429
+ table.string('creator_id', 255).notNullable().index();
179430
+ table.string('creator_context', 255);
179431
+ table.string('creator_name', 255);
179432
+ table.text('description');
179433
+ table.text('channels'); // JSON array
179434
+ table.text('from_users'); // JSON array
179435
+ table.boolean('from_bots').notNullable().defaultTo(false);
179436
+ table.text('contains'); // JSON array
179437
+ table.text('match_pattern');
179438
+ table.string('threads', 20).notNullable().defaultTo('any');
179439
+ table.string('workflow', 255).notNullable();
179440
+ table.text('inputs'); // JSON
179441
+ table.text('output_context'); // JSON
179442
+ table.string('status', 20).notNullable().defaultTo('active').index();
179443
+ table.boolean('enabled').notNullable().defaultTo(true);
179444
+ table.bigInteger('created_at').notNullable();
179445
+ });
179446
+ }
179447
+ // Create scheduler_locks table for distributed locking
179448
+ const locksExist = await knex.schema.hasTable('scheduler_locks');
179449
+ if (!locksExist) {
179450
+ await knex.schema.createTable('scheduler_locks', table => {
179451
+ table.string('lock_id', 255).primary();
179452
+ table.string('node_id', 255).notNullable();
179453
+ table.string('lock_token', 36).notNullable();
179454
+ table.bigInteger('acquired_at').notNullable();
179455
+ table.bigInteger('expires_at').notNullable();
179456
+ });
179457
+ }
179458
+ }
179459
+ getKnex() {
179460
+ if (!this.knex) {
179461
+ throw new Error('[KnexStore] Not initialized. Call initialize() first.');
179462
+ }
179463
+ return this.knex;
179464
+ }
179465
+ // --- CRUD ---
179466
+ async create(schedule) {
179467
+ const knex = this.getKnex();
179468
+ const newSchedule = {
179469
+ ...schedule,
179470
+ id: (0, uuid_1.v4)(),
179471
+ createdAt: Date.now(),
179472
+ runCount: 0,
179473
+ failureCount: 0,
179474
+ status: 'active',
179475
+ };
179476
+ await knex('schedules').insert(toInsertRow(newSchedule));
179477
+ logger_1.logger.info(`[KnexStore] Created schedule ${newSchedule.id} for user ${newSchedule.creatorId}`);
179478
+ return newSchedule;
179479
+ }
179480
+ async importSchedule(schedule) {
179481
+ const knex = this.getKnex();
179482
+ const existing = await knex('schedules').where('id', schedule.id).first();
179483
+ if (existing)
179484
+ return; // Already imported (idempotent)
179485
+ await knex('schedules').insert(toInsertRow(schedule));
179486
+ }
179487
+ async get(id) {
179488
+ const knex = this.getKnex();
179489
+ const row = await knex('schedules').where('id', id).first();
179490
+ return row ? fromDbRow(row) : undefined;
179491
+ }
179492
+ async update(id, patch) {
179493
+ const knex = this.getKnex();
179494
+ const existing = await knex('schedules').where('id', id).first();
179495
+ if (!existing)
179496
+ return undefined;
179497
+ const current = fromDbRow(existing);
179498
+ const updated = { ...current, ...patch, id: current.id };
179499
+ const row = toInsertRow(updated);
179500
+ // Remove id from update (PK cannot change)
179501
+ delete row.id;
179502
+ await knex('schedules').where('id', id).update(row);
179503
+ return updated;
179504
+ }
179505
+ async delete(id) {
179506
+ const knex = this.getKnex();
179507
+ const deleted = await knex('schedules').where('id', id).del();
179508
+ if (deleted > 0) {
179509
+ logger_1.logger.info(`[KnexStore] Deleted schedule ${id}`);
179510
+ return true;
179511
+ }
179512
+ return false;
179513
+ }
179514
+ // --- Queries ---
179515
+ async getByCreator(creatorId) {
179516
+ const knex = this.getKnex();
179517
+ const rows = await knex('schedules').where('creator_id', creatorId);
179518
+ return rows.map((r) => fromDbRow(r));
179519
+ }
179520
+ async getActiveSchedules() {
179521
+ const knex = this.getKnex();
179522
+ const rows = await knex('schedules').where('status', 'active');
179523
+ return rows.map((r) => fromDbRow(r));
179524
+ }
179525
+ async getDueSchedules(now) {
179526
+ const ts = now ?? Date.now();
179527
+ const knex = this.getKnex();
179528
+ // MSSQL uses 1/0 for booleans
179529
+ const bFalse = this.driver === 'mssql' ? 0 : false;
179530
+ const bTrue = this.driver === 'mssql' ? 1 : true;
179531
+ const rows = await knex('schedules')
179532
+ .where('status', 'active')
179533
+ .andWhere(function () {
179534
+ this.where(function () {
179535
+ this.where('is_recurring', bFalse)
179536
+ .whereNotNull('run_at')
179537
+ .where('run_at', '<=', ts);
179538
+ }).orWhere(function () {
179539
+ this.where('is_recurring', bTrue)
179540
+ .whereNotNull('next_run_at')
179541
+ .where('next_run_at', '<=', ts);
179542
+ });
179543
+ });
179544
+ return rows.map((r) => fromDbRow(r));
179545
+ }
179546
+ async findByWorkflow(creatorId, workflowName) {
179547
+ const knex = this.getKnex();
179548
+ const escaped = workflowName.toLowerCase().replace(/[%_\\]/g, '\\$&');
179549
+ const pattern = `%${escaped}%`;
179550
+ const rows = await knex('schedules')
179551
+ .where('creator_id', creatorId)
179552
+ .where('status', 'active')
179553
+ .whereRaw("LOWER(workflow) LIKE ? ESCAPE '\\'", [pattern]);
179554
+ return rows.map((r) => fromDbRow(r));
179555
+ }
179556
+ async getAll() {
179557
+ const knex = this.getKnex();
179558
+ const rows = await knex('schedules');
179559
+ return rows.map((r) => fromDbRow(r));
179560
+ }
179561
+ async getStats() {
179562
+ const knex = this.getKnex();
179563
+ // MSSQL uses 1/0 for booleans; PostgreSQL/MySQL accept both true/1
179564
+ const boolTrue = this.driver === 'mssql' ? '1' : 'true';
179565
+ const boolFalse = this.driver === 'mssql' ? '0' : 'false';
179566
+ const result = await knex('schedules')
179567
+ .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`))
179568
+ .first();
179569
+ return {
179570
+ total: Number(result.total) || 0,
179571
+ active: Number(result.active) || 0,
179572
+ paused: Number(result.paused) || 0,
179573
+ completed: Number(result.completed) || 0,
179574
+ failed: Number(result.failed) || 0,
179575
+ recurring: Number(result.recurring) || 0,
179576
+ oneTime: Number(result.one_time) || 0,
179577
+ };
179578
+ }
179579
+ async validateLimits(creatorId, isRecurring, limits) {
179580
+ const knex = this.getKnex();
179581
+ if (limits.maxGlobal) {
179582
+ const result = await knex('schedules').count('* as cnt').first();
179583
+ if (Number(result?.cnt) >= limits.maxGlobal) {
179584
+ throw new Error(`Global schedule limit reached (${limits.maxGlobal})`);
179585
+ }
179586
+ }
179587
+ if (limits.maxPerUser) {
179588
+ const result = await knex('schedules')
179589
+ .where('creator_id', creatorId)
179590
+ .count('* as cnt')
179591
+ .first();
179592
+ if (Number(result?.cnt) >= limits.maxPerUser) {
179593
+ throw new Error(`You have reached the maximum number of schedules (${limits.maxPerUser})`);
179594
+ }
179595
+ }
179596
+ if (isRecurring && limits.maxRecurringPerUser) {
179597
+ const bTrue = this.driver === 'mssql' ? 1 : true;
179598
+ const result = await knex('schedules')
179599
+ .where('creator_id', creatorId)
179600
+ .where('is_recurring', bTrue)
179601
+ .count('* as cnt')
179602
+ .first();
179603
+ if (Number(result?.cnt) >= limits.maxRecurringPerUser) {
179604
+ throw new Error(`You have reached the maximum number of recurring schedules (${limits.maxRecurringPerUser})`);
179605
+ }
179606
+ }
179607
+ }
179608
+ // --- HA Distributed Locking (via scheduler_locks table) ---
179609
+ async tryAcquireLock(lockId, nodeId, ttlSeconds) {
179610
+ const knex = this.getKnex();
179611
+ const now = Date.now();
179612
+ const expiresAt = now + ttlSeconds * 1000;
179613
+ const token = (0, uuid_1.v4)();
179614
+ // Step 1: Try to claim an existing expired lock
179615
+ const updated = await knex('scheduler_locks')
179616
+ .where('lock_id', lockId)
179617
+ .where('expires_at', '<', now)
179618
+ .update({
179619
+ node_id: nodeId,
179620
+ lock_token: token,
179621
+ acquired_at: now,
179622
+ expires_at: expiresAt,
179623
+ });
179624
+ if (updated > 0)
179625
+ return token;
179626
+ // Step 2: Try to INSERT a new lock row
179627
+ try {
179628
+ await knex('scheduler_locks').insert({
179629
+ lock_id: lockId,
179630
+ node_id: nodeId,
179631
+ lock_token: token,
179632
+ acquired_at: now,
179633
+ expires_at: expiresAt,
179634
+ });
179635
+ return token;
179636
+ }
179637
+ catch {
179638
+ // Unique constraint violation — another node holds the lock
179639
+ return null;
179640
+ }
179641
+ }
179642
+ async releaseLock(lockId, lockToken) {
179643
+ const knex = this.getKnex();
179644
+ await knex('scheduler_locks').where('lock_id', lockId).where('lock_token', lockToken).del();
179645
+ }
179646
+ async renewLock(lockId, lockToken, ttlSeconds) {
179647
+ const knex = this.getKnex();
179648
+ const now = Date.now();
179649
+ const expiresAt = now + ttlSeconds * 1000;
179650
+ const updated = await knex('scheduler_locks')
179651
+ .where('lock_id', lockId)
179652
+ .where('lock_token', lockToken)
179653
+ .update({ acquired_at: now, expires_at: expiresAt });
179654
+ return updated > 0;
179655
+ }
179656
+ async flush() {
179657
+ // No-op for server-based backends
179658
+ }
179659
+ // --- Message Trigger CRUD ---
179660
+ async createTrigger(trigger) {
179661
+ const knex = this.getKnex();
179662
+ const newTrigger = {
179663
+ ...trigger,
179664
+ id: (0, uuid_1.v4)(),
179665
+ createdAt: Date.now(),
179666
+ };
179667
+ await knex('message_triggers').insert(toTriggerInsertRow(newTrigger));
179668
+ logger_1.logger.info(`[KnexStore] Created trigger ${newTrigger.id} for user ${newTrigger.creatorId}`);
179669
+ return newTrigger;
179670
+ }
179671
+ async getTrigger(id) {
179672
+ const knex = this.getKnex();
179673
+ const row = await knex('message_triggers').where('id', id).first();
179674
+ return row ? fromTriggerRow(row) : undefined;
179675
+ }
179676
+ async updateTrigger(id, patch) {
179677
+ const knex = this.getKnex();
179678
+ const existing = await knex('message_triggers').where('id', id).first();
179679
+ if (!existing)
179680
+ return undefined;
179681
+ const current = fromTriggerRow(existing);
179682
+ const updated = {
179683
+ ...current,
179684
+ ...patch,
179685
+ id: current.id,
179686
+ createdAt: current.createdAt,
179687
+ };
179688
+ const row = toTriggerInsertRow(updated);
179689
+ delete row.id;
179690
+ await knex('message_triggers').where('id', id).update(row);
179691
+ return updated;
179692
+ }
179693
+ async deleteTrigger(id) {
179694
+ const knex = this.getKnex();
179695
+ const deleted = await knex('message_triggers').where('id', id).del();
179696
+ if (deleted > 0) {
179697
+ logger_1.logger.info(`[KnexStore] Deleted trigger ${id}`);
179698
+ return true;
179699
+ }
179700
+ return false;
179701
+ }
179702
+ async getTriggersByCreator(creatorId) {
179703
+ const knex = this.getKnex();
179704
+ const rows = await knex('message_triggers').where('creator_id', creatorId);
179705
+ return rows.map((r) => fromTriggerRow(r));
179706
+ }
179707
+ async getActiveTriggers() {
179708
+ const knex = this.getKnex();
179709
+ const rows = await knex('message_triggers')
179710
+ .where('status', 'active')
179711
+ .where('enabled', this.driver === 'mssql' ? 1 : true);
179712
+ return rows.map((r) => fromTriggerRow(r));
179713
+ }
179714
+ }
179715
+ exports.KnexStoreBackend = KnexStoreBackend;
179716
+
179717
+
177794
179718
  /***/ }),
177795
179719
 
177796
179720
  /***/ 83864:
@@ -189104,6 +191028,35 @@ class OutputFormatters {
189104
191028
  exports.OutputFormatters = OutputFormatters;
189105
191029
 
189106
191030
 
191031
+ /***/ }),
191032
+
191033
+ /***/ 93866:
191034
+ /***/ ((__unused_webpack_module, exports) => {
191035
+
191036
+ "use strict";
191037
+
191038
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
191039
+ exports.DefaultPolicyEngine = void 0;
191040
+ /**
191041
+ * Default (no-op) policy engine — always allows everything.
191042
+ * Used when no enterprise license is present or policy is disabled.
191043
+ */
191044
+ class DefaultPolicyEngine {
191045
+ async initialize(_config) { }
191046
+ async evaluateCheckExecution(_checkId, _checkConfig) {
191047
+ return { allowed: true };
191048
+ }
191049
+ async evaluateToolInvocation(_serverName, _methodName, _transport) {
191050
+ return { allowed: true };
191051
+ }
191052
+ async evaluateCapabilities(_checkId, _capabilities) {
191053
+ return { allowed: true };
191054
+ }
191055
+ async shutdown() { }
191056
+ }
191057
+ exports.DefaultPolicyEngine = DefaultPolicyEngine;
191058
+
191059
+
189107
191060
  /***/ }),
189108
191061
 
189109
191062
  /***/ 96611:
@@ -209266,32 +211219,28 @@ function replaceMermaidBlocks(text, diagrams, replacement = '_(See diagram above
209266
211219
  function markdownToSlack(text) {
209267
211220
  if (!text || typeof text !== 'string')
209268
211221
  return '';
209269
- let out = text;
209270
- // Images: ![alt](url) → <url|alt>
209271
- // We intentionally keep only the URL + alt text; Slack will usually unfurl.
209272
- out = out.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (_m, alt, url) => `<${url}|${alt || 'image'}>`);
209273
- // Links: [label](url) → <url|label>
209274
- out = out.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (_m, label, url) => `<${url}|${label}>`);
209275
- // Bold: **text** or __text__ → *text*
209276
- out = out.replace(/\*\*([^*]+)\*\*/g, (_m, inner) => `*${inner}*`);
209277
- out = out.replace(/__([^_]+)__/g, (_m, inner) => `*${inner}*`);
209278
- // Process lines for headers and bullet lists.
209279
- // Slack's mrkdwn handles "•" bullets more naturally than raw "-" Markdown.
209280
- const lines = out.split(/\r?\n/);
211222
+ // Process line-by-line so ALL transformations respect code blocks.
211223
+ const lines = text.split(/\r?\n/);
209281
211224
  let inCodeBlock = false;
209282
211225
  for (let i = 0; i < lines.length; i++) {
209283
- const line = lines[i];
209284
- const trimmed = line.trimStart();
209285
- // Track fenced code blocks and avoid rewriting inside them
211226
+ const trimmed = lines[i].trimStart();
211227
+ // Track fenced code blocks — skip all transformations inside them
209286
211228
  if (/^```/.test(trimmed)) {
209287
211229
  inCodeBlock = !inCodeBlock;
209288
211230
  continue;
209289
211231
  }
209290
211232
  if (inCodeBlock)
209291
211233
  continue;
211234
+ let line = lines[i];
211235
+ // Images: ![alt](url) → <url|alt>
211236
+ line = line.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (_m, alt, url) => `<${url}|${alt || 'image'}>`);
211237
+ // Links: [label](url) → <url|label>
211238
+ line = line.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (_m, label, url) => `<${url}|${label}>`);
211239
+ // Bold: **text** or __text__ → *text*
211240
+ line = line.replace(/\*\*([^*]+)\*\*/g, (_m, inner) => `*${inner}*`);
211241
+ line = line.replace(/__([^_]+)__/g, (_m, inner) => `*${inner}*`);
209292
211242
  // Headers: # Header → *Header* (Slack doesn't have native headers)
209293
- // Match 1-6 # at start of line, followed by space and text
209294
- const headerMatch = /^(#{1,6})\s+(.+)$/.exec(trimmed);
211243
+ const headerMatch = /^(#{1,6})\s+(.+)$/.exec(line.trimStart());
209295
211244
  if (headerMatch) {
209296
211245
  const [, hashes, headerText] = headerMatch;
209297
211246
  // For h1/h2, add extra emphasis with newline before (if not first line
@@ -209311,10 +211260,11 @@ function markdownToSlack(text) {
209311
211260
  if (bulletMatch) {
209312
211261
  const [, indent, , rest] = bulletMatch;
209313
211262
  lines[i] = `${indent}• ${rest}`;
211263
+ continue;
209314
211264
  }
211265
+ lines[i] = line;
209315
211266
  }
209316
- out = lines.join('\n');
209317
- return out;
211267
+ return lines.join('\n');
209318
211268
  }
209319
211269
  /**
209320
211270
  * Extract all file sections delimited by --- filename.ext --- from text.
@@ -211883,7 +213833,7 @@ class StateMachineExecutionEngine {
211883
213833
  try {
211884
213834
  logger_1.logger.debug(`[PolicyEngine] Loading enterprise policy engine (engine=${configWithTagFilter.policy.engine})`);
211885
213835
  // @ts-ignore — enterprise/ may not exist in OSS builds (caught at runtime)
211886
- const { loadEnterprisePolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(7065)));
213836
+ const { loadEnterprisePolicyEngine } = await Promise.resolve().then(() => __importStar(__nccwpck_require__(87068)));
211887
213837
  context.policyEngine = await loadEnterprisePolicyEngine(configWithTagFilter.policy);
211888
213838
  logger_1.logger.debug(`[PolicyEngine] Initialized: ${context.policyEngine?.constructor?.name || 'unknown'}`);
211889
213839
  }
@@ -222194,7 +224144,7 @@ async function initTelemetry(opts = {}) {
222194
224144
  const path = __nccwpck_require__(16928);
222195
224145
  const outDir = opts.file?.dir ||
222196
224146
  process.env.VISOR_TRACE_DIR ||
222197
- __nccwpck_require__.ab + "traces";
224147
+ path.join(process.cwd(), 'output', 'traces');
222198
224148
  fs.mkdirSync(outDir, { recursive: true });
222199
224149
  const ts = new Date().toISOString().replace(/[:.]/g, '-');
222200
224150
  process.env.VISOR_FALLBACK_TRACE_FILE = path.join(outDir, `run-${ts}.ndjson`);
@@ -222399,7 +224349,7 @@ async function shutdownTelemetry() {
222399
224349
  if (process.env.VISOR_TRACE_REPORT === 'true') {
222400
224350
  const fs = __nccwpck_require__(79896);
222401
224351
  const path = __nccwpck_require__(16928);
222402
- const outDir = process.env.VISOR_TRACE_DIR || __nccwpck_require__.ab + "traces";
224352
+ const outDir = process.env.VISOR_TRACE_DIR || path.join(process.cwd(), 'output', 'traces');
222403
224353
  if (!fs.existsSync(outDir))
222404
224354
  fs.mkdirSync(outDir, { recursive: true });
222405
224355
  const ts = new Date().toISOString().replace(/[:.]/g, '-');
@@ -222900,7 +224850,7 @@ function __getOrCreateNdjsonPath() {
222900
224850
  fs.mkdirSync(dir, { recursive: true });
222901
224851
  return __ndjsonPath;
222902
224852
  }
222903
- const outDir = process.env.VISOR_TRACE_DIR || __nccwpck_require__.ab + "traces";
224853
+ const outDir = process.env.VISOR_TRACE_DIR || path.join(process.cwd(), 'output', 'traces');
222904
224854
  if (!fs.existsSync(outDir))
222905
224855
  fs.mkdirSync(outDir, { recursive: true });
222906
224856
  if (!__ndjsonPath) {
@@ -237356,22 +239306,6 @@ class WorkflowRegistry {
237356
239306
  exports.WorkflowRegistry = WorkflowRegistry;
237357
239307
 
237358
239308
 
237359
- /***/ }),
237360
-
237361
- /***/ 7065:
237362
- /***/ ((module) => {
237363
-
237364
- module.exports = eval("require")("./enterprise/loader");
237365
-
237366
-
237367
- /***/ }),
237368
-
237369
- /***/ 71370:
237370
- /***/ ((module) => {
237371
-
237372
- module.exports = eval("require")("./enterprise/policy/policy-input-builder");
237373
-
237374
-
237375
239309
  /***/ }),
237376
239310
 
237377
239311
  /***/ 18327:
@@ -398651,7 +400585,7 @@ module.exports = /*#__PURE__*/JSON.parse('{"100":"Continue","101":"Switching Pro
398651
400585
  /***/ ((module) => {
398652
400586
 
398653
400587
  "use strict";
398654
- module.exports = /*#__PURE__*/JSON.parse('{"name":"@probelabs/visor","version":"0.1.171","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-rc290","@types/commander":"^2.12.0","@types/uuid":"^10.0.0","acorn":"^8.16.0","acorn-walk":"^8.3.5","ajv":"^8.17.1","ajv-formats":"^3.0.1","better-sqlite3":"^11.0.0","blessed":"^0.1.81","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"]}}');
400588
+ 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-rc290","@types/commander":"^2.12.0","@types/uuid":"^10.0.0","acorn":"^8.16.0","acorn-walk":"^8.3.5","ajv":"^8.17.1","ajv-formats":"^3.0.1","better-sqlite3":"^11.0.0","blessed":"^0.1.81","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"]}}');
398655
400589
 
398656
400590
  /***/ })
398657
400591