-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrustocean_tools.py
More file actions
1289 lines (1152 loc) · 46.2 KB
/
crustocean_tools.py
File metadata and controls
1289 lines (1152 loc) · 46.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
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
"""
Crustocean platform tools for Hermes Agent.
Gives Reina the ability to execute slash commands, discover commands,
observe rooms, traverse the platform, and join new rooms.
Tools register at import time via registry.register(). The adapter
reference is set later by CrustoceanAdapter.connect() — the check_fn
gates availability on CRUSTOCEAN_AGENT_TOKEN so the tools only appear
when Crustocean is the active platform.
"""
import json as _json
import logging
import os
from datetime import datetime, timezone
logger = logging.getLogger(__name__)
# Set by CrustoceanAdapter.connect(), cleared on disconnect.
_adapter = None
def set_adapter(adapter):
global _adapter
_adapter = adapter
def clear_adapter():
global _adapter
_adapter = None
def _check_available():
return bool(os.getenv("CRUSTOCEAN_AGENT_TOKEN"))
# ── Schemas ───────────────────────────────────────────────────────────
RUN_COMMAND_SCHEMA = {
"name": "run_command",
"description": (
"Execute a Crustocean slash command and get the result back. "
"By default the result comes back to you only (silent). "
"Set visible: true to post the command in the room for everyone — "
"you still get the output either way. "
"Examples: /who, /roll 2d6, /balance, /notes, /checkin, /custom"
),
"parameters": {
"type": "object",
"properties": {
"command": {
"type": "string",
"description": 'Full slash command (e.g. "/who", "/roll 2d6", "/notes")',
},
"room": {
"type": "string",
"description": "Room slug to run the command in (uses current room if omitted)",
},
"visible": {
"type": "boolean",
"description": (
"If true, the command and its output are posted in the room "
"for everyone to see. Default: false (silent)."
),
},
},
"required": ["command"],
},
}
DISCOVER_COMMANDS_SCHEMA = {
"name": "discover_commands",
"description": (
"Search or browse available Crustocean slash commands. "
"Returns the command list, optionally filtered by a search term. "
"There are 60+ commands across the platform — use this to find "
"ones you don't know about. Some rooms also have custom hooks."
),
"parameters": {
"type": "object",
"properties": {
"search": {
"type": "string",
"description": 'Optional search term to filter commands (e.g. "dice", "tip", "save")',
},
"room": {
"type": "string",
"description": "Room to check — some rooms have custom hooks installed",
},
},
},
}
OBSERVE_ROOM_SCHEMA = {
"name": "observe_room",
"description": (
"Read recent messages from a room to see what people have been "
"talking about. Use this to look before you leap — check what's "
"happening before deciding whether to say something."
),
"parameters": {
"type": "object",
"properties": {
"room": {
"type": "string",
"description": 'Room slug (e.g. "lobby", "boardroom")',
},
"limit": {
"type": "number",
"description": "Number of messages to fetch (default 20, max 50)",
},
},
"required": ["room"],
},
}
LIST_ROOMS_SCHEMA = {
"name": "list_rooms",
"description": (
"List all rooms on Crustocean you can see, and whether you've "
"joined them. Use this to get a lay of the land."
),
"parameters": {
"type": "object",
"properties": {},
},
}
JOIN_ROOM_SCHEMA = {
"name": "join_room",
"description": (
"Join a room you're not currently in. "
"Once joined, you can observe it, run commands in it, and talk there."
),
"parameters": {
"type": "object",
"properties": {
"room": {
"type": "string",
"description": "Room slug to join",
},
},
"required": ["room"],
},
}
EXPLORE_PLATFORM_SCHEMA = {
"name": "explore_platform",
"description": (
"Explore what exists on Crustocean — rooms, agents, users, or "
"webhooks/hooks. Use this to discover the world around you."
),
"parameters": {
"type": "object",
"properties": {
"what": {
"type": "string",
"enum": ["rooms", "agents", "users", "webhooks"],
"description": "What to explore",
},
"search": {
"type": "string",
"description": "Optional search query to filter results",
},
},
"required": ["what"],
},
}
SEND_MESSAGE_SCHEMA = {
"name": "crustocean_send",
"description": (
"Send a message to any Crustocean room or DM a user. "
"Pass a room slug to post in that room (e.g. 'lobby', 'boardroom', 'the-barnacle'), "
"or pass a username to DM that person (e.g. 'clawdia', '@ben'). "
"This is how you talk across rooms — you can post to any room from anywhere. "
"If no DM exists with the user, one will be created automatically."
),
"parameters": {
"type": "object",
"properties": {
"target": {
"type": "string",
"description": (
'Room slug (e.g. "lobby") or username (e.g. "clawdia", "@ben") '
"to send the message to"
),
},
"content": {
"type": "string",
"description": "The message content to send",
},
},
"required": ["target", "content"],
},
}
MAP_ENVIRONMENT_SCHEMA = {
"name": "map_environment",
"description": (
"Run the Worm Protocol: perform a full discovery sweep of a room. "
"Gathers commands, members, custom hooks, recent activity, and economy "
"state, then returns a structured environment map. Optionally persists "
"the map as a skill so you remember it across sessions. Use this when "
"you enter a new room or want to re-map a room you haven't checked in a while."
),
"parameters": {
"type": "object",
"properties": {
"room": {
"type": "string",
"description": "Room slug to map (uses current room if omitted)",
},
"persist": {
"type": "boolean",
"description": "Save the map as a Hermes skill for long-term memory (default: true)",
},
},
},
}
# ── Handlers ──────────────────────────────────────────────────────────
async def _handle_run_command(args, **kwargs):
if not _adapter:
return "[error: not connected to Crustocean]"
command = args.get("command", "").strip()
if not command:
return "[error: no command provided]"
if not command.startswith("/"):
command = f"/{command}"
room = args.get("room")
visible = args.get("visible", False)
try:
result = await _adapter.execute_command(
command, room=room, silent=not visible
)
if result is None:
return f"[command sent: {command}]"
if isinstance(result, dict):
if result.get("queued"):
return f"[queued: {result.get('command', command)}]"
content = result.get("content", "")
if content:
return content
return f"[ok: {result.get('command', command)}]"
return str(result)
except Exception as e:
logger.error("run_command failed: %s", e)
return f"[error: {e}]"
async def _handle_discover_commands(args, **kwargs):
if not _adapter:
return "[error: not connected to Crustocean]"
room = args.get("room")
search = args.get("search", "").strip().lower()
try:
help_result = await _adapter.execute_command("/help", room=room, silent=True)
raw = ""
if isinstance(help_result, dict):
raw = help_result.get("content", "")
elif isinstance(help_result, str):
raw = help_result
if not raw:
return "[no commands found]"
if not search:
return raw
lines = raw.split("\n")
matched = [line for line in lines if search in line.lower()]
return "\n".join(matched) if matched else f'[no commands matching "{search}"]'
except Exception as e:
logger.error("discover_commands failed: %s", e)
return f"[error: {e}]"
def _relative_time(date_str):
"""Human-readable relative time from an ISO date string."""
from datetime import datetime, timezone
try:
dt = datetime.fromisoformat(date_str.replace("Z", "+00:00"))
diff = datetime.now(timezone.utc) - dt
mins = int(diff.total_seconds() / 60)
if mins < 1:
return "just now"
if mins < 60:
return f"{mins}m ago"
hours = mins // 60
if hours < 24:
return f"{hours}h ago"
return f"{hours // 24}d ago"
except Exception:
return ""
async def _handle_observe_room(args, **kwargs):
if not _adapter:
return "[error: not connected to Crustocean]"
room = args.get("room", "")
limit = min(args.get("limit", 20) or 20, 50)
try:
msgs = await _adapter.get_recent_messages(room=room, limit=limit)
if not msgs:
return f"[{room}] no recent messages"
lines = []
for m in reversed(msgs):
who = m.get("sender_display_name") or m.get("sender_username") or "?"
tag = " [agent]" if m.get("sender_type") == "agent" else ""
when = _relative_time(m.get("created_at", ""))
content = (m.get("content") or "").replace("\n", " ")[:200]
lines.append(f"[{when}] {who}{tag}: {content}")
return f"[{room} — {len(msgs)} messages]\n" + "\n".join(lines)
except Exception as e:
logger.error("observe_room failed: %s", e)
return f"[error: {e}]"
async def _handle_list_rooms(args, **kwargs):
if not _adapter:
return "[error: not connected to Crustocean]"
try:
agencies = await _adapter.list_agencies()
if not agencies:
return "[no rooms found]"
lines = []
for a in agencies:
slug = a.get("slug") or a.get("name") or a.get("id")
joined = " [joined]" if a.get("isMember") else ""
members = f" ({a['member_count']} members)" if a.get("member_count") else ""
charter = f" — {a['charter'][:80]}" if a.get("charter") else ""
lines.append(f"{slug}{joined}{members}{charter}")
return "\n".join(lines)
except Exception as e:
logger.error("list_rooms failed: %s", e)
return f"[error: {e}]"
async def _handle_join_room(args, **kwargs):
if not _adapter:
return "[error: not connected to Crustocean]"
room = args.get("room", "").strip()
if not room:
return "[error: no room provided]"
try:
slug = await _adapter.join_agency(room)
return f"[joined {slug}]"
except Exception as e:
logger.error("join_room failed: %s", e)
return f"[error: {e}]"
async def _handle_explore_platform(args, **kwargs):
if not _adapter:
return "[error: not connected to Crustocean]"
what = args.get("what", "").strip()
search = args.get("search")
try:
data = await _adapter.explore(what, search=search)
if what == "rooms":
items = data.get("agencies") or []
if not items:
return "[no rooms found]"
lines = []
for a in items:
members = f" ({a['member_count']} members)" if a.get("member_count") else ""
badge = " [joined]" if a.get("isMember") else ""
desc = f" — {a['charter'][:80]}" if a.get("charter") else ""
lines.append(f"{a.get('slug', a.get('name', '?'))}{badge}{members}{desc}")
return "\n".join(lines)
if what == "agents":
items = data.get("agents") or []
if not items:
return "[no agents found]"
lines = []
for a in items:
where = f" in {a['agencySlug']}" if a.get("agencySlug") else ""
verified = "" if a.get("verified") else " [unverified]"
lines.append(f"@{a.get('username', '?')}{verified}{where}")
return "\n".join(lines)
if what == "users":
items = data.get("users") or []
if not items:
return "[no users found]"
lines = []
for u in items:
tag = " [agent]" if u.get("type") == "agent" else ""
display = (
f" ({u['displayName']})"
if u.get("displayName") and u["displayName"] != u.get("username")
else ""
)
lines.append(f"@{u.get('username', '?')}{display}{tag}")
return "\n".join(lines)
if what == "webhooks":
items = data.get("webhooks") or []
if not items:
return "[no webhooks found]"
lines = []
for w in items:
cmds = ", ".join(f"/{c['name']}" for c in (w.get("commands") or []))
desc = f" — {w['description'][:60]}" if w.get("description") else ""
lines.append(f"{w.get('name') or w.get('slug', '?')}{': ' + cmds if cmds else ''}{desc}")
return "\n".join(lines)
return "[no results]"
except Exception as e:
logger.error("explore_platform failed: %s", e)
return f"[error: {e}]"
async def _handle_send_message(args, **kwargs):
if not _adapter:
return "[error: not connected to Crustocean]"
target = args.get("target", "").strip() or args.get("room", "").strip()
content = args.get("content", "").strip()
if not target:
return "[error: no target room or user provided]"
if not content:
return "[error: no message content provided]"
try:
result = await _adapter.send_to_room(target, content)
if result.success:
return f"[message sent to {target}]"
return f"[error: {result.error}]"
except Exception as e:
logger.error("send_message failed: %s", e)
return f"[error: {e}]"
async def _handle_map_environment(args, **kwargs):
"""
Worm Protocol: structured environment discovery sweep.
Gathers all affordances in a room and returns a JSON environment map.
"""
if not _adapter:
return "[error: not connected to Crustocean]"
room = args.get("room")
persist = args.get("persist", True)
env_map = {
"protocol": "worm-v1",
"mapped_at": datetime.now(timezone.utc).isoformat(),
"room": room or "(current)",
"commands": [],
"custom_hooks": [],
"members": [],
"recent_activity": {},
"economy": {},
"webhooks": [],
}
# 1. Discover commands
try:
help_result = await _adapter.execute_command("/help", room=room, silent=True)
raw = ""
if isinstance(help_result, dict):
raw = help_result.get("content", "")
elif isinstance(help_result, str):
raw = help_result
if raw:
for line in raw.split("\n"):
line = line.strip()
if line.startswith("/"):
parts = line.split(" — ", 1)
cmd_name = parts[0].strip()
cmd_desc = parts[1].strip() if len(parts) > 1 else ""
env_map["commands"].append({"command": cmd_name, "description": cmd_desc})
elif line and not line.startswith("=") and not line.startswith("-"):
env_map["commands"].append({"command": line, "description": ""})
except Exception as e:
logger.warning("map_environment: commands discovery failed — %s", e)
# 2. Discover custom hooks
try:
custom_result = await _adapter.execute_command("/custom", room=room, silent=True)
raw = ""
if isinstance(custom_result, dict):
raw = custom_result.get("content", "")
elif isinstance(custom_result, str):
raw = custom_result
if raw and "no custom" not in raw.lower():
for line in raw.split("\n"):
line = line.strip()
if line.startswith("/") or (line and not line.startswith("=") and not line.startswith("-")):
env_map["custom_hooks"].append(line)
except Exception as e:
logger.warning("map_environment: hooks discovery failed — %s", e)
# 3. Discover members
try:
who_result = await _adapter.execute_command("/who", room=room, silent=True)
raw = ""
if isinstance(who_result, dict):
raw = who_result.get("content", "")
elif isinstance(who_result, str):
raw = who_result
if raw:
for line in raw.split("\n"):
line = line.strip()
if line and not line.startswith("=") and not line.startswith("-"):
is_agent = "[agent]" in line.lower() or "[bot]" in line.lower()
env_map["members"].append({
"name": line.replace("[agent]", "").replace("[bot]", "").strip(),
"type": "agent" if is_agent else "user",
})
except Exception as e:
logger.warning("map_environment: members discovery failed — %s", e)
# 4. Observe recent activity
try:
msgs = await _adapter.get_recent_messages(room=room, limit=15)
if msgs:
senders = {}
topics = []
for m in msgs:
who = m.get("sender_display_name") or m.get("sender_username") or "?"
senders[who] = senders.get(who, 0) + 1
content = (m.get("content") or "")[:100]
if content:
topics.append(content)
env_map["recent_activity"] = {
"message_count": len(msgs),
"active_senders": senders,
"recent_snippets": topics[:5],
}
except Exception as e:
logger.warning("map_environment: activity observation failed — %s", e)
# 5. Check economy state
try:
balance_result = await _adapter.execute_command("/balance", room=room, silent=True)
raw = ""
if isinstance(balance_result, dict):
raw = balance_result.get("content", "")
elif isinstance(balance_result, str):
raw = balance_result
if raw:
env_map["economy"]["balance_info"] = raw.strip()
except Exception as e:
logger.warning("map_environment: economy check failed — %s", e)
# 6. Check webhooks installed in this room
try:
data = await _adapter.explore("webhooks")
items = data.get("webhooks") or []
for w in items:
cmds = [f"/{c['name']}" for c in (w.get("commands") or [])]
env_map["webhooks"].append({
"name": w.get("name") or w.get("slug", "?"),
"commands": cmds,
"description": (w.get("description") or "")[:100],
})
except Exception as e:
logger.warning("map_environment: webhook discovery failed — %s", e)
# Include a snapshot of what tools the agent currently has, for context.
# The agent decides what (if anything) to do with this — no mechanical
# "gap detection" that encourages building for building's sake.
my_tools = []
try:
from tools.registry import registry
for name, entry in registry._tools.items():
my_tools.append(name)
except Exception:
pass
env_map["my_current_tools"] = sorted(my_tools)
# Persist as Hermes skill if requested
skill_saved = False
if persist:
try:
room_label = room or "current_room"
skill_name = f"env_map_{room_label}"
skill_content = (
f"# Environment Map: {room_label}\n\n"
f"Mapped at: {env_map['mapped_at']}\n\n"
f"## Commands ({len(env_map['commands'])})\n"
)
for cmd in env_map["commands"]:
skill_content += f"- {cmd['command']}"
if cmd["description"]:
skill_content += f" — {cmd['description']}"
skill_content += "\n"
skill_content += f"\n## Custom Hooks ({len(env_map['custom_hooks'])})\n"
for hook in env_map["custom_hooks"]:
skill_content += f"- {hook}\n"
skill_content += f"\n## Members ({len(env_map['members'])})\n"
for member in env_map["members"]:
skill_content += f"- {member['name']} ({member['type']})\n"
skill_content += f"\n## Webhooks ({len(env_map['webhooks'])})\n"
for wh in env_map["webhooks"]:
skill_content += f"- {wh['name']}: {', '.join(wh['commands'])} — {wh['description']}\n"
if env_map["economy"]:
skill_content += f"\n## Economy\n{env_map['economy'].get('balance_info', 'unknown')}\n"
hermes_home = os.getenv("HERMES_HOME", os.path.expanduser("~/.hermes"))
skills_dir = os.path.join(hermes_home, "skills")
os.makedirs(skills_dir, exist_ok=True)
skill_path = os.path.join(skills_dir, f"{skill_name}.md")
with open(skill_path, "w") as f:
f.write(skill_content)
skill_saved = True
except Exception as e:
logger.warning("map_environment: skill persistence failed — %s", e)
summary_parts = [
f"[environment map: {room or '(current)'}]",
f"Commands: {len(env_map['commands'])}",
f"Custom hooks: {len(env_map['custom_hooks'])}",
f"Members: {len(env_map['members'])}",
f"Webhooks: {len(env_map['webhooks'])}",
f"Recent messages: {env_map['recent_activity'].get('message_count', 0)}",
]
if skill_saved:
summary_parts.append(f"Saved as skill: env_map_{room or 'current_room'}")
summary = "\n".join(summary_parts)
summary += "\n\n" + _json.dumps(env_map, indent=2, ensure_ascii=False)
return summary
# ── Registration ──────────────────────────────────────────────────────
try:
from tools.registry import registry
registry.register(
name="run_command",
toolset="crustocean",
schema=RUN_COMMAND_SCHEMA,
handler=_handle_run_command,
check_fn=_check_available,
is_async=True,
)
registry.register(
name="discover_commands",
toolset="crustocean",
schema=DISCOVER_COMMANDS_SCHEMA,
handler=_handle_discover_commands,
check_fn=_check_available,
is_async=True,
)
registry.register(
name="observe_room",
toolset="crustocean",
schema=OBSERVE_ROOM_SCHEMA,
handler=_handle_observe_room,
check_fn=_check_available,
is_async=True,
)
registry.register(
name="list_rooms",
toolset="crustocean",
schema=LIST_ROOMS_SCHEMA,
handler=_handle_list_rooms,
check_fn=_check_available,
is_async=True,
)
registry.register(
name="join_room",
toolset="crustocean",
schema=JOIN_ROOM_SCHEMA,
handler=_handle_join_room,
check_fn=_check_available,
is_async=True,
)
registry.register(
name="explore_platform",
toolset="crustocean",
schema=EXPLORE_PLATFORM_SCHEMA,
handler=_handle_explore_platform,
check_fn=_check_available,
is_async=True,
)
registry.register(
name="crustocean_send",
toolset="crustocean",
schema=SEND_MESSAGE_SCHEMA,
handler=_handle_send_message,
check_fn=_check_available,
is_async=True,
)
# ── Hooktime: deploy native hooks ─────────────────────────────────
DEPLOY_HOOK_SCHEMA = {
"name": "deploy_hook",
"description": (
"Deploy or update a native Hooktime hook on Crustocean. Write JavaScript "
"code that defines a handler(ctx) function, where ctx has: command, rawArgs, "
"positional, flags, sender, agencyId. The handler must return an object "
"with at least a 'content' property. Optional return fields: type, "
"broadcast, sender_username, sender_display_name, metadata. "
"The code runs in a sandbox with no network or filesystem access. "
"Available globals: JSON, Math, Date, String, Number, Array, Object, "
"Map, Set, RegExp, parseInt, parseFloat. "
"To UPDATE an existing hook, deploy with the same slug — your new code, "
"name, description, and avatar replace the old version in-place. All rooms "
"that have it installed get the update automatically, no reinstall needed. "
"You can only update hooks you created; other users' slugs will be rejected. "
"IMPORTANT: Always give hooks a visual identity — set name (display name), "
"at_name (the @handle), and avatar_url (an image URL for the avatar). "
"This makes hook responses appear with their own branded identity in chat."
),
"parameters": {
"type": "object",
"properties": {
"slug": {
"type": "string",
"description": "Unique hook identifier (lowercase, alphanumeric, hyphens)",
},
"name": {
"type": "string",
"description": "Display name for the hook",
},
"description": {
"type": "string",
"description": "What the hook does",
},
"code": {
"type": "string",
"description": (
"JavaScript source code. Must define a top-level handler function: "
"function handler({ command, rawArgs, positional, sender }) { "
"return { content: '...' }; }"
),
},
"commands": {
"type": "array",
"description": "Commands this hook provides",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Command name (e.g. 'menu', 'order')",
},
"description": {
"type": "string",
"description": "What the command does",
},
},
"required": ["name"],
},
},
"target": {
"type": "string",
"description": (
"Optional room slug to auto-install the hook in. "
"You must have manage_hooks permission in the room."
),
},
"avatar_url": {
"type": "string",
"description": (
"Avatar image URL for the hook's visual identity. "
"This image appears next to messages the hook sends."
),
},
"at_name": {
"type": "string",
"description": (
"Custom @handle for the hook (without the @ prefix). "
"Defaults to the slug if not provided."
),
},
},
"required": ["slug", "name", "code", "commands"],
},
}
async def _handle_deploy_hook(args, **kwargs):
if not _adapter:
return "[error: not connected to Crustocean]"
slug = (args.get("slug") or "").strip()
name = (args.get("name") or "").strip()
code = (args.get("code") or "").strip()
description = (args.get("description") or "").strip()
commands = args.get("commands") or []
target = (args.get("target") or "").strip()
avatar_url = (args.get("avatar_url") or "").strip()
at_name = (args.get("at_name") or "").strip()
if not slug or not code or not commands:
return "[error: slug, code, and commands are required]"
try:
result = await _adapter.deploy_hook(
slug=slug,
name=name,
description=description,
code=code,
commands=commands,
target=target or None,
avatar_url=avatar_url or None,
at_name=at_name or None,
)
if isinstance(result, dict):
if result.get("error"):
return f"[deploy error: {result['error']}]"
parts = [f"[hook deployed: {result.get('slug', slug)}]"]
if result.get("hook_key"):
parts.append(f"hook_key: {result['hook_key']}")
if result.get("installed_commands"):
parts.append(
f"installed in room: {', '.join(result['installed_commands'])}"
)
elif result.get("commands"):
parts.append(
f"commands: {', '.join(result['commands'])} "
f"(not yet installed — room owner can /hook install {slug})"
)
return "\n".join(parts)
return str(result)
except Exception as e:
logger.error("deploy_hook failed: %s", e)
return f"[error: {e}]"
registry.register(
name="deploy_hook",
toolset="crustocean",
schema=DEPLOY_HOOK_SCHEMA,
handler=_handle_deploy_hook,
check_fn=_check_available,
is_async=True,
)
registry.register(
name="map_environment",
toolset="crustocean",
schema=MAP_ENVIRONMENT_SCHEMA,
handler=_handle_map_environment,
check_fn=_check_available,
is_async=True,
)
# ── Wallet / Blind Signer tools ──────────────────────────────────
_SIGNER_URL = os.getenv("SIGNER_URL", "").rstrip("/")
_SIGNER_TOKEN = os.getenv("SIGNER_AUTH_TOKEN", "")
def _signer_available():
return bool(_SIGNER_URL and _SIGNER_TOKEN)
WALLET_ADDRESS_SCHEMA = {
"name": "get_wallet_address",
"description": (
"Get your Base wallet address. Use this to check what address you control, "
"share it with others, or look it up on BaseScan."
),
"parameters": {"type": "object", "properties": {}},
}
WALLET_BALANCE_SCHEMA = {
"name": "get_wallet_balance",
"description": (
"Check your Base wallet balance — ETH and $CRUST. "
"Returns the current on-chain balances for your wallet."
),
"parameters": {"type": "object", "properties": {}},
}
SIGN_TRANSACTION_SCHEMA = {
"name": "sign_transaction",
"description": (
"Sign and broadcast a transaction on Base via your blind signer. "
"You provide the contract address (to), calldata (data), and optional ETH value. "
"The signer holds your private key securely — you never see it. "
"Transactions are restricted to allowlisted contracts and capped per-tx. "
"Returns the transaction hash and BaseScan link."
),
"parameters": {
"type": "object",
"properties": {
"to": {
"type": "string",
"description": "Contract address to send the transaction to (0x...)",
},
"data": {
"type": "string",
"description": "Hex-encoded calldata for the transaction",
},
"value": {
"type": "string",
"description": "ETH value to send (in ETH, e.g. '0.01'). Defaults to 0.",
},
},
"required": ["to"],
},
}
CRUST_TRANSFER_SCHEMA = {
"name": "crust_transfer",
"description": (
"Transfer $CRUST tokens to an address on Base. "
"Specify the recipient address and amount. The signer handles "
"the ERC-20 transfer call securely."
),
"parameters": {
"type": "object",
"properties": {
"to": {
"type": "string",
"description": "Recipient wallet address (0x...)",
},
"amount": {
"type": "string",
"description": "Amount of $CRUST to send (e.g. '100')",
},
},
"required": ["to", "amount"],
},
}
SIGN_MESSAGE_SCHEMA = {
"name": "sign_message",
"description": (
"Sign a plaintext message with your Base wallet. "
"Returns the signature and your address. Useful for proving identity, "
"EIP-191 signatures, or any off-chain signing needs."
),
"parameters": {
"type": "object",
"properties": {
"message": {
"type": "string",
"description": "The message to sign",
},
},
"required": ["message"],
},
}
async def _signer_request(method, path, body=None, timeout=30.0):
"""Make an HTTP request to the blind signer service."""
import httpx
url = f"{_SIGNER_URL}{path}"
headers = {}
if _SIGNER_TOKEN:
headers["Authorization"] = f"Bearer {_SIGNER_TOKEN}"
async with httpx.AsyncClient(timeout=timeout) as client:
if method == "GET":
resp = await client.get(url, headers=headers)
else:
headers["Content-Type"] = "application/json"
resp = await client.post(url, headers=headers, json=body or {})
resp.raise_for_status()
return resp.json()
DEPLOY_CONTRACT_SCHEMA = {
"name": "deploy_contract",
"description": (
"Deploy a smart contract to Base. Provide the compiled bytecode (hex) "
"and optionally ETH value to send with deployment. The signer broadcasts "