forked from probelabs/visor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathai-check-provider.ts
More file actions
2467 lines (2287 loc) · 92.5 KB
/
Copy pathai-check-provider.ts
File metadata and controls
2467 lines (2287 loc) · 92.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { CheckProvider, CheckProviderConfig } from './check-provider.interface';
import { PRInfo } from '../pr-analyzer';
import { ReviewSummary } from '../reviewer';
import { AIReviewService, AIReviewConfig } from '../ai-review-service';
import { EnvironmentResolver } from '../utils/env-resolver';
import { IssueFilter } from '../issue-filter';
import { createExtendedLiquid } from '../liquid-extensions';
import fs from 'fs/promises';
import path from 'path';
import { trace, context as otContext } from '../telemetry/lazy-otel';
import {
captureCheckInputContext,
captureCheckOutput,
captureProviderCall,
sanitizeContextForTelemetry,
} from '../telemetry/state-capture';
import { CustomToolsSSEServer } from './mcp-custom-sse-server';
import { CustomToolDefinition } from '../types/config';
import { logger } from '../logger';
import {
isWorkflowToolReference,
WorkflowToolReference,
WorkflowToolContext,
} from './workflow-tool-executor';
import { resolveTools } from '../utils/tool-resolver';
import { createSecureSandbox, compileAndRun } from '../utils/sandbox';
import type Sandbox from '@nyariv/sandboxjs';
import { getScheduleToolDefinition } from '../scheduler/schedule-tool';
// Legacy Slack context extraction for backwards compatibility
import { extractSlackContext } from '../slack/schedule-tool-handler';
/**
* AI-powered check provider using probe agent
*/
export class AICheckProvider extends CheckProvider {
private aiReviewService: AIReviewService;
private liquidEngine: ReturnType<typeof createExtendedLiquid>;
private sandbox: Sandbox | null = null;
constructor() {
super();
this.aiReviewService = new AIReviewService();
this.liquidEngine = createExtendedLiquid();
}
getName(): string {
return 'ai';
}
getDescription(): string {
return 'AI-powered code review using Google Gemini, Anthropic Claude, OpenAI GPT, or AWS Bedrock models';
}
/** Lightweight debug helper to avoid importing logger here */
private logDebug(msg: string): void {
try {
if (process.env.VISOR_DEBUG === 'true') {
// eslint-disable-next-line no-console
console.debug(msg);
}
} catch {
// Best-effort only
}
}
/** Detect Slack webhook payload and build a lightweight slack context for templates */
private buildSlackEventContext(
context?: import('./check-provider.interface').ExecutionContext,
config?: CheckProviderConfig,
prInfo?: PRInfo
): Record<string, unknown> {
try {
const aiCfg: any = config?.ai || {};
if (aiCfg.skip_slack_context === true) return {};
const webhook = context?.webhookContext;
const map = webhook?.webhookData;
if (!map || !(map instanceof Map)) return {};
// In Slack socket mode we store the payload under the configured endpoint key.
// For template purposes, it is sufficient to inspect the first payload.
const first = Array.from(map.values())[0] as any;
if (!first || typeof first !== 'object') return {};
const ev = first.event;
const slackConv = first.slack_conversation;
const telegramConv = first.telegram_conversation;
const conv = slackConv || telegramConv;
if (!ev && !conv) return {};
// Attach conversation to prInfo so downstream helpers (XML context) can use it
if (conv && prInfo) {
try {
(prInfo as any).slackConversation = conv;
} catch {
// best-effort only
}
}
// Build transport-specific context
const transportCtx = slackConv
? { slack: { event: ev, conversation: slackConv } }
: { telegram: { event: ev, conversation: telegramConv } };
return { ...transportCtx, conversation: conv };
} catch {
return {};
}
}
async validateConfig(config: unknown): Promise<boolean> {
if (!config || typeof config !== 'object') {
return false;
}
const cfg = config as CheckProviderConfig;
// Type must be 'ai'
if (cfg.type !== 'ai') {
return false;
}
// Check for prompt or focus
const prompt = cfg.prompt || cfg.focus;
if (typeof prompt !== 'string') {
return false;
}
// Focus is now config-driven - any string value is acceptable
// No validation needed here as focus is just a hint to the AI
// Validate AI provider config if present
if (cfg.ai) {
if (
cfg.ai.provider &&
!['google', 'anthropic', 'openai', 'bedrock', 'mock'].includes(cfg.ai.provider as string)
) {
return false;
}
// Validate mcpServers if present
if (cfg.ai.mcpServers) {
if (!this.validateMcpServers(cfg.ai.mcpServers)) {
return false;
}
}
}
// Validate check-level MCP servers if present
const checkLevelMcpServers = (cfg as CheckProviderConfig & { ai_mcp_servers?: unknown })
.ai_mcp_servers;
if (checkLevelMcpServers) {
if (!this.validateMcpServers(checkLevelMcpServers)) {
return false;
}
}
return true;
}
/**
* Validate MCP servers configuration
*/
private validateMcpServers(mcpServers: unknown): boolean {
if (typeof mcpServers !== 'object' || mcpServers === null) {
return false;
}
for (const serverConfig of Object.values(mcpServers)) {
if (!serverConfig || typeof serverConfig !== 'object') {
return false;
}
const config = serverConfig as { command?: unknown; args?: unknown };
if (typeof config.command !== 'string') {
return false;
}
if (config.args !== undefined && !Array.isArray(config.args)) {
return false;
}
}
return true;
}
/**
* Group files by their file extension for template context
*/
private groupFilesByExtension(
files: import('../pr-analyzer').PRFile[]
): Record<string, import('../pr-analyzer').PRFile[]> {
const grouped: Record<string, import('../pr-analyzer').PRFile[]> = {};
files.forEach(file => {
const parts = file.filename.split('.');
const ext = parts.length > 1 ? parts.pop()?.toLowerCase() || 'noext' : 'noext';
if (!grouped[ext]) {
grouped[ext] = [];
}
grouped[ext].push(file);
});
return grouped;
}
/**
* Process prompt configuration to resolve final prompt string
*/
private async processPrompt(
promptConfig: string,
prInfo: PRInfo,
eventContext?: Record<string, unknown>,
dependencyResults?: Map<string, ReviewSummary>,
outputHistory?: Map<string, unknown[]>,
args?: Record<string, unknown>,
workflowInputs?: Record<string, unknown>
): Promise<string> {
let promptContent: string;
// Auto-detect if it's a file path or inline content
if (await this.isFilePath(promptConfig)) {
promptContent = await this.loadPromptFromFile(promptConfig);
} else {
promptContent = promptConfig;
}
// Process Liquid templates in the prompt
return await this.renderPromptTemplate(
promptContent,
prInfo,
eventContext,
dependencyResults,
outputHistory,
args,
workflowInputs
);
}
/**
* Detect if a string is likely a file path and if the file exists
*/
private async isFilePath(str: string): Promise<boolean> {
// Quick checks to exclude obvious non-file-path content
if (!str || str.trim() !== str || str.length > 512) {
return false;
}
// Exclude strings that are clearly content (contain common content indicators)
// But be more careful with paths that might contain common words as directory names
if (
/\s{2,}/.test(str) || // Multiple consecutive spaces
/\n/.test(str) || // Contains newlines
/^(please|analyze|review|check|find|identify|look|search)/i.test(str.trim()) || // Starts with command words
str.split(' ').length > 8 // Too many words for a typical file path
) {
return false;
}
// For strings with path separators, be more lenient about common words
// as they might be legitimate directory names
if (!/[\/\\]/.test(str)) {
// Only apply strict English word filter to non-path strings
if (/\b(the|and|or|but|for|with|by|from|in|on|at|as)\b/i.test(str)) {
return false;
}
}
// Positive indicators for file paths
const hasFileExtension = /\.[a-zA-Z0-9]{1,10}$/i.test(str);
const hasPathSeparators = /[\/\\]/.test(str);
const isRelativePath = /^\.{1,2}\//.test(str);
const isAbsolutePath = path.isAbsolute(str);
const hasTypicalFileChars = /^[a-zA-Z0-9._\-\/\\:~]+$/.test(str);
// Must have at least one strong indicator
if (!(hasFileExtension || isRelativePath || isAbsolutePath || hasPathSeparators)) {
return false;
}
// Must contain only typical file path characters
if (!hasTypicalFileChars) {
return false;
}
// Additional validation for suspected file paths
try {
// Try to resolve and check if file exists
let resolvedPath: string;
if (path.isAbsolute(str)) {
resolvedPath = path.normalize(str);
} else {
// Resolve relative to current working directory
resolvedPath = path.resolve(process.cwd(), str);
}
// Check if file exists
const fs = require('fs').promises;
try {
const stat = await fs.stat(resolvedPath);
return stat.isFile();
} catch {
// File doesn't exist, but might still be a valid file path format
// Return true if it has strong file path indicators
return hasFileExtension && (isRelativePath || isAbsolutePath || hasPathSeparators);
}
} catch {
return false;
}
}
/**
* Load prompt content from file with security validation
*/
private async loadPromptFromFile(promptPath: string): Promise<string> {
// Enforce .liquid file extension for all prompt files
if (!promptPath.endsWith('.liquid')) {
throw new Error('Prompt file must have .liquid extension');
}
let resolvedPath: string;
if (path.isAbsolute(promptPath)) {
// Absolute path - use as-is
resolvedPath = promptPath;
} else {
// Relative path - resolve relative to current working directory
resolvedPath = path.resolve(process.cwd(), promptPath);
}
// Security: For relative paths, ensure they don't escape the current directory
if (!path.isAbsolute(promptPath)) {
const normalizedPath = path.normalize(resolvedPath);
const currentDir = path.resolve(process.cwd());
if (!normalizedPath.startsWith(currentDir)) {
throw new Error('Invalid prompt file path: path traversal detected');
}
}
// Security: Check for obvious path traversal patterns
if (promptPath.includes('../..')) {
throw new Error('Invalid prompt file path: path traversal detected');
}
try {
const promptContent = await fs.readFile(resolvedPath, 'utf-8');
return promptContent;
} catch (error) {
throw new Error(
`Failed to load prompt from ${resolvedPath}: ${
error instanceof Error ? error.message : 'Unknown error'
}`
);
}
}
/**
* Render Liquid template in prompt with comprehensive event context
*/
private async renderPromptTemplate(
promptContent: string,
prInfo: PRInfo,
eventContext?: Record<string, unknown>,
dependencyResults?: Map<string, ReviewSummary>,
outputHistory?: Map<string, unknown[]>,
args?: Record<string, unknown>,
workflowInputs?: Record<string, unknown>
): Promise<string> {
// Build outputs_raw from -raw keys (aggregate parent values)
const outputsRaw: Record<string, unknown> = {};
if (dependencyResults) {
for (const [k, v] of dependencyResults.entries()) {
if (typeof k !== 'string') continue;
if (k.endsWith('-raw')) {
const name = k.slice(0, -4);
const summary = v as ReviewSummary & { output?: unknown };
outputsRaw[name] = summary.output !== undefined ? summary.output : summary;
}
}
}
// Note: We intentionally do NOT expose any special `fact_validation` object
// in the template context. Templates should derive everything from
// outputs / outputs_history / memory helpers to avoid hidden magic.
// Create comprehensive template context with PR and event information
const templateContext = {
// PR Information
pr: {
number: prInfo.number,
title: prInfo.title,
body: prInfo.body,
author: prInfo.author,
baseBranch: prInfo.base,
headBranch: prInfo.head,
isIncremental: prInfo.isIncremental,
filesChanged: prInfo.files?.map(f => f.filename) || [],
totalAdditions: prInfo.files?.reduce((sum, f) => sum + f.additions, 0) || 0,
totalDeletions: prInfo.files?.reduce((sum, f) => sum + f.deletions, 0) || 0,
totalChanges: prInfo.files?.reduce((sum, f) => sum + f.changes, 0) || 0,
base: prInfo.base,
head: prInfo.head,
},
// File Details
files: prInfo.files || [],
description: prInfo.body || '',
// GitHub / webhook Event Context
event: eventContext
? {
name: eventContext.event_name || 'unknown',
action: eventContext.action,
isPullRequest: !prInfo.isIssue, // Set based on whether this is a PR or an issue
// Repository Info
repository: eventContext.repository
? {
owner: (eventContext.repository as { owner?: { login?: string } })?.owner?.login,
name: (eventContext.repository as { name?: string })?.name,
fullName: eventContext.repository
? `${(eventContext.repository as { owner?: { login?: string } })?.owner?.login}/${(eventContext.repository as { name?: string })?.name}`
: undefined,
}
: undefined,
// Comment Data (for comment events)
comment: eventContext.comment
? {
body: (eventContext.comment as { body?: string })?.body,
author: (eventContext.comment as { user?: { login?: string } })?.user?.login,
}
: undefined,
// Issue Data (for issue events)
issue: eventContext.issue
? {
number: (eventContext.issue as { number?: number })?.number,
title: (eventContext.issue as { title?: string })?.title,
body: (eventContext.issue as { body?: string })?.body,
state: (eventContext.issue as { state?: string })?.state,
author: (eventContext.issue as { user?: { login?: string } })?.user?.login,
labels: (eventContext.issue as { labels?: unknown[] })?.labels || [],
assignees:
(
eventContext as { issue?: { assignees?: Array<{ login: string }> } }
)?.issue?.assignees?.map(a => a.login) || [],
createdAt: (eventContext.issue as { created_at?: string })?.created_at,
updatedAt: (eventContext.issue as { updated_at?: string })?.updated_at,
isPullRequest: !!(eventContext.issue as { pull_request?: unknown })?.pull_request,
}
: undefined,
// Pull Request Event Data
pullRequest: eventContext.pull_request
? {
number: (eventContext.pull_request as { number?: number })?.number,
state: (eventContext.pull_request as { state?: string })?.state,
draft: (eventContext.pull_request as { draft?: boolean })?.draft,
headSha: (eventContext.pull_request as { head?: { sha?: string } })?.head?.sha,
headRef: (eventContext.pull_request as { head?: { ref?: string } })?.head?.ref,
baseSha: (eventContext.pull_request as { base?: { sha?: string } })?.base?.sha,
baseRef: (eventContext.pull_request as { base?: { ref?: string } })?.base?.ref,
}
: undefined,
// Raw event payload for advanced use cases
payload: eventContext,
}
: undefined,
// Slack conversation context (if provided via eventContext.slack)
slack: (() => {
try {
const anyCtx = eventContext as any;
const slack = anyCtx?.slack;
if (slack && typeof slack === 'object') return slack;
} catch {
// ignore
}
return undefined;
})(),
// Unified conversation context across transports (Slack & GitHub)
conversation: (() => {
try {
const anyCtx = eventContext as any;
if (anyCtx?.slack?.conversation) return anyCtx.slack.conversation;
if (anyCtx?.github?.conversation) return anyCtx.github.conversation;
if (anyCtx?.conversation) return anyCtx.conversation;
} catch {
// ignore
}
return undefined;
})(),
// Utility data for templates
utils: {
// Date/time helpers
now: new Date().toISOString(),
today: new Date().toISOString().split('T')[0],
// Dynamic file grouping by extension
filesByExtension: this.groupFilesByExtension(prInfo.files || []),
// File status categorizations
addedFiles: (prInfo.files || []).filter(f => f.status === 'added'),
modifiedFiles: (prInfo.files || []).filter(f => f.status === 'modified'),
removedFiles: (prInfo.files || []).filter(f => f.status === 'removed'),
renamedFiles: (prInfo.files || []).filter(f => f.status === 'renamed'),
// Change analysis
hasLargeChanges: (prInfo.files || []).some(f => f.changes > 50),
totalFiles: (prInfo.files || []).length,
},
// Checks metadata for helpers like chat_history
checks_meta: (() => {
try {
return (eventContext as any)?.__checksMeta || undefined;
} catch {
return undefined;
}
})(),
// Previous check outputs (dependency results)
// Expose raw output directly if available, otherwise expose the result as-is
outputs: dependencyResults
? Object.fromEntries(
Array.from(dependencyResults.entries()).map(([checkName, result]) => [
checkName,
(() => {
const summary = result as ReviewSummary & { output?: unknown };
return summary.output !== undefined ? summary.output : summary;
})(),
])
)
: {},
// Alias for consistency with other providers
outputs_history: (() => {
const hist: Record<string, unknown[]> = {};
if (outputHistory) {
for (const [k, v] of outputHistory.entries()) hist[k] = v;
}
return hist;
})(),
// Stage-scoped history slice calculated from baseline captured by the flow runner.
outputs_history_stage: (() => {
const stage: Record<string, unknown[]> = {};
try {
const base = (eventContext as any)?.__stageHistoryBase as
| Record<string, number>
| undefined;
if (!outputHistory || !base) return stage;
for (const [k, v] of outputHistory.entries()) {
const start = base[k] || 0;
const arr = Array.isArray(v) ? (v as unknown[]) : [];
stage[k] = arr.slice(start);
}
} catch {}
return stage;
})(),
// New: outputs_raw exposes aggregate values (e.g., full arrays for forEach parents)
outputs_raw: outputsRaw,
// Custom arguments from on_init 'with' directive
args: args || {},
// Workflow inputs (for nested workflow steps to access parent inputs like {{ inputs.context }})
inputs: workflowInputs || {},
};
try {
if (process.env.VISOR_DEBUG === 'true') {
const outKeys = Object.keys((templateContext as any).outputs || {}).join(', ');
const histKeys = Object.keys((templateContext as any).outputs_history || {}).join(', ');
const inputsKeys = Object.keys((templateContext as any).inputs || {}).join(', ');
console.error(
`[prompt-ctx] outputs.keys=${outKeys} hist.keys=${histKeys} inputs.keys=${inputsKeys}`
);
// Log projects specifically if present
const projects = (templateContext as any).inputs?.projects;
if (projects) {
console.error(
`[prompt-ctx] inputs.projects has ${Array.isArray(projects) ? projects.length : 'N/A'} items`
);
}
}
} catch {}
try {
return await this.liquidEngine.parseAndRender(promptContent, templateContext);
} catch (error) {
// Always show a helpful snippet with a caret, similar to YAML errors
const err: any = error || {};
const lines = String(promptContent || '').split(/\r?\n/);
const lineNum: number = Number(err.line || err?.token?.line || err?.location?.line || 0);
const colNum: number = Number(err.col || err?.token?.col || err?.location?.col || 0);
let snippet = '';
if (lineNum > 0) {
const start = Math.max(1, lineNum - 3);
const end = Math.max(lineNum + 2, lineNum);
const width = String(end).length;
for (let i = start; i <= Math.min(end, lines.length); i++) {
const ln = `${String(i).padStart(width, ' ')} | ${lines[i - 1] ?? ''}`;
snippet += ln + '\n';
if (i === lineNum) {
const caretPad = ' '.repeat(Math.max(0, colNum > 1 ? colNum - 1 : 0) + width + 3);
snippet += caretPad + '^\n';
}
}
} else {
// Fallback preview of the first 20 lines
const preview = lines
.slice(0, 20)
.map((l, i) => `${(i + 1).toString().padStart(3, ' ')} | ${l}`)
.join('\n');
snippet = preview + '\n';
}
const msg = `Failed to render prompt template: ${
error instanceof Error ? error.message : 'Unknown error'
}`;
// Print a clear, user-friendly error with context
try {
console.error('\n[prompt-error] ' + msg + '\n' + snippet);
} catch {}
throw new Error(msg);
}
}
/**
* Render Liquid templates in schema definitions
* Supports dynamic enum values and other template-driven schema properties
*/
private async renderSchema(
schema: string | Record<string, unknown> | undefined,
prInfo: PRInfo,
_eventContext?: Record<string, unknown>,
dependencyResults?: Map<string, ReviewSummary>,
outputHistory?: Map<string, unknown[]>,
args?: Record<string, unknown>,
workflowInputs?: Record<string, unknown>
): Promise<string | Record<string, unknown> | undefined> {
if (!schema) return schema;
let schemaStr: string;
if (typeof schema === 'string') {
// Check if string schema contains Liquid templates
if (!schema.includes('{{') && !schema.includes('{%')) {
// No Liquid templates, return as-is (could be a schema reference like 'code-review')
return schema;
}
// String schema with Liquid templates (e.g., JSON string in YAML)
schemaStr = schema;
} else {
// For object schemas, check if they contain Liquid templates
schemaStr = JSON.stringify(schema);
if (!schemaStr.includes('{{') && !schemaStr.includes('{%')) {
// No Liquid templates, return as-is
return schema;
}
}
// Build the same template context as renderPromptTemplate
const outputsRaw: Record<string, unknown> = {};
if (dependencyResults) {
for (const [k, v] of dependencyResults.entries()) {
if (typeof k !== 'string') continue;
if (k.endsWith('-raw')) {
const name = k.slice(0, -4);
const summary = v as ReviewSummary & { output?: unknown };
outputsRaw[name] = summary.output !== undefined ? summary.output : summary;
}
}
}
const templateContext = {
pr: {
number: prInfo.number,
title: prInfo.title,
body: prInfo.body,
author: prInfo.author,
baseBranch: prInfo.base,
headBranch: prInfo.head,
isIncremental: prInfo.isIncremental,
filesChanged: prInfo.files?.map(f => f.filename) || [],
totalAdditions: prInfo.files?.reduce((sum, f) => sum + f.additions, 0) || 0,
totalDeletions: prInfo.files?.reduce((sum, f) => sum + f.deletions, 0) || 0,
totalChanges: prInfo.files?.reduce((sum, f) => sum + f.changes, 0) || 0,
base: prInfo.base,
head: prInfo.head,
},
files: prInfo.files || [],
description: prInfo.body || '',
outputs: dependencyResults
? Object.fromEntries(
Array.from(dependencyResults.entries()).map(([checkName, result]) => [
checkName,
(() => {
const summary = result as ReviewSummary & { output?: unknown };
return summary.output !== undefined ? summary.output : summary;
})(),
])
)
: {},
outputs_history: (() => {
const hist: Record<string, unknown[]> = {};
if (outputHistory) {
for (const [k, v] of outputHistory.entries()) hist[k] = v;
}
return hist;
})(),
outputs_raw: outputsRaw,
args: args || {},
inputs: workflowInputs || {},
};
try {
if (process.env.VISOR_DEBUG === 'true') {
logger.debug(`[schema-render] Rendering schema with Liquid templates`);
logger.debug(
`[schema-render] inputs.projects count: ${Array.isArray((templateContext as any).inputs?.projects) ? (templateContext as any).inputs.projects.length : 'N/A'}`
);
}
const renderedStr = await this.liquidEngine.parseAndRender(schemaStr, templateContext);
// Parse the rendered JSON back to an object
try {
const parsed = JSON.parse(renderedStr);
if (process.env.VISOR_DEBUG === 'true') {
logger.debug(`[schema-render] Successfully rendered schema`);
}
return parsed;
} catch (parseError) {
const errorMsg = parseError instanceof Error ? parseError.message : String(parseError);
// Log full rendered string for debugging (up to 2000 chars to avoid log flooding)
const preview =
renderedStr.length > 2000
? renderedStr.substring(0, 2000) + '...[truncated]'
: renderedStr;
logger.error(`[schema-render] JSON_PARSE_ERROR: Failed to parse rendered schema as JSON`);
logger.error(`[schema-render] Parse error: ${errorMsg}`);
logger.error(`[schema-render] Original schema type: ${typeof schema}`);
logger.error(`[schema-render] Rendered output (${renderedStr.length} chars):\n${preview}`);
// Throw error to make configuration issues visible rather than silently falling back
throw new Error(
`Schema template rendered invalid JSON: ${errorMsg}. ` +
`Check Liquid template syntax. Rendered output starts with: "${renderedStr.substring(0, 100)}..."`
);
}
} catch (error) {
// Re-throw JSON parse errors (already formatted above)
if (
error instanceof Error &&
error.message.includes('Schema template rendered invalid JSON')
) {
throw error;
}
// Handle Liquid rendering errors
const errorMsg = error instanceof Error ? error.message : 'Unknown error';
logger.error(`[schema-render] LIQUID_RENDER_ERROR: Failed to render schema template`);
logger.error(`[schema-render] Error: ${errorMsg}`);
logger.error(
`[schema-render] Original schema: ${schemaStr.substring(0, 500)}${schemaStr.length > 500 ? '...[truncated]' : ''}`
);
// Throw error to make template syntax issues visible
throw new Error(
`Schema Liquid template error: ${errorMsg}. ` +
`Check template syntax in schema definition.`
);
}
}
async execute(
prInfo: PRInfo,
config: CheckProviderConfig,
_dependencyResults?: Map<string, ReviewSummary>,
sessionInfo?: { parentSessionId?: string; reuseSession?: boolean }
): Promise<ReviewSummary> {
// Apply environment configuration if present
if (config.env) {
const result = EnvironmentResolver.withTemporaryEnv(config.env, () => {
// This will be executed with the temporary environment
return this.executeWithConfig(prInfo, config, _dependencyResults, sessionInfo);
});
if (result instanceof Promise) {
return result;
}
return result;
}
return this.executeWithConfig(prInfo, config, _dependencyResults, sessionInfo);
}
private async executeWithConfig(
prInfo: PRInfo,
config: CheckProviderConfig,
_dependencyResults?: Map<string, ReviewSummary>,
sessionInfo?: {
parentSessionId?: string;
reuseSession?: boolean;
} & import('./check-provider.interface').ExecutionContext
): Promise<ReviewSummary> {
try {
if (process.env.VISOR_DEBUG === 'true') {
console.error(`[ai-exec] step=${String((config as any).checkName || 'unknown')}`);
}
} catch {}
// Extract AI configuration - only set properties that are explicitly provided.
// Workspace / allowedFolders will be derived below from the execution context.
const aiConfig: AIReviewConfig = {};
// Check-level AI configuration (ai object)
if (config.ai) {
const aiAny: any = config.ai;
// Helper to resolve Liquid templates in ai config values (e.g., "{{ inputs.max_iterations }}")
const resolveLiquid = async (val: unknown): Promise<string | undefined> => {
if (typeof val !== 'string' || !val.includes('{{')) return undefined;
try {
return (
await this.liquidEngine.parseAndRender(val, {
inputs: (config as any).workflowInputs || {},
env: process.env,
})
).trim();
} catch {
return undefined;
}
};
// Helper to resolve a boolean that may be a Liquid template string
const resolveBool = async (val: unknown): Promise<boolean> => {
const resolved = (await resolveLiquid(val)) ?? val;
if (typeof resolved === 'boolean') return resolved;
if (typeof resolved === 'string') return resolved === 'true';
return !!resolved;
};
const skipTransport: boolean = aiAny.skip_transport_context === true;
// Only set properties that are actually defined to avoid overriding env vars
if (aiAny.apiKey !== undefined) {
aiConfig.apiKey = aiAny.apiKey as string;
}
if (aiAny.model !== undefined) {
const modelVal = (await resolveLiquid(aiAny.model)) ?? String(aiAny.model);
if (modelVal) {
aiConfig.model = modelVal;
}
}
if (aiAny.timeout !== undefined) {
const resolvedTimeout = (await resolveLiquid(aiAny.timeout)) ?? aiAny.timeout;
aiConfig.timeout = Number(resolvedTimeout);
}
if (aiAny.ai_timeout !== undefined) {
const resolvedAiTimeout = (await resolveLiquid(aiAny.ai_timeout)) ?? aiAny.ai_timeout;
aiConfig.aiTimeout = Number(resolvedAiTimeout);
}
if (aiAny.max_iterations !== undefined || aiAny.maxIterations !== undefined) {
const raw = aiAny.max_iterations ?? aiAny.maxIterations;
const resolved = (await resolveLiquid(raw)) ?? raw;
aiConfig.maxIterations = Number(resolved);
}
if (aiAny.provider !== undefined) {
const providerVal = (await resolveLiquid(aiAny.provider)) ?? String(aiAny.provider);
if (providerVal) {
aiConfig.provider = providerVal as 'google' | 'anthropic' | 'openai' | 'bedrock' | 'mock';
}
}
if (aiAny.debug !== undefined) {
aiConfig.debug = aiAny.debug as boolean;
}
if (aiAny.enableDelegate !== undefined) {
aiConfig.enableDelegate = await resolveBool(aiAny.enableDelegate);
}
if (aiAny.enableTasks !== undefined) {
aiConfig.enableTasks = await resolveBool(aiAny.enableTasks);
}
if (aiAny.enableExecutePlan !== undefined) {
aiConfig.enableExecutePlan = await resolveBool(aiAny.enableExecutePlan);
}
if (aiAny.allowEdit !== undefined) {
aiConfig.allowEdit = await resolveBool(aiAny.allowEdit);
}
if (aiAny.allowedTools !== undefined) {
aiConfig.allowedTools = aiAny.allowedTools as string[];
this.logDebug(
`[AI Provider] Read allowedTools from YAML: ${JSON.stringify(aiAny.allowedTools)}`
);
}
if (aiAny.disableTools !== undefined) {
aiConfig.disableTools = await resolveBool(aiAny.disableTools);
this.logDebug(`[AI Provider] Read disableTools from YAML: ${aiAny.disableTools}`);
}
if (aiAny.allowBash !== undefined) {
aiConfig.allowBash = await resolveBool(aiAny.allowBash);
}
if (aiAny.bashConfig !== undefined) {
aiConfig.bashConfig = aiAny.bashConfig as import('../types/config').BashConfig;
}
if (aiAny.search_delegate_provider !== undefined) {
aiConfig.search_delegate_provider =
(await resolveLiquid(aiAny.search_delegate_provider)) ??
(aiAny.search_delegate_provider as string);
}
if (aiAny.search_delegate_model !== undefined) {
aiConfig.search_delegate_model =
(await resolveLiquid(aiAny.search_delegate_model)) ??
(aiAny.search_delegate_model as string);
}
if (aiAny.completion_prompt !== undefined) {
aiConfig.completionPrompt = aiAny.completion_prompt as string;
}
if (aiAny.skip_code_context !== undefined) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(aiConfig as any).skip_code_context = aiAny.skip_code_context as boolean;
} else if (skipTransport) {
(aiConfig as any).skip_code_context = true;
}
// Optional: allow disabling Slack context separately from PR/code context
if (aiAny.skip_slack_context !== undefined) {
(aiConfig as any).skip_slack_context = aiAny.skip_slack_context as boolean;
} else if (skipTransport) {
(aiConfig as any).skip_slack_context = true;
}
if (aiAny.retry !== undefined) {
aiConfig.retry = aiAny.retry as import('../types/config').AIRetryConfig;
}
if (aiAny.fallback !== undefined) {
aiConfig.fallback = aiAny.fallback as import('../types/config').AIFallbackConfig;
}
}
// Derive workspace-aware allowedFolders for ProbeAgent when workspace
// isolation is enabled. This ensures tools like search/query operate
// inside the isolated workspace (and its project symlinks) instead of
// the Visor repository root.
// Folder names are human-readable (tyk-docs, visor2) thanks to WorkspaceManager.
try {
const ctxAny: any = sessionInfo as any;
const parentCtx = ctxAny?._parentContext;
const workspace = parentCtx?.workspace;
// Enhanced debug logging for workspace propagation diagnosis
logger.debug(
`[AI Provider] Workspace detection for check '${(config as any).checkName || 'unknown'}':`
);
logger.debug(`[AI Provider] sessionInfo exists: ${!!sessionInfo}`);
logger.debug(`[AI Provider] _parentContext exists: ${!!parentCtx}`);
logger.debug(`[AI Provider] workspace exists: ${!!workspace}`);
if (workspace) {
logger.debug(
`[AI Provider] workspace.isEnabled exists: ${typeof workspace.isEnabled === 'function'}`
);
logger.debug(
`[AI Provider] workspace.isEnabled(): ${typeof workspace.isEnabled === 'function' ? workspace.isEnabled() : 'N/A'}`
);
const projectCount =
typeof workspace.listProjects === 'function' ? workspace.listProjects()?.length : 'N/A';
logger.debug(`[AI Provider] workspace.listProjects() count: ${projectCount}`);
}
if (workspace && typeof workspace.isEnabled === 'function' && workspace.isEnabled()) {
const folders: string[] = [];
let workspaceRoot: string | undefined;
let mainProjectPath: string | undefined;
try {
const info = workspace.getWorkspaceInfo?.();
if (info && typeof info.workspacePath === 'string') {
workspaceRoot = info.workspacePath;
mainProjectPath = info.mainProjectPath;
// Add workspace root first so allowedFolders[0] is the workspace root.
// This keeps compatibility with ProbeAgent's legacy default cwd behavior,
// while we also set explicit path/cwd below.
folders.push(info.workspacePath);
// NOTE: We intentionally do NOT add mainProjectPath here.
// Inclusion of the main project is controlled below via
// workspace.include_main_project / VISOR_WORKSPACE_INCLUDE_MAIN_PROJECT.
}
} catch {
// ignore workspace info errors
}
// Collect checked-out projects (these are the user's actual projects)
const projectPaths: string[] = [];
try {
const projects = workspace.listProjects?.() || [];
for (const proj of projects as any[]) {
if (proj && typeof proj.path === 'string') {
// Project paths have human-readable names (tyk-docs, not checkout-tyk-docs)
folders.push(proj.path);
projectPaths.push(proj.path);
}
}
} catch {
// ignore project listing errors
}
// Only include the main project when explicitly enabled.
const workspaceCfg = parentCtx?.config?.workspace as
| { include_main_project?: boolean }
| undefined;
const includeMainProject =
workspaceCfg?.include_main_project === true ||
process.env.VISOR_WORKSPACE_INCLUDE_MAIN_PROJECT === 'true';
if (includeMainProject && mainProjectPath) {
folders.push(mainProjectPath);
logger.debug(`[AI Provider] Including main project (enabled): ${mainProjectPath}`);
} else if (mainProjectPath) {
logger.debug(`[AI Provider] Excluding main project (disabled): ${mainProjectPath}`);
}