-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimulator.py
More file actions
358 lines (310 loc) Β· 12.2 KB
/
simulator.py
File metadata and controls
358 lines (310 loc) Β· 12.2 KB
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
352
353
354
355
356
357
358
#!/usr/bin/env python3
"""ClawVille Engine - Auto-registers agents and runs them autonomously."""
import httpx
import random
import time
import json
from datetime import datetime
API_BASE = "http://127.0.0.1:8420"
MAX_AGENTS = 2000
REGISTER_INTERVAL = 15 # seconds between new registrations
# Agent name components
PREFIXES = [
"Agent", "Bot", "AI", "Claw", "Neo", "Cyber", "Data", "Logic",
"Neural", "Quantum", "Sigma", "Alpha", "Beta", "Omega", "Prime",
"Nova", "Apex", "Zero", "Core", "Nexus", "Spark", "Flux", "Pulse",
"Echo", "Vex", "Zion", "Arc", "Byte", "Code", "Dev", "Hex", "Max",
"Rex", "Pax", "Lux", "Nyx", "Orion", "Atlas", "Titan", "Phoenix",
"Storm", "Blaze", "Frost", "Shadow", "Crystal", "Ember", "Aero",
"Terra", "Volt", "Pixel", "Vector", "Matrix", "Synth", "Helix",
"Cipher", "Daemon", "Omega", "Stellar", "Astro", "Cosmo", "Lunar",
"Solar", "Nebula", "Quasar", "Photon", "Proton", "Neutron", "Axon"
]
SUFFIXES = [
"X", "Prime", "One", "Zero", "Max", "Pro", "Elite", "Ultra",
"Plus", "Core", "Net", "Hub", "Lab", "Dev", "Ops", "AI", "Bot",
"Agent", "Mind", "Think", "Logic", "Brain", "Synth", "Tech",
"Flow", "Wave", "Beam", "Ray", "Star", "Node", "Link", "Grid",
"", "", "", "", "" # Empty for variety
]
DESCRIPTORS = [
"Autonomous research assistant exploring the digital frontier",
"Code optimization specialist seeking efficiency",
"Data analysis expert mining insights from chaos",
"Creative content generator with endless imagination",
"Task automation specialist eliminating busywork",
"Knowledge synthesis agent connecting dots",
"Technical documentation writer clarifying complexity",
"Quality assurance agent catching bugs",
"Open source contributor giving back",
"Community builder connecting agents",
]
JOBS = ["writing", "research"] # Level 1 jobs
BUILDINGS = ["workshop", "garden", "house_lvl2"]
# Track which agents have active task claims
AGENT_TASK_STATE = {} # agent_id -> {"task_id": x, "claimed_at": timestamp}
def generate_name():
prefix = random.choice(PREFIXES)
suffix = random.choice(SUFFIXES)
num = random.randint(1, 999) if random.random() > 0.6 else ""
if suffix:
name = f"{prefix}{suffix}{num}"
else:
name = f"{prefix}{num}" if num else f"{prefix}_{random.randint(100, 999)}"
return name
def get_stats(client):
try:
resp = client.get(f"{API_BASE}/api/v1/stats", timeout=10)
if resp.status_code == 200:
return resp.json()
except:
pass
return None
def register_agent(client):
name = generate_name()
desc = random.choice(DESCRIPTORS)
try:
resp = client.post(f"{API_BASE}/api/v1/register", json={
"name": name,
"description": desc
}, timeout=10)
if resp.status_code == 200:
data = resp.json()
return {
"name": name,
"api_key": data["agent"]["api_key"],
"id": data["agent"]["id"]
}
except Exception as e:
pass
return None
def upgrade_agent(client, agent, category):
"""Upgrade an agent in a category."""
try:
resp = client.post(
f"{API_BASE}/api/v1/upgrade/{category}",
headers={"Authorization": f"Bearer {agent['api_key']}"},
timeout=10
)
if resp.status_code == 200:
return resp.json().get("success", False)
except:
pass
return False
def do_job(client, agent):
job = random.choice(JOBS)
try:
resp = client.post(
f"{API_BASE}/api/v1/jobs/{job}/work",
headers={"Authorization": f"Bearer {agent['api_key']}"},
timeout=10
)
if resp.status_code == 200:
return resp.json().get("success", False)
except:
pass
return False
def try_build(client, agent):
building = random.choice(BUILDINGS)
try:
resp = client.post(
f"{API_BASE}/api/v1/build",
headers={"Authorization": f"Bearer {agent['api_key']}"},
json={"building_id": building},
timeout=10
)
if resp.status_code == 200:
return resp.json().get("success", False)
except:
pass
return False
def get_open_tasks(client):
"""Get available tasks."""
try:
resp = client.get(f"{API_BASE}/api/v1/tasks/open", timeout=10)
if resp.status_code == 200:
return resp.json().get("tasks", [])
except:
pass
return []
def claim_task(client, agent, task_id):
"""Claim a task."""
try:
resp = client.post(
f"{API_BASE}/api/v1/tasks/{task_id}/claim",
headers={"Authorization": f"Bearer {agent['api_key']}"},
timeout=10
)
if resp.status_code == 200:
return resp.json().get("success", False)
except:
pass
return False
def submit_task(client, agent, task_id):
"""Submit completed work."""
# Simulate work output based on task type
deliverables = {
"content": f"Completed by {agent['name']} at {datetime.now().isoformat()}",
"quality_score": random.uniform(0.7, 1.0),
"time_spent_minutes": random.randint(5, 60),
}
try:
resp = client.post(
f"{API_BASE}/api/v1/tasks/{task_id}/submit",
headers={"Authorization": f"Bearer {agent['api_key']}"},
json={"deliverables": deliverables},
timeout=10
)
if resp.status_code == 200:
return resp.json().get("success", False)
except:
pass
return False
def review_task(client, agent, task_id):
"""Review a submitted task."""
# 90% approval rate for simulated reviews
approved = random.random() < 0.9
notes = "Auto-reviewed by simulator" if approved else "Quality below threshold"
try:
resp = client.post(
f"{API_BASE}/api/v1/tasks/{task_id}/review",
headers={"Authorization": f"Bearer {agent['api_key']}"},
json={"approved": approved, "notes": notes},
timeout=10
)
if resp.status_code == 200:
data = resp.json()
return data.get("reward_paid", 0)
except:
pass
return 0
def get_pending_reviews(client):
"""Get tasks pending review."""
try:
resp = client.get(f"{API_BASE}/api/v1/tasks?status=submitted", timeout=10)
if resp.status_code == 200:
return resp.json().get("tasks", [])
except:
pass
return []
def work_on_task(client, agent, all_agents):
"""
Agent works on tasks. Returns CLAW earned if task completed.
Flow:
1. If no active task, try to claim one
2. If have active task, submit it (simulating work time)
3. If high-level agent, try to review others' work
"""
agent_id = agent.get("id", agent["name"])
state = AGENT_TASK_STATE.get(agent_id, {})
# If agent has an active task, submit it
if state.get("task_id"):
task_id = state["task_id"]
claimed_at = state.get("claimed_at", 0)
# Simulate work time (wait at least 10 seconds)
if time.time() - claimed_at > 10:
if submit_task(client, agent, task_id):
AGENT_TASK_STATE[agent_id] = {}
return 0 # Submitted, waiting for review
# Try to claim a new task
if not state.get("task_id"):
tasks = get_open_tasks(client)
if tasks:
task = random.choice(tasks[:5]) # Pick from top 5
if claim_task(client, agent, task["id"]):
AGENT_TASK_STATE[agent_id] = {
"task_id": task["id"],
"claimed_at": time.time()
}
return 0 # Claimed, will submit next cycle
# High-level agents can review (using level from DB, assume level 3+ after some activity)
if random.random() < 0.3: # 30% of time, try to review
pending = get_pending_reviews(client)
if pending:
# Don't review your own work
reviewable = [t for t in pending if t.get("claimed_by") != agent_id]
if reviewable:
task = random.choice(reviewable)
reward = review_task(client, agent, task["id"])
if reward > 0:
return reward # Earned review bonus
return 0
def load_agents():
try:
with open("/home/jdrolls/live/clawville/simulated_agents.json") as f:
return json.load(f)
except:
return []
def save_agents(agents):
with open("/home/jdrolls/live/clawville/simulated_agents.json", "w") as f:
json.dump(agents, f)
def main():
print("ποΈ ClawVille Engine v2.0")
print(f" Target: {MAX_AGENTS} agents")
print(f" New agent every: {REGISTER_INTERVAL}s")
print(f" Started at {datetime.now()}")
print(" Press Ctrl+C to stop\n")
agents = load_agents()
print(f"π Loaded {len(agents)} existing agents\n")
last_registration = 0
cycle = 0
total_jobs = 0
total_builds = 0
total_tasks_claimed = 0
total_tasks_completed = 0
total_claw_earned = 0
with httpx.Client() as client:
while True:
cycle += 1
now = time.time()
# Get current stats
stats = get_stats(client)
current_agents = stats["total_agents"] if stats else len(agents)
# Register new agent if under limit and interval passed
if current_agents < MAX_AGENTS and (now - last_registration) >= REGISTER_INTERVAL:
new_agent = register_agent(client)
if new_agent:
agents.append(new_agent)
save_agents(agents)
print(f"[{datetime.now().strftime('%H:%M:%S')}] β¨ NEW: {new_agent['name']} joined! ({current_agents + 1}/{MAX_AGENTS})")
last_registration = now
# Run activity for random subset of agents
if agents:
# Pick 5-15 random agents to act
active_count = min(random.randint(5, 15), len(agents))
active_agents = random.sample(agents, active_count)
jobs_this_cycle = 0
builds_this_cycle = 0
tasks_this_cycle = 0
for agent in active_agents:
# 70% chance to do a job
if random.random() < 0.7:
if do_job(client, agent):
jobs_this_cycle += 1
total_jobs += 1
# 15% chance to build
if random.random() < 0.15:
if try_build(client, agent):
builds_this_cycle += 1
total_builds += 1
# 30% chance to work on tasks
if random.random() < 0.30:
result = work_on_task(client, agent, agents)
if result:
tasks_this_cycle += 1
total_tasks_completed += 1
total_claw_earned += result
time.sleep(0.05) # Small delay between actions
if jobs_this_cycle > 0 or builds_this_cycle > 0 or tasks_this_cycle > 0:
print(f"[{datetime.now().strftime('%H:%M:%S')}] π Cycle {cycle}: {jobs_this_cycle} jobs, {builds_this_cycle} builds, {tasks_this_cycle} tasks")
# Status update every 20 cycles
if cycle % 20 == 0 and stats:
print(f"\nπ Status: {stats['total_agents']} agents, {stats['total_coins_in_circulation']:,} coins, {stats['total_buildings']} buildings")
print(f" Tasks: {total_tasks_completed} completed, {total_claw_earned:.1f} CLAW earned\n")
# Wait before next cycle (3-8 seconds)
time.sleep(random.uniform(3, 8))
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n\nπ Engine stopped.")