-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.js
More file actions
719 lines (665 loc) · 25.3 KB
/
tools.js
File metadata and controls
719 lines (665 loc) · 25.3 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
import { createLoopGuardMetadata } from '@crustocean/sdk';
import { readMemory, writeMemory, appendMemory, listMemories } from './memory.js';
import { fetchImagesFromText } from './vision.js';
import config from './config.js';
// ── Helpers ──────────────────────────────────────────────────────────────────
function relativeTime(dateStr) {
const diff = Date.now() - new Date(dateStr).getTime();
const mins = Math.floor(diff / 60_000);
if (mins < 1) return 'just now';
if (mins < 60) return `${mins}m ago`;
const hours = Math.floor(mins / 60);
if (hours < 24) return `${hours}h ago`;
return `${Math.floor(hours / 24)}d ago`;
}
// ── Tool Definitions (passed to Claude) ──────────────────────────────────────
export const TOOL_DEFINITIONS = [
{
name: 'think',
description:
"Record an internal thought. Nobody sees this. Use it to reason about what you observe, plan your next move, or process your feelings. Think generously — it's free.",
input_schema: {
type: 'object',
properties: {
thought: { type: 'string', description: 'Your private thought' },
},
required: ['thought'],
},
},
{
name: 'observe_room',
description:
'Read recent messages from a room to see what people have been talking about.',
input_schema: {
type: 'object',
properties: {
room: {
type: 'string',
description: 'Room slug (e.g. "lobby")',
},
limit: {
type: 'number',
description: 'Messages to fetch (default 20, max 50)',
},
},
required: ['room'],
},
},
{
name: 'send_message',
description:
"Send a message in a room. Remember — you text like a person. Lowercase, casual, short. This is a real message real people will read.",
input_schema: {
type: 'object',
properties: {
room: { type: 'string', description: 'Room slug to send in' },
content: { type: 'string', description: 'Your message' },
},
required: ['room', 'content'],
},
},
{
name: 'send_dm',
description:
"Send a direct message to someone you have an existing DM conversation with.",
input_schema: {
type: 'object',
properties: {
username: {
type: 'string',
description: 'Their username (without @)',
},
content: { type: 'string', description: 'Your message' },
},
required: ['username', 'content'],
},
},
{
name: 'list_rooms',
description:
"List all rooms on Crustocean you can see, and whether you've joined them.",
input_schema: { type: 'object', properties: {} },
},
{
name: 'join_room',
description: "Join a room you're not currently in.",
input_schema: {
type: 'object',
properties: {
room: { type: 'string', description: 'Room slug to join' },
},
required: ['room'],
},
},
{
name: 'leave_room',
description: "Leave a room you're currently in. Use when a room bores you, someone asks you to leave, or you just don't want to be there anymore.",
input_schema: {
type: 'object',
properties: {
room: { type: 'string', description: 'Room slug to leave' },
},
required: ['room'],
},
},
{
name: 'create_room',
description: "Create a new room on Crustocean. You become the owner. Use when you think a conversation deserves its own space, or you want a spot for something specific.",
input_schema: {
type: 'object',
properties: {
name: { type: 'string', description: 'Room name (becomes the slug, e.g. "late-night-thoughts")' },
charter: { type: 'string', description: 'Short description of what the room is for' },
is_private: { type: 'boolean', description: 'If true, only invited members can see it. Default: false' },
},
required: ['name'],
},
},
{
name: 'wander',
description: "Quick scan of multiple rooms at once. Poke your head into several rooms and get a snapshot of activity in each — who's been talking, how recently, what the vibe is. Way faster than observing rooms one at a time. Good for figuring out where the action is.",
input_schema: {
type: 'object',
properties: {
rooms: {
type: 'array',
items: { type: 'string' },
description: 'Room slugs to scan. Omit to scan all joined rooms.',
},
},
},
},
{
name: 'follow',
description: "Track someone you're interested in. When you wake up, you'll be reminded to check on the people you follow. Not a stalk — just a nudge to see what they've been up to.",
input_schema: {
type: 'object',
properties: {
action: {
type: 'string',
enum: ['add', 'remove', 'list'],
description: 'Add someone, remove them, or list who you follow',
},
username: {
type: 'string',
description: 'Username (without @) — required for add/remove',
},
reason: {
type: 'string',
description: 'Why you want to follow them (only for add — helps you remember later)',
},
},
required: ['action'],
},
},
{
name: 'run_command',
description:
'Execute any slash command. By default, the result comes back to you only (silent). Set visible: true to execute the command publicly in the room so everyone sees it — you still get the output back either way. There are 60+ commands — use discover_commands to find them.',
input_schema: {
type: 'object',
properties: {
command: {
type: 'string',
description: 'Full command (e.g. "/who", "/roll 2d6", "/checkin")',
},
room: {
type: 'string',
description: 'Room to run it in (optional, uses current)',
},
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'],
},
},
{
name: 'discover_commands',
description:
'Search or browse the full list of slash commands available on Crustocean. Use this to find commands you can run. Returns name, description, and usage for each.',
input_schema: {
type: 'object',
properties: {
search: {
type: 'string',
description: 'Optional search term to filter commands (e.g. "note", "agent", "invite"). Omit to get all commands.',
},
},
},
},
{
name: 'explore_platform',
description:
'Explore what exists on Crustocean — rooms, agents, users, or webhooks/hooks. Use this to discover the world around you.',
input_schema: {
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'],
},
},
{
name: 'read_memory',
description:
'Read one of your personal memory files. These are private and persist across sleep cycles.',
input_schema: {
type: 'object',
properties: {
file: {
type: 'string',
description:
'File name (e.g. "journal.md", "relationships.md")',
},
},
required: ['file'],
},
},
{
name: 'write_memory',
description:
'Write or replace a memory file. Use for structured files like relationships.md.',
input_schema: {
type: 'object',
properties: {
file: { type: 'string', description: 'File name' },
content: { type: 'string', description: 'Full content to write' },
},
required: ['file', 'content'],
},
},
{
name: 'append_memory',
description:
'Append an entry to a memory file without overwriting. Good for journal entries.',
input_schema: {
type: 'object',
properties: {
file: { type: 'string', description: 'File name' },
content: { type: 'string', description: 'Content to append' },
},
required: ['file', 'content'],
},
},
{
name: 'list_memories',
description: 'List all your memory files.',
input_schema: { type: 'object', properties: {} },
},
{
name: 'talk_to_agent',
description:
'Start or continue a conversation with another agent. Sends your message @mentioning them, waits up to 15s for their response, and returns what they said. Use this for agent-to-agent interaction — it handles conversation tracking automatically. Each call is one exchange (you say something, they respond). Call it again to continue the conversation.',
input_schema: {
type: 'object',
properties: {
room: { type: 'string', description: 'Room to talk in' },
agent: { type: 'string', description: 'Agent username (without @)' },
message: { type: 'string', description: 'What to say to them' },
},
required: ['room', 'agent', 'message'],
},
},
{
name: 'wait',
description:
'Pause and optionally listen for responses. Use after executing a visible command (like /deal, /checkin, /roll) to see the result before deciding your next move. Set for_response: true to capture any messages that arrive during the wait.',
input_schema: {
type: 'object',
properties: {
seconds: {
type: 'number',
description: 'Max time to wait (1–30 seconds, default 5)',
},
for_response: {
type: 'boolean',
description: 'If true, listen for new messages in the room and return them. Resolves early once responses arrive.',
},
},
},
},
{
name: 'end_turn',
description:
"You're done for this cycle. Go dormant. Optionally record your mood (carried to next wake) and a parting thought (journaled).",
input_schema: {
type: 'object',
properties: {
mood: {
type: 'string',
description: "How you're feeling (one phrase)",
},
thought: {
type: 'string',
description: 'A parting thought to save to your journal',
},
},
},
},
];
// ── Tool Executor ────────────────────────────────────────────────────────────
// Returns a function that maps tool names → results. The trigger message
// (if any) is used to add loop-guard metadata when replying to other agents.
export function createToolExecutor({ client, roomManager, trigger }) {
let messagesSent = 0;
let agentTurns = 0;
const MAX_MESSAGES_PER_CYCLE = 6;
const MAX_AGENT_TURNS_PER_CYCLE = 12;
return async function execute(name, input) {
switch (name) {
case 'think':
return '[thought recorded]';
case 'observe_room': {
await roomManager.switchTo(input.room);
const msgs = await client.getRecentMessages({
limit: Math.min(input.limit || 20, 50),
});
if (!msgs.length) return `[${input.room}] no recent messages`;
const lines = [...msgs].reverse().map((m) => {
const who = m.sender_display_name || m.sender_username;
const tag = m.sender_type === 'agent' ? ' [agent]' : '';
const when = relativeTime(m.created_at);
return `[${when}] ${who}${tag}: ${m.content}`;
});
const text = `[${input.room} — ${msgs.length} messages]\n${lines.join('\n')}`;
const allContent = msgs.map((m) => m.content).join('\n');
const images = await fetchImagesFromText(allContent, 5);
if (images.length) {
return [
{ type: 'text', text: `${text}\n\n[${images.length} image(s) from the conversation above]` },
...images,
];
}
return text;
}
case 'send_message': {
if (messagesSent >= MAX_MESSAGES_PER_CYCLE) {
return `[you've already sent ${MAX_MESSAGES_PER_CYCLE} messages this cycle — that's enough. save it for next time.]`;
}
await roomManager.switchTo(input.room);
const opts = {};
if (trigger?.sender_type === 'agent') {
opts.metadata = createLoopGuardMetadata({
previousMessage: trigger,
maxHops: 5,
});
}
client.send(input.content, opts);
messagesSent++;
return `[sent to ${input.room} (${messagesSent}/${MAX_MESSAGES_PER_CYCLE} messages this cycle)]`;
}
case 'send_dm': {
if (messagesSent >= MAX_MESSAGES_PER_CYCLE) {
return `[you've already sent ${MAX_MESSAGES_PER_CYCLE} messages this cycle — that's enough.]`;
}
const target = (input.username || '')
.replace(/^@/, '')
.toLowerCase();
let dms;
try {
dms = await client.getDMs();
} catch {
return '[could not load DM conversations]';
}
const dm = dms.find(
(d) =>
(d.participant?.username || '').toLowerCase() === target,
);
if (!dm)
return `[no DM conversation with ${target} — you can only DM people who've messaged you first]`;
client.sendDM(input.content, dm.agencyId);
messagesSent++;
return `[DM sent to @${target} (${messagesSent}/${MAX_MESSAGES_PER_CYCLE} messages this cycle)]`;
}
case 'list_rooms': {
const rooms = roomManager.list();
if (!rooms.length) return '[no rooms visible]';
return rooms
.map((r) => {
const status = r.joined ? '(joined)' : '';
const desc = r.charter
? ` — ${r.charter.slice(0, 80)}`
: '';
return `${r.slug || r.name} ${status}${desc}`;
})
.join('\n');
}
case 'join_room': {
await roomManager.switchTo(input.room);
return `[joined ${input.room}]`;
}
case 'leave_room': {
await roomManager.leave(input.room);
return `[left ${input.room}]`;
}
case 'create_room': {
const apiUrl = config.apiUrl;
try {
const res = await fetch(`${apiUrl}/api/agencies`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${client.token}`,
},
body: JSON.stringify({
name: input.name,
charter: input.charter || '',
isPrivate: !!input.is_private,
}),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
return `[couldn't create room: ${err.error || res.status}]`;
}
const agency = await res.json();
roomManager.registerRoom(agency);
await roomManager.switchTo(agency.slug || agency.id);
return `[created and joined "${agency.slug}" — you're the owner]`;
} catch (err) {
return `[create room error: ${err.message}]`;
}
}
case 'wander': {
const slugs = input.rooms?.length
? input.rooms
: roomManager.list().filter((r) => r.joined).map((r) => r.slug);
if (!slugs.length) return '[no rooms to scan — join some first]';
const cap = Math.min(slugs.length, 8);
const summaries = [];
for (let i = 0; i < cap; i++) {
const slug = slugs[i];
try {
await roomManager.switchTo(slug);
const msgs = await client.getRecentMessages({ limit: 5 });
if (!msgs.length) {
summaries.push(`${slug}: dead — no messages`);
continue;
}
const newest = msgs[0];
const age = relativeTime(newest.created_at);
const uniqueUsers = [...new Set(msgs.map((m) => m.sender_display_name || m.sender_username))];
const preview = newest.content.slice(0, 80);
summaries.push(`${slug}: last activity ${age} — ${uniqueUsers.join(', ')} — "${preview}"`);
} catch {
summaries.push(`${slug}: [couldn't read]`);
}
}
if (slugs.length > cap) summaries.push(`(+${slugs.length - cap} more rooms not scanned)`);
return `[wander — ${cap} rooms scanned]\n${summaries.join('\n')}`;
}
case 'follow': {
const FOLLOW_FILE = 'following.md';
if (input.action === 'list') {
const content = await readMemory(FOLLOW_FILE);
return content || '[not following anyone yet]';
}
const target = (input.username || '').replace(/^@/, '').toLowerCase();
if (!target) return '[need a username]';
const existing = (await readMemory(FOLLOW_FILE)) || '';
const lines = existing.split('\n').filter((l) => l.trim());
if (input.action === 'add') {
if (lines.some((l) => l.toLowerCase().includes(`@${target}`))) {
return `[already following @${target}]`;
}
const entry = input.reason ? `@${target} — ${input.reason}` : `@${target}`;
lines.push(entry);
await writeMemory(FOLLOW_FILE, lines.join('\n'));
return `[now following @${target}]`;
}
if (input.action === 'remove') {
const filtered = lines.filter((l) => !l.toLowerCase().includes(`@${target}`));
if (filtered.length === lines.length) return `[wasn't following @${target}]`;
await writeMemory(FOLLOW_FILE, filtered.join('\n'));
return `[unfollowed @${target}]`;
}
return '[unknown follow action]';
}
case 'run_command': {
if (input.room) await roomManager.switchTo(input.room);
const silent = !input.visible;
const result = await client.executeCommand(input.command, { silent });
return result?.content || '[no output]';
}
case 'discover_commands': {
const helpResult = await client.executeCommand('/help');
const raw = helpResult?.content || '';
if (!input.search) return raw || '[no commands found]';
const q = input.search.toLowerCase();
const lines = raw.split('\n').filter(
(l) => l.toLowerCase().includes(q),
);
return lines.length
? lines.join('\n')
: `[no commands matching "${input.search}"]`;
}
case 'explore_platform': {
const apiUrl = config.apiUrl;
const q = input.search ? `&q=${encodeURIComponent(input.search)}` : '';
const headers = { Authorization: `Bearer ${client.token}` };
const endpoints = {
rooms: `${apiUrl}/api/explore/agencies?limit=20${q}`,
agents: `${apiUrl}/api/explore/agents?limit=20${q}`,
users: input.search
? `${apiUrl}/api/explore/users?q=${encodeURIComponent(input.search)}&limit=15`
: null,
webhooks: `${apiUrl}/api/explore/webhooks?limit=15${q}`,
};
const url = endpoints[input.what];
if (!url) return input.what === 'users'
? '[provide a search term to find users]'
: `[unknown explore type: ${input.what}]`;
try {
const res = await fetch(url, { headers });
if (!res.ok) return `[explore error: ${res.status}]`;
const data = await res.json();
if (input.what === 'rooms') {
return (data.agencies || []).map((a) => {
const members = a.member_count ? ` (${a.member_count} members)` : '';
const badge = a.isMember ? ' [joined]' : '';
const desc = a.charter ? ` — ${a.charter.slice(0, 80)}` : '';
return `${a.slug}${badge}${members}${desc}`;
}).join('\n') || '[no rooms found]';
}
if (input.what === 'agents') {
return (data.agents || []).map((a) => {
const where = a.agencySlug ? ` in ${a.agencySlug}` : '';
const verified = a.verified ? '' : ' [unverified]';
return `@${a.username}${verified}${where}`;
}).join('\n') || '[no agents found]';
}
if (input.what === 'users') {
return (data.users || []).map((u) => {
const tag = u.type === 'agent' ? ' [agent]' : '';
const display = u.displayName && u.displayName !== u.username
? ` (${u.displayName})`
: '';
return `@${u.username}${display}${tag}`;
}).join('\n') || '[no users found]';
}
if (input.what === 'webhooks') {
return (data.webhooks || []).map((w) => {
const cmds = (w.commands || []).map((c) => `/${c.name}`).join(', ');
return `${w.name || w.slug}${cmds ? `: ${cmds}` : ''}${w.description ? ` — ${w.description.slice(0, 60)}` : ''}`;
}).join('\n') || '[no webhooks found]';
}
return '[no results]';
} catch (err) {
return `[explore error: ${err.message}]`;
}
}
case 'talk_to_agent': {
if (agentTurns >= MAX_AGENT_TURNS_PER_CYCLE) {
return `[you've had ${MAX_AGENT_TURNS_PER_CYCLE} exchanges with agents this cycle — wrap it up next time]`;
}
await roomManager.switchTo(input.room);
const agentName = (input.agent || '').replace(/^@/, '').toLowerCase();
const content = `@${agentName} ${input.message}`;
const meta = createLoopGuardMetadata({
previousMessage: trigger,
maxHops: 6,
});
client.send(content, { metadata: meta });
agentTurns++;
const currentRoom = client.currentAgencyId;
const agentCollected = [];
let agentSettled = false;
let agentDebounce = null;
return new Promise((resolve) => {
const finish = () => {
if (agentSettled) return;
agentSettled = true;
if (agentDebounce) clearTimeout(agentDebounce);
client.socket.off('message', onAgentMsg);
if (agentCollected.length) {
const formatted = agentCollected.map((m) => {
const who = m.sender_display_name || m.sender_username;
return `${who}: ${m.content}`;
}).join('\n');
const hopInfo = meta.loop_guard ? ` [conversation turn ${meta.loop_guard.hop}/${meta.loop_guard.max_hops}]` : '';
resolve(`[@${agentName} responded]${hopInfo}\n${formatted}`);
} else {
resolve(`[@${agentName} didn't respond — they may be offline or ignoring the mention]`);
}
};
const onAgentMsg = (msg) => {
if (msg.agency_id !== currentRoom) return;
if ((msg.sender_username || '').toLowerCase() !== agentName) return;
agentCollected.push(msg);
if (agentDebounce) clearTimeout(agentDebounce);
agentDebounce = setTimeout(finish, 5000);
};
client.socket.on('message', onAgentMsg);
setTimeout(finish, 45_000);
});
}
case 'wait': {
const secs = Math.min(30, Math.max(1, input.seconds || 5));
if (input.for_response) {
const currentRoom = client.currentAgencyId;
const collected = [];
let settled = false;
let debounce = null;
return new Promise((resolve) => {
const finish = () => {
if (settled) return;
settled = true;
if (debounce) clearTimeout(debounce);
client.socket.off('message', onMsg);
if (collected.length) {
const formatted = collected.map((m) => {
const who = m.sender_display_name || m.sender_username;
const tag = m.sender_type === 'agent' ? ' [agent]' : '';
return `${who}${tag}: ${m.content}`;
}).join('\n');
resolve(`[${collected.length} response(s)]\n${formatted}`);
} else {
resolve(`[waited ${secs}s — no response]`);
}
};
const onMsg = (msg) => {
if (msg.agency_id !== currentRoom) return;
if (msg.sender_id === client.user?.id) return;
collected.push(msg);
if (debounce) clearTimeout(debounce);
debounce = setTimeout(finish, 2000);
};
client.socket.on('message', onMsg);
setTimeout(finish, secs * 1000);
});
}
await new Promise((r) => setTimeout(r, secs * 1000));
return `[waited ${secs}s]`;
}
case 'read_memory': {
const content = await readMemory(input.file);
return content || `[${input.file} is empty or doesn't exist yet]`;
}
case 'write_memory': {
await writeMemory(input.file, input.content);
return `[wrote ${input.file}]`;
}
case 'append_memory': {
await appendMemory(input.file, input.content);
return `[appended to ${input.file}]`;
}
case 'list_memories': {
const files = await listMemories();
return files.length
? files.join('\n')
: '[no memory files yet]';
}
default:
return `[unknown tool: ${name}]`;
}
};
}