jarvis-ai-agent-cli 2.0.0__py3-none-any.whl
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.
- agent/__init__.py +0 -0
- agent/actor.py +182 -0
- agent/chains/__init__.py +0 -0
- agent/chains/code_chain.py +46 -0
- agent/chains/rag_chain.py +35 -0
- agent/chains/research_chain.py +58 -0
- agent/chains/task_chain.py +85 -0
- agent/executor.py +508 -0
- agent/observer.py +74 -0
- agent/planner.py +157 -0
- agent/reflector.py +61 -0
- agents/__init__.py +0 -0
- agents/base.py +98 -0
- agents/code_review_agent.py +42 -0
- agents/coordinator.py +72 -0
- agents/email_agent.py +130 -0
- agents/file_agent.py +44 -0
- agents/github_agent.py +79 -0
- agents/system_agent.py +42 -0
- agents/web_agent.py +30 -0
- api/__init__.py +0 -0
- api/auth.py +81 -0
- api/gateway.py +82 -0
- api/middleware.py +102 -0
- api/routes/__init__.py +0 -0
- api/routes/chat.py +71 -0
- api/routes/memory.py +65 -0
- api/routes/system.py +54 -0
- api/routes/tools.py +47 -0
- api/routes/voice.py +51 -0
- api/websocket.py +145 -0
- assistant/__init__.py +0 -0
- assistant/core.py +224 -0
- assistant/llm.py +197 -0
- assistant/memory.py +63 -0
- banner.py +169 -0
- cli.py +763 -0
- config/mcp_servers.json +16 -0
- core/__init__.py +0 -0
- core/config.py +186 -0
- core/context_assembler.py +51 -0
- core/event_bus.py +74 -0
- core/exceptions.py +32 -0
- core/intent_router.py +52 -0
- core/session.py +99 -0
- daemon.py +719 -0
- interface/__init__.py +0 -0
- interface/gui.py +165 -0
- jarvis_ai_agent_cli-2.0.0.dist-info/METADATA +93 -0
- jarvis_ai_agent_cli-2.0.0.dist-info/RECORD +179 -0
- jarvis_ai_agent_cli-2.0.0.dist-info/WHEEL +5 -0
- jarvis_ai_agent_cli-2.0.0.dist-info/entry_points.txt +3 -0
- jarvis_ai_agent_cli-2.0.0.dist-info/top_level.txt +33 -0
- jarvis_input.py +232 -0
- llm/__init__.py +0 -0
- llm/context_window.py +32 -0
- llm/providers/__init__.py +0 -0
- llm/providers/anthropic.py +85 -0
- llm/providers/base.py +18 -0
- llm/providers/gemini.py +90 -0
- llm/providers/ollama.py +112 -0
- llm/providers/openai.py +66 -0
- llm/providers/opencode.py +67 -0
- llm/providers/openrouter.py +67 -0
- llm/router.py +69 -0
- main.py +240 -0
- mcp/__init__.py +0 -0
- mcp/client.py +141 -0
- mcp/connection_manager.py +87 -0
- mcp/server_registry.py +60 -0
- mcp/tool_adapter.py +34 -0
- memory/__init__.py +0 -0
- memory/episodic_memory.py +185 -0
- memory/memory_manager.py +112 -0
- memory/semantic_memory.py +116 -0
- memory/user_profile.py +55 -0
- memory/working_memory.py +86 -0
- observability/__init__.py +0 -0
- observability/logger.py +90 -0
- observability/metrics.py +96 -0
- observability/tracer.py +80 -0
- output/__init__.py +0 -0
- output/clipboard.py +24 -0
- output/notification.py +33 -0
- output/terminal_ui.py +48 -0
- output/tts/__init__.py +0 -0
- output/tts/coqui_tts.py +6 -0
- output/tts/edge_tts.py +42 -0
- output/tts/pyttsx3_tts.py +22 -0
- perception/__init__.py +0 -0
- perception/file_parser/__init__.py +0 -0
- perception/file_parser/code_parser.py +75 -0
- perception/file_parser/csv_parser.py +24 -0
- perception/file_parser/docx_parser.py +14 -0
- perception/file_parser/image_parser.py +31 -0
- perception/file_parser/pdf_parser.py +34 -0
- perception/stt/__init__.py +0 -0
- perception/stt/audio_capture.py +45 -0
- perception/stt/vad.py +62 -0
- perception/stt/whisper_engine.py +43 -0
- perception/vision/__init__.py +0 -0
- perception/vision/llava_vision.py +6 -0
- perception/vision/ocr.py +19 -0
- perception/vision/screenshot.py +41 -0
- plugins/__init__.py +0 -0
- plugins/base_plugin.py +22 -0
- plugins/examples/__init__.py +0 -0
- plugins/examples/github_plugin.py +98 -0
- plugins/examples/homeassistant_plugin.py +86 -0
- plugins/examples/spotify_plugin.py +53 -0
- plugins/loader.py +78 -0
- scheduler/__init__.py +0 -0
- scheduler/cron_manager.py +81 -0
- scheduler/proactive_agent.py +113 -0
- scheduler/reminder.py +157 -0
- scripts/build_binary.py +40 -0
- scripts/test_gemini_key.py +35 -0
- scripts/test_openrouter_key.py +45 -0
- security/__init__.py +0 -0
- security/audit_log.py +58 -0
- security/auth.py +66 -0
- security/encryption.py +63 -0
- security/permission_guard.py +88 -0
- security/sandboxing.py +126 -0
- skills/__init__.py +0 -0
- skills/base.py +132 -0
- skills/bundled/debug.md +21 -0
- skills/bundled/generate_test.md +22 -0
- skills/bundled/refactor.md +21 -0
- skills/bundled/research.md +21 -0
- skills/bundled/review.md +22 -0
- skills/bundled/summarize.md +17 -0
- skills/conditional.py +46 -0
- skills/executor.py +88 -0
- skills/loader.py +100 -0
- skills/registry.py +75 -0
- system/__init__.py +0 -0
- system/hardware_detector.py +260 -0
- system/hardware_profile.py +173 -0
- tools/__init__.py +0 -0
- tools/apps/__init__.py +0 -0
- tools/apps/calendar_tool.py +18 -0
- tools/apps/email_tool.py +94 -0
- tools/calendar/__init__.py +0 -0
- tools/calendar/google_calendar.py +148 -0
- tools/code/__init__.py +0 -0
- tools/code/executor.py +65 -0
- tools/code/repl.py +34 -0
- tools/files.py +23 -0
- tools/messaging/__init__.py +0 -0
- tools/messaging/email.py +183 -0
- tools/messaging/whatsapp.py +695 -0
- tools/os/__init__.py +0 -0
- tools/os/clipboard.py +29 -0
- tools/os/file_manager.py +80 -0
- tools/os/process_manager.py +54 -0
- tools/os/shell.py +58 -0
- tools/os/window_manager.py +82 -0
- tools/registry.py +35 -0
- tools/system/__init__.py +233 -0
- tools/system/monitor.py +31 -0
- tools/system/scheduler_tool.py +73 -0
- tools/voice.py +94 -0
- tools/web/__init__.py +10 -0
- tools/web/browser.py +71 -0
- tools/web/scraper.py +36 -0
- tools/web/search.py +111 -0
- ui/__init__.py +20 -0
- ui/animation.py +57 -0
- ui/box.py +90 -0
- ui/components.py +76 -0
- ui/dialog.py +100 -0
- ui/input.py +142 -0
- ui/keybindings.py +119 -0
- ui/progress.py +80 -0
- ui/spinner.py +96 -0
- ui/statusline.py +70 -0
- ui/theme.py +153 -0
- wizard.py +144 -0
agent/__init__.py
ADDED
|
File without changes
|
agent/actor.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from core.exceptions import ToolExecutionError
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass
|
|
8
|
+
class ToolResult:
|
|
9
|
+
success: bool
|
|
10
|
+
data: Any = None
|
|
11
|
+
error: str = ""
|
|
12
|
+
tool_name: str = ""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
TOOL_ALIASES = {
|
|
16
|
+
"run_command": "shell_exec",
|
|
17
|
+
"shell": "shell_exec",
|
|
18
|
+
"python_interpreter": "run_python",
|
|
19
|
+
"python": "run_python",
|
|
20
|
+
"fetch_page": "web_fetch",
|
|
21
|
+
"list_dir": "list_directory",
|
|
22
|
+
"get_system_info": "system_info",
|
|
23
|
+
"search_memory": "memory_search",
|
|
24
|
+
# NOTE: "open_app" is the actual registered tool name — do NOT alias it
|
|
25
|
+
"app_launch": "open_app", # alias the old name TO the real name
|
|
26
|
+
"screenshot": "screen_capture",
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Actor:
|
|
31
|
+
def __init__(self, tool_registry=None):
|
|
32
|
+
self._registry = tool_registry or {}
|
|
33
|
+
|
|
34
|
+
def register_tool(self, name: str, fn):
|
|
35
|
+
self._registry[name] = fn
|
|
36
|
+
|
|
37
|
+
def _resolve_tool(self, name: str, registry) -> object | None:
|
|
38
|
+
def _try_get(r, n):
|
|
39
|
+
val = r.get(n)
|
|
40
|
+
if isinstance(val, dict) and 'handler' in val:
|
|
41
|
+
return val['handler']
|
|
42
|
+
if callable(val):
|
|
43
|
+
return val
|
|
44
|
+
if isinstance(val, dict) and callable(val.get('handler')):
|
|
45
|
+
return val['handler']
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
fn = _try_get(registry, name)
|
|
49
|
+
if fn:
|
|
50
|
+
return fn
|
|
51
|
+
aliased = TOOL_ALIASES.get(name)
|
|
52
|
+
if aliased:
|
|
53
|
+
fn = _try_get(registry, aliased)
|
|
54
|
+
if fn:
|
|
55
|
+
return fn
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
def execute_step(self, step, tool_registry=None) -> ToolResult:
|
|
59
|
+
registry = tool_registry or self._registry
|
|
60
|
+
tool_name = step.tool
|
|
61
|
+
if not tool_name:
|
|
62
|
+
return ToolResult(success=True, data=step.description, tool_name="")
|
|
63
|
+
fn = self._resolve_tool(tool_name, registry)
|
|
64
|
+
if not fn:
|
|
65
|
+
return ToolResult(
|
|
66
|
+
success=False,
|
|
67
|
+
error=f"Unknown tool: {tool_name}",
|
|
68
|
+
tool_name=tool_name,
|
|
69
|
+
)
|
|
70
|
+
try:
|
|
71
|
+
import inspect
|
|
72
|
+
if isinstance(step.args, dict) and step.args:
|
|
73
|
+
try:
|
|
74
|
+
sig = inspect.signature(fn)
|
|
75
|
+
params = list(sig.parameters.keys())
|
|
76
|
+
if params and params[0] == "self":
|
|
77
|
+
params = params[1:]
|
|
78
|
+
if len(step.args) == 1 and params:
|
|
79
|
+
passed_key = list(step.args.keys())[0]
|
|
80
|
+
if passed_key not in params:
|
|
81
|
+
step.args = {params[0]: step.args[passed_key]}
|
|
82
|
+
except Exception:
|
|
83
|
+
pass
|
|
84
|
+
result = fn(**step.args) if isinstance(step.args, dict) else fn(step.args)
|
|
85
|
+
return ToolResult(success=True, data=self._format_result(result, tool_name), tool_name=tool_name)
|
|
86
|
+
except ToolExecutionError:
|
|
87
|
+
raise
|
|
88
|
+
except Exception as e:
|
|
89
|
+
return ToolResult(success=False, error=str(e), tool_name=tool_name)
|
|
90
|
+
|
|
91
|
+
def _format_result(self, result, tool_name: str) -> str:
|
|
92
|
+
"""Convert raw tool output to a clean human-readable string."""
|
|
93
|
+
if result is None:
|
|
94
|
+
return "(no output)"
|
|
95
|
+
|
|
96
|
+
# Shell execution result
|
|
97
|
+
if isinstance(result, dict) and "stdout" in result:
|
|
98
|
+
stdout = (result.get("stdout") or "").strip()
|
|
99
|
+
stderr = (result.get("stderr") or "").strip()
|
|
100
|
+
exit_code = result.get("exit_code", result.get("returncode", 0))
|
|
101
|
+
if stdout:
|
|
102
|
+
return stdout
|
|
103
|
+
if stderr:
|
|
104
|
+
return f"[stderr] {stderr}"
|
|
105
|
+
return f"Command completed (exit code: {exit_code})"
|
|
106
|
+
|
|
107
|
+
# Python execution result
|
|
108
|
+
if isinstance(result, dict) and "success" in result and "stdout" in result:
|
|
109
|
+
stdout = (result.get("stdout") or "").strip()
|
|
110
|
+
stderr = (result.get("stderr") or "").strip()
|
|
111
|
+
if stdout:
|
|
112
|
+
return stdout
|
|
113
|
+
if stderr:
|
|
114
|
+
return f"[error] {stderr}"
|
|
115
|
+
return "Code executed successfully (no output)"
|
|
116
|
+
|
|
117
|
+
# Web search results (list of dicts with title/snippet)
|
|
118
|
+
if isinstance(result, list) and result and isinstance(result[0], dict):
|
|
119
|
+
# Check if it looks like search results
|
|
120
|
+
if "snippet" in result[0] or "title" in result[0]:
|
|
121
|
+
lines = []
|
|
122
|
+
for i, r in enumerate(result[:5], 1):
|
|
123
|
+
title = r.get("title", "").strip()
|
|
124
|
+
snippet = r.get("snippet", "").strip()
|
|
125
|
+
link = r.get("link", "").strip()
|
|
126
|
+
if title or snippet:
|
|
127
|
+
lines.append(f"{i}. {title}")
|
|
128
|
+
if snippet and snippet != title:
|
|
129
|
+
lines.append(f" {snippet[:200]}")
|
|
130
|
+
if link:
|
|
131
|
+
lines.append(f" {link}")
|
|
132
|
+
return "\n".join(lines) if lines else "(no results)"
|
|
133
|
+
# Process list (pid, name, cpu)
|
|
134
|
+
if "pid" in result[0] or "name" in result[0]:
|
|
135
|
+
lines = []
|
|
136
|
+
for p in result[:15]:
|
|
137
|
+
name = p.get("name", "?")
|
|
138
|
+
pid = p.get("pid", "?")
|
|
139
|
+
cpu = p.get("cpu_percent", 0)
|
|
140
|
+
mem = p.get("memory_percent", 0)
|
|
141
|
+
lines.append(f" PID {pid:>6} {name:<30} CPU {cpu:.1f}% MEM {mem:.1f}%")
|
|
142
|
+
return "\n".join(lines)
|
|
143
|
+
# File list
|
|
144
|
+
if "name" in result[0] and "type" in result[0]:
|
|
145
|
+
lines = []
|
|
146
|
+
for f in result[:30]:
|
|
147
|
+
icon = "📁" if f.get("type") == "dir" else "📄"
|
|
148
|
+
size_str = ""
|
|
149
|
+
if f.get("type") == "file":
|
|
150
|
+
size = f.get("size") or f.get("sizeBytes") or f.get("size_bytes")
|
|
151
|
+
if size is not None:
|
|
152
|
+
try:
|
|
153
|
+
size = int(size)
|
|
154
|
+
if size > 1024 * 1024 * 1024:
|
|
155
|
+
size_str = f" ({size / (1024*1024*1024):.1f} GB)"
|
|
156
|
+
elif size > 1024 * 1024:
|
|
157
|
+
size_str = f" ({size / (1024*1024):.1f} MB)"
|
|
158
|
+
elif size > 1024:
|
|
159
|
+
size_str = f" ({size / 1024:.1f} KB)"
|
|
160
|
+
else:
|
|
161
|
+
size_str = f" ({size} B)"
|
|
162
|
+
except Exception:
|
|
163
|
+
pass
|
|
164
|
+
lines.append(f" {icon} {f['name']}{size_str}")
|
|
165
|
+
return "\n".join(lines)
|
|
166
|
+
|
|
167
|
+
# System info dict
|
|
168
|
+
if isinstance(result, dict) and "cpu" in result:
|
|
169
|
+
cpu = result.get("cpu", {})
|
|
170
|
+
mem = result.get("memory", {})
|
|
171
|
+
disk = result.get("disk", {})
|
|
172
|
+
return (
|
|
173
|
+
f"CPU: {cpu.get('percent', '?')}% used ({cpu.get('count', '?')} cores)\n"
|
|
174
|
+
f"RAM: {round(mem.get('used', 0)/1e9, 1)}GB / {round(mem.get('total', 0)/1e9, 1)}GB "
|
|
175
|
+
f"({mem.get('percent', '?')}% used)\n"
|
|
176
|
+
f"Disk: {round(disk.get('free', 0)/1e9, 1)}GB free / {round(disk.get('total', 0)/1e9, 1)}GB total"
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
# Plain string or anything else
|
|
180
|
+
text = str(result).strip()
|
|
181
|
+
return text[:5000] if text else "(no output)"
|
|
182
|
+
|
agent/chains/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
from core.exceptions import LLMError
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class CodeChain:
|
|
5
|
+
def __init__(self, llm_router=None):
|
|
6
|
+
self.llm = llm_router
|
|
7
|
+
|
|
8
|
+
async def generate(self, spec: str) -> str:
|
|
9
|
+
if not self.llm:
|
|
10
|
+
return "# Code generation requires an LLM"
|
|
11
|
+
prompt = (
|
|
12
|
+
f"Generate Python code for the following specification:\n{spec}\n\n"
|
|
13
|
+
"Return only the code inside a single python code block. "
|
|
14
|
+
"Include imports, error handling, and a main() function if applicable."
|
|
15
|
+
)
|
|
16
|
+
try:
|
|
17
|
+
response = await self.llm.generate([{"role": "user", "content": prompt}])
|
|
18
|
+
return self._extract_code(response)
|
|
19
|
+
except LLMError:
|
|
20
|
+
raise
|
|
21
|
+
except Exception as e:
|
|
22
|
+
raise LLMError(f"Code generation failed: {e}") from e
|
|
23
|
+
|
|
24
|
+
async def review(self, code: str) -> str:
|
|
25
|
+
if not self.llm:
|
|
26
|
+
return "Code review requires an LLM"
|
|
27
|
+
prompt = (
|
|
28
|
+
f"Review the following Python code for bugs, style issues, security problems, "
|
|
29
|
+
f"and performance concerns:\n\n```python\n{code}\n```\n\n"
|
|
30
|
+
"Provide a structured review with: Issues Found, Severity, Suggestions."
|
|
31
|
+
)
|
|
32
|
+
try:
|
|
33
|
+
return await self.llm.generate([{"role": "user", "content": prompt}])
|
|
34
|
+
except LLMError:
|
|
35
|
+
raise
|
|
36
|
+
except Exception as e:
|
|
37
|
+
raise LLMError(f"Code review failed: {e}") from e
|
|
38
|
+
|
|
39
|
+
def _extract_code(self, text: str) -> str:
|
|
40
|
+
import re
|
|
41
|
+
match = re.search(r"```(?:python)?\n?(.*?)```", text, re.DOTALL)
|
|
42
|
+
if match:
|
|
43
|
+
return match.group(1).strip()
|
|
44
|
+
lines = text.strip().split("\n")
|
|
45
|
+
code_lines = [l for l in lines if l.strip() and not l.strip().startswith("#")]
|
|
46
|
+
return "\n".join(code_lines) if code_lines else text.strip()
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from core.exceptions import LLMError
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class RAGChain:
|
|
5
|
+
def __init__(self, llm_router=None):
|
|
6
|
+
self.llm = llm_router
|
|
7
|
+
|
|
8
|
+
async def run(self, query: str, memory_manager=None) -> str:
|
|
9
|
+
context = ""
|
|
10
|
+
if memory_manager:
|
|
11
|
+
try:
|
|
12
|
+
results = memory_manager.recall(query, limit=5)
|
|
13
|
+
if results:
|
|
14
|
+
context = "\n".join(
|
|
15
|
+
r.get("content", r.get("data", str(r)))[:1000] for r in results
|
|
16
|
+
)
|
|
17
|
+
context = f"Relevant context:\n{context}\n\n"
|
|
18
|
+
except Exception:
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
prompt = (
|
|
22
|
+
f"{context}Answer the following question based on the context above "
|
|
23
|
+
f"and your knowledge. If the context is not relevant, use your own knowledge.\n\n"
|
|
24
|
+
f"Question: {query}"
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
if not self.llm:
|
|
28
|
+
return f"Based on available information:\n{context[:1000] if context else 'No context available.'}"
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
return await self.llm.generate([{"role": "user", "content": prompt}])
|
|
32
|
+
except LLMError:
|
|
33
|
+
raise
|
|
34
|
+
except Exception as e:
|
|
35
|
+
raise LLMError(f"RAG chain failed: {e}") from e
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
from core.exceptions import LLMError
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ResearchChain:
|
|
5
|
+
def __init__(self, llm_router=None, web_search_fn=None):
|
|
6
|
+
self.llm = llm_router
|
|
7
|
+
self.search = web_search_fn
|
|
8
|
+
|
|
9
|
+
async def research(self, topic: str, depth: int = 2) -> str:
|
|
10
|
+
if not self.search:
|
|
11
|
+
if self.llm:
|
|
12
|
+
return await self.llm.generate([
|
|
13
|
+
{"role": "user", "content": f"Provide a comprehensive summary of: {topic}"}
|
|
14
|
+
])
|
|
15
|
+
return f"No search capability available for researching: {topic}"
|
|
16
|
+
|
|
17
|
+
all_findings = []
|
|
18
|
+
queries = self._generate_queries(topic, depth)
|
|
19
|
+
|
|
20
|
+
for i, query in enumerate(queries):
|
|
21
|
+
try:
|
|
22
|
+
results = self.search(query)
|
|
23
|
+
if isinstance(results, list):
|
|
24
|
+
snippets = [r.get("snippet", r.get("content", str(r)))[:500] for r in results[:3]]
|
|
25
|
+
all_findings.extend(snippets)
|
|
26
|
+
elif isinstance(results, str):
|
|
27
|
+
all_findings.append(results[:1000])
|
|
28
|
+
except Exception:
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
if not all_findings:
|
|
32
|
+
return f"No research results found for: {topic}"
|
|
33
|
+
|
|
34
|
+
combined = "\n".join(f"- {f}" for f in all_findings[:15])
|
|
35
|
+
|
|
36
|
+
if not self.llm:
|
|
37
|
+
return f"Research findings on '{topic}':\n{combined}"
|
|
38
|
+
|
|
39
|
+
synthesis_prompt = (
|
|
40
|
+
f"Synthesize the following research findings on '{topic}' into a coherent summary:\n\n"
|
|
41
|
+
f"{combined}\n\nProvide key insights, main points, and a conclusion."
|
|
42
|
+
)
|
|
43
|
+
try:
|
|
44
|
+
synthesis = await self.llm.generate([{"role": "user", "content": synthesis_prompt}])
|
|
45
|
+
return synthesis
|
|
46
|
+
except LLMError:
|
|
47
|
+
raise
|
|
48
|
+
except Exception as e:
|
|
49
|
+
return f"Research findings on '{topic}':\n{combined}\n\n(Synthesis failed: {e})"
|
|
50
|
+
|
|
51
|
+
def _generate_queries(self, topic: str, depth: int) -> list[str]:
|
|
52
|
+
queries = [topic]
|
|
53
|
+
if depth > 1:
|
|
54
|
+
queries.append(f"{topic} overview 2026")
|
|
55
|
+
if depth > 2:
|
|
56
|
+
queries.append(f"{topic} latest developments")
|
|
57
|
+
queries.append(f"{topic} tutorial guide")
|
|
58
|
+
return queries
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
from core.event_bus import event_bus, EVENTS
|
|
2
|
+
from core.exceptions import AgentError
|
|
3
|
+
|
|
4
|
+
from agent.planner import Planner
|
|
5
|
+
from agent.actor import Actor
|
|
6
|
+
from agent.observer import Observer
|
|
7
|
+
from agent.reflector import Reflector
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class TaskChain:
|
|
11
|
+
def __init__(self, llm_router=None, tool_registry=None):
|
|
12
|
+
self.llm = llm_router
|
|
13
|
+
self.tools = tool_registry or {}
|
|
14
|
+
self.planner = Planner(llm_router)
|
|
15
|
+
self.actor = Actor(tool_registry)
|
|
16
|
+
self.observer = Observer(llm_router)
|
|
17
|
+
self.reflector = Reflector()
|
|
18
|
+
self.max_iterations = 10
|
|
19
|
+
|
|
20
|
+
async def execute(self, goal: str) -> str:
|
|
21
|
+
event_bus.emit(EVENTS["AGENT_START"], task=goal)
|
|
22
|
+
|
|
23
|
+
try:
|
|
24
|
+
steps = await self.planner.plan(goal)
|
|
25
|
+
if not steps:
|
|
26
|
+
return await self._fallback_llm(goal)
|
|
27
|
+
except Exception as e:
|
|
28
|
+
event_bus.emit(EVENTS["AGENT_ERROR"], error=str(e))
|
|
29
|
+
return f"Planning failed: {e}"
|
|
30
|
+
|
|
31
|
+
completed = []
|
|
32
|
+
|
|
33
|
+
for iteration in range(self.max_iterations):
|
|
34
|
+
pending = [s for s in steps if s.status == "pending"]
|
|
35
|
+
if not pending:
|
|
36
|
+
break
|
|
37
|
+
|
|
38
|
+
step = pending[0]
|
|
39
|
+
step.status = "in_progress"
|
|
40
|
+
event_bus.emit(EVENTS["AGENT_STEP"], step=step.id, description=step.description)
|
|
41
|
+
|
|
42
|
+
try:
|
|
43
|
+
result = self.actor.execute_step(step, self.tools)
|
|
44
|
+
except Exception as e:
|
|
45
|
+
step.status = "failed"
|
|
46
|
+
event_bus.emit(EVENTS["AGENT_ERROR"], error=str(e))
|
|
47
|
+
diagnosis = self.reflector.reflect(str(e))
|
|
48
|
+
fix = self.reflector.suggest_fix(str(e))
|
|
49
|
+
new_steps = await self.planner.replan(step, f"{diagnosis} {fix}")
|
|
50
|
+
if new_steps:
|
|
51
|
+
steps.extend(new_steps)
|
|
52
|
+
continue
|
|
53
|
+
|
|
54
|
+
observation = await self.observer.analyze_result(result, goal)
|
|
55
|
+
step.status = "success" if observation.success else "failed"
|
|
56
|
+
completed.append(result)
|
|
57
|
+
|
|
58
|
+
if observation.goal_satisfied:
|
|
59
|
+
event_bus.emit(EVENTS["AGENT_COMPLETE"], task=goal)
|
|
60
|
+
return self._summarize(completed)
|
|
61
|
+
|
|
62
|
+
if not observation.success:
|
|
63
|
+
diagnosis = self.reflector.reflect(result.error or "")
|
|
64
|
+
fix = self.reflector.suggest_fix(result.error or "")
|
|
65
|
+
new_steps = await self.planner.replan(step, f"{diagnosis} {fix}")
|
|
66
|
+
if new_steps:
|
|
67
|
+
steps.extend(new_steps)
|
|
68
|
+
|
|
69
|
+
event_bus.emit(EVENTS["AGENT_COMPLETE"], task=goal)
|
|
70
|
+
return self._summarize(completed)
|
|
71
|
+
|
|
72
|
+
async def _fallback_llm(self, goal: str) -> str:
|
|
73
|
+
if self.llm:
|
|
74
|
+
try:
|
|
75
|
+
return await self.llm.generate([{"role": "user", "content": goal}])
|
|
76
|
+
except Exception:
|
|
77
|
+
pass
|
|
78
|
+
return f"Unable to process: {goal}"
|
|
79
|
+
|
|
80
|
+
def _summarize(self, results) -> str:
|
|
81
|
+
parts = []
|
|
82
|
+
for i, r in enumerate(results):
|
|
83
|
+
icon = "✓" if r.success else "✗"
|
|
84
|
+
parts.append(f"{icon} Step {i+1}: {str(r.data or r.error)[:200]}")
|
|
85
|
+
return "\n".join(parts)
|