-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent_executor.py
More file actions
426 lines (360 loc) · 18.3 KB
/
Copy pathagent_executor.py
File metadata and controls
426 lines (360 loc) · 18.3 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
import asyncio
import json
import re
import sys
import websockets
import subprocess
import time
import http.client
import os
# Настройка окружения для корректной работы UTF-8
os.environ["PYTHONIOENCODING"] = "utf-8"
def get_dynamic_page_id():
"""Автоматически находит ID первой подходящей страницы через HTTP API Chrome"""
try:
conn = http.client.HTTPConnection("localhost", 9222)
conn.request("GET", "/json")
response = conn.getresponse()
if response.status == 200:
data = json.loads(response.read())
for item in data:
if item.get('type') == 'page' and 'url' in item:
print(f"[*] Found page: {item.get('title')} (ID: {item.get('id')})")
return item.get('id')
return None
except Exception as e:
print(f"Error fetching page ID: {e}")
return None
async def get_page_text(websocket):
"""Возвращает весь текст страницы"""
await websocket.send(json.dumps({
'id': 1,
'method': 'Runtime.evaluate',
'params': {'expression': 'document.body.innerText', 'returnByValue': True}
}))
response = await websocket.recv()
return json.loads(response).get('result', {}).get('result', {}).get('value', '')
async def find_input_selector(websocket):
"""Ищет маркер на странице. Если находит - возвращает новый селектор и очищает поле."""
js_find = """
(function() {
const marker = "[[INPUT_AREA]]";
const potentials = document.querySelectorAll('textarea, input, [contenteditable="true"]');
let target = null;
for (let el of potentials) {
if ((el.value || el.innerText || "").includes(marker)) { target = el; break; }
}
if (!target) return null;
const getPath = (el) => {
if (el.id) return '#' + el.id;
const path = [];
while (el && el.nodeType === Node.ELEMENT_NODE) {
let selector = el.nodeName.toLowerCase();
let sib = el, nth = 1;
while (sib = sib.previousElementSibling) {
if (sib.nodeName.toLowerCase() == selector) nth++;
}
if (nth != 1) selector += ":nth-of-type(" + nth + ")";
path.unshift(selector);
el = el.parentNode;
}
return path.join(" > ");
};
const selector = getPath(target);
target.focus();
// 1. Выделяем всё (Ctrl+A)
target.dispatchEvent(new KeyboardEvent('keydown', {
key: 'a', code: 'KeyA', ctrlKey: true, bubbles: true
}));
// 2. Удаляем (Backspace)
target.dispatchEvent(new KeyboardEvent('keydown', {
key: 'Backspace', code: 'Backspace', bubbles: true
}));
if (target.isContentEditable) {
const range = document.createRange();
range.selectNodeContents(target);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else {
target.select();
}
document.execCommand('insertText', false, '');
target.dispatchEvent(new Event('input', { bubbles: true }));
target.dispatchEvent(new Event('change', { bubbles: true }));
return selector;
})()
"""
await websocket.send(json.dumps({
'id': 10,
'method': 'Runtime.evaluate',
'params': {'expression': js_find, 'returnByValue': True}
}))
response = await websocket.recv()
return json.loads(response).get('result', {}).get('result', {}).get('value')
def system_send_enter():
"""Отправляет системное нажатие Enter через PowerShell"""
try:
# Небольшая задержка, чтобы браузер успел обработать фокус
time.sleep(0.2)
cmd = "$wshell = New-Object -ComObject WScript.Shell; $wshell.SendKeys('{ENTER}')"
subprocess.run(["pwsh", "-NoProfile", "-Command", cmd], capture_output=True)
return True
except Exception as e:
print(f"System Enter Error: {e}")
return False
async def send_reply(websocket, text, selector):
import base64
formatted_text = "```\n" + text + "\n```"
"""Фокусирует поле через JS и вставляет текст через буфер обмена Windows"""
js_focus = f"""
(function() {{
let target = document.querySelector({json.dumps(selector)});
if (!target) {{
const potentials = Array.from(document.querySelectorAll('textarea, input, [contenteditable="true"]'));
const chatFields = potentials.filter(el => {{
const rect = el.getBoundingClientRect();
if (rect.width < 150 || rect.height < 30) return false;
const attrs = (el.id + el.className + (el.placeholder || "") + (el.getAttribute('aria-label') || "")).toLowerCase();
return !attrs.includes('search') && !attrs.includes('find');
}});
target = chatFields[0] || potentials[0];
}}
if (!target) return false;
target.focus();
return true;
}})()
"""
await websocket.send(json.dumps({
'id': 3,
'method': 'Runtime.evaluate',
'params': {'expression': js_focus, 'returnByValue': True}
}))
await websocket.recv()
try:
b64_text = base64.b64encode(formatted_text.encode('utf-8')).decode('utf-8')
ps_cmd = f"$text = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('{b64_text}')); Set-Clipboard -Value $text; $wshell = New-Object -ComObject WScript.Shell; $wshell.SendKeys('^{{V}}');"
subprocess.run(["pwsh", "-NoProfile", "-Command", ps_cmd], capture_output=True)
time.sleep(0.1)
except Exception as e:
print(f"Clipboard Error: {e}")
def execute_command(cmd):
print(f" > Executing Terminal: {cmd}")
try:
script_dir = os.path.dirname(os.path.abspath(__file__))
prefix = (
"[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "
"chcp 65001 > $null; "
f"Set-Location '{script_dir}'; "
)
full_cmd = prefix + cmd
result = subprocess.run(
["pwsh", "-NoProfile", "-Command", full_cmd],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=60
)
output = result.stdout if result.stdout else ""
if result.stderr:
output += "\nError:\n" + result.stderr
return output.strip()
except Exception as e:
return f"Execution Error: {str(e)}"
patched_files = {} # path -> True (для защиты от двойного патча)
read_counter = 0
def execute_file_tool(content):
print(f" > Executing File Tool...")
global read_counter
try:
content_stripped = content.strip()
data = {}
# 1. Пробуем JSON
if content_stripped.startswith("{"):
try:
data = json.loads(content_stripped)
except Exception as e:
print(f" [!] JSON parse error: {e}")
# 2. Если не JSON или пустой, пробуем YAML-style
if not data:
lines = content_stripped.splitlines()
in_new_text = False
new_text_lines = []
for line in lines:
if in_new_text:
new_text_lines.append(line)
continue
if ":" not in line: continue
key, val = line.split(":", 1)
key, val = key.strip().lower(), val.strip()
if key in ["read", "patch", "symbols"]:
data["action"] = key
data["path"] = val.strip('"\'')
elif key == "path":
data["path"] = val.strip('"\'')
elif key in ["start", "end"]:
data[key] = int(val)
elif key == "new_text":
if val != "|":
return "Error: Valid key for new_text is ` |`"
in_new_text = True
if "action" not in data: data["action"] = "patch"
if in_new_text:
data["new_text"] = "\n".join(new_text_lines) + "\n"
if not data:
return "Error: Could not parse file tool parameters."
action = data.get("action")
path = data.get("path")
# === Защита от двойного патча ===
if action == "patch":
if path in patched_files:
return f"Error: Double patch detected for {path} without read/symbols in between. This can lead to incorrect changes. Do read and then patch again"
patched_files[path] = True
elif action in ["read", "symbols"]:
if path in patched_files:
del patched_files[path]
if action == "read":
read_counter += 1
# Находим filetool.py рядом со скриптом
script_dir = os.path.dirname(os.path.abspath(__file__))
filetool_path = os.path.join(script_dir, "filetool.py")
process = subprocess.Popen(
[sys.executable, filetool_path],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, encoding="utf-8"
)
stdout, stderr = process.communicate(input=json.dumps(data))
output = stdout.strip()
if stderr: output += "\nError:\n" + stderr
print(f" [+] File Tool Output: {output[:50]}...")
if read_counter > 10:
read_counter = 0
if read_counter == 1:
output = "Note: don't forget use symbols mode to more practical answers\n" + output
return output
except Exception as e:
return f"File Tool Error: {str(e)}"
async def main_loop():
page_id = get_dynamic_page_id()
if not page_id:
print("Error: Could not find page. Check if Chrome is open with --remote-debugging-port=9222")
return
uri = f'ws://localhost:9222/devtools/page/{page_id}'
last_processed_msgid = None
try:
async with websockets.connect(uri) as websocket:
print(f"--- MSGID-based Agent Executor Started (Page: {page_id}) ---")
print("[*] Monitoring for messages and [[INPUT_AREA]] for calibration...")
input_selector = None
last_processed_msgid = None
agent_end_wait_couner = 0
while True:
# 1. Постоянно ищем маркер для калибровки/перекалибровки
new_selector = await find_input_selector(websocket)
if new_selector:
input_selector = new_selector
print(f"\n[*] Input selector updated: {input_selector}")
# 2. Если селектор еще ни разу не был найден, просто ждем
if not input_selector:
await asyncio.sleep(1)
continue
full_text = await get_page_text(websocket)
# Ищем последнее сообщение агента
if "[[AGENT_START]]" in full_text:
# Извлекаем все после последнего START
parts = full_text.split("[[AGENT_START]]")
last_part = parts[-1]
# ВАЖНО: Ждем завершения сообщения (AGENT_END)
if "[[AGENT_END]]" not in last_part:
if agent_end_wait_couner > 60:
error_text = (
f"Error: last [[AGENT_START]] was more then {agent_end_wait_couner} seconds ago but [[AGENT_END]] was not created."
)
print(f"\n[!] {error_text}")
# Сообщение еще печатается, ждем
await asyncio.sleep(1)
agent_end_wait_couner += 1
continue
else:
agent_end_wait_couner = 0
# Теперь у нас есть полное сообщение между START и END
last_msg = last_part.split("[[AGENT_END]]")[0]
# Извлекаем MSGID (более гибко)
msgid_match = re.search(r"MSGID:?\s*([a-zA-Z0-9_-]+)", last_msg, re.IGNORECASE)
if msgid_match:
current_msgid = msgid_match.group(1)
# === Извлекаем предпоследний MSGID ===
pr_msgid = None
if len(parts) >= 2: # значит есть как минимум два блока START
prev_part = parts[-2]
# Проверяем, что предпоследний блок тоже завершён
if "[[AGENT_END]]" in prev_part:
prev_msg = prev_part.split("[[AGENT_END]]")[0]
pr_match = re.search(r"MSGID:?\s*([a-zA-Z0-9_-]+)", prev_msg, re.IGNORECASE)
if pr_match:
pr_msgid = pr_match.group(1)
if current_msgid != last_processed_msgid:
print(f"\n[!] New message detected (MSGID: {current_msgid})")
if pr_msgid is not None and last_processed_msgid is not None and pr_msgid != last_processed_msgid:
error_text = (
"Error: Multiple [[AGENT_START]] / [[AGENT_END]] blocks were sent.\n"
f"Previous unprocessed MSGID: {pr_msgid}\n"
"Only one [[AGENT_START]] ... [[AGENT_END]] block per message is allowed.\n"
"Please group all tool calls inside a single block and try again."
)
await send_reply(websocket, error_text, input_selector)
system_send_enter()
last_processed_msgid = current_msgid
await asyncio.sleep(2)
continue
# Глубокая очистка и нормализация текста
# 1. Удаляем невидимые Unicode-разделители
clean_msg = re.sub(r'[\u200b-\u200d\ufeff]', '', last_msg)
# Ищем TOOL CALLS (TERMINAL)
terminal_pattern = r'\[+[^\]]*TOOL_START\s*:\s*TERMINAL[^\]]*\]+(.*?)\[+[^\]]*TOOL_END\s*:\s*TERMINAL[^\]]*\]+'
terminal_calls = re.findall(terminal_pattern, clean_msg, re.DOTALL | re.IGNORECASE)
# Ищем TOOL CALLS (FILE)
file_pattern = r'\[+[^\]]*TOOL_START\s*:\s*FILE[^\]]*\]+(.*?)\[+[^\]]*TOOL_END\s*:\s*FILE[^\]]*\]+'
file_calls = re.findall(file_pattern, clean_msg, re.DOTALL | re.IGNORECASE)
if terminal_calls or file_calls:
print(f" > Found {len(terminal_calls)} terminal and {len(file_calls)} file tool(s).")
final_reply = []
for content in file_calls:
output = execute_file_tool(content)
final_reply.append(f"[[TOOL_START:FILE]]\n{output}\n[[TOOL_END:FILE]]")
for cmd_raw in terminal_calls:
cmd = cmd_raw.strip()
cmd = re.sub(r'```[a-zA-Z]*\n?', '', cmd)
cmd = cmd.replace('```', '').strip()
if not cmd: continue
output = execute_command(cmd)
final_reply.append(f"[[TOOL_START:TERMINAL]]\nCommand: {cmd}\n{output}\n[[TOOL_END:TERMINAL]]")
await send_reply(websocket, "\n\n".join(final_reply), input_selector)
await asyncio.sleep(1)
await send_reply(websocket, "".join("[[Result complete]]"), input_selector)
system_send_enter()
print(" > Response sent. Waiting for agent's next move...")
last_processed_msgid = current_msgid
await asyncio.sleep(1)
else:
print(f" > No tools found in MSGID {current_msgid}. Marking as processed.")
last_processed_msgid = current_msgid
else:
# Тот же ID, ничего не делаем
pass
else:
# Сообщение есть, но MSGID еще не написан или отсутствует
print("\r[*] Waiting for MSGID in last message...", end="")
await asyncio.sleep(1)
except Exception as e:
print(f"\nPipeline Error: {e}")
print("Attempting to reconnect in 5 seconds...")
await asyncio.sleep(5)
await main_loop()
if __name__ == "__main__":
try:
asyncio.run(main_loop())
except KeyboardInterrupt:
print("\n[!] Shutdown requested by user. Exiting...")
sys.exit(0)