forked from rpamis/comet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhook-adapter.ts
More file actions
217 lines (198 loc) · 6.52 KB
/
Copy pathhook-adapter.ts
File metadata and controls
217 lines (198 loc) · 6.52 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
import { readFileSync } from 'fs';
import path from 'path';
import type { CometHookDecision, CometHookProcessOutput, CometHookRequest } from './hook-types.js';
const WRITE_TOOL_NAMES = new Set([
'applypatch',
'create',
'createfile',
'deletefile',
'edit',
'editfile',
'patch',
'strreplaceeditor',
'write',
'writefile',
'writefiletool',
]);
const NON_WRITE_TOOL_NAMES = new Set([
'glob',
'grep',
'listfiles',
'read',
'readfile',
'search',
'view',
]);
const SINGULAR_PATH_KEYS = ['file_path', 'filePath', 'path', 'target_file', 'targetFile'] as const;
const PLURAL_PATH_KEYS = ['file_paths', 'filePaths', 'paths', 'files', 'targets'] as const;
const NESTED_TARGET_KEYS = ['operations', 'edits'] as const;
const PATCH_KEYS = ['patch', 'diff', 'patchText', 'patch_text', 'changes'] as const;
export const COMET_HOOK_PLATFORM_IDS = new Set([
'claude',
'codex',
'windsurf',
'github-copilot',
'gemini',
'amazon-q',
'qwen',
'kiro',
'codebuddy',
'qoder',
'trae',
'trae-cn',
]);
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
}
function normalizedToolName(value: string): string {
return value.toLowerCase().replace(/[^a-z0-9]+/gu, '');
}
function readToolName(input: Record<string, unknown>): string | null {
for (const key of ['tool_name', 'toolName', 'tool', 'name'] as const) {
const value = input[key];
if (typeof value === 'string' && value.trim()) return value.trim();
}
return null;
}
function readWorkingDirectory(input: Record<string, unknown>): string | undefined {
for (const key of ['cwd', 'working_directory', 'workspaceRoot'] as const) {
const value = input[key];
if (typeof value !== 'string' || !value.trim() || !path.isAbsolute(value.trim())) continue;
return path.resolve(value.trim());
}
return undefined;
}
function parseJsonValue(value: unknown): unknown {
if (typeof value !== 'string') return value;
const source = value.trim();
if (!source.startsWith('{') && !source.startsWith('[')) return value;
try {
return JSON.parse(source) as unknown;
} catch {
return value;
}
}
function readToolArguments(input: Record<string, unknown>): unknown {
for (const key of ['tool_input', 'toolInput', 'toolArgs', 'tool_args', 'arguments'] as const) {
if (input[key] !== undefined) return parseJsonValue(input[key]);
}
return input;
}
function patchTargets(source: string): string[] {
const targets: string[] = [];
const patterns = [
/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,
/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu,
];
for (const pattern of patterns) {
for (const match of source.matchAll(pattern)) {
const target = match[1]?.trim();
if (target && target !== '/dev/null') targets.push(target);
}
}
return targets;
}
function addTarget(targets: string[], value: unknown): void {
if (typeof value === 'string') {
const target = value.trim();
if (target) targets.push(target);
return;
}
if (Array.isArray(value)) {
for (const entry of value) addTarget(targets, entry);
return;
}
if (!isRecord(value)) return;
for (const key of SINGULAR_PATH_KEYS) addTarget(targets, value[key]);
for (const key of PLURAL_PATH_KEYS) addTarget(targets, value[key]);
for (const key of NESTED_TARGET_KEYS) addTarget(targets, value[key]);
}
function collectTargets(input: Record<string, unknown>, args: unknown): string[] {
const targets: string[] = [];
const records = [args, input].filter(isRecord);
for (const record of records) {
for (const key of SINGULAR_PATH_KEYS) addTarget(targets, record[key]);
for (const key of PLURAL_PATH_KEYS) addTarget(targets, record[key]);
for (const key of NESTED_TARGET_KEYS) addTarget(targets, record[key]);
for (const key of PATCH_KEYS) {
const value = record[key];
if (typeof value === 'string') targets.push(...patchTargets(value));
}
}
if (typeof args === 'string') targets.push(...patchTargets(args));
return [...new Set(targets)];
}
export function parseCometHookRequest(source: string, filePath?: string): CometHookRequest {
if (filePath?.trim()) {
return { intent: 'write', targets: [filePath.trim()], toolName: null };
}
if (!source.trim()) return { intent: 'unknown', targets: [], toolName: null };
let input: unknown;
try {
input = JSON.parse(source) as unknown;
} catch {
const targets = patchTargets(source);
if (targets.length > 0) {
return { intent: 'write', targets: [...new Set(targets)], toolName: 'apply_patch' };
}
return { intent: 'unknown', targets: [], toolName: null };
}
if (!isRecord(input)) return { intent: 'unknown', targets: [], toolName: null };
const toolName = readToolName(input);
const targets = collectTargets(input, readToolArguments(input));
const cwd = readWorkingDirectory(input);
if (toolName && WRITE_TOOL_NAMES.has(normalizedToolName(toolName))) {
return {
intent: targets.length > 0 ? 'write' : 'unknown',
targets,
toolName,
...(cwd ? { cwd } : {}),
};
}
if (toolName && NON_WRITE_TOOL_NAMES.has(normalizedToolName(toolName))) {
return { intent: 'non-write', targets: [], toolName, ...(cwd ? { cwd } : {}) };
}
if (toolName) return { intent: 'unknown', targets, toolName, ...(cwd ? { cwd } : {}) };
return {
intent: targets.length > 0 ? 'write' : 'unknown',
targets,
toolName: null,
...(cwd ? { cwd } : {}),
};
}
export function readCometHookRequest(): CometHookRequest {
const filePath = process.env.FILE_PATH;
if (filePath?.trim()) return parseCometHookRequest('', filePath);
if (process.stdin.isTTY) return parseCometHookRequest('', filePath);
try {
return parseCometHookRequest(readFileSync(0, 'utf8'), filePath);
} catch {
return parseCometHookRequest('', filePath);
}
}
export function renderCometHookDecision(
platformId: string,
decision: CometHookDecision,
): CometHookProcessOutput {
if (!COMET_HOOK_PLATFORM_IDS.has(platformId)) {
return {
exitCode: 64,
stdout: '',
stderr: `Unsupported Comet Hook platform: ${platformId}\n`,
};
}
if (platformId === 'github-copilot') {
return {
exitCode: 0,
stdout: decision.allowed
? '{}\n'
: `${JSON.stringify({
permissionDecision: 'deny',
permissionDecisionReason: decision.reason,
})}\n`,
stderr: '',
};
}
if (decision.allowed) return { exitCode: 0, stdout: '', stderr: '' };
return { exitCode: 2, stdout: '', stderr: `${decision.reason}\n` };
}