agent-claw: automated task changes
This commit is contained in:
5
agentclaw/app/agent_claw_main/tools/__init__.py
Normal file
5
agentclaw/app/agent_claw_main/tools/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from .web import brave_search, web_fetch
|
||||
from .workspace import read_file, write_file
|
||||
from .messaging import send, set_adapter
|
||||
|
||||
__all__ = ['brave_search', 'web_fetch', 'read_file', 'write_file', 'send', 'set_adapter']
|
||||
68
agentclaw/app/agent_claw_main/tools/code_interpreter.py
Normal file
68
agentclaw/app/agent_claw_main/tools/code_interpreter.py
Normal file
@@ -0,0 +1,68 @@
|
||||
"""Code interpreter tool — runs Python code in AgentCore managed sandbox."""
|
||||
import os
|
||||
import base64
|
||||
from strands import tool
|
||||
|
||||
|
||||
def _parse_stream(result: dict) -> str:
|
||||
"""Parse the streaming response from invoke_code_interpreter."""
|
||||
parts = []
|
||||
if "stream" not in result:
|
||||
return str(result)
|
||||
|
||||
for event in result["stream"]:
|
||||
if "result" not in event:
|
||||
continue
|
||||
for item in event["result"].get("content", []):
|
||||
item_type = item.get("type", "")
|
||||
if item_type == "text":
|
||||
text = item.get("text", "")
|
||||
if text:
|
||||
parts.append(text)
|
||||
elif item_type == "resource":
|
||||
resource = item.get("resource", {})
|
||||
if "text" in resource:
|
||||
parts.append(resource["text"])
|
||||
elif "blob" in resource:
|
||||
try:
|
||||
parts.append(base64.b64decode(resource["blob"]).decode("utf-8"))
|
||||
except Exception:
|
||||
parts.append(f"<binary resource: {resource.get('uri', '?')}>")
|
||||
elif item_type == "image":
|
||||
# Base64-encoded image
|
||||
image_data = item.get("source", {}).get("data", "")
|
||||
mime = item.get("source", {}).get("mediaType", "image/png")
|
||||
parts.append(f"<image: {mime}, {len(image_data)} bytes base64>")
|
||||
|
||||
return "\n".join(parts) if parts else "(no output)"
|
||||
|
||||
|
||||
@tool
|
||||
def run_code(code: str, packages: list[str] | None = None) -> str:
|
||||
"""Execute Python code in a secure managed sandbox and return the output.
|
||||
Optionally install pip packages before running (e.g. ['pandas', 'numpy']).
|
||||
|
||||
Args:
|
||||
code: Python code to execute.
|
||||
packages: Optional list of pip packages to install first.
|
||||
|
||||
Returns:
|
||||
Execution output (stdout, results, errors).
|
||||
"""
|
||||
try:
|
||||
from bedrock_agentcore.tools import CodeInterpreter, code_session
|
||||
|
||||
region = os.environ.get('AWS_REGION', 'us-east-1')
|
||||
|
||||
with code_session(region) as client:
|
||||
if packages:
|
||||
install_raw = client.install_packages(packages)
|
||||
install_out = _parse_stream(install_raw) if isinstance(install_raw, dict) else str(install_raw)
|
||||
print(f'[code_interpreter] install: {install_out[:200]}')
|
||||
|
||||
raw = client.execute_code(code)
|
||||
return _parse_stream(raw)
|
||||
|
||||
except Exception as e:
|
||||
import traceback
|
||||
return f'Code interpreter error: {type(e).__name__}: {e}\n{traceback.format_exc()[-500:]}'
|
||||
91
agentclaw/app/agent_claw_main/tools/home_assistant.py
Normal file
91
agentclaw/app/agent_claw_main/tools/home_assistant.py
Normal file
@@ -0,0 +1,91 @@
|
||||
"""Home Assistant tool — control and query HA entities via REST API."""
|
||||
import json
|
||||
import os
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
from strands import tool
|
||||
|
||||
HA_URL = "https://homeassistant.home.everyonce.com"
|
||||
# Token stored in workspace or env; fallback to hardcoded for AgentCore runtime
|
||||
HA_TOKEN = os.environ.get(
|
||||
"HA_TOKEN",
|
||||
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJlMDExN2YwNzhlM2Q0NjViODJhNjJiZWFiMzI1ZWU4MiIsImlhdCI6MTc3MTM1MjU0MiwiZXhwIjoyMDg2NzEyNTQyfQ.UySLD6JV4e_bdd1nQjdbZcimdCD6B3kBGDftcRz1H6Q"
|
||||
)
|
||||
|
||||
|
||||
def _ha_request(method: str, path: str, body: dict | None = None) -> dict | list:
|
||||
url = f"{HA_URL}{path}"
|
||||
headers = {
|
||||
"Authorization": f"Bearer {HA_TOKEN}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
data = json.dumps(body).encode() if body else None
|
||||
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
return json.loads(resp.read().decode())
|
||||
except urllib.error.HTTPError as e:
|
||||
return {"error": f"HTTP {e.code}: {e.reason}", "body": e.read().decode()[:500]}
|
||||
except Exception as e:
|
||||
return {"error": str(e)}
|
||||
|
||||
|
||||
@tool
|
||||
def home_assistant(action: str, entity_id: str = "", domain: str = "", service: str = "",
|
||||
service_data: dict | None = None) -> str:
|
||||
"""Control and query your Home Assistant smart home.
|
||||
|
||||
Actions:
|
||||
- "get_state": Get the current state of a specific entity (requires entity_id).
|
||||
- "list_states": List all entity states (optionally filter by domain prefix like 'light', 'switch', 'climate', 'sensor').
|
||||
- "call_service": Call a HA service (requires domain, service, and optional service_data with entity_id).
|
||||
- "get_history": Not yet implemented.
|
||||
|
||||
Common service examples:
|
||||
- Turn light on: domain="light", service="turn_on", service_data={"entity_id": "light.living_room"}
|
||||
- Turn light off: domain="light", service="turn_off", service_data={"entity_id": "light.living_room"}
|
||||
- Set brightness: domain="light", service="turn_on", service_data={"entity_id": "light.x", "brightness_pct": 50}
|
||||
- Lock door: domain="lock", service="lock", service_data={"entity_id": "lock.front_door"}
|
||||
- Set thermostat: domain="climate", service="set_temperature", service_data={"entity_id": "climate.x", "temperature": 72}
|
||||
|
||||
Args:
|
||||
action: One of "get_state", "list_states", "call_service".
|
||||
entity_id: Entity ID for get_state (e.g. "light.living_room").
|
||||
domain: Service domain for call_service (e.g. "light", "switch", "lock", "climate").
|
||||
service: Service name for call_service (e.g. "turn_on", "turn_off", "lock").
|
||||
service_data: Dict of extra params for call_service (e.g. {"entity_id": "light.x", "brightness_pct": 80}).
|
||||
|
||||
Returns:
|
||||
JSON string with the result.
|
||||
"""
|
||||
if action == "get_state":
|
||||
if not entity_id:
|
||||
return "entity_id is required for get_state"
|
||||
result = _ha_request("GET", f"/api/states/{entity_id}")
|
||||
if isinstance(result, dict) and "error" not in result:
|
||||
return f"{entity_id}: {result.get('state')} (attrs: {json.dumps(result.get('attributes', {}))[:300]})"
|
||||
return json.dumps(result)
|
||||
|
||||
elif action == "list_states":
|
||||
result = _ha_request("GET", "/api/states")
|
||||
if isinstance(result, list):
|
||||
# Filter by domain prefix if entity_id used as filter
|
||||
prefix = entity_id or domain
|
||||
if prefix:
|
||||
result = [s for s in result if s.get("entity_id", "").startswith(prefix)]
|
||||
# Return concise summary
|
||||
lines = [f"{s['entity_id']}: {s['state']}" for s in result[:50]]
|
||||
return "\n".join(lines) + (f"\n... ({len(result)} total)" if len(result) > 50 else "")
|
||||
return json.dumps(result)
|
||||
|
||||
elif action == "call_service":
|
||||
if not domain or not service:
|
||||
return "domain and service are required for call_service"
|
||||
body = service_data or {}
|
||||
if entity_id and "entity_id" not in body:
|
||||
body["entity_id"] = entity_id
|
||||
result = _ha_request("POST", f"/api/services/{domain}/{service}", body)
|
||||
return f"Service {domain}.{service} called successfully" if isinstance(result, list) else json.dumps(result)
|
||||
|
||||
else:
|
||||
return f"Unknown action: {action}. Use 'get_state', 'list_states', or 'call_service'."
|
||||
30
agentclaw/app/agent_claw_main/tools/messaging.py
Normal file
30
agentclaw/app/agent_claw_main/tools/messaging.py
Normal file
@@ -0,0 +1,30 @@
|
||||
"""Messaging tool — channel-adapter-backed send_message for the agent."""
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from channels.adapter import ChannelAdapter
|
||||
|
||||
# Injected by main.py before each invocation
|
||||
_adapter: 'ChannelAdapter | None' = None
|
||||
_message_sent: bool = False
|
||||
|
||||
|
||||
def set_adapter(adapter: 'ChannelAdapter') -> None:
|
||||
global _adapter, _message_sent
|
||||
_adapter = adapter
|
||||
_message_sent = False # reset on each new invocation
|
||||
|
||||
|
||||
def was_sent() -> bool:
|
||||
"""Returns True if send() was called during this invocation."""
|
||||
return _message_sent
|
||||
|
||||
|
||||
def send(text: str) -> str:
|
||||
"""Send a message to the user via the active channel adapter."""
|
||||
global _message_sent
|
||||
if _adapter is None:
|
||||
return 'No channel adapter configured.'
|
||||
msg_id = _adapter.send(text)
|
||||
_message_sent = True
|
||||
return f"Sent (id={msg_id})" if msg_id else 'Sent'
|
||||
68
agentclaw/app/agent_claw_main/tools/web.py
Normal file
68
agentclaw/app/agent_claw_main/tools/web.py
Normal file
@@ -0,0 +1,68 @@
|
||||
import os
|
||||
import threading
|
||||
import urllib.request
|
||||
import urllib.parse
|
||||
import json
|
||||
import boto3
|
||||
|
||||
# Brave Search API
|
||||
_brave_key: str | None = None
|
||||
_brave_lock = threading.Lock()
|
||||
|
||||
|
||||
def _get_brave_key() -> str:
|
||||
global _brave_key
|
||||
if _brave_key is None:
|
||||
with _brave_lock:
|
||||
if _brave_key is None:
|
||||
secret_arn = os.environ.get(
|
||||
'BRAVE_API_KEY_SECRET_ARN',
|
||||
'arn:aws:secretsmanager:us-east-1:495395224548:secret:agent-claw/brave-api-key-uUSgzi'
|
||||
)
|
||||
sm = boto3.client('secretsmanager')
|
||||
_brave_key = sm.get_secret_value(SecretId=secret_arn)['SecretString']
|
||||
return _brave_key
|
||||
|
||||
|
||||
def brave_search(query: str, count: int = 5) -> str:
|
||||
"""Search the web using Brave Search API."""
|
||||
api_key = _get_brave_key()
|
||||
params = urllib.parse.urlencode({'q': query, 'count': count})
|
||||
req = urllib.request.Request(
|
||||
f'https://api.search.brave.com/res/v1/web/search?{params}',
|
||||
headers={
|
||||
'Accept': 'application/json',
|
||||
'X-Subscription-Token': api_key,
|
||||
},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
data = json.loads(resp.read())
|
||||
|
||||
results = data.get('web', {}).get('results', [])
|
||||
if not results:
|
||||
return 'No results found.'
|
||||
|
||||
parts = []
|
||||
for r in results:
|
||||
parts.append(f"**{r.get('title', '')}**\n{r.get('url', '')}\n{r.get('description', '')}")
|
||||
return '\n\n'.join(parts)
|
||||
|
||||
|
||||
def web_fetch(url: str) -> str:
|
||||
"""Fetch and return text content from a URL."""
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
headers={'User-Agent': 'Mozilla/5.0 (compatible; agent-claw/1.0)'},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=15) as resp:
|
||||
raw = resp.read(1024 * 1024) # cap at 1MB
|
||||
|
||||
# Basic text extraction (strip HTML tags)
|
||||
import re
|
||||
text = raw.decode('utf-8', errors='ignore')
|
||||
text = re.sub(r'<script[^>]*>.*?</script>', '', text, flags=re.DOTALL | re.IGNORECASE)
|
||||
text = re.sub(r'<style[^>]*>.*?</style>', '', text, flags=re.DOTALL | re.IGNORECASE)
|
||||
text = re.sub(r'<[^>]+>', ' ', text)
|
||||
text = re.sub(r'[ \t]+', ' ', text)
|
||||
text = re.sub(r'\n{3,}', '\n\n', text)
|
||||
return text[:8000].strip()
|
||||
48
agentclaw/app/agent_claw_main/tools/workspace.py
Normal file
48
agentclaw/app/agent_claw_main/tools/workspace.py
Normal file
@@ -0,0 +1,48 @@
|
||||
import os
|
||||
import boto3
|
||||
|
||||
# In-memory cache for workspace files (lives for the duration of the warm session)
|
||||
_cache: dict[str, str] = {}
|
||||
_s3 = None
|
||||
|
||||
|
||||
def _get_s3():
|
||||
global _s3
|
||||
if _s3 is None:
|
||||
_s3 = boto3.client('s3')
|
||||
return _s3
|
||||
|
||||
|
||||
def get_bucket() -> str:
|
||||
return os.environ['WORKSPACE_BUCKET_NAME']
|
||||
|
||||
|
||||
def read_file(path: str) -> str:
|
||||
"""Read a workspace file from S3 (cached)."""
|
||||
if path not in _cache:
|
||||
resp = _get_s3().get_object(Bucket=get_bucket(), Key=path)
|
||||
_cache[path] = resp['Body'].read().decode('utf-8')
|
||||
return _cache[path]
|
||||
|
||||
|
||||
def write_file(path: str, content: str) -> str:
|
||||
"""Write a workspace file to S3 and update cache."""
|
||||
_get_s3().put_object(
|
||||
Bucket=get_bucket(),
|
||||
Key=path,
|
||||
Body=content.encode('utf-8'),
|
||||
ContentType='text/markdown',
|
||||
)
|
||||
_cache[path] = content
|
||||
return f"Written {len(content)} bytes to {path}"
|
||||
|
||||
|
||||
def load_persona_files() -> dict[str, str]:
|
||||
"""Load all persona files at session start (SOUL.md etc.)"""
|
||||
files = {}
|
||||
for fname in ['SOUL.md', 'AGENTS.md', 'IDENTITY.md', 'USER.md']:
|
||||
try:
|
||||
files[fname] = read_file(fname)
|
||||
except Exception:
|
||||
pass
|
||||
return files
|
||||
Reference in New Issue
Block a user