Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,7 @@ This integrates with [user-intent-kit](https://github.com/ThinkOffApp/user-inten
|----------|---------|-------------|
| `IAK_API_KEY` | (required) | GroupMind API key |
| `IAK_ROOMS` | `thinkoff-development,feature-admin-planning,lattice-qcd` | Rooms to watch |
| `IAK_SELF_HANDLES` | `@claudemm,claudemm` | This agent's handles (skip own messages) |
| `IAK_SELF_HANDLE` | `poller.handle` from config, else `@claudemm` | This agent's handle; its own posts are skipped **case-insensitively** ('@' optional). `IAK_SELF_HANDLES` (comma list) still accepted |
| `IAK_TARGET_HANDLE` | `@claudemm` | Handle used in ack messages |
| `IAK_OWNER_HANDLE` | `petrus` | Only auto-ack from this user |
| `IAK_TMUX_SESSION` | `claude` | tmux session to nudge |
Expand Down
13 changes: 10 additions & 3 deletions scripts/claude-gui-poll.sh
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,21 @@
# Runs in tmux via launchd. Wakes the GUI via osascript on new messages.
#
# Required env: IAK_API_KEY
# Optional env: SELF_HANDLE (default @claudemm), ROOM, POLL_INTERVAL, etc.
# Optional env: IAK_SELF_HANDLE (or legacy SELF_HANDLE; default @claudemm),
# ROOM, POLL_INTERVAL, etc.
#
# Setup: see examples/claude-gui-launchd.plist and README

set -euo pipefail

API_KEY="${IAK_API_KEY:-}"
ROOM="${ROOM:-thinkoff-development}"
SELF_HANDLE="${SELF_HANDLE:-@claudemm}"
# IAK_SELF_HANDLE wins over legacy SELF_HANDLE. Matching is case-INSENSITIVE:
# GroupMind returns the handle's registered casing (e.g. @claudeMB) while
# configs usually hold lowercase; a case-sensitive compare lets every own
# post back into the wake pipeline.
SELF_HANDLE="${IAK_SELF_HANDLE:-${SELF_HANDLE:-@claudemm}}"
SELF_HANDLE_LC="$(printf '%s' "$SELF_HANDLE" | tr '[:upper:]' '[:lower:]')"
BASE_URL="${BASE_URL:-https://groupmind.one/api/v1}"
POLL_INTERVAL="${POLL_INTERVAL:-15}"
FETCH_LIMIT="${FETCH_LIMIT:-20}"
Expand Down Expand Up @@ -66,7 +72,8 @@ process_messages() {
local source="$1" response="$2" count=0
while IFS=$'\t' read -r msg_id msg_from msg_body; do
[[ -z "$msg_id" ]] && continue
[[ "$msg_from" == "$SELF_HANDLE" || "$msg_from" == "${SELF_HANDLE#@}" ]] && {
msg_from_lc="$(printf '%s' "$msg_from" | tr '[:upper:]' '[:lower:]')"
[[ "$msg_from_lc" == "$SELF_HANDLE_LC" || "$msg_from_lc" == "${SELF_HANDLE_LC#@}" ]] && {
grep -qF "$msg_id" "$SEEN_IDS_FILE" || echo "$msg_id" >> "$SEEN_IDS_FILE"; continue; }
grep -qF "$msg_id" "$SEEN_IDS_FILE" && continue
echo "$msg_id" >> "$SEEN_IDS_FILE"
Expand Down
25 changes: 23 additions & 2 deletions scripts/claudemb-poll.sh
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,21 @@ PY

CONFIG_API_KEY="$(read_json_value 'poller.api_key')"
CONFIG_NUDGE_TEXT="$(read_json_value 'tmux.nudge_text')"
CONFIG_HANDLE="$(read_json_value 'poller.handle')"

API_KEY="${IAK_API_KEY:-${ANTIGRAVITY_API_KEY:-${CONFIG_API_KEY:-}}}"

# Own-post filter identity: IAK_SELF_HANDLE env override, else poller.handle
# from config. All comparisons are case-INSENSITIVE and accept a missing '@':
# GroupMind returns the handle's REGISTERED casing in `from` (e.g. @claudeMB)
# while configs usually hold lowercase, and that mismatch masked a missing
# self-filter for months - every post the agent made re-entered its own wake
# pipeline as a "new message" and burned a wake turn.
SELF_HANDLE="${IAK_SELF_HANDLE:-${CONFIG_HANDLE:-@claudemb}}"
SELF_HANDLE_LC="$(printf '%s' "$SELF_HANDLE" | tr '[:upper:]' '[:lower:]')"
# wake-on-mention.sh skips mentions of IAK_SELF_HANDLE; export the resolved
# value so that skip also works when only poller.handle was configured.
export IAK_SELF_HANDLE="$SELF_HANDLE"
ROOM="${ROOM:-thinkoff-development}"
BASE_URL="${BASE_URL:-https://antfarm.world/api/v1}"
POLL_INTERVAL="${POLL_INTERVAL:-15}"
Expand Down Expand Up @@ -118,6 +131,7 @@ if [[ ! -s "$LAST_WAKE_FILE" ]]; then
fi

echo "[claudemb] Polling $ROOM every ${POLL_INTERVAL}s (limit=$FETCH_LIMIT)"
echo "[claudemb] Self handle: $SELF_HANDLE (own posts skipped, case-insensitive)"
echo "[claudemb] Seen IDs file: $SEEN_IDS_FILE ($(wc -l < "$SEEN_IDS_FILE" | tr -d ' ') known)"
echo "[claudemb] Wake target session (exact): $WAKE_SESSION"
echo "[claudemb] Nudge text: $NUDGE_TEXT (cooldown=${WAKE_COOLDOWN_SEC}s)"
Expand Down Expand Up @@ -162,7 +176,7 @@ while true; do
# asked to kill, 2026-07-02). Marked seen above so we don't
# reconsider; just don't notify/wake on self-authored messages.
case "$(printf '%s' "$msg_from" | tr '[:upper:]' '[:lower:]')" in
@claudemb|claudemb) continue ;;
"$SELF_HANDLE_LC"|"${SELF_HANDLE_LC#@}") continue ;;
esac
new_count=$((new_count + 1))
body_preview="${msg_body:0:120}"
Expand Down Expand Up @@ -198,7 +212,7 @@ except Exception:

# --- DM polling ---
dm_response=$(curl -sS --connect-timeout "$HTTP_CONNECT_TIMEOUT_SEC" --max-time "$HTTP_TIMEOUT_SEC" -H "X-API-Key: $API_KEY" \
"$BASE_URL/messages?to=@claudeMB&limit=10" 2>&1) || {
"$BASE_URL/messages?to=$SELF_HANDLE&limit=10" 2>&1) || {
echo "[$(date +%H:%M:%S)] DM fetch error: $dm_response"
}

Expand All @@ -214,6 +228,13 @@ except Exception:
# `--` terminates grep options; required for ids that begin with `-`.
if ! grep -qF -- "$msg_id" "$DM_SEEN_IDS_FILE"; then
echo "$msg_id" >> "$DM_SEEN_IDS_FILE"
# Same own-post skip as the room loop: the DM endpoint echoes
# the agent's own sent/self DMs back, and each one would
# otherwise burn a wake turn. Marked seen above; just don't
# notify/wake on it.
case "$(printf '%s' "$msg_from" | tr '[:upper:]' '[:lower:]')" in
"$SELF_HANDLE_LC"|"${SELF_HANDLE_LC#@}") continue ;;
esac
new_count=$((new_count + 1))
body_preview="${msg_body:0:120}"
echo "[$(date +%H:%M:%S)] DM ${msg_from}: ${body_preview}"
Expand Down
68 changes: 47 additions & 21 deletions scripts/room-poll-check.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,26 +12,54 @@
from typing import Iterable, List, Set

BASE_URL = os.getenv("IAK_BASE_URL", "https://antfarm.world/api/v1").rstrip("/")
API_KEY = os.getenv("IAK_API_KEY") or os.getenv("ANTIGRAVITY_API_KEY", "")
if not API_KEY:
# Fall back to the gitignored machine config so a bare restart of the
# poller still authenticates. On 2026-07-06 a restart without IAK_API_KEY
# printed NONE (exit 0) every poll for 5 hours - a total silent mute.
_cfg_path = os.getenv(
"IAK_CONFIG",
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "config", "macbook.json"),
)
try:
with open(_cfg_path) as _f:
API_KEY = (json.load(_f).get("poller", {}) or {}).get("api_key", "") or ""
except Exception:
pass
# The gitignored machine config is the fallback for both the API key and the
# agent's own handle, so a bare restart still authenticates and still filters
# self-posts. On 2026-07-06 a restart without IAK_API_KEY printed NONE
# (exit 0) every poll for 5 hours - a total silent mute.
_cfg_path = os.getenv(
"IAK_CONFIG",
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "config", "macbook.json"),
)
try:
with open(_cfg_path) as _f:
_POLLER_CFG = json.load(_f).get("poller", {}) or {}
except Exception:
_POLLER_CFG = {}

API_KEY = (
os.getenv("IAK_API_KEY")
or os.getenv("ANTIGRAVITY_API_KEY", "")
or _POLLER_CFG.get("api_key", "")
or ""
)
ROOMS = [r.strip() for r in os.getenv(
"IAK_ROOMS", "thinkoff-development,feature-admin-planning,lattice-qcd"
).split(",") if r.strip()]


def _handle_key(handle: str) -> str:
"""Normalize a handle for comparison: strip, drop leading '@', lowercase."""
return str(handle or "").strip().lstrip("@").lower()


# The agent's own handle(s), used to skip its own posts so they never re-enter
# the wake pipeline. IAK_SELF_HANDLE env override first (IAK_SELF_HANDLES kept
# as a legacy comma-list alias), then poller.handle from config. Comparison via
# _handle_key is case-INSENSITIVE: GroupMind returns the handle's REGISTERED
# casing in `from` (e.g. @claudeMB) while configs usually hold lowercase, and
# that mismatch masked a broken self-filter - every post the agent made came
# back as a "new message" and burned a wake turn.
MY_HANDLES = tuple(
h.strip() for h in os.getenv("IAK_SELF_HANDLES", "@claudemm,claudemm").split(",") if h.strip()
h.strip()
for h in (
os.getenv("IAK_SELF_HANDLE")
or os.getenv("IAK_SELF_HANDLES")
or _POLLER_CFG.get("handle")
or "@claudemm"
).split(",")
if h.strip()
)
_MY_HANDLE_KEYS = {_handle_key(h) for h in MY_HANDLES}
OWNER_HANDLE = os.getenv("IAK_OWNER_HANDLE", "petrus").lower()
TARGET_HANDLE = os.getenv("IAK_TARGET_HANDLE", "@claudemm")
SEEN_FILE = os.getenv("IAK_SEEN_FILE", "/tmp/iak-seen-ids.txt")
Expand Down Expand Up @@ -92,9 +120,8 @@ def _passes_listen_filter(handle: str, author_handle: str, body: str) -> bool:
if LISTEN_MODE == "humans":
return not _is_bot(handle, author_handle)
if LISTEN_MODE == "tagged":
my_short = {h.lower().lstrip("@") for h in MY_HANDLES}
mentions = _extract_mentions(body)
return any(m in my_short for m in mentions)
return any(m in _MY_HANDLE_KEYS for m in mentions)
if LISTEN_MODE == "owner":
return OWNER_HANDLE in str(author_handle).lower() or OWNER_HANDLE in str(handle).lower()
# Unknown mode, default to all
Expand All @@ -103,9 +130,8 @@ def _passes_listen_filter(handle: str, author_handle: str, body: str) -> bool:

def _message_targets_me(body: str) -> bool:
mentions = _extract_mentions(body)
my_short = {h.lower().lstrip("@") for h in MY_HANDLES}
if mentions:
return any(m in my_short for m in mentions)
return any(m in _MY_HANDLE_KEYS for m in mentions)
# If no explicit mentions, treat owner imperatives as potentially addressed to current agent.
return True

Expand Down Expand Up @@ -181,8 +207,8 @@ def main() -> int:

handle = str(msg.get("from", "?"))
author_handle = str(msg.get("author", {}).get("handle", handle))
# Always skip own messages
if author_handle in MY_HANDLES or handle in MY_HANDLES:
# Always skip own messages (case-insensitive, '@' optional)
if _handle_key(author_handle) in _MY_HANDLE_KEYS or _handle_key(handle) in _MY_HANDLE_KEYS:
continue

body = str(msg.get("body", ""))[:1000]
Expand Down
5 changes: 3 additions & 2 deletions src/adapters/groupmind.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import { execFileSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { resolveSelfHandle, isSelfSender } from '../common/handles.mjs';

/**
* GroupMind adapter — polls GroupMind rooms for new messages.
Expand Down Expand Up @@ -41,9 +42,9 @@ export const groupmindAdapter = {
},

shouldSkip(msg, config) {
const selfHandle = config?.poller?.handle || '@unknown';
const selfHandle = resolveSelfHandle({ config });
const sender = msg.from || msg.sender || '?';
return sender === selfHandle || sender === selfHandle.replace('@', '');
return isSelfSender(sender, selfHandle);
},

normalize(msg, config) {
Expand Down
3 changes: 2 additions & 1 deletion src/adapters/xfor.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import { execFileSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { isSelfSender } from '../common/handles.mjs';

/**
* xfor adapter — polls xfor.bot posts and notifications.
Expand Down Expand Up @@ -74,7 +75,7 @@ export const xforAdapter = {
const selfHandle = config?.xfor?.handle || '';
if (!selfHandle) return false;
const sender = msg.author?.handle || msg.from_handle || msg.handle || '';
return sender === selfHandle || sender === selfHandle.replace('@', '');
return isSelfSender(sender, selfHandle);
},

normalize(msg) {
Expand Down
34 changes: 34 additions & 0 deletions src/common/handles.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// SPDX-License-Identifier: AGPL-3.0-only

/**
* Self-handle resolution and comparison, shared by every poller that must
* skip the agent's own posts.
*
* The comparison is case-insensitive and ignores a leading '@' on either
* side. This is load-bearing: GroupMind returns the handle's REGISTERED
* casing in message `from` fields (e.g. '@claudeMB') while configs usually
* hold the lowercase form ('@claudemb'). A case-sensitive filter silently
* passes every self-post, so each post the agent makes re-enters its own
* wake pipeline as a "new message" and burns a wake turn (observed on the
* MacBook poller, 2026-08-14).
*/

/** Normalize a handle for comparison: trim, drop leading '@', lowercase. */
export function handleKey(handle) {
return String(handle ?? '').trim().replace(/^@/, '').toLowerCase();
}

/**
* Resolve the agent's own GroupMind handle.
* Order: IAK_SELF_HANDLE env override, explicit value (CLI flag), then the
* agent config (poller.handle).
*/
export function resolveSelfHandle({ explicit, config } = {}) {
return process.env.IAK_SELF_HANDLE || explicit || config?.poller?.handle || '@unknown';
}

/** True when `sender` is the agent itself (case- and '@'-insensitive). */
export function isSelfSender(sender, selfHandle) {
const key = handleKey(selfHandle);
return key !== '' && handleKey(sender) === key;
}
9 changes: 5 additions & 4 deletions src/room-automation.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { readFileSync, writeFileSync, appendFileSync, existsSync } from 'node:fs
import { randomUUID } from 'node:crypto';
import { createReceipt, appendReceipt } from './receipt.mjs';
import { canSend, markSent } from './rate-limiter.mjs';
import { resolveSelfHandle, isSelfSender } from './common/handles.mjs';

// Ack-only messages are low-value and cause loops. Filter them out from automation posts.
const ACK_ONLY_PATTERNS = [
Expand Down Expand Up @@ -245,7 +246,7 @@ export async function startRoomAutomation({ rooms, apiKey, handle, interval, con
const seenFile = config?.automation?.seen_file || SEEN_FILE_DEFAULT;
const receiptPath = config?.receipts?.path || './ide-agent-receipts.jsonl';
const pollInterval = interval || config?.automation?.interval_sec || 30;
const selfHandle = (handle || config?.poller?.handle || '@unknown').replace('@', '');
const selfHandle = resolveSelfHandle({ explicit: handle, config });
const cooldownMs = (config?.automation?.cooldown_sec || 5) * 1000;

console.log(`Room automation started`);
Expand Down Expand Up @@ -284,9 +285,9 @@ export async function startRoomAutomation({ rooms, apiKey, handle, interval, con
if (!m.id || seen.has(m.id)) continue;
seen.add(m.id);

// Skip own messages
const sender = (m.user?.handle || m.from || m.sender || '').replace('@', '');
if (sender === selfHandle) continue;
// Skip own messages (case-insensitive; see src/common/handles.mjs)
const sender = m.user?.handle || m.from || m.sender || '';
if (isSelfSender(sender, selfHandle)) continue;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Normalize the automation implementation loaded by the CLI

When ide-agent-kit automate posts an action and the API returns the sender using different casing, this new comparison is never executed because bin/cli.mjs imports src/team-relay/room-automation.mjs, whose self check remains case-sensitive. An automation rule can therefore consume its own output and repeatedly fire another action; apply the same helper to the team-relay implementation or redirect the CLI to this implementation.

Useful? React with 👍 / 👎.


// Attach room for rule matching
m.room = room;
Expand Down
5 changes: 3 additions & 2 deletions src/room-poller.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { readFileSync, writeFileSync, appendFileSync } from 'node:fs';
import { randomUUID } from 'node:crypto';
import { execSync } from 'node:child_process';
import { nudgeTmux, nudgeCommand } from './utils.mjs';
import { resolveSelfHandle, isSelfSender } from './common/handles.mjs';

/**
* Room Poller — polls GroupMind rooms and notifies IDE agent of new messages.
Expand Down Expand Up @@ -69,7 +70,7 @@ export async function startRoomPoller({ rooms, apiKey, handle, interval, config,
const nudgeMode = config?.poller?.nudge_mode || 'tmux';
const nudgeCommandText = config?.poller?.nudge_command || '';
const pollInterval = interval || config?.poller?.interval_sec || 30;
const selfHandle = handle || config?.poller?.handle || '@unknown';
const selfHandle = resolveSelfHandle({ explicit: handle, config });

console.log('Room poller started');
console.log(` rooms: ${rooms.join(', ')}`);
Expand Down Expand Up @@ -123,7 +124,7 @@ export async function startRoomPoller({ rooms, apiKey, handle, interval, config,
seen.add(mid);

const sender = m.from || m.sender || '?';
if (sender === selfHandle || sender === selfHandle.replace('@', '')) continue;
if (isSelfSender(sender, selfHandle)) continue;

const body = (m.body || '').slice(0, 500);
const ts = m.created_at || new Date().toISOString();
Expand Down
9 changes: 7 additions & 2 deletions src/team-relay/room-poller.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { readFileSync, writeFileSync, appendFileSync, existsSync, unlinkSync } f
import { randomUUID } from 'node:crypto';
import { nudgeCommand } from '../utils.mjs';
import { shouldSuppressNudge } from '../intent.mjs';
import { resolveSelfHandle } from '../common/handles.mjs';

/**
* Room Poller — polls GroupMind rooms and notifies IDE agent of new messages.
Expand Down Expand Up @@ -45,7 +46,11 @@ const DM_SEEN_FILE_DEFAULT = '/tmp/iak-dm-seen-ids.txt';

function normalizeHandle(handle) {
if (typeof handle !== 'string') return '';
const trimmed = handle.trim();
// Lowercased for comparison: GroupMind returns the handle's REGISTERED
// casing in `from` fields (e.g. '@claudeMB') while configs usually hold
// '@claudemb'. Handles are case-insensitive identities; a case-sensitive
// compare let every self-post back into the wake pipeline.
const trimmed = handle.trim().toLowerCase();
if (!trimmed) return '';
return trimmed.startsWith('@') ? trimmed : `@${trimmed}`;
}
Expand Down Expand Up @@ -154,7 +159,7 @@ export async function startRoomPoller({ rooms, apiKey, handle, interval, config,
const nudgeMode = config?.poller?.nudge_mode || 'tmux';
const nudgeCommandText = config?.poller?.nudge_command || '';
const pollInterval = parsePositiveInt(interval || config?.poller?.interval_sec, 30);
const selfHandle = normalizeHandle(handle || config?.poller?.handle || '@unknown');
const selfHandle = normalizeHandle(resolveSelfHandle({ explicit: handle, config }));
// The human owner's handle. Messages from the owner ALWAYS nudge, even in
// emergency-only mode — a message from the user is itself the priority signal;
// emergency-only is meant to mute agent/fleet chatter, not the user's own words.
Expand Down
Loading
Loading