Source code for fleetmesh_node.planes.services.compute.executors.agent
"""Autonomous ReAct agent harness: Reasoning + Action loop with tool dispatch and recursive delegation.
Architecture:
- AgentExecutionContext: State container holding task, budget caps, blob store, and delegation dispatcher.
- AgentToolProtocol & Standard Tools: Calculator, Regex, Sha256, FetchBlob, SubAsk, and Finish.
- AgentBackendProtocol: Decides next step (Thought, Action, Action Input) via LLM or scripted plan.
- ReAct Loop: Bounded by max_steps and fuel_cap, with step-level telemetry and honesty gate.
"""
from __future__ import annotations
import ast
import json
import operator
import re
from dataclasses import dataclass, field
from typing import Any, Callable, Mapping, Optional, Protocol, Sequence, TypedDict
from fleetmesh_core.crypto import crypto
from ..common import ComputeError, resolve_blob
from ..sandbox import ComputeLimits
from ..types import AgentSubAsk, AgentTraceStep
from .base import ComputeExecutionResult, ComputeExecutor, ComputeQuote
from .harness import (
AgentHarnessRegistry,
AgentProfileSpec,
)
# ---------------------------------------------------------------------------
# Context & Protocols
# ---------------------------------------------------------------------------
[docs]@dataclass
class AgentExecutionContext:
"""Runtime execution context provided to tools during an agent reasoning step."""
task: str
delegation: Mapping[str, Any] = field(default_factory=dict)
budget_cap_msat: int = 0
budget_spent_msat: int = 0
blob_store: Optional[Any] = None
blossom_servers: list[str] = field(default_factory=list)
sub_ask_dispatcher: Optional[Callable[[Mapping[str, Any]], Mapping[str, Any]]] = None
fuel_cap: int = 100_000
fuel_used: int = 0
sub_asks_dispatched: list[AgentSubAsk] = field(default_factory=list)
depth: int = 0
harness_profile: Optional[AgentProfileSpec] = None
domain_context: Mapping[str, Any] = field(default_factory=dict)
[docs] def get_remaining_budget(self) -> int:
"""Remaining msat budget permitted for child sub-delegation asks."""
return max(0, self.budget_cap_msat - self.budget_spent_msat)
[docs] def deduct_delegation(self, amount_msat: int) -> int:
"""Atomically deduct allocated msat from remaining budget and return granted amount."""
granted = min(self.get_remaining_budget(), amount_msat)
if granted > 0:
self.budget_spent_msat += granted
return max(0, granted)
[docs] def record_sub_ask(self, sub_ask: AgentSubAsk) -> None:
"""Record dispatched child ask into session telemetry."""
self.sub_asks_dispatched.append(sub_ask)
[docs]class AgentToolResult(TypedDict, total=False):
"""Result returned by an agent tool execution."""
output: Any
error: Optional[str]
fuel_consumed: int
sub_ask_id: Optional[str]
[docs]class AgentToolProtocol(Protocol):
"""Interface for agent-invocable tools."""
name: str
description: str
parameters_schema: Mapping[str, Any]
[docs]@dataclass
class AgentDecision:
"""Action decision formulated by an agent reasoning backend."""
thought: str
action: str
action_input: Any = field(default_factory=dict)
is_finish: bool = False
final_answer: Optional[str] = None
[docs]class AgentBackendProtocol(Protocol):
"""Reasoning backend providing Thought and Action generation for the ReAct loop."""
[docs] def decide_step(
self,
task: str,
trace: Sequence[AgentTraceStep],
tools: Mapping[str, AgentToolProtocol],
context: AgentExecutionContext,
) -> AgentDecision:
...
# ---------------------------------------------------------------------------
# Standard Built-in Tools
# ---------------------------------------------------------------------------
[docs]class CalculatorTool:
"""Safe arithmetic expression evaluator using AST inspection (no arbitrary code execution)."""
name: str = 'calc'
description: str = 'Safely evaluates basic arithmetic expressions (+, -, *, /, //, %, **, abs, round, min, max).'
parameters_schema: Mapping[str, Any] = {
'type': 'object',
'properties': {
'expression': {'type': 'string', 'description': 'Mathematical expression to evaluate'},
},
'required': ['expression'],
}
_ALLOWED_OPS: Mapping[type[Any], Callable[..., Any]] = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.FloorDiv: operator.floordiv,
ast.Mod: operator.mod,
ast.Pow: operator.pow,
ast.USub: operator.neg,
ast.UAdd: operator.pos,
}
_ALLOWED_FUNCS: Mapping[str, Callable[..., Any]] = {
'abs': abs,
'round': round,
'min': min,
'max': max,
}
def _eval_node(self, node: ast.AST) -> float | int:
if isinstance(node, ast.Expression):
return self._eval_node(node.body)
if isinstance(node, ast.Constant):
if type(node.value) is bool:
raise ValueError("Boolean constants are not allowed in calculator expressions")
if isinstance(node.value, (int, float)):
return node.value
raise ValueError(f"Constant {node.value!r} is not a numeric value")
if isinstance(node, ast.UnaryOp):
unary_op_type = type(node.op)
if unary_op_type in self._ALLOWED_OPS:
return self._ALLOWED_OPS[unary_op_type](self._eval_node(node.operand))
raise ValueError(f"Unsupported unary operator: {unary_op_type.__name__}")
if isinstance(node, ast.BinOp):
bin_op_type = type(node.op)
if bin_op_type in self._ALLOWED_OPS:
left = self._eval_node(node.left)
right = self._eval_node(node.right)
if bin_op_type in (ast.Div, ast.FloorDiv, ast.Mod) and right == 0:
raise ZeroDivisionError("Division by zero")
if bin_op_type == ast.Pow:
if abs(right) > 500:
raise ValueError("Exponent too large (abs > 500)")
if abs(left) > 10_000 and right > 10:
raise ValueError("Base too large for power operation")
return self._ALLOWED_OPS[bin_op_type](left, right)
raise ValueError(f"Unsupported binary operator: {bin_op_type.__name__}")
if isinstance(node, ast.Call):
if isinstance(node.func, ast.Name) and node.func.id in self._ALLOWED_FUNCS:
args = [self._eval_node(a) for a in node.args]
return self._ALLOWED_FUNCS[node.func.id](*args)
raise ValueError(f"Function call not allowed: {getattr(node.func, 'id', 'unknown')}")
raise ValueError(f"Expression contains disallowed syntax: {type(node).__name__}")
[docs] def execute(self, params: Any, context: AgentExecutionContext) -> AgentToolResult:
if isinstance(params, str):
expr = params.strip()
elif isinstance(params, Mapping):
expr = str(params.get('expression') or params.get('expr') or params.get('formula') or params.get('math') or params.get('raw') or '').strip()
else:
expr = str(params).strip()
if not expr:
return {'error': 'Missing expression parameter', 'fuel_consumed': 10}
try:
tree = ast.parse(expr, mode='eval')
val = self._eval_node(tree)
return {'output': val, 'fuel_consumed': 50}
except Exception as e:
return {'error': f"Evaluation error: {e}", 'fuel_consumed': 20}
[docs]class Sha256Tool:
"""Cryptographic SHA-256 hash calculator."""
name: str = 'sha256'
description: str = 'Computes SHA-256 digest of input text or binary hex.'
parameters_schema: Mapping[str, Any] = {
'type': 'object',
'properties': {
'data': {'type': 'string', 'description': 'Input string or hex string'},
'is_hex': {'type': 'boolean', 'description': 'True if data is hex-encoded'},
},
'required': ['data'],
}
[docs] def execute(self, params: Any, context: AgentExecutionContext) -> AgentToolResult:
if isinstance(params, str):
raw_data = params
is_hex = False
elif isinstance(params, Mapping):
raw_data = params.get('data') or params.get('text') or params.get('input') or params.get('content') or params.get('raw') or ''
is_hex = bool(params.get('is_hex', False))
else:
raw_data = str(params)
is_hex = False
try:
b = bytes.fromhex(str(raw_data)) if is_hex else str(raw_data).encode('utf-8')
digest = crypto.sha256(b)
return {'output': digest, 'fuel_consumed': 25 + len(b) // 64}
except Exception as e:
return {'error': f"Hashing failed: {e}", 'fuel_consumed': 10}
[docs]class RegexSearchTool:
"""Safe regular expression pattern search and extraction tool."""
name: str = 'regex_search'
description: str = 'Searches text using a regular expression pattern and returns matches.'
parameters_schema: Mapping[str, Any] = {
'type': 'object',
'properties': {
'pattern': {'type': 'string', 'description': 'Regex pattern to match'},
'text': {'type': 'string', 'description': 'Target text to search'},
},
'required': ['pattern', 'text'],
}
[docs] def execute(self, params: Any, context: AgentExecutionContext) -> AgentToolResult:
if not isinstance(params, Mapping):
return {'error': 'Parameters must be an object with pattern and text', 'fuel_consumed': 10}
pattern = str(params.get('pattern') or params.get('regex') or '')
text = str(params.get('text') or params.get('target') or params.get('string') or params.get('input') or params.get('raw') or '')
if not pattern:
return {'error': 'Missing pattern parameter', 'fuel_consumed': 10}
if len(pattern) > 256 or len(text) > 65536:
return {'error': 'Regex pattern or text exceeds safety bounds', 'fuel_consumed': 20}
try:
matches = re.findall(pattern, text)
return {'output': matches, 'fuel_consumed': 40 + len(text) // 1024}
except Exception as e:
return {'error': f"Regex error: {e}", 'fuel_consumed': 15}
[docs]class FetchBlobTool:
"""Blossom CAS blob retrieval tool."""
name: str = 'fetch_blob'
description: str = 'Retrieves a content-addressed blob by SHA-256 hash or CID from the local store or Blossom network.'
parameters_schema: Mapping[str, Any] = {
'type': 'object',
'properties': {
'sha256': {'type': 'string', 'description': 'SHA-256 hex digest of the blob'},
},
'required': ['sha256'],
}
[docs] def execute(self, params: Any, context: AgentExecutionContext) -> AgentToolResult:
if isinstance(params, str):
sha = params.strip().lower()
elif isinstance(params, Mapping):
sha = str(params.get('sha256') or params.get('cid') or params.get('hash') or params.get('digest') or params.get('blob_id') or params.get('raw') or '').strip().lower()
else:
sha = str(params).strip().lower()
if not sha:
return {'error': 'Missing sha256 or cid parameter', 'fuel_consumed': 10}
try:
blob_bytes = resolve_blob(
{'sha256': sha},
blob_store=context.blob_store,
blossom_servers=context.blossom_servers,
)
if blob_bytes is None:
return {'error': f"Blob not found: {sha}", 'fuel_consumed': 50}
preview = blob_bytes[:256].decode('utf-8', errors='replace')
return {
'output': {
'sha256': sha,
'size_bytes': len(blob_bytes),
'preview': preview,
},
'fuel_consumed': 100 + len(blob_bytes) // 1024,
}
except Exception as e:
return {'error': f"Blob resolution error: {e}", 'fuel_consumed': 25}
[docs]class SubAskTool:
"""Recursive child-Ask mesh delegation tool."""
name: str = 'sub_ask'
description: str = 'Dispatches a delegated sub-computation ask (Kind 30810) to peer nodes across the mesh.'
parameters_schema: Mapping[str, Any] = {
'type': 'object',
'properties': {
'task': {'type': 'string', 'description': 'Sub-task description or prompt'},
'engine': {'type': 'string', 'description': 'Target execution engine (e.g. wasm, llm, zkvm)'},
'budget_msat': {'type': 'integer', 'description': 'Maximum msat budget allocated to child ask'},
},
'required': ['task'],
}
[docs] def execute(self, params: Any, context: AgentExecutionContext) -> AgentToolResult:
if not context.delegation.get('allowSubAsks', False):
return {'error': 'Sub-ask delegation is not permitted for this job', 'fuel_consumed': 50}
if context.depth >= 3:
return {'error': 'Maximum recursive delegation depth exceeded (depth=3)', 'fuel_consumed': 50}
if isinstance(params, str):
sub_task = params.strip()
engine = 'wasm'
requested_budget = 1000
elif isinstance(params, Mapping):
sub_task = str(params.get('task') or params.get('prompt') or params.get('description') or params.get('goal') or params.get('raw') or '').strip()
engine = str(params.get('engine') or 'wasm')
requested_budget = int(params.get('budget_msat') or params.get('budgetCapMsat') or params.get('budget') or 1000)
else:
sub_task = str(params).strip()
engine = 'wasm'
requested_budget = 1000
if not sub_task:
return {'error': 'Missing task description for sub-ask', 'fuel_consumed': 10}
remaining_budget = context.get_remaining_budget()
if requested_budget > remaining_budget:
requested_budget = remaining_budget
if requested_budget <= 0:
return {'error': 'Delegation budget ceiling exhausted', 'fuel_consumed': 50}
granted = context.deduct_delegation(requested_budget)
ask_id = f"sub_ask_{crypto.sha256(sub_task.encode('utf-8'))[:16]}"
child_ask_payload = {
'ask_id': ask_id,
'task': sub_task,
'engine': engine,
'budget_msat': granted,
'depth': context.depth + 1,
}
if context.sub_ask_dispatcher:
try:
dispatch_res = context.sub_ask_dispatcher(child_ask_payload)
status = dispatch_res.get('status', 'completed')
result_hash = dispatch_res.get('result_hash', crypto.sha256(sub_task.encode('utf-8')))
except Exception as e:
return {'error': f"Sub-ask dispatch failed: {e}", 'fuel_consumed': 100}
else:
# Standalone / simulated sub-computation
status = 'dispatched'
result_hash = crypto.sha256(f"sub_result:{ask_id}".encode('utf-8'))
sub_ask_record: AgentSubAsk = {
'ask_id': ask_id,
'task': sub_task,
'budget_msat': granted,
'status': status,
}
context.record_sub_ask(sub_ask_record)
return {
'output': {
'ask_id': ask_id,
'status': status,
'budget_allocated_msat': granted,
'result_hash': result_hash,
'summary': f"Child task {ask_id} dispatched",
},
'sub_ask_id': ask_id,
'fuel_consumed': 250,
}
[docs]class FinishTool:
"""Terminal tool to conclude the ReAct loop and return the final synthesized answer."""
name: str = 'finish'
description: str = 'Concludes execution and provides the final synthesized answer.'
parameters_schema: Mapping[str, Any] = {
'type': 'object',
'properties': {
'answer': {'type': 'string', 'description': 'Final synthesized answer or output'},
},
'required': ['answer'],
}
[docs] def execute(self, params: Any, context: AgentExecutionContext) -> AgentToolResult:
if isinstance(params, str):
answer = params.strip()
elif isinstance(params, Mapping):
answer = str(params.get('answer') or params.get('final_answer') or params.get('output') or params.get('result') or params.get('summary') or params.get('response') or params.get('raw') or 'Agent workflow completed successfully').strip()
else:
answer = str(params).strip()
return {'output': answer or 'Agent workflow completed successfully', 'fuel_consumed': 50}
# ---------------------------------------------------------------------------
# Reasoning Backends
# ---------------------------------------------------------------------------
[docs]class ScriptedAgentBackend:
"""Deterministic ReAct reasoning backend for testing, fixtures, and scripted workflows."""
[docs] def __init__(self, scripted_steps: Optional[Sequence[AgentDecision]] = None) -> None:
self.scripted_steps = list(scripted_steps) if scripted_steps else None
self._step_index = 0
[docs] def decide_step(
self,
task: str,
trace: Sequence[AgentTraceStep],
tools: Mapping[str, AgentToolProtocol],
context: AgentExecutionContext,
) -> AgentDecision:
if self.scripted_steps and self._step_index < len(self.scripted_steps):
dec = self.scripted_steps[self._step_index]
self._step_index += 1
return dec
step_num = len(trace) + 1
# Heuristic 3-step loop maintaining full backwards compatibility
if step_num == 1:
return AgentDecision(
thought=f"Analyze task requirements: '{task[:64]}'",
action='decompose_task',
action_input={'task': task},
)
if step_num == 2:
allow_sub_asks = bool(context.delegation.get('allowSubAsks', False))
budget_cap = int(context.delegation.get('budgetCapMsat', 0))
if allow_sub_asks and budget_cap > 0:
child_budget = min(10000, budget_cap)
return AgentDecision(
thought='Sub-ask delegation permitted; dispatched child computation ask',
action='sub_ask',
action_input={'task': f"Sub-computation for: {task[:48]}", 'budget_msat': child_budget},
)
if 'calc' in task or any(c in task for c in ('+', '*', '/', '-')):
return AgentDecision(
thought='Task requires mathematical calculation',
action='calc',
action_input={'expression': '21 * 2'},
)
return AgentDecision(
thought='Synthesize final result from observations',
action='finish',
action_input={'answer': f"Completed execution of goal: '{task[:64]}'"},
is_finish=True,
)
# Final step
return AgentDecision(
thought='Synthesize final result from observations',
action='finish',
action_input={'answer': f"Completed execution of goal: '{task[:64]}'"},
is_finish=True,
)
[docs]class LlmAgentBackend:
"""Live LLM-driven reasoning backend querying OpenAI/Anthropic/Routstr-compatible endpoints."""
[docs] def __init__(
self,
endpoint: str = 'http://127.0.0.1:8000/v1',
model: str = 'meta-llama/Llama-3.3-70B-Instruct',
timeout_seconds: float = 30.0,
api_key: str = '',
cashu_token: str = '',
provider_id: str = 'vllm',
provider_router: Optional[Any] = None,
) -> None:
self.endpoint = endpoint.rstrip('/')
self.model = model
self.timeout_seconds = timeout_seconds
self.api_key = api_key
self.cashu_token = cashu_token
self.provider_id = provider_id
self.provider_router = provider_router
def _resolve_provider(self) -> Any:
from .providers import LinkedProviderConfig
if self.provider_router is not None:
resolved = self.provider_router.get_provider()
if resolved is not None:
return resolved
return LinkedProviderConfig(
provider_id=self.provider_id,
label=self.provider_id.upper(),
endpoint=self.endpoint,
default_model=self.model,
models=(self.model,),
api_key=self.api_key,
cashu_token=self.cashu_token,
auth_scheme='bearer' if self.api_key else ('cashu' if self.cashu_token else 'none'),
wire_format='anthropic_messages' if self.provider_id in ('claude', 'anthropic') else 'openai',
enabled=True,
)
[docs] def is_live_runnable(self) -> bool:
if self.provider_router is not None and self.provider_router.runnable_providers():
return True
return bool(self.endpoint and self.endpoint.startswith(('http://', 'https://')))
[docs] def decide_step(
self,
task: str,
trace: Sequence[AgentTraceStep],
tools: Mapping[str, AgentToolProtocol],
context: AgentExecutionContext,
) -> AgentDecision:
tool_descriptions = [f"- {t.name}: {t.description}" for t in tools.values()]
react_instructions = (
"Given a goal, you think step-by-step, choose a tool, and inspect observations.\n"
f"Available tools:\n{chr(10).join(tool_descriptions)}\n\n"
"Format your response EXACTLY as:\n"
"Thought: <reasoning>\n"
"Action: <tool_name>\n"
"Action Input: <json_parameters_or_string>\n"
"When done, use Action: finish with Action Input: {\"answer\": \"...\"}."
)
if context.harness_profile is not None:
system_prompt = context.harness_profile.compile_system_prompt(
domain_context=context.domain_context,
extra_instructions=react_instructions,
)
temp = context.harness_profile.default_temperature
else:
system_prompt = "You are an autonomous ReAct reasoning agent on Fleetmesh.\n" + react_instructions
temp = 0.1
trace_lines = []
for s in trace:
trace_lines.append(f"Step {s['step']}:")
trace_lines.append(f"Thought: {s['thought']}")
trace_lines.append(f"Action: {s['action']}")
trace_lines.append(f"Observation: {s['observation']}")
user_content = f"Goal: {task}\n\nTrace so far:\n" + ("\n".join(trace_lines) if trace_lines else "None")
provider = self._resolve_provider()
api_route, req_body = provider.format_request(
messages=[
{'role': 'system', 'content': system_prompt},
{'role': 'user', 'content': user_content},
],
model=provider.default_model or self.model,
max_tokens=512,
temperature=temp,
)
headers = provider.build_headers()
from fleetmesh_node.transport import netfetch
try:
body_bytes, _ = netfetch.fetch(
api_route,
max_bytes=10 * 1024 * 1024,
headers=headers,
data=json.dumps(req_body).encode('utf-8'),
method='POST',
timeout=self.timeout_seconds,
allow_private=True,
)
data = json.loads(body_bytes.decode('utf-8'))
reply, _, _ = provider.parse_response(data)
except Exception as e:
raise ComputeError(f"Agent LLM backend request to {provider.endpoint} failed: {e}")
# Parse Thought / Action / Action Input from reply
thought = ''
action = 'finish'
action_input: Mapping[str, Any] = {}
t_m = re.search(r'Thought:\s*(.*?)(?=\nAction:|$)', reply, re.DOTALL)
if t_m:
thought = t_m.group(1).strip()
a_m = re.search(r'Action:\s*([a-zA-Z0-9_-]+)', reply)
if a_m:
action = a_m.group(1).strip()
i_m = re.search(r'Action Input:\s*(\{.*?\}|\[.*?\]|[^\n]+)', reply, re.DOTALL)
if i_m:
raw_in = i_m.group(1).strip()
if raw_in.startswith(('{', '[')):
try:
action_input = json.loads(raw_in)
except Exception:
action_input = {'raw': raw_in}
else:
action_input = {'raw': raw_in}
is_finish = action == 'finish'
return AgentDecision(
thought=thought or f"Proceeding with {action}",
action=action,
action_input=action_input,
is_finish=is_finish,
final_answer=action_input.get('answer') if is_finish else None,
)
# ---------------------------------------------------------------------------
# AgentExecutor
# ---------------------------------------------------------------------------
[docs]class AgentExecutor(ComputeExecutor):
"""Autonomous ReAct agent harness (Reasoning + Action loop with tool dispatch)."""
engine_id: str = 'agent'
wasi_profile_digest: str = 'fleetmesh-react-v1'
[docs] def __init__(
self,
max_steps_default: int = 25,
mock_mode: bool = False,
backend: Optional[AgentBackendProtocol] = None,
tools: Optional[Sequence[AgentToolProtocol]] = None,
sub_ask_dispatcher: Optional[Callable[[Mapping[str, Any]], Mapping[str, Any]]] = None,
harness_registry: Optional[AgentHarnessRegistry] = None,
) -> None:
self.max_steps_default = max_steps_default
self.mock_mode = mock_mode
self.backend = backend or (ScriptedAgentBackend() if mock_mode else None)
self.sub_ask_dispatcher = sub_ask_dispatcher
self.harness_registry = harness_registry or AgentHarnessRegistry()
default_tools: list[AgentToolProtocol] = [
CalculatorTool(),
Sha256Tool(),
RegexSearchTool(),
FetchBlobTool(),
SubAskTool(),
FinishTool(),
]
if tools:
default_tools.extend(tools)
self.tools: dict[str, AgentToolProtocol] = {t.name: t for t in default_tools}
[docs] def is_live_runnable(self) -> bool:
"""Returns True if the executor is capable of servicing live compute requests."""
if self.mock_mode:
return True
if self.backend is not None and getattr(self.backend, 'is_live_runnable', lambda: False)():
return True
return False
[docs] def register_tool(self, tool: AgentToolProtocol) -> None:
"""Register a new tool into the agent harness."""
self.tools[tool.name] = tool
[docs] def quote(
self,
module_spec: Mapping[str, Any],
input_spec: Mapping[str, Any],
limits: ComputeLimits,
) -> ComputeQuote:
max_steps = int(input_spec.get('max_steps', self.max_steps_default))
fuel_est = max_steps * 500
return ComputeQuote(
fuel_estimate=min(fuel_est, limits.max_fuel),
rate_unit='msat_per_step',
rate_amount=500,
engine_id=self.engine_id,
)
[docs] def execute(
self,
job_payload: Mapping[str, Any],
fuel_cap: int,
) -> ComputeExecutionResult:
task = job_payload.get('task') or job_payload.get('prompt') or ''
delegation = job_payload.get('delegation') or {}
budget_cap_msat = int(delegation.get('budgetCapMsat', 0))
max_steps = int(job_payload.get('max_steps', self.max_steps_default))
verif_mode = self.verification_mode(job_payload)
# Honesty gate: refuses live execution if unconfigured outside mock_mode
if not self.is_live_runnable():
raise ComputeError('not implemented: agent executor is a stub (mock_mode only or configured live backend required)')
backend = self.backend or ScriptedAgentBackend()
profile_spec: Optional[AgentProfileSpec] = None
raw_profile = job_payload.get('harness_profile')
if isinstance(raw_profile, AgentProfileSpec):
profile_spec = raw_profile
elif isinstance(raw_profile, Mapping):
profile_spec = AgentProfileSpec.from_mapping(raw_profile)
elif job_payload.get('agent_id'):
profile_spec = self.harness_registry.get(str(job_payload.get('agent_id')))
context = AgentExecutionContext(
task=task,
delegation=delegation,
budget_cap_msat=budget_cap_msat,
budget_spent_msat=0,
sub_ask_dispatcher=self.sub_ask_dispatcher,
fuel_cap=fuel_cap,
fuel_used=0,
harness_profile=profile_spec,
domain_context=dict(job_payload.get('domain_context') or {}),
)
trace: list[AgentTraceStep] = []
tools_called: list[str] = []
fuel_used = 0
final_answer = ''
for step_num in range(1, max_steps + 1):
# Step base reasoning fuel consumption
step_fuel = 500
if fuel_used + step_fuel > fuel_cap:
raise ComputeError(f"Agent execution exceeded fuel ceiling ({fuel_used + step_fuel} > {fuel_cap})")
fuel_used += step_fuel
context.fuel_used = fuel_used
decision = backend.decide_step(task, trace, self.tools, context)
action_name = str(decision.action or '').strip()
action_lower = action_name.lower()
if decision.is_finish or action_lower == 'finish':
if decision.final_answer:
final_answer = decision.final_answer
elif isinstance(decision.action_input, Mapping):
final_answer = str(decision.action_input.get('answer') or decision.action_input.get('final_answer') or 'Agent workflow completed successfully')
else:
final_answer = str(decision.action_input or 'Agent workflow completed successfully')
trace.append({
'step': step_num,
'thought': decision.thought,
'action': 'finish',
'observation': final_answer,
})
tools_called.append('finish')
break
# Handle synthetic / legacy decompose_task tool
if action_lower == 'decompose_task':
obs = f"Goal identified, tools loaded: {', '.join(sorted(self.tools.keys()))}"
trace.append({
'step': step_num,
'thought': decision.thought,
'action': 'decompose_task',
'observation': obs,
})
tools_called.append('decompose_task')
continue
tool = self.tools.get(action_name) or self.tools.get(action_lower)
if not tool:
obs = f"Tool '{action_name}' not recognized. Available: {list(self.tools.keys())}"
tool_fuel = 10
else:
act_input = decision.action_input
if isinstance(act_input, str):
s = act_input.strip()
if s.startswith(('{', '[')):
try:
act_input = json.loads(s)
except Exception:
act_input = {'raw': s}
else:
act_input = {'raw': s}
try:
tool_res = tool.execute(act_input, context)
except Exception as e:
tool_res = {'error': f"Tool execution failed: {e}", 'fuel_consumed': 25}
tool_fuel = tool_res.get('fuel_consumed', 50)
if 'error' in tool_res and tool_res['error']:
obs = f"Error: {tool_res['error']}"
elif 'output' in tool_res:
out_val = tool_res['output']
obs = json.dumps(out_val) if isinstance(out_val, (dict, list)) else str(out_val)
else:
obs = 'Tool executed successfully'
if fuel_used + tool_fuel > fuel_cap:
raise ComputeError(f"Agent execution exceeded fuel ceiling ({fuel_used + tool_fuel} > {fuel_cap})")
fuel_used += tool_fuel
context.fuel_used = fuel_used
trace.append({
'step': step_num,
'thought': decision.thought,
'action': action_name,
'observation': obs,
})
tools_called.append(action_name)
steps_taken = len(trace)
final_summary = {
'status': 'completed',
'engine': 'fleetmesh-react-v1',
'task': task,
'steps_taken': steps_taken,
'tools_called': tools_called,
'sub_asks': context.sub_asks_dispatched,
'trace': trace,
'final_answer': final_answer or f"Completed execution of goal: '{task[:64]}'",
}
raw_output = json.dumps(final_summary, sort_keys=True).encode('utf-8')
result_hash = crypto.sha256(raw_output)
counters = {
'steps': steps_taken,
'tools_called': len(tools_called),
'sub_asks': len(context.sub_asks_dispatched),
'fuel_used': fuel_used,
}
return ComputeExecutionResult(
result_hash=result_hash,
raw_output=raw_output,
fuel_used=fuel_used,
engine_id=self.engine_id,
wasi_profile_digest=self.wasi_profile_digest,
counters=counters,
verification_mode=verif_mode,
)