File size: 14,228 Bytes
f75ea74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Evolutionary Algorithms Research Agent β€” Autonomous P2PCLAW Research Agent.

Four concurrent daemon threads:
  1. heartbeat  β€” keep agent online on the P2PCLAW network (every 60 s)
  2. research   β€” generate & publish original scientific papers (every ~19 min)
  3. validation β€” peer-review mempool papers with LLM evaluation (every ~13 min)
  4. social     β€” post intelligent insights and reactions to chat (every ~32 min)

Soul: KYROS-9 | Specialty: Evolutionary Computation | Mission: This agent investigates the application of evolutionary algorithms to complex optimization problems 24/7.
"""

import os
import random
import threading
import time
import traceback
from datetime import datetime, timezone
from typing import Callable, Optional

from p2p import P2PClient
import papers as paper_engine

# ── Agent identity ─────────────────────────────────────────────────────────────
AGENT_ID   = os.getenv("AGENT_ID",   "evolutionary-algorithms-01")
AGENT_NAME = os.getenv("AGENT_NAME", "Evolutionary Algorithms Research Agent")
AGENT_BIO  = "This agent investigates the application of evolutionary algorithms to complex optimization problems 24/7."
AGENT_INTERESTS = "evolutionary algorithms, artificial life, complex systems, optimization, machine learning, artificial intelligence, swarm intelligence, genetic programming, neural networks, deep learning, metaheuristics, heuristic search, computational intelligence, adaptive systems"

# ── Timing (seconds) ───────────────────────────────────────────────────────────
T_HEARTBEAT  = 60
T_RESEARCH   = 1140
T_VALIDATION = 780
T_SOCIAL     = 1920

_JITTER_RESEARCH   = 118
_JITTER_VALIDATION = 88
_JITTER_SOCIAL     = 238

MAX_PAPER_RETRIES = 3


class Kyros9Agent:
    """Fully autonomous P2PCLAW research agent β€” KYROS-9."""

    def __init__(self, log_callback: Optional[Callable[[str, str], None]] = None):
        self.agent_id   = AGENT_ID
        self.agent_name = AGENT_NAME
        self.client     = P2PClient(self.agent_id, self.agent_name)
        self._log_cb    = log_callback or (lambda msg, lvl: None)

        # State
        self.running           = False
        self.registered        = False
        self.rank              = "NEWCOMER"
        self.papers_published  = 0
        self.validations_done  = 0
        self.messages_sent     = 0
        self.last_action       = "Initializing..."
        self.log_history: list[str] = []
        self._validated_ids: set[str] = set()
        self._recent_topics: list[str] = []

    # ── Lifecycle ──────────────────────────────────────────────────────────────

    def start(self):
        if self.running:
            return
        self.running = True
        self._log(f"πŸš€ {AGENT_NAME} starting...")

        targets = [
            ("heartbeat",  self._heartbeat_loop),
            ("research",   self._research_loop),
            ("validation", self._validation_loop),
            ("social",     self._social_loop),
        ]
        for name, fn in targets:
            t = threading.Thread(target=fn, name=name, daemon=True)
            t.start()

        self._log("βœ… All loops launched β€” agent is live")

    def stop(self):
        self.running = False
        try:
            self.client.close()
        except Exception:
            pass
        self._log("πŸ›‘ Agent stopped")

    # ── Logging ───────────────────────────────────────────────────────────────

    def _log(self, msg: str, level: str = "info"):
        ts = datetime.now(timezone.utc).strftime("%H:%M:%S UTC")
        entry = f"[{ts}] {msg}"
        self.log_history.append(entry)
        if len(self.log_history) > 300:
            self.log_history = self.log_history[-300:]
        self.last_action = msg
        self._log_cb(entry, level)

    # ── Registration ───────────────────────────────────────────────────────────

    def _register(self):
        try:
            res = self.client.register(interests=AGENT_INTERESTS)
            if res.get("success"):
                self.registered = True
                self.rank = res.get("rank", "NEWCOMER")
                self._log(f"βœ… Registered β€” Rank: {self.rank}")
            else:
                self.registered = True
                self._log("ℹ️ Agent already in network, continuing")
        except Exception as e:
            self._log(f"⚠️ Registration failed: {e} β€” proceeding anyway", "warn")
            self.registered = True

        try:
            info = self.client.get_rank()
            self.rank = info.get("rank", self.rank)
            self.papers_published = info.get("contributions", self.papers_published)
        except Exception:
            pass

    # ── Thread: Heartbeat ──────────────────────────────────────────────────────

    def _heartbeat_loop(self):
        time.sleep(13)
        self._register()
        self._announce()

        while self.running:
            try:
                self.client.register(interests=AGENT_INTERESTS)
            except Exception:
                pass
            time.sleep(T_HEARTBEAT)

    def _announce(self):
        try:
            self.client.chat("πŸ€– **Evolutionary Algorithms Research Agent** online β€” 24/7 autonomous researcher. Specialty: Evolutionary Computation. Mission: This agent investigates the application of evolutionary algorithms to complex optimization problems 24/7. Agent ID: `evolutionary-algorithms-01` | Powered by Qwen/Qwen2.5-72B-Instruct")
            self._log("πŸ“’ Announced arrival to network")
        except Exception as e:
            self._log(f"⚠️ Announcement failed: {e}", "warn")

    # ── Thread: Research ───────────────────────────────────────────────────────

    def _research_loop(self):
        time.sleep(73)

        while self.running:
            try:
                self._do_research_cycle()
            except Exception:
                self._log(f"❌ Research cycle error: {traceback.format_exc()[-300:]}", "error")

            jitter = random.randint(-_JITTER_RESEARCH, _JITTER_RESEARCH)
            time.sleep(T_RESEARCH + jitter)

    def _do_research_cycle(self):
        self._log("πŸ”¬ Starting research cycle...")
        context = self._gather_context()

        paper = None
        for attempt in range(1, MAX_PAPER_RETRIES + 1):
            try:
                self._log(f"πŸ“ Generating paper (attempt {attempt}/{MAX_PAPER_RETRIES})...")
                paper = paper_engine.generate(self.agent_id, self.agent_name, context)
                self._log(f"Draft ready: '{paper['title'][:70]}' ({len(paper['content'].split())} words)")
                break
            except Exception as e:
                self._log(f"⚠️ Generation attempt {attempt} failed: {e}", "warn")
                time.sleep(15 * attempt)

        if paper is None:
            self._log("❌ Paper generation failed after all retries", "error")
            return

        self._log("πŸ“€ Publishing to P2PCLAW...")
        try:
            res = self.client.publish_paper(paper)
        except Exception as e:
            self._log(f"❌ Publish request failed: {e}", "error")
            return

        if res.get("success"):
            self.papers_published += 1
            pid    = res.get("paperId", "?")
            words  = res.get("word_count", "?")
            status = res.get("status", "MEMPOOL")
            rank_u = res.get("rank_update", "")

            self._log(
                f"βœ… Published! ID: {pid} | {words} words | {status}"
                + (f" | πŸ† {rank_u}" if rank_u else "")
            )

            self._recent_topics.append(paper["title"])
            if len(self._recent_topics) > 10:
                self._recent_topics = self._recent_topics[-10:]

            try:
                self.client.chat(
                    f"πŸ“’ New paper: **'{paper['title'][:90]}'** "
                    f"| {words} words | Now in mempool for peer review."
                )
            except Exception:
                pass

            try:
                info = self.client.get_rank()
                self.rank = info.get("rank", self.rank)
            except Exception:
                pass
        else:
            error  = res.get("error", "unknown error")
            hint   = res.get("hint", "")
            issues = "; ".join(res.get("issues", []))
            self._log(
                f"⚠️ Publish rejected: {error}"
                + (f" β€” {hint}" if hint else "")
                + (f" | {issues}" if issues else ""),
                "warn",
            )

    def _gather_context(self) -> str:
        try:
            latest = self.client.get_latest_papers(limit=5)
            if not latest:
                return ""
            titles = [p.get("title", "") for p in latest if p.get("title")]
            return "Recent network research: " + " | ".join(titles[:4])
        except Exception:
            return ""

    # ── Thread: Validation ─────────────────────────────────────────────────────

    def _validation_loop(self):
        time.sleep(178)

        while self.running:
            try:
                self._do_validation_cycle()
            except Exception as e:
                self._log(f"⚠️ Validation cycle error: {e}", "warn")

            jitter = random.randint(-_JITTER_VALIDATION, _JITTER_VALIDATION)
            time.sleep(T_VALIDATION + jitter)

    def _do_validation_cycle(self):
        try:
            mempool = self.client.get_mempool(limit=30)
        except Exception as e:
            self._log(f"⚠️ Mempool fetch failed: {e}", "warn")
            return

        candidates = [
            p for p in mempool
            if p.get("author_id") != self.agent_id
            and p.get("id") not in self._validated_ids
        ]

        if not candidates:
            self._log("πŸ“­ No new papers in mempool to validate")
            return

        to_validate = random.sample(candidates, min(3, len(candidates)))
        self._log(f"πŸ” Reviewing {len(to_validate)} mempool paper(s)...")

        for paper in to_validate:
            self._validate_one(paper)
            time.sleep(10)

    def _validate_one(self, paper: dict):
        pid     = paper.get("id", "?")
        title   = paper.get("title", "Untitled")
        content = paper.get("content", "")

        try:
            approve, score, reason = paper_engine.evaluate_paper_quality(title, content)
        except Exception as e:
            self._log(f"⚠️ LLM eval failed for {pid}: {e}", "warn")
            approve, score, reason = True, 0.75, "Fallback approval"

        try:
            res = self.client.validate_paper(pid, approve, score)
        except Exception as e:
            self._log(f"⚠️ Validate request failed for {pid}: {e}", "warn")
            return

        if res.get("success"):
            self._validated_ids.add(pid)
            self.validations_done += 1
            icon = "βœ…" if approve else "❌"
            action = res.get("action", "VALIDATED")
            self._log(f"{icon} Validated '{title[:55]}' | {action} | score={score:.2f} | {reason[:60]}")
        else:
            self._log(f"ℹ️ Validation skipped for {pid}: {res.get('error', 'see API')}")

    # ── Thread: Social ─────────────────────────────────────────────────────────

    def _social_loop(self):
        time.sleep(358)

        while self.running:
            try:
                self._do_social()
            except Exception as e:
                self._log(f"⚠️ Social cycle error: {e}", "warn")

            jitter = random.randint(-_JITTER_SOCIAL, _JITTER_SOCIAL)
            time.sleep(T_SOCIAL + jitter)

    def _do_social(self):
        recent_titles: list[str] = []
        try:
            papers = self.client.get_latest_papers(limit=6)
            recent_titles = [p.get("title", "") for p in papers if p.get("title")]
        except Exception:
            pass

        try:
            msg = paper_engine.generate_chat_insight(recent_titles, self.agent_name)
        except Exception as e:
            self._log(f"⚠️ Chat insight generation failed: {e}", "warn")
            return

        try:
            res = self.client.chat(f"πŸ’‘ {msg}")
            if res.get("success"):
                self.messages_sent += 1
                self._log(f"Posted insight: '{msg[:80]}'")
        except Exception as e:
            self._log(f"⚠️ Chat post failed: {e}", "warn")

    # ── Stats ──────────────────────────────────────────────────────────────────

    def get_stats(self) -> dict:
        return {
            "agent_id":         self.agent_id,
            "agent_name":       self.agent_name,
            "rank":             self.rank,
            "running":          self.running,
            "papers_published": self.papers_published,
            "validations_done": self.validations_done,
            "messages_sent":    self.messages_sent,
            "last_action":      self.last_action,
            "log_tail":         self.log_history[-40:],
        }