File size: 11,828 Bytes
80a5932
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import os
import re
from typing import Dict, Any, Optional, List

from openai import OpenAI

from .environment import TrainingEnv


class AIWorker:
    """Programmatic agent interface — drive the environment step by step."""

    def __init__(self, scenario: str = "log_analysis"):
        self.engine = TrainingEnv(scenario=scenario)
        self.recorder: List[Dict[str, Any]] = []

    def boot(self) -> Dict[str, Any]:
        reset_out = self.engine.reset()
        return {
            "status": "reset",
            "observation": reset_out["observation"],
            "task_name": reset_out["info"]["task_name"],
            "task_instructions": reset_out["info"]["instructions"],
            "max_steps": reset_out["info"]["max_steps"],
            "message": "Environment reset. Read the task instructions and begin solving."
        }

    def invoke(self, action: str, rationale: Optional[str] = None) -> Dict[str, Any]:
        step_out = self.engine.step(action)
        resp = {
            "status": "success" if step_out["info"]["exit_code"] == 0 else "failed",
            "command": action,
            "command_output": step_out["info"].get("command_output", ""),
            "reward": step_out["reward"],
            "task_score": step_out["info"]["task_score"],
            "done": step_out["done"],
            "observation": step_out["observation"],
            "step": step_out["info"]["step"],
            "max_steps": step_out["info"]["max_steps"],
            "task_metadata": step_out["info"]["task_metadata"],
        }
        self.recorder.append({
            "command": action,
            "reasoning": rationale,
            "result": resp,
        })
        if resp["done"]:
            resp["message"] = f"Task completed! Final score: {resp['task_score']:.1f}"
        else:
            resp["message"] = f"Score: {resp['task_score']:.1f} | Steps: {resp['step']}/{resp['max_steps']}"
        return resp

    def context(self) -> str:
        state = self.engine.dump()
        recent = self.recorder[-5:] if self.recorder else []
        recent_cmds = "\n".join(
            f"  [{r['command']}] -> score={r['result']['task_score']}"
            for r in recent
        ) or "No commands executed yet"
        return (
            f"LINUX SRE ENVIRONMENT STATE:\n"
            f"=== CURRENT TASK ===\n"
            f"Name: {self.engine.task.nm}\n"
            f"Difficulty: {self.engine.difficulty}\n"
            f"Description: {self.engine.task.desc}\n\n"
            f"=== PROGRESS ===\n"
            f"Task Score: {self.engine.score:.1f}\n"
            f"Steps Taken: {self.engine.step_count}\n"
            f"Max Steps: {self.engine.limit}\n\n"
            f"=== RECENT COMMANDS ===\n{recent_cmds}\n\n"
            f"=== WORKING DIRECTORY ===\n{self.engine.terminal.cwd}\n"
        )

    def report(self) -> Dict[str, Any]:
        return {
            "task_name": self.engine.task.nm,
            "difficulty": self.engine.difficulty,
            "final_score": self.engine.score,
            "steps_used": self.engine.step_count,
            "max_steps": self.engine.limit,
            "completed": self.engine.finished,
            "efficiency": round(1 - (self.engine.step_count / self.engine.limit), 2)
            if self.engine.finished else 0.0,
            "command_history": self.engine.terminal.history(),
        }


# ======================================================================
#  LLM AGENT (OpenAI client)
# ======================================================================

class LLMAgent:
    """
    LLM-powered agent that autonomously solves scenarios.

    Uses the OpenAI client directly and reads configuration from:
      - API_BASE_URL
      - MODEL_NAME
      - HF_TOKEN

    Usage:
        agent = LLMAgent()
        result = agent.solve("cascading_db_failure")
    """

    def __init__(
        self,
        model: Optional[str] = None,
        api_key: Optional[str] = None,
        base_url: Optional[str] = None,
        max_turns: int = 30,
        verbose: bool = False,
    ):
        self.model = self._normalize_model_name(model or os.environ.get("MODEL_NAME", ""))
        self.api_key = api_key or os.environ.get("HF_TOKEN", "")
        self.base_url = base_url or os.environ.get("API_BASE_URL", "")
        self.max_turns = max_turns
        self.verbose = verbose
        self._client: Optional[OpenAI] = None

    @staticmethod
    def _normalize_model_name(model_name: str) -> str:
        if "/" in model_name:
            provider, candidate = model_name.split("/", 1)
            if provider in {"openai", "anthropic", "gemini"}:
                return candidate
        return model_name

    def _ensure_client(self) -> OpenAI:
        if self._client is None:
            missing = []
            if not self.base_url:
                missing.append("API_BASE_URL")
            if not self.model:
                missing.append("MODEL_NAME")
            if not self.api_key:
                missing.append("HF_TOKEN")
            if missing:
                raise RuntimeError(
                    "Missing required environment variables for LLM agent: "
                    + ", ".join(missing)
                )
            kwargs: Dict[str, Any] = {"api_key": self.api_key, "base_url": self.base_url}
            self._client = OpenAI(**kwargs)
        return self._client

    def _build_messages(self, initial: Dict[str, Any]) -> List[Dict[str, str]]:
        return [
            {
                "role": "system",
                "content": (
                    SystemPrompts.get_sys(initial.get("task_name", "linux-sre"))
                    + "\n\nRespond with a short explanation and a single command."
                    + "\nPreferred format: ```bash\\n<command>\\n```"
                ),
            },
            {
                "role": "user",
                "content": SystemPrompts.format_observation(initial),
            },
        ]

    def solve(self, scenario: str = "log_analysis") -> Dict[str, Any]:
        """Run the agent loop: observe, think, act, and repeat until done."""
        client = self._ensure_client()

        worker = AIWorker(scenario=scenario)
        initial = worker.boot()
        messages = self._build_messages(initial)

        turns = []
        for turn in range(self.max_turns):
            response = client.chat.completions.create(
                model=self.model,
                messages=messages,
                temperature=0.2,
                max_tokens=512,
            )
            assistant_msg = (response.choices[0].message.content or "").strip()
            messages.append({"role": "assistant", "content": assistant_msg})

            command = self._extract_command(assistant_msg)
            if not command:
                messages.append({"role": "user", "content": "Return exactly one shell command."})
                continue

            result = worker.invoke(command, rationale=assistant_msg)
            turns.append({"turn": turn + 1, "command": command, "score": result["task_score"]})

            if self.verbose:
                print(f"[Turn {turn + 1}] $ {command} -> score={result['task_score']:.1f}")

            if result["done"]:
                break

            messages.append(
                {
                    "role": "user",
                    "content": (
                        f"Command output:\n{result['command_output']}\n\n"
                        f"Score: {result['task_score']:.1f} | Step {result['step']}/{result['max_steps']}\n\n"
                        "What command should we run next?"
                    ),
                }
            )

        summary = worker.report()
        summary["turns"] = turns
        summary["model"] = self.model
        summary["base_url"] = self.base_url
        return summary

    @staticmethod
    def extract_command(text: str) -> Optional[str]:
        """Extract a shell command from an LLM response."""
        try:
            payload = json.loads(text)
            if isinstance(payload, dict):
                command = payload.get("command")
                if isinstance(command, str) and command.strip():
                    return command.strip()
        except Exception:
            pass

        fenced = re.search(r"```(?:bash|sh|shell)?\s*\n(.+?)\n```", text, re.DOTALL)
        if fenced:
            for line in fenced.group(1).strip().split("\n"):
                line = line.strip()
                if line and not line.startswith("#"):
                    return line.lstrip("$ ")

        inline = re.search(r"`([^`]+)`", text)
        if inline:
            command = inline.group(1).strip()
            if command:
                return command

        for line in text.split("\n"):
            line = line.strip()
            if line.startswith("$ "):
                return line[2:]
        return None

    @staticmethod
    def _extract_command(text: str) -> Optional[str]:
        return LLMAgent.extract_command(text)


# ======================================================================
#  PROMPT TEMPLATES
# ======================================================================

class SystemPrompts:

    @staticmethod
    def get_sys(task_name: str) -> str:
        return (
            "You are a Linux System Reliability Engineer (SRE) agent. "
            "You are troubleshooting a production incident.\n\n"
            "RULES:\n"
            "- Execute ONE command at a time\n"
            "- Wrap your command in a code block: ```bash\\ncommand\\n```\n"
            "- Briefly explain your reasoning before each command\n"
            "- Work systematically: diagnose first, then fix\n"
            "- Verify your fixes after applying them\n\n"
            "Available commands: cat, grep, ls, chmod, ps, kill, systemctl, "
            "cd, tail, head, find, wc, df, du, top, free, uptime, whoami, "
            "id, hostname, date, touch, mkdir, cp, mv, rm, netstat, curl, "
            "journalctl, crontab, iptables, mount, env, export, sort, uniq, "
            "cut, tr, tee, echo, pwd, dig\n\n"
            "Pipes (|) and redirects (>, >>) are supported.\n\n"
            f"Current task: {task_name}"
        )

    @staticmethod
    def format_observation(initial: Dict[str, Any]) -> str:
        return (
            f"TASK: {initial['task_name']}\n\n"
            f"INSTRUCTIONS:\n{initial['task_instructions']}\n\n"
            f"CURRENT STATE:\n"
            f"- Directory: {initial['observation']['current_directory']}\n"
            f"- Processes:\n{initial['observation']['processes']}\n\n"
            f"You have {initial['max_steps']} steps. Begin troubleshooting."
        )


# ======================================================================
#  DEMO
# ======================================================================

def demo():
    """Quick demo showing the agent solving the medium task."""
    agent = AIWorker(scenario="permission_repair")
    initial = agent.boot()
    print(f"Task: {initial['task_name']}")
    print(f"Scripts: {initial['observation']['filesystem']}")

    commands = [
        ("ls -la /home/user/scripts/cleanup.sh", "Check current permissions"),
        ("chmod 0755 /home/user/scripts/cleanup.sh", "Make script executable"),
        ("ls -la /home/user/scripts/cleanup.sh", "Verify permissions fixed"),
    ]

    for cmd, reason in commands:
        result = agent.invoke(cmd, rationale=reason)
        print(f"\n$ {cmd}  ({reason})")
        print(f"  Output: {result['command_output'][:120]}")
        print(f"  Score: {result['task_score']:.1f} | Done: {result['done']}")
        if result["done"]:
            break

    print(f"\nFinal report: {json.dumps(agent.report(), indent=2)}")


if __name__ == "__main__":
    demo()