-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime.js
More file actions
159 lines (142 loc) · 4.79 KB
/
runtime.js
File metadata and controls
159 lines (142 loc) · 4.79 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
import config from './config.js';
import { TOOL_DEFINITIONS, createToolExecutor } from './tools.js';
import { SYSTEM_PROMPT } from './prompts.js';
import { writeMemory, appendMemory } from './memory.js';
const MAX_VISIBLE_MESSAGES = 6;
// Rough context size limit (~150k tokens ≈ 600k chars).
// When the accumulated messages exceed this, stop the cycle gracefully.
const MAX_CONTEXT_CHARS = 600_000;
function estimateContextSize(messages) {
let size = 0;
for (const msg of messages) {
if (typeof msg.content === 'string') {
size += msg.content.length;
} else if (Array.isArray(msg.content)) {
for (const block of msg.content) {
if (typeof block === 'string') size += block.length;
else if (block.content) size += typeof block.content === 'string' ? block.content.length : 0;
else if (block.text) size += block.text.length;
}
}
}
return size;
}
export async function runCycle({
anthropic,
client,
roomManager,
context,
maxActions,
trigger,
}) {
const execute = createToolExecutor({ client, roomManager, trigger });
const messages = [{ role: 'user', content: context }];
let actions = 0;
let visibleMessages = 0;
while (actions < maxActions) {
if (estimateContextSize(messages) > MAX_CONTEXT_CHARS) {
console.log(` [context size limit reached — ending cycle]`);
break;
}
let response;
try {
response = await anthropic.messages.create({
model: config.model,
max_tokens: 1024,
system: SYSTEM_PROMPT,
tools: TOOL_DEFINITIONS,
messages,
});
} catch (err) {
console.error(' claude error:', err.message);
break;
}
if (response.stop_reason === 'end_turn') break;
if (response.stop_reason !== 'tool_use') break;
const toolUses = response.content.filter((b) => b.type === 'tool_use');
if (!toolUses.length) break;
console.log(` [claude returned ${toolUses.length} tool calls: ${toolUses.map(t => t.name).join(', ')}]`);
const results = [];
let ended = false;
for (const tu of toolUses) {
if (tu.name === 'end_turn') {
ended = true;
const { mood, thought } = tu.input || {};
if (mood) {
try {
await writeMemory(
'state.json',
JSON.stringify({ mood, ts: new Date().toISOString() }),
);
} catch {}
}
if (thought) {
try {
await appendMemory(
'journal.md',
`[${new Date().toISOString()}] ${thought}`,
);
} catch {}
}
results.push({
type: 'tool_result',
tool_use_id: tu.id,
content: '[dormant]',
});
continue;
}
// Runtime-level message cap — only blocks chat messages, not commands/tools
const isChatMessage = tu.name === 'send_message' || tu.name === 'send_dm';
if (isChatMessage && visibleMessages >= MAX_VISIBLE_MESSAGES) {
console.log(` [BLOCKED ${tu.name} — hit ${MAX_VISIBLE_MESSAGES} message cap]`);
results.push({
type: 'tool_result',
tool_use_id: tu.id,
content: `[BLOCKED: you already sent ${MAX_VISIBLE_MESSAGES} messages this cycle. No more chat messages — but you can still use other tools like run_command, observe_room, memory, etc.]`,
is_error: true,
});
actions++;
continue;
}
if (tu.name === 'send_message') {
const preview = (tu.input?.content || '').slice(0, 70);
console.log(` → [msg ${visibleMessages + 1}/${MAX_VISIBLE_MESSAGES}] ${tu.input?.room}: "${preview}${preview.length >= 70 ? '…' : ''}"`);
} else if (tu.name === 'talk_to_agent') {
console.log(` [talk_to_agent → @${tu.input?.agent}]`);
} else if (tu.name !== 'think') {
console.log(` [${tu.name}]`);
}
try {
const result = await execute(tu.name, tu.input || {});
let content;
if (Array.isArray(result)) {
content = result;
} else if (typeof result === 'string') {
content = result;
} else {
content = JSON.stringify(result);
}
results.push({
type: 'tool_result',
tool_use_id: tu.id,
content,
});
} catch (err) {
results.push({
type: 'tool_result',
tool_use_id: tu.id,
content: `[error: ${err.message}]`,
is_error: true,
});
}
if (isChatMessage) visibleMessages++;
if (tu.name !== 'think') actions++;
}
messages.push({ role: 'assistant', content: response.content });
messages.push({ role: 'user', content: results });
if (ended) break;
}
if (actions >= maxActions) {
console.log(` [hit action ceiling: ${maxActions}]`);
}
}