principles-disciple 1.61.0 → 1.63.0

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.
@@ -1,175 +0,0 @@
1
- /**
2
- * Bash Risk Analysis Module
3
- *
4
- * Analyzes bash command security risks and determines command categorization.
5
- *
6
- * **Responsibilities:**
7
- * - De-obfuscate Unicode/Cyrillic lookalike characters (security bypass prevention)
8
- * - Tokenize command chains to detect multi-command bypasses
9
- * - Classify commands as: 'safe', 'dangerous', or 'normal'
10
- * - Pattern matching against safe/dangerous regex patterns
11
- * - Fail-closed behavior (invalid regex = dangerous)
12
- *
13
- * **Configuration:**
14
- * - Bash safe patterns from gfi_gate.bash_safe_patterns
15
- * - Bash dangerous patterns from gfi_gate.bash_dangerous_patterns
16
- */
17
-
18
- // TODO: Extract types from gate.ts related to bash risk analysis
19
- export interface BashRiskConfig {
20
- bash_safe_patterns?: string[];
21
- bash_dangerous_patterns?: string[];
22
- }
23
-
24
- export type BashRiskLevel = 'safe' | 'dangerous' | 'normal';
25
-
26
- /**
27
- * Analyzes a bash command to determine its risk level.
28
- *
29
- * Implements security features:
30
- * - Unicode/Cyrillic de-obfuscation to detect homograph attacks
31
- * - Command chain tokenization to catch multi-command bypasses
32
- * - Pattern matching against safe/dangerous regex patterns
33
- * - Fail-closed behavior (invalid dangerous regex = dangerous)
34
- *
35
- * @param command - The bash command to analyze
36
- * @param safePatterns - Regex patterns that indicate safe commands
37
- * @param dangerousPatterns - Regex patterns that indicate dangerous commands
38
- * @param logger - Optional logger for warnings about invalid patterns
39
- * @returns The risk level: 'safe', 'dangerous', or 'normal'
40
- */
41
-
42
-
43
- export function analyzeBashCommand(
44
- command: string,
45
- safePatterns: string[],
46
- dangerousPatterns: string[],
47
- logger?: { warn?: ( _message: string) => void }
48
- ): BashRiskLevel {
49
- let normalizedCmd = command.trim().toLowerCase();
50
-
51
- // Unicode de-obfuscation — convert Cyrillic/Unicode lookalikes to ASCII equivalents
52
- // Common Cyrillic lookalikes that could bypass detection: аеорсух (Cyrillic) → aeopcyx (Latin)
53
- const CYRILLIC_TO_LATIN: Record<string, string> = {
54
- 'а': 'a', 'е': 'e', 'о': 'o', 'р': 'p', 'с': 'c', 'у': 'y', 'х': 'x',
55
- 'А': 'a', 'Е': 'e', 'О': 'o', 'Р': 'p', 'С': 'c', 'У': 'y', 'Х': 'x',
56
- // Additional confusable chars
57
- 'і': 'i', 'ј': 'j', 'ѕ': 's', 'ԁ': 'd', 'ɡ': 'g', 'һ': 'h', 'ⅰ': 'i',
58
- 'ƚ': 'l', 'м': 'm', 'п': 'n', 'ѵ': 'v', 'ѡ': 'w', 'ᴦ': 'r', 'ꜱ': 's',
59
- };
60
- normalizedCmd = normalizedCmd.replace(/[а-яА-Яіјѕԁɡһⅰƚмпеꜱѵѡᴦꜱ]/g, m => CYRILLIC_TO_LATIN[m] ?? m);
61
-
62
- // Zero-width character detection — detect hidden characters that could bypass pattern matching
63
- // Common zero-width characters used in command injection:
64
- // - Zero-width space (U+200B)
65
- // - Zero-width non-joiner (U+200C)
66
- // - Zero-width joiner (U+200D)
67
- // - Word joiner (U+2060)
68
- // - Zero-width invisible separator (U+FEFF)
69
-
70
- const ZERO_WIDTH_CHARS = /\u200B|\u200C|\u200D|\u2060|\uFEFF/g;
71
- if (ZERO_WIDTH_CHARS.test(command)) {
72
- logger?.warn?.(`[PD_GATE] Bash command contains zero-width characters — blocking as dangerous`);
73
- return 'dangerous'; // Fail-closed: zero-width chars are suspicious
74
- }
75
-
76
- // Tokenize command chain before pattern matching to catch `cmd1 && cmd2` bypasses
77
- // Only split on statement separators (; && ||), NOT on pipe (|) which is part of the command
78
- const tokens = normalizedCmd
79
- .split(/\s*(?:;|&&|\|\|)\s*/)
80
- .map(t => t.trim())
81
- .filter(t => t.length > 0);
82
-
83
- // If no tokens (e.g., pure pipe-only), use the original
84
- const segments = tokens.length > 0 ? tokens : [normalizedCmd];
85
-
86
- // Also strip outer $() and backticks from each segment, but PRESERVE inner content
87
- const cleanSegments = segments.map(seg => {
88
- let s = seg;
89
- // Extract inner content from $() or ${} or backtick-wrapped commands
90
- // IMPORTANT: Preserve the inner command for analysis, don't drop it entirely
91
- s = s.replace(/^\$\(([^)]+)\)$/, '$1').replace(/^\$\{([^}]+)\}$/, '$1').replace(/^`([^`]+)`$/, '$1');
92
- return s.trim();
93
- }).filter(s => s.length > 0);
94
-
95
- // SECURITY: If original input was non-empty but we have no analyzable content, fail closed
96
- if (cleanSegments.length === 0 && normalizedCmd.trim().length > 0) {
97
- logger?.warn?.(`[PD_GATE] Bash command analysis produced empty segments from non-empty input, failing closed: ${normalizedCmd.substring(0, 100)}`);
98
- return 'dangerous';
99
- }
100
-
101
- // 1. Check dangerous patterns against each segment
102
- for (const seg of cleanSegments) {
103
- for (const pattern of dangerousPatterns) {
104
- try {
105
- if (new RegExp(pattern, 'i').test(seg)) {
106
- return 'dangerous';
107
- }
108
- } catch (error) {
109
- logger?.warn?.(`[PD_GATE] Invalid dangerous bash regex "${pattern}": ${String(error)}. Failing closed.`);
110
- return 'dangerous';
111
- // Fail-closed: 无效的危险模式正则视为匹配危险命令
112
- }
113
- }
114
- }
115
-
116
- // 2. Check safe patterns (only if ALL segments are safe)
117
- for (const seg of cleanSegments) {
118
- let isSafe = false;
119
- for (const pattern of safePatterns) {
120
- try {
121
- if (new RegExp(pattern, 'i').test(seg)) {
122
- isSafe = true;
123
- break;
124
- }
125
- } catch (error) {
126
- logger?.warn?.(`[PD_GATE] Invalid safe bash regex "${pattern}": ${String(error)}. Ignoring safe override.`);
127
- }
128
- }
129
- if (!isSafe) {
130
- // Not all segments are safe → treat as normal
131
- return 'normal';
132
- }
133
- }
134
-
135
- // All segments are safe
136
- return 'safe';
137
- }
138
-
139
- export interface DynamicThresholdConfig {
140
- large_change_lines: number;
141
- ep_tier_multipliers: Record<string, number>;
142
- }
143
-
144
- /**
145
- * Calculates the dynamic GFI threshold based on EP tier and line changes.
146
- *
147
- * The threshold is adjusted by:
148
- * 1. EP tier multiplier (higher tiers get higher thresholds)
149
- * 2. Large change reduction (big edits lower the threshold to catch more issues)
150
- *
151
- * @param baseThreshold - The base GFI threshold (typically 50 for GFI)
152
- * @param epTier - Current EP tier (1-5)
153
- * @param lineChanges - Number of lines being changed
154
- * @param config - Configuration with large_change_lines and ep_tier_multipliers
155
- * @returns The adjusted threshold (minimum 0)
156
- */
157
-
158
- export function calculateDynamicThreshold(
159
- baseThreshold: number,
160
- epTier: number,
161
- lineChanges: number,
162
- config: DynamicThresholdConfig
163
- ): number {
164
- // 1. EP Tier multiplier
165
- const tierMultiplier = config.ep_tier_multipliers[epTier.toString()] || 1.0;
166
- let threshold = baseThreshold * tierMultiplier;
167
-
168
- // 2. Large scale modification reduces threshold
169
- if (lineChanges > config.large_change_lines) {
170
- const ratio = Math.min(lineChanges / 200, 0.5); // Reduce by up to 50%
171
- threshold = threshold * (1 - ratio);
172
- }
173
-
174
- return Math.round(Math.max(threshold, 0));
175
- }
@@ -1,302 +0,0 @@
1
- /**
2
- * Edit Verification Module
3
- *
4
- * Enforces P-03 (precise verification principle) for edit tool operations.
5
- *
6
- * **Responsibilities:**
7
- * - Verify oldText matches current file content before edit
8
- * - Fuzzy matching for whitespace-agnostic comparison
9
- * - File size limits and binary file detection
10
- * - Automatic correction of whitespace mismatches
11
- * - Detailed error messages with guidance for fix
12
- *
13
- * **Configuration:**
14
- * - Edit verification settings from profile.edit_verification
15
- * - Max file size threshold (default 10MB)
16
- * - Fuzzy match threshold (default 0.8)
17
- * - Skip action for large files (warn/block)
18
- */
19
-
20
- import * as fs from 'fs';
21
- import * as path from 'path';
22
- import type { PluginHookBeforeToolCallEvent, PluginHookBeforeToolCallResult } from '../openclaw-sdk.js';
23
- import type { WorkspaceContext } from '../core/workspace-context.js';
24
-
25
- export interface EditVerificationConfig {
26
- enabled?: boolean;
27
- max_file_size_bytes?: number;
28
- fuzzy_match_enabled?: boolean;
29
- fuzzy_match_threshold?: number;
30
- skip_large_file_action?: 'warn' | 'block';
31
- }
32
-
33
- /**
34
- * Normalize a line for fuzzy matching by collapsing whitespace
35
- */
36
- export function normalizeLine(line: string): string {
37
- return line.replace(/\s+/g, ' ').trim();
38
- }
39
-
40
- /**
41
- * Find fuzzy match between oldText and current file content
42
- * @param lines - File content split into lines
43
- * @param oldLines - oldText split into lines
44
- * @param threshold - Match threshold (0-1)
45
- * @returns Match index or -1 if not found
46
- */
47
- export function findFuzzyMatch(lines: string[], oldLines: string[], threshold = 0.8): number {
48
- if (oldLines.length === 0) return -1; // P2 fix: empty array boundary check
49
-
50
- const normalizedLines = lines.map(normalizeLine);
51
- const normalizedOldLines = oldLines.map(normalizeLine);
52
-
53
- // Try to find matching sequence
54
- for (let i = 0; i <= lines.length - oldLines.length; i++) {
55
- let matchCount = 0;
56
- for (let j = 0; j < oldLines.length; j++) {
57
- if (normalizedLines[i + j] === normalizedOldLines[j]) {
58
- matchCount++;
59
- }
60
- }
61
-
62
- // Use threshold from config
63
- if (matchCount >= oldLines.length * threshold) {
64
- return i;
65
- }
66
- }
67
-
68
- return -1;
69
- }
70
-
71
- /**
72
- * Try to find a fuzzy match for oldText in current content
73
- * @param currentContent - Current file content
74
- * @param oldText - Text to match
75
- * @param threshold - Match threshold (0-1)
76
- * @returns Object with found status and corrected text if found
77
- */
78
- export function tryFuzzyMatch(currentContent: string, oldText: string, threshold = 0.8): { found: boolean; correctedText?: string } {
79
- const lines = currentContent.split('\n');
80
- const oldLines = oldText.split('\n');
81
-
82
- const matchIndex = findFuzzyMatch(lines, oldLines, threshold);
83
-
84
- if (matchIndex !== -1) {
85
- // Found fuzzy match, extract actual text from file
86
- const correctedText = lines.slice(matchIndex, matchIndex + oldLines.length).join('\n');
87
- return { found: true, correctedText };
88
- }
89
-
90
- return { found: false };
91
- }
92
-
93
- /**
94
- * Generate a helpful error message for edit verification failure
95
- */
96
- export function generateEditError(filePath: string, oldText: string, currentContent: string): string {
97
- const expectedSnippet = oldText.split('\n').slice(0, 3).join('\n').substring(0, 200);
98
- const actualSnippet = currentContent.substring(0, 200);
99
-
100
- return `[P-03 Violation] Edit verification failed
101
-
102
- File: ${filePath}
103
-
104
- The text you're trying to replace does not match the current file content.
105
-
106
- Expected to find:
107
- ${expectedSnippet}${oldText.length > 200 ? '...' : ''}
108
-
109
- Actual file contains:
110
- ${actualSnippet}${currentContent.length > 200 ? '...' : ''}
111
-
112
- Possible reasons:
113
- - File has been modified by another process
114
- - Whitespace characters do not match (spaces, tabs, newlines)
115
- - Context compression caused outdated information
116
-
117
- Solution:
118
- 1. Use 'read' tool to get current file content
119
- 2. Update your edit command with exact text from file
120
- 3. Retry edit operation
121
-
122
- This is enforced by P-03 (精确匹配前验证原则).`;
123
- }
124
-
125
- /**
126
- * Handle edit tool verification before allowing operation
127
- * This enforces P-03 at the tool layer
128
- */
129
-
130
-
131
- export function handleEditVerification(
132
- event: PluginHookBeforeToolCallEvent,
133
- wctx: WorkspaceContext,
134
-
135
- ctx: { logger?: any; sessionId?: string },
136
- config: EditVerificationConfig = {}
137
- ): PluginHookBeforeToolCallResult | void {
138
- // Skip verification if disabled - return early without any processing or logging
139
- if (config.enabled === false) {
140
- return;
141
- }
142
-
143
- const logger = ctx.logger || console;
144
- const maxSizeBytes = config.max_file_size_bytes ?? 10 * 1024 * 1024; // Default 10MB
145
- const fuzzyMatchEnabled = config.fuzzy_match_enabled !== false;
146
- const fuzzyMatchThreshold = config.fuzzy_match_threshold ?? 0.8;
147
- const skipAction: 'warn' | 'block' = config.skip_large_file_action ?? 'warn';
148
-
149
- // 1. Extract parameters (handle both parameter naming conventions)
150
- const filePath = event.params.file_path || event.params.path || event.params.file;
151
- const oldText = event.params.oldText || event.params.old_string;
152
-
153
- if (!filePath || !oldText) {
154
- // Missing required parameters, let it fail naturally
155
- return;
156
- }
157
-
158
- // 2. Resolve and read file
159
-
160
-
161
- let absolutePath: string;
162
- try {
163
- absolutePath = wctx.resolve(filePath);
164
- } catch (_error) { // eslint-disable-line @typescript-eslint/no-unused-vars -- Reason: intentionally unused - let it fail naturally on path resolution error
165
- // Path resolution error, let it fail naturally
166
- return;
167
- }
168
-
169
- // 2.5. Skip verification for binary files
170
- const BINARY_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.svg',
171
- '.pdf', '.zip', '.tar', '.gz', '.7z', '.rar',
172
- '.exe', '.dll', '.so', '.dylib', '.bin',
173
- '.mp3', '.mp4', '.avi', '.mov', '.wav',
174
- '.ttf', '.otf', '.woff', '.woff2',
175
- '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx'];
176
- const ext = path.extname(absolutePath).toLowerCase();
177
- if (BINARY_EXTENSIONS.includes(ext)) {
178
- logger?.info?.(`[PD_GATE:EDIT_VERIFY] Skipping verification for binary file: ${path.basename(filePath)}`);
179
- return;
180
- }
181
-
182
- try {
183
- // 2.6. Check file size before reading (P-03 improvement)
184
- try {
185
- const stats = fs.statSync(absolutePath);
186
- const fileSizeBytes = stats.size;
187
- const fileSizeMB = fileSizeBytes / (1024 * 1024);
188
-
189
- if (fileSizeBytes > maxSizeBytes) {
190
- const message = `[PD_GATE:EDIT_VERIFY] File size check: ${path.basename(filePath)} is ${fileSizeMB.toFixed(2)}MB (threshold: ${(maxSizeBytes / (1024 * 1024)).toFixed(2)}MB)`;
191
-
192
- if (skipAction === 'block') {
193
- logger?.warn?.(message + ' - BLOCKED');
194
- return {
195
- block: true,
196
- blockReason: `${message}\n\nFile is too large for edit verification. Increase max_file_size_bytes in PROFILE.json or reduce file size.`
197
- };
198
- } else {
199
- logger?.warn?.(message + ' - SKIPPING verification');
200
- return; // Skip verification but allow operation
201
- }
202
- }
203
-
204
- logger?.info?.(`[PD_GATE:EDIT_VERIFY] File size check passed: ${path.basename(filePath)} (${fileSizeMB.toFixed(2)}MB)`);
205
- } catch (statError) {
206
- // File stat error (e.g., permission denied)
207
- const errStr = statError instanceof Error ? statError.message : String(statError);
208
- const errCode = (statError as { code?: string }).code;
209
-
210
- if (errCode === 'EACCES' || errCode === 'EPERM') {
211
- logger?.error?.(`[PD_GATE:EDIT_VERIFY] Permission denied accessing file: ${path.basename(filePath)} (${errStr})`);
212
- return {
213
- block: true,
214
- blockReason: `[P-03 Error] Permission denied: Cannot access file ${absolutePath}\n\nError: ${errStr}\n\nSolution: Check file permissions or run with appropriate access rights.`
215
- };
216
- } else if (errCode === 'ENOENT') {
217
- logger?.warn?.(`[PD_GATE:EDIT_VERIFY] File not found: ${path.basename(filePath)} (${errStr})`);
218
- // File doesn't exist - let edit operation proceed (it will create file)
219
- return;
220
- } else {
221
- logger?.warn?.(`[PD_GATE:EDIT_VERIFY] Stat error: ${errStr}`);
222
- // Let it fail naturally on read attempt
223
- }
224
- }
225
-
226
- // 3. Read current file content with improved error handling
227
-
228
-
229
- let currentContent: string;
230
- try {
231
- currentContent = fs.readFileSync(absolutePath, 'utf-8');
232
- } catch (readError) {
233
- const errStr = readError instanceof Error ? readError.message : String(readError);
234
- const errCode = (readError as { code?: string }).code;
235
-
236
- if (errCode === 'EACCES' || errCode === 'EPERM') {
237
- logger?.error?.(`[PD_GATE:EDIT_VERIFY] Permission denied reading file: ${path.basename(filePath)} (${errStr})`);
238
- return {
239
- block: true,
240
- blockReason: `[P-03 Error] Permission denied: Cannot read file ${absolutePath}\n\nError: ${errStr}\n\nSolution: Check file permissions or run with appropriate access rights.`
241
- };
242
- } else if (errCode === 'ENOENT') {
243
- logger?.warn?.(`[PD_GATE:EDIT_VERIFY] File not found: ${path.basename(filePath)} (${errStr})`);
244
- // File doesn't exist - let edit operation proceed
245
- return;
246
- } else if (errStr.includes('UTF-8') || errStr.includes('encoding')) {
247
- logger?.error?.(`[PD_GATE:EDIT_VERIFY] Encoding error reading file: ${path.basename(filePath)} (${errStr})`);
248
- return {
249
- block: true,
250
- blockReason: `[P-03 Error] Encoding error: Cannot read file ${absolutePath}\n\nError: ${errStr}\n\nThe file appears to use an encoding other than UTF-8. Edit verification requires UTF-8 readable text files.\n\nSolution: Ensure file is UTF-8 encoded text, or mark binary extensions to skip verification.`
251
- };
252
- } else {
253
- logger?.warn?.(`[PD_GATE:EDIT_VERIFY] Read error: ${errStr}`);
254
- // Let it fail naturally
255
- return;
256
- }
257
- }
258
-
259
- // 4. Verify oldText exists in current content
260
- if (!currentContent.includes(oldText)) {
261
- logger?.info?.(`[PD_GATE:EDIT_VERIFY] Exact match failed for ${path.basename(filePath)}, trying fuzzy match`);
262
-
263
- // 5. Try fuzzy matching (if enabled)
264
- if (fuzzyMatchEnabled) {
265
- const fuzzyResult = tryFuzzyMatch(currentContent, oldText, fuzzyMatchThreshold);
266
-
267
- if (fuzzyResult.found && fuzzyResult.correctedText) {
268
- logger?.info?.(`[PD_GATE:EDIT_VERIFY] Fuzzy match found for ${path.basename(filePath)}, auto-correcting oldText`);
269
-
270
- // Return corrected parameters
271
- return {
272
- params: {
273
- ...event.params,
274
- oldText: fuzzyResult.correctedText,
275
- old_string: fuzzyResult.correctedText
276
- }
277
- };
278
- }
279
- }
280
-
281
- // 6. No match found, block operation with helpful error
282
- const errorMsg = generateEditError(absolutePath, oldText, currentContent);
283
-
284
- logger?.error?.(`[PD_GATE:EDIT_VERIFY] Block edit on ${path.basename(filePath)}: oldText not found`);
285
-
286
- return {
287
- block: true,
288
- blockReason: errorMsg
289
- };
290
- }
291
-
292
- // 7. Verification passed, allow edit to proceed
293
- logger?.info?.(`[PD_GATE:EDIT_VERIFY] Verified edit on ${path.basename(filePath)}`);
294
- return;
295
-
296
- } catch (error) {
297
- // Unexpected error - let it fail naturally
298
- const errorStr = error instanceof Error ? error.message : String(error);
299
- logger?.warn?.(`[PD_GATE:EDIT_VERIFY] Unexpected error: ${errorStr}`);
300
- return;
301
- }
302
- }
@@ -1,186 +0,0 @@
1
- /**
2
- * GFI Gate Module
3
- *
4
- * Handles Fatigue Index (GFI) based tool blocking with TIER 0-3 classification.
5
- *
6
- * **Responsibilities:**
7
- * - Calculate dynamic GFI thresholds based on EP tier and line changes
8
- * - Apply tier-based tool blocking:
9
- * - TIER 0: Read-only tools (never blocked)
10
- * - TIER 1: Low-risk writes (blocked when GFI >= low_risk_block threshold)
11
- * - TIER 2: High-risk operations (blocked when GFI >= high_risk_block threshold)
12
- * - TIER 3: Bash commands (content-dependent blocking)
13
- * - Prevent subagent spawn at critically high GFI (>=90)
14
- *
15
- * **Configuration:**
16
- * - GFI thresholds from config.gfi_gate
17
- * - EP tier multipliers for dynamic threshold calculation
18
- * - Large change adjustments
19
- *
20
- * **Block Persistence:**
21
- * - Uses shared `recordGateBlockAndReturn` from gate-block-helper.ts
22
- * - Ensures single authoritative block persistence path
23
- */
24
-
25
- import { getSession } from '../core/session-tracker.js';
26
- import { estimateLineChanges } from '../core/risk-calculator.js';
27
- import { analyzeBashCommand, calculateDynamicThreshold } from './bash-risk.js';
28
- import { BASH_TOOLS_SET, HIGH_RISK_TOOLS, LOW_RISK_WRITE_TOOLS, AGENT_TOOLS } from '../constants/tools.js';
29
- import { AGENT_SPAWN_GFI_THRESHOLD } from '../config/index.js';
30
- import { recordGateBlockAndReturn } from './gate-block-helper.js';
31
- import { getEvolutionEngine } from '../core/evolution-engine.js';
32
- import type { WorkspaceContext } from '../core/workspace-context.js';
33
- import type { PluginHookBeforeToolCallEvent, PluginHookBeforeToolCallResult } from '../openclaw-sdk.js';
34
-
35
- export interface GfiGateConfig {
36
- enabled?: boolean;
37
- thresholds?: {
38
- low_risk_block?: number;
39
- high_risk_block?: number;
40
- };
41
- large_change_lines?: number;
42
- ep_tier_multipliers?: Record<string, number>;
43
- bash_safe_patterns?: string[];
44
- bash_dangerous_patterns?: string[];
45
- }
46
-
47
- /**
48
- * Internal helper to call the shared block helper with gfi-gate source tag.
49
- */
50
-
51
-
52
- function block(
53
- wctx: WorkspaceContext,
54
- filePath: string,
55
- reason: string,
56
- toolName: string,
57
- sessionId: string | undefined,
58
-
59
- logger?: { info?: (message: string) => void; warn?: (message: string) => void; error?: (message: string) => void }
60
-
61
- ): PluginHookBeforeToolCallResult {
62
- return recordGateBlockAndReturn(wctx, {
63
- filePath,
64
- reason,
65
- toolName,
66
- sessionId,
67
- blockSource: 'gfi-gate',
68
- }, logger ||
69
- { warn: () => { /* no-op */ }, error: () => { /* no-op */ } } as const);
70
- }
71
-
72
-
73
-
74
- export function checkGfiGate(
75
- event: PluginHookBeforeToolCallEvent,
76
- wctx: WorkspaceContext,
77
- sessionId: string | undefined,
78
- config: GfiGateConfig,
79
-
80
- logger?: { info?: (message: string) => void; warn?: (message: string) => void }
81
-
82
- ): PluginHookBeforeToolCallResult | undefined {
83
- if (!config || config.enabled === false || !sessionId) {
84
- return undefined;
85
- }
86
-
87
- const session = getSession(sessionId);
88
- const currentGfi = session?.currentGfi || 0;
89
-
90
- const getEpTier = (): number => {
91
- return getEvolutionEngine(wctx.workspaceDir).getTier();
92
- };
93
-
94
- // TIER 3: Bash commands
95
- if (BASH_TOOLS_SET.has(event.toolName)) {
96
- const command = String(event.params.command || event.params.args || '');
97
- const bashRisk = analyzeBashCommand(
98
- command,
99
- config.bash_safe_patterns || [],
100
- config.bash_dangerous_patterns || [],
101
- logger
102
- );
103
-
104
- if (bashRisk === 'dangerous') {
105
- logger?.warn?.(`[PD:GFI_GATE] Dangerous bash command blocked: ${command.substring(0, 50)}...`);
106
- return block(wctx, command.substring(0, 100), `危险命令被拦截。检测到危险命令模式,需要确认执行意图。`, event.toolName, sessionId, logger);
107
- }
108
-
109
- if (bashRisk === 'safe') {
110
- return undefined;
111
- }
112
-
113
- // normal bash - check GFI threshold
114
- const tier = getEpTier();
115
- const baseThreshold = config.thresholds?.low_risk_block || 70;
116
- const dynamicThreshold = calculateDynamicThreshold(
117
- baseThreshold,
118
- tier,
119
- 0,
120
- {
121
- large_change_lines: config.large_change_lines || 50,
122
- ep_tier_multipliers: config.ep_tier_multipliers || { '1': 0.5, '2': 0.75, '3': 1.0, '4': 1.5, '5': 2.0 },
123
- }
124
- );
125
-
126
- if (currentGfi >= dynamicThreshold) {
127
- logger?.warn?.(`[PD:GFI_GATE] Bash blocked by GFI: ${currentGfi} >= ${dynamicThreshold}`);
128
- return block(wctx, command.substring(0, 100), `疲劳指数过高 (GFI: ${currentGfi}/${dynamicThreshold})。系统进入保护模式。`, event.toolName, sessionId, logger);
129
- }
130
-
131
- return undefined;
132
- }
133
-
134
- // TIER 2: High-risk tools
135
- if (HIGH_RISK_TOOLS.has(event.toolName)) {
136
- const tier = getEpTier();
137
- const baseThreshold = config.thresholds?.high_risk_block || 40;
138
- const dynamicThreshold = calculateDynamicThreshold(
139
- baseThreshold,
140
- tier,
141
- 0,
142
- {
143
- large_change_lines: config.large_change_lines || 50,
144
- ep_tier_multipliers: config.ep_tier_multipliers || { '1': 0.5, '2': 0.75, '3': 1.0, '4': 1.5, '5': 2.0 },
145
- }
146
- );
147
-
148
- if (currentGfi >= dynamicThreshold) {
149
- const filePath = event.params.file_path || event.params.path || event.params.file || event.params.target || 'unknown';
150
- logger?.warn?.(`[PD:GFI_GATE] High-risk tool "${event.toolName}" blocked by GFI: ${currentGfi} >= ${dynamicThreshold}`);
151
- return block(wctx, filePath, `高风险操作被拦截。GFI: ${currentGfi}/${dynamicThreshold}。高风险工具需要更低的阈值。`, event.toolName, sessionId, logger);
152
- }
153
- }
154
-
155
- // TIER 1: Low-risk write tools
156
- if (LOW_RISK_WRITE_TOOLS.has(event.toolName)) {
157
- const tier = getEpTier();
158
- const lineChanges = estimateLineChanges({ toolName: event.toolName, params: event.params });
159
- const baseThreshold = config.thresholds?.low_risk_block || 70;
160
- const dynamicThreshold = calculateDynamicThreshold(
161
- baseThreshold,
162
- tier,
163
- lineChanges,
164
- {
165
- large_change_lines: config.large_change_lines || 50,
166
- ep_tier_multipliers: config.ep_tier_multipliers || { '1': 0.5, '2': 0.75, '3': 1.0, '4': 1.5, '5': 2.0 },
167
- }
168
- );
169
-
170
- if (currentGfi >= dynamicThreshold) {
171
- const filePath = event.params.file_path || event.params.path || event.params.file || event.params.target || 'unknown';
172
- logger?.warn?.(`[PD:GFI_GATE] Low-risk tool "${event.toolName}" blocked by GFI: ${currentGfi} >= ${dynamicThreshold}`);
173
- return block(wctx, filePath, `疲劳指数过高 (GFI: ${currentGfi}/${dynamicThreshold})。系统进入保护模式。`, event.toolName, sessionId, logger);
174
- }
175
- }
176
-
177
- // AGENT_TOOLS: Block subagent spawn when GFI is critically high
178
- if (AGENT_TOOLS.has(event.toolName)) {
179
- if (currentGfi >= AGENT_SPAWN_GFI_THRESHOLD) {
180
- logger?.warn?.(`[PD:GFI_GATE] Agent tool "${event.toolName}" blocked by GFI: ${currentGfi} >= ${AGENT_SPAWN_GFI_THRESHOLD}`);
181
- return block(wctx, 'subagent-spawn', `疲劳指数过高,禁止派生子智能体。GFI: ${currentGfi}/${AGENT_SPAWN_GFI_THRESHOLD}`, event.toolName, sessionId, logger);
182
- }
183
- }
184
-
185
- return undefined;
186
- }