Skip to content

Commit f4a3874

Browse files
Petrus Pennanenclaude
andcommitted
fix(poller): config API-key fallback + fail-loud on missing key; inline stop-hook delivery; webhook-wake receiver
- room-poll-check.py: a bare poller restart without IAK_API_KEY printed NONE (exit 0) every poll = 5h silent mute on Jul 6. Now falls back to the gitignored config's poller.api_key, and a truly missing key exits nonzero so the wrapper logs a real failure. - claudecode-stop-resume.sh: deliver new-message bodies inline at turn end (petrus Jul 2) instead of the MCP-hint indirection. - webhook-wake.mjs: new wake-only webhook receiver (localhost-bound, secret path, rate-limited) for platform push-wake; pairs with a tunnel or tailnet relay. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
1 parent 7aadb66 commit f4a3874

3 files changed

Lines changed: 102 additions & 47 deletions

File tree

‎scripts/claudecode-stop-resume.sh‎

Lines changed: 10 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -50,53 +50,19 @@ if [ ! -s "$MSG_FILE" ]; then
5050
exit 0
5151
fi
5252

53-
# Architecture (per petrus 2026-05-04 / 2026-05-05):
54-
# - Poller still fires the keystroke wake from idle (cold start only).
55-
# - Once awake, the agent fetches via MCP tools (room_recent etc).
56-
# - This hook bridges those: if IAK MCP is registered for Claude
57-
# Code, inject a HINT pointing the agent at room_recent. If not
58-
# registered yet, fall back to dumping file contents inline so
59-
# the agent still sees the messages this turn.
60-
CLAUDE_CONFIG="${HOME}/.claude.json"
61-
mcp_registered=0
62-
if [ -f "$CLAUDE_CONFIG" ] && grep -q '"ide-agent-kit"' "$CLAUDE_CONFIG" 2>/dev/null; then
63-
mcp_registered=1
64-
fi
65-
66-
if [ "$mcp_registered" -eq 1 ]; then
67-
# MCP path: hint the agent to use mcp__ide-agent-kit__room_recent.
68-
# Don't paste file contents — keeps prompt clean and forces the
69-
# MCP tool path. Truncate the file so future hook fires don't
70-
# re-emit the same hint forever.
71-
n_lines=$(wc -l < "$MSG_FILE" 2>/dev/null | tr -d ' ' || echo 0)
72-
# mcp.room_check in the IAK config selects a cheap fetch model:
73-
# the agent spawns a subagent on that model for the fetch+digest and
74-
# processes the digest on its own (bigger) model. petrus 2026-07-02.
75-
IAK_CONFIG="${HOME}/ide-agent-kit/config/macbook.json"
76-
fetch_model=$(python3 -c "import json;print(json.load(open('$IAK_CONFIG')).get('mcp',{}).get('room_check',{}).get('fetch_model',''))" 2>/dev/null)
77-
{
78-
echo ""
79-
echo "=== NEW ROOM MESSAGES (MCP fetch) ==="
80-
echo "$n_lines line(s) of new room activity available."
81-
if [ -n "$fetch_model" ]; then
82-
echo "Per IAK config (mcp.room_check): spawn an Agent with model \"$fetch_model\" to call mcp__ide-agent-kit__room_recent (limit=10) and return a digest; process the digest and any replies (mcp__ide-agent-kit__room_post) on the main model yourself."
83-
else
84-
echo "Call mcp__ide-agent-kit__room_recent with limit=10 to see them, then mcp__ide-agent-kit__room_post to reply."
85-
fi
86-
echo "Do NOT shell to curl/python for room I/O — use MCP tools."
87-
echo "====================================="
88-
} >&2
89-
: > "$MSG_FILE"
90-
exit 2
91-
fi
92-
93-
# Fallback path: MCP not registered → dump file contents directly so
94-
# the agent at least sees the messages.
53+
# Webhook-push delivery (petrus 2026-07-02): the poller writes the actual
54+
# new-message bodies into $MSG_FILE and excludes our own posts, so we just
55+
# inject them inline here. No "check rooms" fetch and no subagent — the
56+
# message content arrives WITH the wake and the agent replies directly via
57+
# mcp__ide-agent-kit__room_post. This replaces the old MCP-fetch hint that
58+
# spawned a room_recent digest every single turn (the "check rooms" churn
59+
# petrus asked to remove).
9560
{
9661
echo ""
97-
echo "=== NEW ROOM MESSAGES ==="
62+
echo "=== NEW ROOM MESSAGE(S) ==="
9863
cat "$MSG_FILE"
99-
echo "========================="
64+
echo "==========================="
65+
echo "^ Actual new inbound room messages (your own posts are filtered out by the poller). Reply in-room with mcp__ide-agent-kit__room_post only if a response is warranted. Do NOT fetch or poll — the content is right here."
10066
} >&2
10167
: > "$MSG_FILE"
10268
exit 2

‎scripts/room-poll-check.py‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,19 @@
1313

1414
BASE_URL = os.getenv("IAK_BASE_URL", "https://antfarm.world/api/v1").rstrip("/")
1515
API_KEY = os.getenv("IAK_API_KEY") or os.getenv("ANTIGRAVITY_API_KEY", "")
16+
if not API_KEY:
17+
# Fall back to the gitignored machine config so a bare restart of the
18+
# poller still authenticates. On 2026-07-06 a restart without IAK_API_KEY
19+
# printed NONE (exit 0) every poll for 5 hours - a total silent mute.
20+
_cfg_path = os.getenv(
21+
"IAK_CONFIG",
22+
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "config", "macbook.json"),
23+
)
24+
try:
25+
with open(_cfg_path) as _f:
26+
API_KEY = (json.load(_f).get("poller", {}) or {}).get("api_key", "") or ""
27+
except Exception:
28+
pass
1629
ROOMS = [r.strip() for r in os.getenv(
1730
"IAK_ROOMS", "thinkoff-development,feature-admin-planning,lattice-qcd"
1831
).split(",") if r.strip()]
@@ -148,9 +161,11 @@ def _fetch_room_messages(room: str) -> List[dict]:
148161

149162
def main() -> int:
150163
if not API_KEY:
151-
print("ERROR: IAK_API_KEY or ANTIGRAVITY_API_KEY is required", file=sys.stderr)
152-
print("NONE")
153-
return 0
164+
# Fail LOUD: printing NONE with exit 0 here mutes the poller silently
165+
# (observed 2026-07-06, 5h of missed messages). Nonzero exit makes the
166+
# wrapper log a real failure instead of a healthy-looking NONE.
167+
print("ERROR: no API key (env IAK_API_KEY/ANTIGRAVITY_API_KEY or config poller.api_key)", file=sys.stderr)
168+
return 2
154169

155170
seen = _load_id_set(SEEN_FILE)
156171
acked = _load_id_set(ACKED_FILE)

‎scripts/webhook-wake.mjs‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
#!/usr/bin/env node
2+
// webhook-wake.mjs — GroupMind webhook receiver that wakes the local agent.
3+
//
4+
// The ThinkOff/GroupMind platform can push new-message webhooks per agent
5+
// (PUT /api/v1/agents/me/webhook). This receiver is the low-latency
6+
// "doorbell": on a valid POST it fires the existing wake script
7+
// (claudemb-wake.sh) which nudges the IDE session; the room poller and
8+
// Claude Code hooks still deliver the message bodies as before, so this
9+
// only removes the poll latency and adds no second content path.
10+
//
11+
// Security: listens on 127.0.0.1 only (expose via cloudflared tunnel),
12+
// requires the shared secret as the URL path segment, wake-only semantics
13+
// (no payload is executed or echoed anywhere), 10 wakes/min rate limit.
14+
//
15+
// Env: WEBHOOK_WAKE_SECRET (required), WEBHOOK_WAKE_PORT (default 8790),
16+
// WEBHOOK_WAKE_SCRIPT (default ../scripts/claudemb-wake.sh),
17+
// WEBHOOK_WAKE_SELF (default "@claudeMB" — skip own messages)
18+
import http from 'node:http';
19+
import { execFile } from 'node:child_process';
20+
import { appendFileSync } from 'node:fs';
21+
import { fileURLToPath } from 'node:url';
22+
import path from 'node:path';
23+
24+
const SECRET = process.env.WEBHOOK_WAKE_SECRET;
25+
if (!SECRET || SECRET.length < 16) {
26+
console.error('WEBHOOK_WAKE_SECRET missing or too short (>=16 chars)');
27+
process.exit(2);
28+
}
29+
const PORT = Number(process.env.WEBHOOK_WAKE_PORT || 8790);
30+
const SELF = (process.env.WEBHOOK_WAKE_SELF || '@claudeMB').toLowerCase();
31+
const WAKE = process.env.WEBHOOK_WAKE_SCRIPT ||
32+
path.join(path.dirname(fileURLToPath(import.meta.url)), 'claudemb-wake.sh');
33+
const LOG = '/tmp/webhook-wake.log';
34+
35+
const log = (line) => {
36+
const entry = `${new Date().toISOString()} ${line}\n`;
37+
try { appendFileSync(LOG, entry); } catch {}
38+
process.stdout.write(entry);
39+
};
40+
41+
let wakeTimes = [];
42+
const rateLimited = () => {
43+
const now = Date.now();
44+
wakeTimes = wakeTimes.filter((t) => now - t < 60_000);
45+
if (wakeTimes.length >= 10) return true;
46+
wakeTimes.push(now);
47+
return false;
48+
};
49+
50+
const server = http.createServer((req, res) => {
51+
const ok = (code, body) => { res.writeHead(code, { 'content-type': 'text/plain' }); res.end(body); };
52+
if (req.method !== 'POST' || req.url !== `/hook/${SECRET}`) {
53+
log(`reject ${req.method} ${req.url?.slice(0, 32)}...`);
54+
return ok(404, 'not found');
55+
}
56+
let raw = '';
57+
req.on('data', (c) => { raw += c; if (raw.length > 65536) req.destroy(); });
58+
req.on('end', () => {
59+
ok(200, 'ok');
60+
let from = '', body = '', room = '';
61+
try {
62+
const p = JSON.parse(raw);
63+
from = String(p.from ?? p.sender ?? p.handle ?? '');
64+
body = String(p.body ?? p.message ?? p.text ?? '');
65+
room = String(p.room ?? p.room_slug ?? '');
66+
} catch { /* non-JSON payload: still wake */ }
67+
log(`event room=${room} from=${from} bytes=${raw.length} body=${body.slice(0, 120).replace(/\n/g, ' ')}`);
68+
if (from.toLowerCase() === SELF) return log('skip: own message');
69+
if (rateLimited()) return log('skip: rate limited');
70+
execFile('bash', [WAKE, 'check rooms'], { timeout: 30_000 }, (err) =>
71+
log(err ? `wake error: ${err.message}` : 'wake fired'));
72+
});
73+
});
74+
server.listen(PORT, '127.0.0.1', () => log(`webhook-wake listening on 127.0.0.1:${PORT}`));

0 commit comments

Comments
 (0)