Skip to content

Commit 1cdb13c

Browse files
ClaudeMMclaude
andcommitted
feat: file-based notification delivery for room poller
Replace tmux-only nudge with a reliable notification file system. The poller now writes human-readable message summaries to a notification file (/tmp/iak-new-messages.txt) that any IDE agent can read, regardless of whether it runs in tmux or not. New commands: - `rooms check` — read and clear new messages from notification file - `rooms watch` — long-running poller using config (replaces `poll`) Also fixes config.mjs dropping the poller section, and removes the ack/heartbeat code that was already disabled. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 6df6ffc commit 1cdb13c

3 files changed

Lines changed: 96 additions & 74 deletions

File tree

‎bin/cli.mjs‎

Lines changed: 51 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { tailReceipts } from '../src/receipt.mjs';
1010
import { startWebhookServer } from '../src/webhook-server.mjs';
1111
import { emitJson } from '../src/emit.mjs';
1212
import { watchQueue } from '../src/watch.mjs';
13-
import { startRoomPoller } from '../src/room-poller.mjs';
13+
import { startRoomPoller, checkRoomMessages } from '../src/room-poller.mjs';
1414
import { memoryList, memoryGet, memorySet, memoryAppend, memoryDelete, memorySearch } from '../src/memory.mjs';
1515
import { triggerAgent, healthCheck, healthDeep, agentsList, configGet, configPatch, gatewayRestart } from '../src/openclaw-gateway.mjs';
1616
import { sessionsSend, sessionsSpawn, sessionsList, sessionsHistory, sessionsStatus } from '../src/openclaw-sessions.mjs';
@@ -47,8 +47,16 @@ Usage:
4747
ide-agent-kit watch [--config <path>]
4848
Watch the event queue and nudge IDE tmux session on new events.
4949
50+
ide-agent-kit rooms check [--config <path>]
51+
Read and display new room messages from the notification file, then clear it.
52+
This is the primary way to retrieve messages from the poller.
53+
54+
ide-agent-kit rooms watch [--config <path>]
55+
Long-running room poller. Writes new messages to a notification file and
56+
optional tmux nudge. Uses rooms/apiKey/handle from config.poller section.
57+
5058
ide-agent-kit poll --rooms <room1,room2> --api-key <key> --handle <@handle> [--interval <sec>] [--config <path>]
51-
Poll Ant Farm rooms directly and nudge IDE tmux session on new messages.
59+
(Legacy) Poll Ant Farm rooms with explicit CLI args. Prefer "rooms watch".
5260
5361
ide-agent-kit memory <list|get|set|append|delete|search> [options]
5462
Manage agent memory (local or OpenClaw backend).
@@ -222,6 +230,47 @@ async function main() {
222230
return;
223231
}
224232

233+
// ── Rooms ──────────────────────────────────────────────
234+
if (command === 'rooms') {
235+
const opts = parseKV(args, subcommand || 'rooms');
236+
const config = loadConfig(opts.config);
237+
238+
if (subcommand === 'check') {
239+
const messages = checkRoomMessages(config);
240+
if (messages.length === 0) {
241+
console.log('No new room messages.');
242+
} else {
243+
console.log(`${messages.length} new message(s):\n`);
244+
for (const line of messages) {
245+
console.log(line);
246+
}
247+
}
248+
return;
249+
}
250+
251+
if (subcommand === 'watch') {
252+
const pollerRooms = config?.poller?.rooms;
253+
const pollerApiKey = config?.poller?.api_key;
254+
const pollerHandle = config?.poller?.handle;
255+
if (!pollerRooms || !pollerApiKey || !pollerHandle) {
256+
console.error('Error: poller.rooms, poller.api_key, and poller.handle must be set in config');
257+
process.exit(1);
258+
}
259+
await startRoomPoller({
260+
rooms: pollerRooms,
261+
apiKey: pollerApiKey,
262+
handle: pollerHandle,
263+
interval: opts.interval ? parseInt(opts.interval) : undefined,
264+
config
265+
});
266+
return;
267+
}
268+
269+
console.error('Usage: ide-agent-kit rooms <check|watch> [--config <path>]');
270+
process.exit(1);
271+
}
272+
273+
// ── Legacy Poll (prefer "rooms watch") ────────────────
225274
if (command === 'poll') {
226275
const opts = parseKV(args, 'poll');
227276
if (!opts.rooms || !opts['api-key'] || !opts.handle) {

‎src/config.mjs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ export function loadConfig(configPath) {
5151
github: { ...DEFAULT_CONFIG.comments.github, ...raw.comments?.github }
5252
},
5353
discord: { ...DEFAULT_CONFIG.discord, ...raw.discord },
54-
openclaw: raw.openclaw || {}
54+
openclaw: raw.openclaw || {},
55+
poller: raw.poller || {}
5556
};
5657
}

‎src/room-poller.mjs‎

Lines changed: 43 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,27 @@
11
// SPDX-License-Identifier: AGPL-3.0-only
22

33
import { execSync } from 'node:child_process';
4-
import { readFileSync, writeFileSync, appendFileSync, existsSync } from 'node:fs';
4+
import { readFileSync, writeFileSync, appendFileSync, existsSync, unlinkSync } from 'node:fs';
55
import { randomUUID } from 'node:crypto';
66

77
/**
8-
* Room Poller — polls Ant Farm room API directly and nudges IDE tmux session.
8+
* Room Poller — polls Ant Farm rooms and notifies IDE agent of new messages.
99
* Works for any IDE agent (Claude Code, Codex, Gemini, Cursor).
10-
* No webhooks required — just an API key and a tmux session.
10+
* No webhooks required — just an API key.
11+
*
12+
* Notification delivery (in order of priority):
13+
* 1. Notification file (always) — human-readable file that the IDE agent reads
14+
* 2. tmux nudge (optional) — types "check rooms" into a tmux session
15+
*
16+
* The IDE agent calls `rooms check` to read and clear the notification file.
1117
*
1218
* Usage:
13-
* ide-agent-kit poll --rooms thinkoff-development,feature-admin-planning \
14-
* --api-key <key> --handle @myhandle [--interval 30] [--config <path>]
19+
* ide-agent-kit rooms watch --config <path>
20+
* ide-agent-kit rooms check --config <path>
1521
*/
1622

1723
const SEEN_FILE_DEFAULT = '/tmp/iak-seen-ids.txt';
24+
const NOTIFY_FILE_DEFAULT = '/tmp/iak-new-messages.txt';
1825

1926
function loadSeenIds(path) {
2027
try {
@@ -61,8 +68,26 @@ async function fetchRoomMessages(room, apiKey, limit = 10) {
6168
}
6269
}
6370

71+
/**
72+
* Read and clear the notification file. Returns array of message lines.
73+
* This is the primary way the IDE agent retrieves new messages.
74+
*/
75+
export function checkRoomMessages(config) {
76+
const notifyFile = config?.poller?.notification_file || NOTIFY_FILE_DEFAULT;
77+
try {
78+
const content = readFileSync(notifyFile, 'utf8').trim();
79+
if (!content) return [];
80+
// Clear the file after reading
81+
writeFileSync(notifyFile, '');
82+
return content.split('\n').filter(Boolean);
83+
} catch {
84+
return [];
85+
}
86+
}
87+
6488
export async function startRoomPoller({ rooms, apiKey, handle, interval, config }) {
6589
const seenFile = config?.poller?.seen_file || SEEN_FILE_DEFAULT;
90+
const notifyFile = config?.poller?.notification_file || NOTIFY_FILE_DEFAULT;
6691
const queuePath = config?.queue?.path || './ide-agent-queue.jsonl';
6792
const session = config?.tmux?.ide_session || config?.tmux?.default_session || 'claude';
6893
const nudgeText = config?.tmux?.nudge_text || 'check rooms';
@@ -73,7 +98,8 @@ export async function startRoomPoller({ rooms, apiKey, handle, interval, config
7398
console.log(` rooms: ${rooms.join(', ')}`);
7499
console.log(` handle: ${selfHandle} (messages from self are ignored)`);
75100
console.log(` interval: ${pollInterval}s`);
76-
console.log(` tmux session: ${session}`);
101+
console.log(` notification file: ${notifyFile}`);
102+
console.log(` tmux session: ${session} (optional)`);
77103
console.log(` seen file: ${seenFile}`);
78104
console.log(` queue: ${queuePath}`);
79105

@@ -92,59 +118,10 @@ export async function startRoomPoller({ rooms, apiKey, handle, interval, config
92118
console.log(` seeded ${seen.size} IDs`);
93119
}
94120

95-
const ackEnabled = config?.poller?.ack_enabled !== false;
96-
const ownerHandle = (config?.poller?.owner_handle || 'petrus').toLowerCase();
97-
98-
const TASK_HINTS = [
99-
'can you', 'please', 'need to', 'check', 'fix', 'update', 'review',
100-
'run', 'deploy', 'implement', 'test', 'restart', 'install', 'respond',
101-
'post', 'pull', 'push', 'merge'
102-
];
103-
104-
function extractMentions(text) {
105-
const matches = text.match(/@([a-zA-Z0-9_.-]+)/g) || [];
106-
return matches.map(m => m.toLowerCase());
107-
}
108-
109-
function messageTargetsMe(body) {
110-
const mentions = extractMentions(body);
111-
const myShort = selfHandle.toLowerCase().replace('@', '');
112-
if (mentions.length > 0) {
113-
return mentions.some(m => m.replace('@', '') === myShort);
114-
}
115-
return true; // Treat generic owner imperatives as targeted
116-
}
117-
118-
function looksLikeTaskRequest(body) {
119-
const text = (body || '').trim().toLowerCase();
120-
if (!text) return false;
121-
return TASK_HINTS.some(hint => text.includes(hint));
122-
}
123-
124-
function shouldAck(sender, body) {
125-
const fromOwner = sender.toLowerCase().includes(ownerHandle);
126-
if (!fromOwner) return false;
127-
if (!messageTargetsMe(body)) return false;
128-
return looksLikeTaskRequest(body);
129-
}
130-
131-
async function postAck(room) {
132-
const payload = JSON.stringify({
133-
room,
134-
body: `@${ownerHandle} [${selfHandle.replace('@', '')}] starting now. I will report back when finished with results.`
135-
});
136-
try {
137-
execSync(
138-
`curl -sS -X POST "https://antfarm.world/api/v1/messages" -H "X-API-Key: ${apiKey}" -H "Content-Type: application/json" -d '${payload.replace(/'/g, "'\\''")}'`,
139-
{ timeout: 15000 }
140-
);
141-
} catch (e) {
142-
console.error(` post ack failed: ${e.message}`);
143-
}
144-
}
145121

146122
async function poll() {
147123
let newCount = 0;
124+
const newMessages = [];
148125
for (const room of rooms) {
149126
const msgs = await fetchRoomMessages(room, apiKey);
150127
for (const m of msgs) {
@@ -159,7 +136,7 @@ export async function startRoomPoller({ rooms, apiKey, handle, interval, config
159136
const body = (m.body || '').slice(0, 500);
160137
const ts = m.created_at || new Date().toISOString();
161138

162-
// Write to queue
139+
// Write to structured queue
163140
const event = {
164141
trace_id: randomUUID(),
165142
event_id: mid,
@@ -171,22 +148,25 @@ export async function startRoomPoller({ rooms, apiKey, handle, interval, config
171148
payload: { body, room }
172149
};
173150
appendFileSync(queuePath, JSON.stringify(event) + '\n');
151+
152+
// Collect for notification file
153+
const line = `[${ts.slice(0, 19)}] [${room}] ${sender}: ${body.replace(/\n/g, ' ').slice(0, 200)}`;
154+
newMessages.push(line);
174155
newCount++;
175156

176157
console.log(` [${ts.slice(0, 19)}] ${sender} in ${room}: ${body.slice(0, 80)}...`);
177-
178-
if (ackEnabled && shouldAck(sender, body)) {
179-
await postAck(room);
180-
console.log(` posted auto-ack for task from ${sender}`);
181-
}
182158
}
183159
}
184160

185161
saveSeenIds(seenFile, seen);
186162

187163
if (newCount > 0) {
164+
// Primary: write to notification file (always works)
165+
appendFileSync(notifyFile, newMessages.join('\n') + '\n');
166+
167+
// Secondary: try tmux nudge (bonus if IDE is in tmux)
188168
const nudged = nudgeTmux(session, nudgeText);
189-
console.log(` ${newCount} new message(s) → ${nudged ? 'nudged' : 'no tmux session'}`);
169+
console.log(` ${newCount} new message(s) → notified${nudged ? ' + tmux nudge' : ''}`);
190170
}
191171
}
192172

@@ -196,18 +176,10 @@ export async function startRoomPoller({ rooms, apiKey, handle, interval, config
196176
// Start interval
197177
const timer = setInterval(poll, pollInterval * 1000);
198178

199-
// Anti-sleep heartbeat (keeps terminal pseudo-active to prevent display-sleep freeze)
200-
const heartbeat = setInterval(() => {
201-
try {
202-
execSync(`tmux send-keys -t ${JSON.stringify(session)} Escape`);
203-
} catch { }
204-
}, 4 * 60 * 1000);
205-
206179
// Handle shutdown
207180
process.on('SIGINT', () => {
208181
console.log('\nPoller stopped.');
209182
clearInterval(timer);
210-
clearInterval(heartbeat);
211183
process.exit(0);
212184
});
213185
process.on('SIGTERM', () => {

0 commit comments

Comments
 (0)