feat(routing): engage modes + sender scope + accumulate/drop + per-agent fan-out
Replaces the opaque trigger_rules JSON + response_scope enum on
messaging_group_agents with four explicit orthogonal columns:
engage_mode 'pattern' | 'mention' | 'mention-sticky'
engage_pattern regex source; required when mode='pattern';
'.' is the "always" sentinel
sender_scope 'all' | 'known'
ignored_message_policy 'drop' | 'accumulate'
Inbound routing becomes a fan-out — every wired agent is evaluated
independently. A match gets its own session + container wake. A miss
with accumulate keeps the message as context-only (trigger=0) in that
agent's session, so when the agent does eventually engage it sees the
prior chatter.
## Schema
- Migration 010 (`engage-modes`): adds the 4 new columns, backfills
from trigger_rules.pattern + requiresTrigger + response_scope, drops
the legacy columns.
- messages_in gains `trigger INTEGER NOT NULL DEFAULT 1` (session DB
schema + `migrateMessagesInTable` forward-compat).
- countDueMessages gates waking on `trigger = 1`.
## Routing
- `pickAgent` (returns one) → loop over all wired agents. Per agent:
evaluate engage_mode; run access gate + sender-scope gate; on full
match → resolveSession + writeSessionMessage(trigger=1) + wake. On
miss with accumulate → writeSessionMessage(trigger=0), no wake. On
miss with drop → skip.
- New `findSessionForAgent(agentGroupId, mgId, threadId)` scopes
session lookup by agent so fan-out doesn't cross sessions.
- `messageIdForAgent` namespaces inbound message ids by agent_group_id
so PRIMARY KEY doesn't collide across per-agent session DBs.
## Adapter layer
- `ConversationConfig` replaces `triggerPattern` + `requiresTrigger`
with `engageMode` + `engagePattern`.
- Chat SDK bridge stores `Map<platformId, ConversationConfig[]>` (multi-
agent per conversation) and applies union gating pre-onInbound:
* onSubscribedMessage: engage if any wiring keeps firing in
subscribed state (mention-sticky or pattern)
* onNewMention: engage on mention; only subscribes the thread if
at least one wiring is `mention-sticky`
* onDirectMessage: engage per mode; sticky follows same rule
- Bridge no longer unconditionally calls `thread.subscribe()`.
## Sender scope
- Permissions module registers a second hook `setSenderScopeGate` that
runs per-wiring after the existing access gate. `sender_scope='known'`
requires canAccessAgentGroup(); `'all'` is a no-op. Not installed →
no-op everywhere (default allow).
## Container side
- Host passes `NANOCLAW_MAX_MESSAGES_PER_PROMPT` (reuses existing
MAX_MESSAGES_PER_PROMPT config; was dead code from v1).
- `getPendingMessages` queries `ORDER BY seq DESC LIMIT N`, reverses to
chronological order for the prompt — accumulated context rides along
with trigger rows up to the cap.
- `MessageInRow` gains `trigger: number` so the container can tell them
apart in downstream code (container still processes both; only the
host uses `trigger=0` for don't-wake).
## Defaults (per ACTION-ITEMS item 1 decision)
- DM (is_group=0): `engage_mode='pattern'`, `engage_pattern='.'` (always)
- Threaded group: `engage_mode='mention-sticky'` (seed-discord)
- Non-threaded group / CLI: pattern '.' in bootstrap scripts
## Tests
- src/host-core.test.ts: 3 new cases — fan-out (2 agents, 2 sessions,
2 wakes), accumulate (trigger=0 + no wake), drop (no session created).
- Existing 10 host-core tests still pass.
- Migration 010 runs on an empty DB in 0-row path — verified.
Closes: ACTION-ITEMS items 1, 4.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -9,8 +9,19 @@
|
||||
export interface ConversationConfig {
|
||||
platformId: string;
|
||||
agentGroupId: string;
|
||||
triggerPattern?: string; // regex string (for native channels)
|
||||
requiresTrigger: boolean;
|
||||
/**
|
||||
* When does the agent engage on messages from this conversation?
|
||||
*
|
||||
* 'pattern' — regex test against message text; engagePattern='.'
|
||||
* means "always" (match everything)
|
||||
* 'mention' — fires only on @mention
|
||||
* 'mention-sticky' — fires on @mention, then auto-subscribes to the thread
|
||||
* and treats subsequent messages as engage-all.
|
||||
* Threaded platforms only (Slack/Discord/Linear).
|
||||
*/
|
||||
engageMode: 'pattern' | 'mention' | 'mention-sticky';
|
||||
/** Regex source when engageMode='pattern'. '.' is the "always" sentinel. */
|
||||
engagePattern?: string | null;
|
||||
sessionMode: 'shared' | 'per-thread' | 'agent-shared';
|
||||
}
|
||||
|
||||
|
||||
@@ -148,8 +148,10 @@ describe('channel + router integration', () => {
|
||||
id: 'mga-1',
|
||||
messaging_group_id: 'mg-1',
|
||||
agent_group_id: 'ag-1',
|
||||
trigger_rules: null,
|
||||
response_scope: 'all',
|
||||
engage_mode: 'pattern',
|
||||
engage_pattern: '.',
|
||||
sender_scope: 'all',
|
||||
ignored_message_policy: 'drop',
|
||||
session_mode: 'shared',
|
||||
priority: 0,
|
||||
created_at: now(),
|
||||
|
||||
@@ -71,23 +71,89 @@ export function createChatSdkBridge(config: ChatSdkBridgeConfig): ChannelAdapter
|
||||
let chat: Chat;
|
||||
let state: SqliteStateAdapter;
|
||||
let setupConfig: ChannelSetup;
|
||||
// NOTE: populated at setup() and updateConversations(), but currently not
|
||||
// read by any inbound handler. When adapter-level gating lands (engage_mode
|
||||
// applied here) or when dynamic group registration is added, this map goes
|
||||
// stale after setup unless updateConversations() is actively called on every
|
||||
// messaging_groups / messaging_group_agents mutation. See ACTION-ITEMS.md
|
||||
// item 17.
|
||||
let conversations: Map<string, ConversationConfig>;
|
||||
// Keyed by platformId. Multiple agents may be wired to the same
|
||||
// conversation — this holds all their configs so the bridge can apply the
|
||||
// most-permissive engage rule at gate time and only subscribe when at
|
||||
// least one wiring requested 'mention-sticky'.
|
||||
//
|
||||
// STALENESS: populated at setup() and updateConversations(). If wirings
|
||||
// change after setup, updateConversations() must be called to refresh
|
||||
// (ACTION-ITEMS item 17).
|
||||
let conversations: Map<string, ConversationConfig[]>;
|
||||
let gatewayAbort: AbortController | null = null;
|
||||
|
||||
function buildConversationMap(configs: ConversationConfig[]): Map<string, ConversationConfig> {
|
||||
const map = new Map<string, ConversationConfig>();
|
||||
function buildConversationMap(configs: ConversationConfig[]): Map<string, ConversationConfig[]> {
|
||||
const map = new Map<string, ConversationConfig[]>();
|
||||
for (const conv of configs) {
|
||||
map.set(conv.platformId, conv);
|
||||
const existing = map.get(conv.platformId);
|
||||
if (existing) existing.push(conv);
|
||||
else map.set(conv.platformId, [conv]);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* Should a message from (channelId, kind) engage any of the wired agents?
|
||||
*
|
||||
* - `mention` — engages only when the message actually @-mentions
|
||||
* the bot (the bridge already sees it here because
|
||||
* Chat SDK only forwards subscribed / mentioned /
|
||||
* DM messages)
|
||||
* - `mention-sticky` — same as `mention` for gating, PLUS we subscribe
|
||||
* the thread so later messages arrive via the
|
||||
* subscribed path and fall through to an
|
||||
* engage-all style treatment
|
||||
* - `pattern` — regex test against message text; `.` = always
|
||||
*
|
||||
* We take the union across wired agents — if any one of them would engage,
|
||||
* the message goes through. Per-agent filtering after that happens in the
|
||||
* host router (see src/router.ts pickAgents).
|
||||
*/
|
||||
function shouldEngage(
|
||||
channelId: string,
|
||||
source: 'subscribed' | 'mention' | 'dm',
|
||||
text: string,
|
||||
): { engage: boolean; stickySubscribe: boolean } {
|
||||
const configs = conversations.get(channelId);
|
||||
// Unknown conversation — forward anyway (may be a new group that
|
||||
// hasn't been registered yet; central routing will log + drop cleanly).
|
||||
if (!configs || configs.length === 0) return { engage: true, stickySubscribe: false };
|
||||
|
||||
let engage = false;
|
||||
let stickySubscribe = false;
|
||||
|
||||
for (const cfg of configs) {
|
||||
switch (cfg.engageMode) {
|
||||
case 'mention':
|
||||
if (source === 'mention' || source === 'dm') engage = true;
|
||||
break;
|
||||
case 'mention-sticky':
|
||||
if (source === 'mention' || source === 'dm') {
|
||||
engage = true;
|
||||
stickySubscribe = true;
|
||||
} else if (source === 'subscribed') {
|
||||
// Thread was already subscribed on a prior mention — treat as
|
||||
// engage-all so follow-ups in the thread reach the agent.
|
||||
engage = true;
|
||||
}
|
||||
break;
|
||||
case 'pattern': {
|
||||
const pattern = cfg.engagePattern ?? '.';
|
||||
try {
|
||||
if (pattern === '.' || new RegExp(pattern).test(text)) engage = true;
|
||||
} catch {
|
||||
// Invalid regex → fail open so the admin can see something and fix.
|
||||
engage = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (engage && stickySubscribe) break;
|
||||
}
|
||||
|
||||
return { engage, stickySubscribe };
|
||||
}
|
||||
|
||||
async function messageToInbound(message: ChatMessage): Promise<InboundMessage> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const serialized = message.toJSON() as Record<string, any>;
|
||||
@@ -166,33 +232,54 @@ export function createChatSdkBridge(config: ChatSdkBridgeConfig): ChannelAdapter
|
||||
logger: 'silent',
|
||||
});
|
||||
|
||||
// Subscribed threads — forward all messages
|
||||
// Subscribed threads — the conversation is already active (via prior
|
||||
// mention-sticky engagement or admin wiring). Gate on engageMode so a
|
||||
// plain 'mention' wiring doesn't keep firing after a one-off mention.
|
||||
chat.onSubscribedMessage(async (thread, message) => {
|
||||
const channelId = adapter.channelIdFromThreadId(thread.id);
|
||||
const text = typeof message.content === 'string' ? message.content : '';
|
||||
const decision = shouldEngage(channelId, 'subscribed', text);
|
||||
if (!decision.engage) return;
|
||||
await setupConfig.onInbound(channelId, thread.id, await messageToInbound(message));
|
||||
});
|
||||
|
||||
// @mention in unsubscribed thread — forward + subscribe
|
||||
// @mention in an unsubscribed thread — always engage; subscribe only
|
||||
// if the wiring is 'mention-sticky'.
|
||||
chat.onNewMention(async (thread, message) => {
|
||||
const channelId = adapter.channelIdFromThreadId(thread.id);
|
||||
const text = typeof message.content === 'string' ? message.content : '';
|
||||
const decision = shouldEngage(channelId, 'mention', text);
|
||||
if (!decision.engage) return;
|
||||
await setupConfig.onInbound(channelId, thread.id, await messageToInbound(message));
|
||||
await thread.subscribe();
|
||||
if (decision.stickySubscribe) {
|
||||
await thread.subscribe();
|
||||
}
|
||||
});
|
||||
|
||||
// DMs — always forward + subscribe. Pass thread.id so sub-thread
|
||||
// context carries through to delivery (Slack users can open threads
|
||||
// inside a DM). The router collapses DM sub-threads to one session
|
||||
// (is_group=0 short-circuits the per-thread escalation).
|
||||
// DMs — apply engage rules too, but DMs typically default to pattern='.'
|
||||
// at setup time so this is a pass-through in practice. sticky subscribe
|
||||
// follows the same rule as a group mention.
|
||||
//
|
||||
// Thread id is passed through so sub-thread context reaches delivery
|
||||
// (Slack users can open threads inside a DM). The router collapses DM
|
||||
// sub-threads to one session (is_group=0 short-circuits the per-thread
|
||||
// escalation).
|
||||
chat.onDirectMessage(async (thread, message) => {
|
||||
const channelId = adapter.channelIdFromThreadId(thread.id);
|
||||
const text = typeof message.content === 'string' ? message.content : '';
|
||||
const decision = shouldEngage(channelId, 'dm', text);
|
||||
log.info('Inbound DM received', {
|
||||
adapter: adapter.name,
|
||||
channelId,
|
||||
sender: (message.author as any)?.fullName ?? (message.author as any)?.userId ?? 'unknown',
|
||||
threadId: thread.id,
|
||||
engage: decision.engage,
|
||||
});
|
||||
if (!decision.engage) return;
|
||||
await setupConfig.onInbound(channelId, thread.id, await messageToInbound(message));
|
||||
await thread.subscribe();
|
||||
if (decision.stickySubscribe) {
|
||||
await thread.subscribe();
|
||||
}
|
||||
});
|
||||
|
||||
// Handle button clicks (ask_user_question)
|
||||
|
||||
Reference in New Issue
Block a user