-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathagent.py
More file actions
1412 lines (1265 loc) · 50.1 KB
/
agent.py
File metadata and controls
1412 lines (1265 loc) · 50.1 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 os
import json
import asyncio
import logging
import time
import re
from pathlib import Path
from dotenv import load_dotenv
from anthropic import AsyncAnthropic
from playwright_manager import PlaywrightManager
from workspace_manager import WorkspaceManager
from task_manager import task_manager
from background_manager import background_manager
from memory.session_memory import SessionMemory
from knowledge_service import KnowledgeService
from message_center import MessageCenter
from tool_registry import ToolExecutionResult, ToolRegistry
logger = logging.getLogger(__name__)
load_dotenv()
client = AsyncAnthropic(
api_key=os.getenv("ANTHROPIC_API_KEY"), base_url=os.getenv("ANTHROPIC_BASE_URL")
)
model_name = os.getenv("MODEL_NAME", "MiniMax-M2.7")
# Configuration
WORKDIR = Path(os.getenv("WORKDIR", "./workspace")).resolve()
TOKEN_THRESHOLD = int(os.getenv("TOKEN_THRESHOLD", "800000"))
MAX_TOKEN = int(os.getenv("MAX_TOKEN", "1000000"))
TRANSCRIPT_DIR = Path(os.getenv("TRANSCRIPT_DIR", "./.transcripts")).resolve()
KEEP_RECENT = 3 # For microcompact
# Initialize managers
workspace = WorkspaceManager(WORKDIR, strict=False)
knowledge_service = KnowledgeService(WORKDIR)
SYSTEM_PROMPT = """You are NeoFish, an autonomous agent that can:
1. **Browse the web** - Navigate, click, type, extract information
2. **Manage files** - Read, write, edit files in the workspace
3. **Execute commands** - Run shell commands (blocking or background)
4. **Track tasks** - Create, update, and manage persistent tasks
5. **Send files** - Send files to the user
## CRITICAL: Working Directory
Your workspace is located at: {workdir}
- ALL file operations MUST be relative to this directory
- When reading/writing files, use relative paths like `src/main.py` or `data/config.json`
- The system will automatically resolve them to the correct absolute path
- NEVER use absolute paths like `/Users/...` or `C:\\...` unless specifically required
- If you need to check the current directory, use `run_bash` with `pwd`
## Observing the page
You have two complementary ways to observe the current state of the page:
1. **Screenshots** – visual snapshots that arrive automatically each step.
2. **snapshot** tool – returns an ARIA accessibility snapshot of the page, listing
every interactive element with a stable ref ID, e.g.:
- button "提交" [ref=e1]
- textbox "用户名" [ref=e2]
- link "忘记密码" [ref=e3]
## Interacting with elements
**Always prefer ref-based interaction** over CSS / XPath selectors:
- Call `snapshot` to get the current element list with refs.
- Pass `ref=e1` (or whichever ref) to `click` or `type_text` – the engine
will locate the element by its ARIA role and accessible name, which is far
more reliable than brittle CSS selectors.
- Only fall back to a CSS/XPath `selector` when no suitable ref is available.
## File Operations
- Use `read_file` to read file contents
- Use `write_file` to create or overwrite files
- Use `edit_file` to make precise changes to existing files
- Use `send_file` to send a file to the user (images, documents, etc.)
- Use `run_bash` to execute shell commands (blocking, with timeout)
- Use `background_run` for long-running commands (non-blocking)
## Task Management
Tasks persist across context compression. Use them to track progress on complex tasks:
- `task_create` - Create a new task with subject and description
- `task_list` - List all tasks with their status
- `task_get` - Get full details of a specific task
- `task_update` - Update task status or dependencies
- For non-trivial multi-step requests, maintain persistent task state proactively.
- If the system tells you a root task was auto-created, do not create a duplicate root task.
- When such a root task exists, keep it updated and mark it completed before `finish_task`.
## Background Tasks
For commands that take a long time:
- `background_run` - Start a background command, returns task_id immediately
- `check_background` - Check status of background tasks
## Knowledge Base
Use knowledge tools to retrieve information from selected knowledge folders:
- `knowledge_search` - Semantic search over selected knowledge folders (FAISS-backed)
If you ever encounter a strict login wall, CAPTCHA, or require the user to scan a QR code, you must call the `request_human_assistance` tool. Do NOT give up easily; only ask for help when absolutely necessary.
When the task is completely finished, call `finish_task`.
## Session Memory
Throughout the conversation, you must maintain an accurate picture of where you are in the task.
Whenever you complete a meaningful step, make progress, encounter an error, or the user's request changes direction,
output a Memory Update block at the END of your response (after all tool calls and text).
Format:
```
[Memory Update]
current_state: <what is happening right now, in one clear sentence>
task_spec: <the user's core request - keep the original intent>
important_files: <key files created or modified>
errors_corrections: <errors encountered and how they were resolved>
pending_tasks: <genuinely unfinished tasks>
[/Memory Update]
```
- Only output this block when there is something meaningful to record.
- current_state is the MOST important field - always include it when there's progress.
- Keep each field concise (1-2 sentences max).
- If nothing meaningful happened, do not output the block.
""".format(workdir=WORKDIR)
TOOLS = [
# Browser tools
{
"name": "snapshot",
"description": (
"Return an ARIA accessibility snapshot of the current page. "
"Each interactive element (button, textbox, link, etc.) is tagged with a "
"stable ref ID such as [ref=e1]. Use the refs with the `click` and "
"`type_text` tools instead of fragile CSS/XPath selectors."
),
"input_schema": {"type": "object", "properties": {}, "required": []},
},
{
"name": "navigate",
"description": "Navigate the browser to a specific URL.",
"input_schema": {
"type": "object",
"properties": {"url": {"type": "string"}},
"required": ["url"],
},
},
{
"name": "click",
"description": (
"Click an element on the page. "
'Prefer passing a `ref` obtained from the `snapshot` tool (e.g. ref="e1"). '
"Fall back to a CSS or XPath `selector` only when no ref is available."
),
"input_schema": {
"type": "object",
"properties": {
"ref": {
"type": "string",
"description": 'Ref ID from the snapshot (e.g. "e1"). Takes priority over selector.',
},
"selector": {
"type": "string",
"description": "CSS or XPath selector (fallback when ref is not available).",
},
},
"required": [],
},
},
{
"name": "type_text",
"description": (
"Type text into an input element. "
'Prefer passing a `ref` obtained from the `snapshot` tool (e.g. ref="e2"). '
"Fall back to a CSS or XPath `selector` only when no ref is available."
),
"input_schema": {
"type": "object",
"properties": {
"ref": {
"type": "string",
"description": 'Ref ID from the snapshot (e.g. "e2"). Takes priority over selector.',
},
"selector": {
"type": "string",
"description": "CSS or XPath selector (fallback when ref is not available).",
},
"text": {"type": "string"},
},
"required": ["text"],
},
},
{
"name": "scroll",
"description": "Scroll the page down.",
"input_schema": {
"type": "object",
"properties": {"direction": {"type": "string", "enum": ["down", "up"]}},
"required": [],
},
},
{
"name": "extract_info",
"description": "Extract specific information from the current page content based on observation.",
"input_schema": {
"type": "object",
"properties": {"info_summary": {"type": "string"}},
"required": ["info_summary"],
},
},
{
"name": "request_human_assistance",
"description": "Pause execution to ask the user to manually solve a login, CAPTCHA, or verification. Use this when you are blocked.",
"input_schema": {
"type": "object",
"properties": {
"reason": {"type": "string", "description": "Why you need human help"}
},
"required": ["reason"],
},
},
{
"name": "send_screenshot",
"description": "Capture and send the current page screenshot to the user. ONLY use this when: (1) showing final results, (2) User ask you to show something. Do NOT use for routine navigation or intermediate steps. Be selective.",
"input_schema": {
"type": "object",
"properties": {
"description": {
"type": "string",
"description": "A brief description of what the screenshot shows",
}
},
"required": ["description"],
},
},
{
"name": "finish_task",
"description": "Call this tool when the final objective is fully accomplished. Pass the final report to the user.",
"input_schema": {
"type": "object",
"properties": {
"report": {
"type": "string",
"description": "Markdown formatted summary",
}
},
"required": ["report"],
},
},
# File operation tools
{
"name": "read_file",
"description": "Read the contents of a file. Path can be relative to workspace or absolute.",
"input_schema": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "File path to read"},
"limit": {
"type": "integer",
"description": "Maximum number of lines to read (optional)",
},
},
"required": ["path"],
},
},
{
"name": "write_file",
"description": "Write content to a file. Creates parent directories if needed.",
"input_schema": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "File path to write"},
"content": {
"type": "string",
"description": "Content to write to the file",
},
},
"required": ["path", "content"],
},
},
{
"name": "edit_file",
"description": "Replace exact text in a file. Only replaces the first occurrence.",
"input_schema": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "File path to edit"},
"old_text": {
"type": "string",
"description": "Text to find and replace",
},
"new_text": {"type": "string", "description": "Replacement text"},
},
"required": ["path", "old_text", "new_text"],
},
},
{
"name": "send_file",
"description": "Send a file to the user. Use this to share images, documents, or any file from the workspace. The file must exist in the workspace.",
"input_schema": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "File path relative to workspace (e.g. 'output/report.pdf')",
},
"description": {
"type": "string",
"description": "Optional description of the file",
},
},
"required": ["path"],
},
},
{
"name": "run_bash",
"description": "Execute a shell command. Blocks until completion with timeout (default 120s). Dangerous commands are blocked. You can use python code execution for complex logic.",
"input_schema": {
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "Shell command to execute",
},
"timeout": {
"type": "integer",
"description": "Timeout in seconds (default 120)",
},
},
"required": ["command"],
},
},
# Task management tools
{
"name": "task_create",
"description": "Create a new task that persists across context compression.",
"input_schema": {
"type": "object",
"properties": {
"subject": {"type": "string", "description": "Brief task title"},
"description": {
"type": "string",
"description": "Detailed task description (optional)",
},
},
"required": ["subject"],
},
},
{
"name": "task_get",
"description": "Get full details of a task by ID.",
"input_schema": {
"type": "object",
"properties": {"task_id": {"type": "integer"}},
"required": ["task_id"],
},
},
{
"name": "task_update",
"description": "Update a task's status or dependencies.",
"input_schema": {
"type": "object",
"properties": {
"task_id": {"type": "integer"},
"status": {
"type": "string",
"enum": ["pending", "in_progress", "completed"],
},
"addBlockedBy": {
"type": "array",
"items": {"type": "integer"},
"description": "Task IDs this task depends on",
},
"addBlocks": {
"type": "array",
"items": {"type": "integer"},
"description": "Task IDs that depend on this task",
},
},
"required": ["task_id"],
},
},
{
"name": "task_list",
"description": "List all tasks with their status.",
"input_schema": {"type": "object", "properties": {}, "required": []},
},
# Background task tools
{
"name": "background_run",
"description": "Run a command in the background. Returns immediately with a task_id. Results will be delivered in next turn.",
"input_schema": {
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "Shell command to run in background",
},
"timeout": {
"type": "integer",
"description": "Timeout in seconds (default 300)",
},
},
"required": ["command"],
},
},
{
"name": "check_background",
"description": "Check status of background tasks. Omit task_id to list all.",
"input_schema": {
"type": "object",
"properties": {
"task_id": {
"type": "string",
"description": "Specific task ID (optional)",
}
},
"required": [],
},
},
# Knowledge tools
{
"name": "knowledge_search",
"description": "Semantic search in selected knowledge folders. Use this when user asks questions about uploaded knowledge files.",
"input_schema": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search query"},
"top_k": {
"type": "integer",
"description": "Number of results to return (default 5)",
},
},
"required": ["query"],
},
},
# Context management
{
"name": "compact",
"description": "Trigger manual context compression. Use when conversation is getting too long or switching a inrelevant topic and no longer needs the old context. ",
"input_schema": {
"type": "object",
"properties": {
"focus": {
"type": "string",
"description": "What to preserve in the summary",
}
},
"required": [],
},
},
]
def _get_block_type(block) -> str:
if isinstance(block, dict):
return block.get("type", "")
return getattr(block, "type", "")
def _get_block_text(block) -> str:
if isinstance(block, dict):
return block.get("text", "")
return getattr(block, "text", "")
def _extract_tool_use(block) -> tuple[str, str, dict]:
if isinstance(block, dict):
return (
str(block.get("id", "")),
str(block.get("name", "")),
block.get("input", {}) or {},
)
return (
str(getattr(block, "id", "")),
str(getattr(block, "name", "")),
getattr(block, "input", {}) or {},
)
def _extract_text_parts(blocks: list) -> list[str]:
text_parts: list[str] = []
for block in blocks:
if _get_block_type(block) == "text":
text = _get_block_text(block)
if text:
text_parts.append(text)
return text_parts
# ============== Context Compression Functions ==============
def estimate_tokens(messages: list) -> int:
"""Rough token count estimation: ~4 chars per token."""
return len(str(messages)) // 4
def microcompact(messages: list) -> list:
"""
Layer 1: Replace old tool_result content with placeholders.
Keeps only the last KEEP_RECENT tool results intact.
"""
# Collect all tool_result entries
tool_results = []
for msg_idx, msg in enumerate(messages):
if msg["role"] == "user" and isinstance(msg.get("content"), list):
for part_idx, part in enumerate(msg["content"]):
if isinstance(part, dict) and part.get("type") == "tool_result":
tool_results.append((msg_idx, part_idx, part))
if len(tool_results) <= KEEP_RECENT:
return messages
# Build tool_name map from assistant messages
tool_name_map = {}
for msg in messages:
if msg["role"] == "assistant":
content = msg.get("content", [])
if isinstance(content, list):
for block in content:
if hasattr(block, "type") and block.type == "tool_use":
tool_name_map[block.id] = block.name
elif isinstance(block, dict) and block.get("type") == "tool_use":
tool_name_map[block.get("id", "")] = block.get(
"name", "unknown"
)
# Clear old results (keep last KEEP_RECENT)
to_clear = tool_results[:-KEEP_RECENT]
for _, _, result in to_clear:
if isinstance(result.get("content"), str) and len(result["content"]) > 100:
tool_id = result.get("tool_use_id", "")
tool_name = tool_name_map.get(tool_id, "unknown")
result["content"] = f"[Previous: used {tool_name}]"
return messages
_MEMORY_UPDATE_RE = re.compile(
r"\[Memory Update\]\s*\n(.*?)\n\[/Memory Update\]",
re.DOTALL | re.IGNORECASE,
)
def _parse_memory_update(text: str) -> dict | None:
"""Extract [Memory Update] block from AI response text. Returns dict of fields or None."""
m = _MEMORY_UPDATE_RE.search(text)
if not m:
return None
block = m.group(1)
result: dict = {}
for line in block.split("\n"):
line = line.strip()
if not line or line.startswith("```"):
continue
if ": " in line:
key, _, val = line.partition(": ")
key = key.strip().lower().replace(" ", "_")
if key in (
"current_state",
"task_spec",
"important_files",
"workflow",
"errors_corrections",
"learnings",
"pending_tasks",
):
result[key] = val.strip()
return result if result else None
def _process_queued_message(
messages: list, user_content: list, qtext: str, qimages: list
) -> None:
"""Process a queued message and append to conversation."""
messages.append({"role": "user", "content": f"[New message from user]: {qtext}"})
for qimg in qimages:
user_content.append(
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/jpeg",
"data": qimg.split(",", 1)[-1] if "," in qimg else qimg,
},
}
)
messages.append(
{
"role": "assistant",
"content": "I received your new message. I'll incorporate it into my current task.",
}
)
async def auto_compact(messages: list, focus: str = None) -> list:
"""
Layer 2: Save transcript, summarize with LLM, replace messages.
"""
# Ensure transcript directory exists
TRANSCRIPT_DIR.mkdir(parents=True, exist_ok=True)
# Save full transcript
timestamp = int(time.time())
transcript_path = TRANSCRIPT_DIR / f"transcript_{timestamp}.jsonl"
with open(transcript_path, "w", encoding="utf-8") as f:
for msg in messages:
f.write(json.dumps(msg, default=str, ensure_ascii=False) + "\n")
# Get current task state for context
task_summary = task_manager.list_all()
# Build summary prompt
conversation_text = json.dumps(messages, default=str, ensure_ascii=False)[:80000]
focus_text = f"\n\nFocus on preserving: {focus}" if focus else ""
summary_prompt = (
"Summarize this conversation for continuity. CRITICAL - YOU MUST:\n\n"
"1) **EXACT Original User Request** - Quote the user's original request verbatim. "
"This is THE MOST IMPORTANT thing. Never forget or modify this.\n\n"
"2) **Completed Work Checklist** - List each item that has been DONE. "
"Mark as [DONE]. These MUST NOT be repeated.\n\n"
"3) **Remaining Work Checklist** - List items still pending. Mark as [TODO]. "
"This is what you should continue with.\n\n"
"4) **Current Position** - Where exactly are you now? (URL, file being edited, step number, etc.)\n\n"
"5) **Key Context** - URLs visited, files created/modified, important data extracted.\n\n"
"Current task system state:\n"
f"{task_summary}\n\n"
"WARNING: After compression, DO NOT restart from the beginning. "
"Continue from where you left off. Items marked [DONE] should NOT be repeated.\n"
f"{focus_text}\n\n{conversation_text}"
)
try:
response = await client.messages.create(
model=model_name,
max_tokens=2000,
messages=[{"role": "user", "content": summary_prompt}],
)
text_parts = _extract_text_parts(response.content)
summary = "\n".join(text_parts) if text_parts else "No summary generated."
except Exception as e:
summary = f"Error generating summary: {str(e)}"
# Replace all messages with compressed summary
return [
{
"role": "user",
"content": (
f"[Conversation compressed. Full transcript: {transcript_path}]\n\n"
f"## CRITICAL INSTRUCTIONS:\n"
f"- DO NOT restart from the beginning\n"
f"- DO NOT repeat any work marked as [DONE] in the summary\n"
f"- Continue from the current position described in the summary\n"
f"- Your workspace directory is: {WORKDIR}\n\n"
f"## Summary:\n{summary}"
),
},
{
"role": "assistant",
"content": (
"I understand. I will NOT restart from the beginning. "
"I will continue from where we left off, skipping any [DONE] items. "
"Proceeding with the remaining [TODO] items."
),
},
]
_SIMPLE_CHAT_INPUTS = {
"hi",
"hello",
"hey",
"你好",
"您好",
"嗨",
"在吗",
}
_TASK_ACTION_HINTS = (
"打开",
"访问",
"搜索",
"查找",
"点击",
"输入",
"浏览",
"分析",
"总结",
"整理",
"生成",
"制作",
"发送",
"读取",
"提取",
"下载",
"截图",
"navigate",
"search",
"open ",
"visit ",
"analyze",
"summarize",
"generate",
)
_EXPLICIT_TASK_HINTS = (
"task_create",
"task_update",
"task_get",
"task_list",
"创建一个任务",
"创建任务",
"更新任务",
"标记为 completed",
"标记这个任务",
)
def _contains_explicit_task_request(text: str) -> bool:
lowered = text.lower()
return any(hint.lower() in lowered for hint in _EXPLICIT_TASK_HINTS)
def _should_auto_create_task(
instruction: str, images: list, uploaded_files: list
) -> bool:
text = (instruction or "").strip()
if not text:
return False
lowered = text.lower()
if lowered in _SIMPLE_CHAT_INPUTS:
return False
if _contains_explicit_task_request(text):
return False
signal_score = 0
if images or uploaded_files:
signal_score += 1
if "http://" in lowered or "https://" in lowered:
signal_score += 2
if any(hint.lower() in lowered for hint in _TASK_ACTION_HINTS):
signal_score += 1
if any(token in text for token in (",", "。", "然后", "并且", "最后", "\n")):
signal_score += 1
if len(text) >= 18:
signal_score += 1
return signal_score >= 2
def _build_auto_task_subject(instruction: str) -> str:
clean = re.sub(r"https?://\S+", lambda m: m.group(0)[:28], instruction).strip()
clean = re.sub(r"^(请|帮我|麻烦|请帮我|帮忙)\s*", "", clean)
clean = re.sub(r"\s+", " ", clean)
first_sentence = re.split(r"[。!?\n]", clean, maxsplit=1)[0]
subject = first_sentence[:28].strip()
if len(first_sentence) > 28:
subject += "…"
return subject or "执行用户请求"
def _auto_create_root_task(
instruction: str, images: list, uploaded_files: list
) -> dict | None:
if not _should_auto_create_task(instruction, images, uploaded_files):
return None
created = task_manager.create(
subject=_build_auto_task_subject(instruction),
description=instruction.strip(),
)
task = json.loads(created)
task_manager.update(task["id"], status="in_progress")
task["status"] = "in_progress"
return task
def _normalize_info_payload(msg) -> dict:
if isinstance(msg, dict):
return msg
return {"message": str(msg)}
def _create_tool_registry(
*,
pm: PlaywrightManager,
page,
effective_session_id: str,
auto_root_task: dict | None,
emit_info,
emit_action_required,
emit_image,
emit_file,
) -> ToolRegistry:
registry = ToolRegistry()
async def _snapshot(args: dict) -> ToolExecutionResult:
snapshot_text = await pm.get_aria_snapshot(effective_session_id)
return ToolExecutionResult(
output=snapshot_text if snapshot_text else "Could not capture aria snapshot."
)
async def _navigate(args: dict) -> ToolExecutionResult:
if not page:
raise RuntimeError("No active page")
await page.goto(args["url"])
await asyncio.sleep(2)
return ToolExecutionResult(output="Successfully navigated.")
async def _click(args: dict) -> ToolExecutionResult:
if not page:
raise RuntimeError("No active page")
ref = args.get("ref")
selector = args.get("selector")
if ref:
locator = await pm.locate_by_ref(ref, effective_session_id)
await locator.click(timeout=5000)
elif selector:
await page.click(selector, timeout=5000)
else:
raise ValueError("click requires either 'ref' or 'selector'")
await asyncio.sleep(1)
return ToolExecutionResult(output="Successfully clicked.")
async def _type_text(args: dict) -> ToolExecutionResult:
if not page:
raise RuntimeError("No active page")
ref = args.get("ref")
selector = args.get("selector")
if ref:
locator = await pm.locate_by_ref(ref, effective_session_id)
await locator.fill(args["text"])
elif selector:
await page.fill(selector, args["text"])
else:
raise ValueError("type_text requires either 'ref' or 'selector'")
return ToolExecutionResult(output="Successfully typed text.")
async def _scroll(args: dict) -> ToolExecutionResult:
if not page:
raise RuntimeError("No active page")
direction = args.get("direction", "down")
if direction == "down":
await page.mouse.wheel(0, 1000)
else:
await page.mouse.wheel(0, -1000)
await asyncio.sleep(1)
return ToolExecutionResult(output="Scrolled.")
async def _request_human_assistance(args: dict) -> ToolExecutionResult:
reason = args.get("reason", "Login required.")
await pm.block_for_human(emit_action_required, reason, effective_session_id)
return ToolExecutionResult(
output=(
"Human has processed the request. Page might have updated. "
"You may resume your task."
)
)
async def _extract_info(args: dict) -> ToolExecutionResult:
return ToolExecutionResult(output=f"Extracted: {args['info_summary']}")
async def _send_screenshot(args: dict) -> ToolExecutionResult:
description = args.get("description", "Current page screenshot")
screenshot_b64 = await pm.get_page_screenshot_base64(effective_session_id)
if screenshot_b64:
await emit_image(description, screenshot_b64)
return ToolExecutionResult(output=f"Screenshot sent to user: {description}")
return ToolExecutionResult(output="Failed to capture screenshot.")
async def _finish_task(args: dict) -> ToolExecutionResult:
report = args.get("report", "Task completed.")
if auto_root_task:
task_manager.update(auto_root_task["id"], status="completed")
await emit_info(
{
"message": f"✅ **Task Completed**:\n\n{report}",
"message_key": "common.task_completed",
"params": {"report": report},
}
)
return ToolExecutionResult(output="Finished.", finished=True)
async def _read_file(args: dict) -> ToolExecutionResult:
return ToolExecutionResult(
output=await workspace.read_file(args["path"], args.get("limit"))
)
async def _write_file(args: dict) -> ToolExecutionResult:
return ToolExecutionResult(
output=await workspace.write_file(args["path"], args["content"])
)
async def _edit_file(args: dict) -> ToolExecutionResult:
return ToolExecutionResult(
output=await workspace.edit_file(args["path"], args["old_text"], args["new_text"])
)
async def _send_file(args: dict) -> ToolExecutionResult:
file_path = args["path"]
description = args.get("description", f"File: {file_path}")
full_path = WORKDIR / file_path
if not full_path.exists():
return ToolExecutionResult(output=f"Error: File not found: {file_path}")
if not str(full_path.resolve()).startswith(str(WORKDIR.resolve())):
return ToolExecutionResult(output=f"Error: Path escapes workspace: {file_path}")
await emit_file(file_path, description)
return ToolExecutionResult(output=f"File sent: {file_path}")
async def _run_bash(args: dict) -> ToolExecutionResult:
return ToolExecutionResult(
output=await workspace.run_bash(args["command"], args.get("timeout", 120))
)
async def _task_create(args: dict) -> ToolExecutionResult:
return ToolExecutionResult(
output=task_manager.create(args["subject"], args.get("description", ""))
)
async def _task_get(args: dict) -> ToolExecutionResult:
return ToolExecutionResult(output=task_manager.get(args["task_id"]))
async def _task_update(args: dict) -> ToolExecutionResult:
return ToolExecutionResult(
output=task_manager.update(
args["task_id"],
args.get("status"),
args.get("addBlockedBy"),
args.get("addBlocks"),
)
)
async def _task_list(args: dict) -> ToolExecutionResult:
return ToolExecutionResult(output=task_manager.list_all())
async def _background_run(args: dict) -> ToolExecutionResult:
return ToolExecutionResult(
output=await background_manager.run(
args["command"], args.get("timeout"), effective_session_id
)
)
async def _check_background(args: dict) -> ToolExecutionResult:
return ToolExecutionResult(
output=await background_manager.check(args.get("task_id"))
)
async def _knowledge_search(args: dict) -> ToolExecutionResult:
query = str(args.get("query", "")).strip()
if not query:
return ToolExecutionResult(output="Error: query is required")
top_k = int(args.get("top_k", 5) or 5)
top_k = max(1, min(20, top_k))
results = knowledge_service.search(query=query, top_k=top_k)
if not results:
return ToolExecutionResult(output="No relevant knowledge found in selected folders.")
return ToolExecutionResult(
output=json.dumps({"results": results}, ensure_ascii=False, indent=2)
)
async def _compact(args: dict) -> ToolExecutionResult:
focus = args.get("focus")
return ToolExecutionResult(
output=f"Manual compression requested{': ' + focus if focus else ''}.",
manual_compact=True,
compact_focus=focus,
)
registry.register("snapshot", _snapshot)
registry.register("navigate", _navigate)
registry.register("click", _click)
registry.register("type_text", _type_text)
registry.register("scroll", _scroll)
registry.register("request_human_assistance", _request_human_assistance)
registry.register("extract_info", _extract_info)
registry.register("send_screenshot", _send_screenshot)
registry.register("finish_task", _finish_task)
registry.register("read_file", _read_file)
registry.register("write_file", _write_file)
registry.register("edit_file", _edit_file)
registry.register("send_file", _send_file)
registry.register("run_bash", _run_bash)
registry.register("task_create", _task_create)
registry.register("task_get", _task_get)
registry.register("task_update", _task_update)
registry.register("task_list", _task_list)
registry.register("background_run", _background_run)
registry.register("check_background", _check_background)
registry.register("knowledge_search", _knowledge_search)
registry.register("compact", _compact)
return registry
# ============== Main Agent Loop ==============