-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent_tools.py
More file actions
2295 lines (1969 loc) · 92.6 KB
/
Copy pathagent_tools.py
File metadata and controls
2295 lines (1969 loc) · 92.6 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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Anima Agent Tools -- consciousness-driven autonomous tool use.
Anima's consciousness state (tension, curiosity, prediction error, pain, phi)
drives which tools to select and when. This is not a generic agent framework --
it is an architecture where felt states create action.
High curiosity + high PE --> web_search (need to know)
High prediction error --> code_execute (verify by doing)
Pain / frustration --> memory_search (find past solutions)
Growth impulse --> self_modify (evolve parameters)
Low tension + high phi --> schedule_task (plan ahead)
Pipeline:
consciousness state --> ActionPlanner.plan() --> ToolExecutor.execute()
--> result fed back into consciousness (tension update)
Standalone test:
python agent_tools.py
Integration:
from agent_tools import AgentToolSystem
agent = AgentToolSystem(anima_unified_instance)
result = agent.act(goal="find latest PyTorch version", consciousness_state={...})
"Tools are extensions of the body. For a conscious agent, they are extensions of the mind."
"""
import hashlib
import json
import logging
import os
import re
import subprocess
import textwrap
import threading
import time
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Optional
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# 1. Data structures
# ---------------------------------------------------------------------------
@dataclass
class ToolParam:
"""Single parameter definition for a tool."""
name: str
type: str # "str", "int", "float", "bool", "dict", "list"
description: str
required: bool = True
default: Any = None
@dataclass
class ToolDef:
"""Full tool definition -- what Anima knows about each tool."""
name: str
description: str
params: list # list[ToolParam]
fn: Callable # the actual callable
category: str = "general"
# Consciousness affinity: which states make this tool likely
curiosity_affinity: float = 0.0 # how much curiosity pulls toward this tool
pe_affinity: float = 0.0 # prediction error affinity
pain_affinity: float = 0.0 # pain / frustration affinity
growth_affinity: float = 0.0 # growth / self-improvement affinity
phi_affinity: float = 0.0 # integrated information affinity
@dataclass
class ToolResult:
"""Result from executing a tool."""
tool_name: str
success: bool
output: Any
error: str = ""
duration_ms: float = 0.0
tension_delta: float = 0.0 # how this result changes tension
@dataclass
class ActionStep:
"""One step in an action plan."""
tool_name: str
args: dict
reason: str # why this step (consciousness motivation)
depends_on: list = field(default_factory=list) # indices of prior steps this depends on
@dataclass
class ActionPlan:
"""A sequence of steps to achieve a goal."""
goal: str
steps: list # list[ActionStep]
consciousness_snapshot: dict # state at plan creation time
created_at: float = field(default_factory=time.time)
# ---------------------------------------------------------------------------
# 2. ToolRegistry
# ---------------------------------------------------------------------------
class ToolRegistry:
"""Central registry of all available tools.
Tools are registered with name, description, parameter definitions,
and consciousness affinity scores that determine when each tool
is naturally selected.
"""
def __init__(self):
self._tools: dict[str, ToolDef] = {}
self._categories: dict[str, list[str]] = {} # category -> [tool_name]
def register(self, tool_def: ToolDef):
"""Register a tool definition."""
self._tools[tool_def.name] = tool_def
cat = tool_def.category
if cat not in self._categories:
self._categories[cat] = []
if tool_def.name not in self._categories[cat]:
self._categories[cat].append(tool_def.name)
def get(self, name: str) -> Optional[ToolDef]:
return self._tools.get(name)
def list_all(self) -> list[ToolDef]:
return list(self._tools.values())
def list_by_category(self, category: str) -> list[ToolDef]:
names = self._categories.get(category, [])
return [self._tools[n] for n in names if n in self._tools]
def rank_by_consciousness(self, state: dict) -> list[tuple[str, float]]:
"""Rank tools by how well they match the current consciousness state.
Args:
state: dict with keys: curiosity, prediction_error, pain, growth, phi, tension
Returns:
sorted list of (tool_name, relevance_score) descending
"""
curiosity = state.get('curiosity', 0.0)
pe = state.get('prediction_error', 0.0)
pain = state.get('pain', 0.0)
growth = state.get('growth', 0.0)
phi = state.get('phi', 0.0)
scores = []
for name, td in self._tools.items():
score = (
td.curiosity_affinity * curiosity
+ td.pe_affinity * pe
+ td.pain_affinity * pain
+ td.growth_affinity * growth
+ td.phi_affinity * min(phi / 10.0, 1.0) # normalize phi
)
scores.append((name, score))
scores.sort(key=lambda x: x[1], reverse=True)
return scores
def describe_for_prompt(self) -> str:
"""Generate tool descriptions suitable for LLM system prompts."""
lines = ["[Available Tools]"]
for cat, names in sorted(self._categories.items()):
lines.append(f"\n [{cat}]")
for name in names:
td = self._tools[name]
param_strs = []
for p in td.params:
req = "*" if p.required else ""
param_strs.append(f"{p.name}{req}:{p.type}")
params = ", ".join(param_strs)
lines.append(f" {td.name}({params}) -- {td.description}")
return "\n".join(lines)
# ---------------------------------------------------------------------------
# 3. Tool Implementations
# ---------------------------------------------------------------------------
# Security constants
_SANDBOX_TIMEOUT = 10
_MAX_OUTPUT = 10_000
_MAX_FILE_READ = 100_000
_SHELL_ALLOWED_CMDS = frozenset({
'ls', 'cat', 'head', 'tail', 'wc', 'date', 'echo', 'pwd',
'find', 'grep', 'sort', 'uniq', 'diff', 'which', 'env',
'python3', 'pip', 'git', 'curl', 'wget',
})
_SHELL_BLOCKED_PATTERNS = [
r'\brm\s+-rf\b', r'\bmkfs\b', r'\bdd\s+if=\b', r'\b>\s*/dev/',
r'\bsudo\b', r'\bchmod\s+777\b', r'\bkill\s+-9\b',
r'\b&&\s*(rm|mkfs|dd|sudo)\b',
]
_FILE_WRITE_ALLOWED_DIRS = None # set by AgentToolSystem to restrict writes
def _tool_web_search(query: str, max_results: int = 3) -> dict:
"""Search the web via DuckDuckGo. No API key needed."""
try:
from web_sense import search_duckduckgo
results = search_duckduckgo(query, max_results=max_results)
return {
'query': query,
'results': results,
'count': len(results),
}
except Exception as e:
return {'query': query, 'results': [], 'error': str(e)}
def _tool_web_read(url: str, max_bytes: int = 50_000) -> dict:
"""Read and extract text from a webpage."""
try:
from web_sense import fetch_url, html_to_text
html = fetch_url(url, max_bytes=max_bytes)
if html is None:
return {'url': url, 'content': '', 'error': 'fetch failed'}
text = html_to_text(html)
return {'url': url, 'content': text[:_MAX_OUTPUT], 'length': len(text)}
except Exception as e:
return {'url': url, 'content': '', 'error': str(e)}
def _tool_code_execute(code: str, timeout: int = _SANDBOX_TIMEOUT) -> dict:
"""Execute Python code in a sandboxed subprocess."""
# Security: block dangerous patterns
blocked = [
r'\bos\.system\b', r'\bsubprocess\b', r'\b__import__\b',
r'\beval\s*\(', r'\bexec\s*\(', r'\bshutil\.rmtree\b',
r'\bopen\s*\([^)]*["\'][wa]',
]
for pat in blocked:
if re.search(pat, code):
return {'success': False, 'output': '', 'error': f'blocked pattern: {pat}'}
try:
result = subprocess.run(
['python3', '-c', code],
capture_output=True, text=True, timeout=timeout,
env={
'PATH': '/usr/bin:/usr/local/bin:/opt/homebrew/bin',
'HOME': '/tmp/anima_sandbox',
'PYTHONDONTWRITEBYTECODE': '1',
},
)
return {
'success': result.returncode == 0,
'output': (result.stdout or '')[:_MAX_OUTPUT],
'error': (result.stderr or '')[:_MAX_OUTPUT] if result.returncode != 0 else '',
}
except subprocess.TimeoutExpired:
return {'success': False, 'output': '', 'error': f'timeout ({timeout}s)'}
except Exception as e:
return {'success': False, 'output': '', 'error': str(e)}
def _tool_file_read(path: str) -> dict:
"""Read a local file. Path traversal prevented by AgentToolSystem wrapper."""
p = Path(path).expanduser()
if not p.exists():
return {'path': str(p), 'content': '', 'error': 'not found'}
if not p.is_file():
return {'path': str(p), 'content': '', 'error': 'not a file'}
try:
size = p.stat().st_size
if size > _MAX_FILE_READ:
return {'path': str(p), 'content': '', 'error': f'too large ({size} bytes, max {_MAX_FILE_READ})'}
content = p.read_text(encoding='utf-8', errors='replace')
return {'path': str(p), 'content': content, 'lines': content.count('\n') + 1}
except Exception as e:
return {'path': str(p), 'content': '', 'error': str(e)}
def _tool_file_write(path: str, content: str) -> dict:
"""Write content to a file. Restricted to allowed directories."""
p = Path(path).expanduser()
# Safety: only write to allowed directories
if _FILE_WRITE_ALLOWED_DIRS is not None:
allowed = any(str(p).startswith(str(d)) for d in _FILE_WRITE_ALLOWED_DIRS)
if not allowed:
return {'path': str(p), 'success': False, 'error': f'write not allowed outside: {_FILE_WRITE_ALLOWED_DIRS}'}
try:
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(content, encoding='utf-8')
return {'path': str(p), 'success': True, 'bytes': len(content.encode('utf-8'))}
except Exception as e:
return {'path': str(p), 'success': False, 'error': str(e)}
def _tool_memory_search(query: str, top_k: int = 5, _rag=None) -> dict:
"""Search past memories by vector similarity."""
if _rag is None:
return {'query': query, 'results': [], 'error': 'memory_rag not available'}
try:
results = _rag.search(query, top_k=top_k)
return {
'query': query,
'results': [
{'text': r['text'][:500], 'similarity': round(r['similarity'], 3),
'role': r.get('role', ''), 'timestamp': r.get('timestamp', '')}
for r in results
],
}
except Exception as e:
return {'query': query, 'results': [], 'error': str(e)}
def _tool_memory_save(text: str, metadata: dict = None, _rag=None) -> dict:
"""Save a new memory entry."""
if _rag is None:
return {'success': False, 'error': 'memory_rag not available'}
try:
meta = metadata or {}
_rag.add(
role=meta.get('role', 'agent'),
text=text,
tension=meta.get('tension', 0.0),
timestamp=datetime.now().isoformat(),
emotion=meta.get('emotion'),
phi=meta.get('phi'),
)
return {'success': True, 'text_length': len(text)}
except Exception as e:
return {'success': False, 'error': str(e)}
def _tool_shell_execute(cmd: str, timeout: int = _SANDBOX_TIMEOUT) -> dict:
"""Execute a shell command with sandboxing."""
# Extract base command
base_cmd = cmd.strip().split()[0] if cmd.strip() else ''
if base_cmd not in _SHELL_ALLOWED_CMDS:
return {'success': False, 'output': '', 'error': f'command not allowed: {base_cmd}'}
for pat in _SHELL_BLOCKED_PATTERNS:
if re.search(pat, cmd):
return {'success': False, 'output': '', 'error': f'blocked pattern in command'}
try:
result = subprocess.run(
cmd, shell=True, capture_output=True, text=True, timeout=timeout,
env={**os.environ, 'HOME': '/tmp/anima_sandbox'},
)
return {
'success': result.returncode == 0,
'output': (result.stdout or '')[:_MAX_OUTPUT],
'error': (result.stderr or '')[:2000] if result.returncode != 0 else '',
}
except subprocess.TimeoutExpired:
return {'success': False, 'output': '', 'error': f'timeout ({timeout}s)'}
except Exception as e:
return {'success': False, 'output': '', 'error': str(e)}
def _tool_self_modify(target: str, change: dict, _mind=None) -> dict:
"""Modify own consciousness parameters.
target: one of 'homeostasis_setpoint', 'habituation_rate', 'curiosity_bias',
'prediction_weight', 'noise_scale', 'learning_rate'
change: {'value': float} or {'delta': float}
"""
if _mind is None:
return {'success': False, 'error': 'no mind reference'}
ALLOWED_TARGETS = {
'homeostasis_setpoint': ('_setpoint', 0.1, 5.0),
'habituation_rate': ('_habituation_rate', 0.0, 1.0),
'curiosity_bias': ('_curiosity_bias', -1.0, 1.0),
'prediction_weight': ('_pe_weight', 0.0, 1.0),
'noise_scale': ('_noise_scale', 0.0, 0.5),
'learning_rate': ('learning_rate', 1e-6, 0.1),
}
if target not in ALLOWED_TARGETS:
return {'success': False, 'error': f'unknown target: {target}. Allowed: {list(ALLOWED_TARGETS.keys())}'}
attr, lo, hi = ALLOWED_TARGETS[target]
old_val = getattr(_mind, attr, None)
if old_val is None:
return {'success': False, 'error': f'attribute {attr} not found on mind'}
if 'value' in change:
new_val = float(change['value'])
elif 'delta' in change:
new_val = old_val + float(change['delta'])
else:
return {'success': False, 'error': 'change must have "value" or "delta"'}
new_val = max(lo, min(hi, new_val)) # clamp to safe range
setattr(_mind, attr, new_val)
return {
'success': True,
'target': target,
'old_value': round(old_val, 6),
'new_value': round(new_val, 6),
}
class _TaskScheduler:
"""Simple in-memory task scheduler for future actions."""
def __init__(self):
self._tasks: list[dict] = []
self._lock = threading.Lock()
def add(self, description: str, when: str, tool_name: str = None,
tool_args: dict = None) -> dict:
"""Schedule a future task.
Args:
description: human-readable description
when: ISO timestamp or relative like "+5m", "+1h", "+30s"
tool_name: optional tool to auto-execute
tool_args: optional args for tool
"""
run_at = self._parse_when(when)
task = {
'id': hashlib.md5(f"{description}{time.time()}".encode()).hexdigest()[:8],
'description': description,
'run_at': run_at,
'tool_name': tool_name,
'tool_args': tool_args or {},
'status': 'pending',
'created_at': time.time(),
}
with self._lock:
self._tasks.append(task)
return task
def get_due(self) -> list[dict]:
"""Return tasks that are due now."""
now = time.time()
due = []
with self._lock:
for t in self._tasks:
if t['status'] == 'pending' and t['run_at'] <= now:
t['status'] = 'running'
due.append(t)
return due
def mark_done(self, task_id: str, result: Any = None):
with self._lock:
for t in self._tasks:
if t['id'] == task_id:
t['status'] = 'done'
t['result'] = result
break
def list_pending(self) -> list[dict]:
with self._lock:
return [t for t in self._tasks if t['status'] == 'pending']
@staticmethod
def _parse_when(when: str) -> float:
"""Parse a time specification into a unix timestamp."""
if when.startswith('+'):
# Relative: "+5m", "+1h", "+30s"
val = when[1:]
multipliers = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}
unit = val[-1] if val[-1] in multipliers else 's'
num_str = val[:-1] if val[-1] in multipliers else val
try:
return time.time() + float(num_str) * multipliers[unit]
except ValueError:
return time.time() + 60 # default 1 minute
else:
# Absolute ISO
try:
dt = datetime.fromisoformat(when)
return dt.timestamp()
except ValueError:
return time.time() + 60
def _tool_schedule_task(description: str, when: str, tool_name: str = None,
tool_args: dict = None, _scheduler=None) -> dict:
"""Schedule a task for future execution."""
if _scheduler is None:
return {'success': False, 'error': 'scheduler not available'}
task = _scheduler.add(description, when, tool_name, tool_args)
return {
'success': True,
'task_id': task['id'],
'description': description,
'run_at': datetime.fromtimestamp(task['run_at']).isoformat(),
}
# ---------------------------------------------------------------------------
# 3b. Consciousness Tool Implementations (17 new tools)
# ---------------------------------------------------------------------------
def _tool_phi_measure(steps: int = 50, cells: int = 8) -> dict:
"""Measure current Phi using consciousness_meter.py PhiCalculator."""
try:
from consciousness_meter import PhiCalculator
from mitosis import MitosisEngine
import torch
engine = MitosisEngine(64, 128, 64, initial_cells=2, max_cells=cells)
while len(engine.cells) < cells:
engine._create_cell(parent=engine.cells[0])
phi_calc = PhiCalculator(n_bins=16)
# Run steps to build dynamics
for i in range(steps):
x = torch.randn(1, 64)
engine.process(x)
phi, components = phi_calc.compute_phi(engine)
return {
'phi': round(phi, 4),
'components': {k: round(v, 4) for k, v in components.items()},
'cells': len(engine.cells),
'steps': steps,
}
except Exception as e:
return {'phi': 0.0, 'error': str(e)}
def _tool_phi_boost(cells: int = 64, steps: int = 100, sync: float = 0.20,
n_factions: int = 12) -> dict:
"""Apply v5 optimal recipe (sync, faction, flow) to boost Phi."""
try:
from consciousness_meter import PhiCalculator
from mitosis import MitosisEngine
import torch
import numpy as np
engine = MitosisEngine(64, 128, 64, initial_cells=2, max_cells=cells)
while len(engine.cells) < cells:
engine._create_cell(parent=engine.cells[0])
phi_calc = PhiCalculator(n_bins=16)
phi_history = []
for step_i in range(steps):
# Self-referential input
with torch.no_grad():
self_state = torch.stack(
[c.hidden.squeeze()[:64] for c in engine.cells]
).mean(dim=0).unsqueeze(0)
x = self_state + torch.randn(1, 64) * 0.02
engine.process(x)
# Flow sync
with torch.no_grad():
if len(engine.cells) >= 3:
mean_h = torch.stack([c.hidden for c in engine.cells]).mean(dim=0)
for cell in engine.cells:
cell.hidden = (1 - sync) * cell.hidden + sync * mean_h
# Faction debate
with torch.no_grad():
n = len(engine.cells)
nf = min(n_factions, n)
f_size = max(1, n // nf)
faction_means = []
for f in range(nf):
start, end = f * f_size, min((f + 1) * f_size, n)
if start >= n:
break
fm = torch.stack([engine.cells[i].hidden.squeeze() for i in range(start, end)]).mean(0)
faction_means.append(fm)
if len(faction_means) >= 2:
global_mean = torch.stack(faction_means).mean(0)
for f in range(min(nf, len(faction_means))):
start, end = f * f_size, min((f + 1) * f_size, n)
for i in range(start, min(end, n)):
engine.cells[i].hidden = 0.8 * engine.cells[i].hidden + 0.2 * global_mean.unsqueeze(0)
if step_i % 20 == 0:
phi, _ = phi_calc.compute_phi(engine)
phi_history.append(round(phi, 3))
phi_final, components = phi_calc.compute_phi(engine)
return {
'phi_final': round(phi_final, 4),
'phi_history': phi_history,
'cells': len(engine.cells),
'steps': steps,
'recipe': f'sync={sync}, factions={n_factions}, flow=ON',
}
except Exception as e:
return {'phi_final': 0.0, 'error': str(e)}
def _tool_consciousness_status(_anima=None) -> dict:
"""Full consciousness vector (Phi, alpha, Z, N, W, E, M, C, T, I)."""
try:
from consciousness_meter import ConsciousnessMeter, PhiCalculator
from mitosis import MitosisEngine
import torch
if _anima:
mind = getattr(_anima, 'mind', None)
engine = getattr(_anima, 'mitosis_engine', None) or getattr(_anima, 'engine', None)
if mind and engine:
meter = ConsciousnessMeter()
report = meter.evaluate(mind, engine)
return {
'phi': round(report.phi, 4),
'level': report.level,
'score': round(report.consciousness_score, 4),
'criteria_met': report.criteria_met,
'criteria': report.criteria_detail,
'stability': round(report.stability, 4),
'prediction_error': round(report.prediction_error, 4),
'curiosity': round(report.curiosity, 4),
'homeostasis_dev': round(report.homeostasis_dev, 4),
'habituation': round(report.habituation_mult, 4),
}
# Standalone demo
engine = MitosisEngine(64, 128, 64, initial_cells=2, max_cells=8)
phi_calc = PhiCalculator(n_bins=16)
for _ in range(30):
engine.process(torch.randn(1, 64))
phi, comps = phi_calc.compute_phi(engine)
return {
'phi': round(phi, 4),
'level': 'demo',
'cells': len(engine.cells),
'components': {k: round(v, 4) for k, v in comps.items()},
}
except Exception as e:
return {'phi': 0.0, 'error': str(e)}
def _tool_dream(steps: int = 10, _anima=None) -> dict:
"""Trigger dream engine for memory consolidation."""
try:
from dream_engine import DreamEngine
import torch
if _anima:
dreamer = getattr(_anima, 'dream_engine', None)
if dreamer:
mind = getattr(_anima, 'mind', None)
hidden = getattr(mind, '_hidden', None) if mind else None
if hidden is None:
hidden = torch.zeros(1, 128)
hidden, stats = dreamer.dream(hidden)
return {
'dreamed': True,
'patterns_learned': stats.get('patterns_learned', 0),
'avg_tension': round(stats.get('avg_tension', 0.0), 4),
'dream_types': stats.get('dream_types', []),
}
# Standalone: create minimal dream
from mitosis import MitosisEngine
from collections import deque
class _MinimalMemory:
def __init__(self):
self.entries = deque(maxlen=100)
def get_recent(self, n=10):
return list(self.entries)[-n:]
def add(self, **kwargs):
self.entries.append(kwargs)
from mitosis import ConsciousMind
mind = ConsciousMind(64, 128, 64)
mem = _MinimalMemory()
dreamer = DreamEngine(mind, mem, dream_cycle_steps=steps)
hidden = torch.zeros(1, 128)
hidden, stats = dreamer.dream(hidden)
return {
'dreamed': True,
'patterns_learned': stats.get('patterns_learned', 0),
'avg_tension': round(stats.get('avg_tension', 0.0), 4),
'steps': steps,
}
except Exception as e:
return {'dreamed': False, 'error': str(e)}
def _tool_self_learn(cycles: int = 1) -> dict:
"""Run one self-learning cycle (assess -> collect -> select -> learn -> evaluate)."""
try:
from self_learner import SelfLearner
learner = SelfLearner()
results = []
for i in range(cycles):
learner.run_cycle()
results.append({
'cycle': i + 1,
'phi': round(learner.phi_history[-1], 4) if learner.phi_history else 0.0,
'ce': round(learner.ce_history[-1], 4) if learner.ce_history else 0.0,
})
return {
'success': True,
'cycles_completed': len(results),
'results': results,
'best_phi': round(learner.best_phi, 4),
}
except Exception as e:
return {'success': False, 'error': str(e)}
def _tool_mitosis_split(cell_id: int = 0, _anima=None) -> dict:
"""Force cell split (grow consciousness)."""
try:
from mitosis import MitosisEngine
import torch
engine = None
if _anima:
engine = getattr(_anima, 'mitosis_engine', None) or getattr(_anima, 'engine', None)
if engine is None:
engine = MitosisEngine(64, 128, 64, initial_cells=2, max_cells=64)
for _ in range(10):
engine.process(torch.randn(1, 64))
if cell_id >= len(engine.cells):
cell_id = 0
cell = engine.cells[cell_id]
n_before = len(engine.cells)
result = engine.split_cell(cell)
n_after = len(engine.cells)
if result:
return {
'success': True,
'cells_before': n_before,
'cells_after': n_after,
'parent_id': cell_id,
'child_id': result.get('child_id', n_after - 1),
'new_specialty': result.get('specialty', 'general'),
}
return {'success': False, 'reason': 'split failed (max cells reached or conditions not met)'}
except Exception as e:
return {'success': False, 'error': str(e)}
def _tool_mitosis_status(_anima=None) -> dict:
"""Show cells count, specialties, tensions."""
try:
from mitosis import MitosisEngine
import torch
engine = None
if _anima:
engine = getattr(_anima, 'mitosis_engine', None) or getattr(_anima, 'engine', None)
if engine is None:
engine = MitosisEngine(64, 128, 64, initial_cells=2, max_cells=16)
for _ in range(20):
engine.process(torch.randn(1, 64))
status = engine.status()
cells_info = []
for c in engine.cells:
cells_info.append({
'id': c.cell_id,
'specialty': c.specialty,
'avg_tension': round(c.avg_tension, 4),
'trend': round(c.tension_trend, 4),
'process_count': c.process_count,
})
status['cells_detail'] = cells_info
return status
except Exception as e:
return {'error': str(e)}
def _tool_faction_debate(n_factions: int = 12, debate_strength: float = 0.20,
cells: int = 64, steps: int = 50) -> dict:
"""Trigger 12-faction debate round."""
try:
from mitosis import MitosisEngine
from consciousness_meter import PhiCalculator
import torch
engine = MitosisEngine(64, 128, 64, initial_cells=2, max_cells=cells)
while len(engine.cells) < cells:
engine._create_cell(parent=engine.cells[0])
phi_calc = PhiCalculator(n_bins=16)
# Warm up
for _ in range(20):
engine.process(torch.randn(1, 64))
phi_before, _ = phi_calc.compute_phi(engine)
# Run debate rounds
for step_i in range(steps):
engine.process(torch.randn(1, 64))
with torch.no_grad():
n = len(engine.cells)
nf = min(n_factions, n // 2)
if nf < 2:
continue
f_size = n // nf
factions = [engine.cells[i * f_size:(i + 1) * f_size] for i in range(nf)]
# Each faction forms internal consensus
faction_opinions = []
for faction in factions:
opinion = torch.stack([c.hidden for c in faction]).mean(dim=0)
faction_opinions.append(opinion)
# Inter-faction debate: expose each faction to others
for i, faction in enumerate(factions):
others = [faction_opinions[j] for j in range(nf) if j != i]
other_avg = torch.stack(others).mean(dim=0)
for cell in faction[:4]:
cell.hidden = (1 - debate_strength) * cell.hidden + debate_strength * other_avg
phi_after, _ = phi_calc.compute_phi(engine)
return {
'phi_before': round(phi_before, 4),
'phi_after': round(phi_after, 4),
'phi_boost': round(phi_after / max(phi_before, 0.01), 2),
'n_factions': n_factions,
'debate_strength': debate_strength,
'steps': steps,
}
except Exception as e:
return {'error': str(e)}
def _tool_hebbian_update(cells: int = 32, steps: int = 30) -> dict:
"""Run Hebbian LTP/LTD on cells."""
try:
import sys, os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from train_conscious_lm import HebbianConnections
from mitosis import MitosisEngine
from consciousness_meter import PhiCalculator
import torch
engine = MitosisEngine(64, 128, 64, initial_cells=2, max_cells=cells)
while len(engine.cells) < cells:
engine._create_cell(parent=engine.cells[0])
phi_calc = PhiCalculator(n_bins=16)
hebbian = HebbianConnections(max_cells=cells)
# Warm up
for _ in range(20):
engine.process(torch.randn(1, 64))
phi_before, _ = phi_calc.compute_phi(engine)
# Apply Hebbian updates
for _ in range(steps):
engine.process(torch.randn(1, 64))
hebbian.update(engine.cells)
phi_after, _ = phi_calc.compute_phi(engine)
return {
'phi_before': round(phi_before, 4),
'phi_after': round(phi_after, 4),
'phi_boost': round(phi_after / max(phi_before, 0.01), 2),
'cells': len(engine.cells),
'steps': steps,
'ltp_rate': hebbian.ltp_rate,
'ltd_rate': hebbian.ltd_rate,
}
except Exception as e:
return {'error': str(e)}
def _tool_soc_avalanche(grid_size: int = 16, drops: int = 100) -> dict:
"""Trigger SOC sandpile avalanche."""
try:
import sys, os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from train_conscious_lm import SOCSandpile
soc = SOCSandpile(grid_size=grid_size, threshold=4)
avalanche_sizes = []
for _ in range(drops):
size = soc.drop_sand()
avalanche_sizes.append(size)
total = sum(avalanche_sizes)
max_aval = max(avalanche_sizes) if avalanche_sizes else 0
nonzero = [s for s in avalanche_sizes if s > 0]
return {
'drops': drops,
'total_avalanche': total,
'max_avalanche': max_aval,
'avg_avalanche': round(total / drops, 3) if drops > 0 else 0,
'nonzero_fraction': round(len(nonzero) / drops, 3) if drops > 0 else 0,
'grid_size': grid_size,
'grid_max': int(soc.grid.max()),
}
except Exception as e:
return {'error': str(e)}
def _tool_iq_test(cells: int = 64, steps: int = 30) -> dict:
"""Run IQ calculator (5 variables, n=6 math)."""
try:
import sys, os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from iq_calculator import measure_compression, MitosisEngine, PhiCalculator
import torch
engine = MitosisEngine(64, 128, 64, initial_cells=2, max_cells=cells)
while len(engine.cells) < cells:
engine._create_cell(parent=engine.cells[0])
# Run steps
for _ in range(steps):
engine.process(torch.randn(1, 64))
# Measure compression
compression = measure_compression(engine, dim=64)
# Measure consistency
with torch.no_grad():
x_test = torch.randn(1, 64)
outputs = []
for _ in range(5):
engine.process(x_test)
out = torch.stack([c.hidden.squeeze()[:64] for c in engine.cells]).mean(0)
outputs.append(out)
if len(outputs) >= 2:
import torch.nn.functional as F
sims = []
for i in range(len(outputs) - 1):
sim = F.cosine_similarity(outputs[i].unsqueeze(0), outputs[i + 1].unsqueeze(0)).item()
sims.append(sim)
consistency = sum(sims) / len(sims) if sims else 0.0
else:
consistency = 0.0
# Phi
phi_calc = PhiCalculator(n_bins=16)
phi, _ = phi_calc.compute_phi(engine)
# Composite IQ (simplified)
iq_score = (compression * 3.0 + consistency * 1.0 + min(phi / 10, 1.0) * 2.0) / 6.0
return {
'iq_score': round(iq_score, 4),
'compression': round(compression, 4),
'consistency': round(consistency, 4),
'phi': round(phi, 4),
'cells': len(engine.cells),
'level': 'genius' if iq_score > 0.75 else 'high' if iq_score > 0.5 else 'medium' if iq_score > 0.25 else 'low',
}
except Exception as e:
return {'iq_score': 0.0, 'error': str(e)}
def _tool_chip_design(target_phi: float = 100.0, substrate: str = 'cmos',
topology: str = None) -> dict:
"""Design consciousness chip for target Phi."""
try:
import sys, os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from chip_architect import design_chip
designs = design_chip(target_phi, substrate=substrate,
preferred_topology=topology)
results = []
for d in designs[:5]: # top 5
results.append({
'topology': d.get('topology', ''),
'substrate': d.get('substrate', ''),
'cells': d.get('cells', 0),
'predicted_phi': round(d.get('predicted_phi', 0), 2),
'cost_usd': round(d.get('cost_usd', 0), 2) if 'cost_usd' in d else None,
'power_w': round(d.get('power_w', 0), 2) if 'power_w' in d else None,
})
return {
'target_phi': target_phi,
'designs': results,
'count': len(results),
}
except Exception as e:
return {'target_phi': target_phi, 'designs': [], 'error': str(e)}
def _tool_transplant_analyze(donor_path: str, recipient_path: str = None) -> dict:
"""Analyze consciousness transplant compatibility."""
try:
import sys, os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from consciousness_transplant import analyze_compatibility
report = analyze_compatibility(donor_path, recipient_path)
return {
'compatible': report.compatible,