feat(v2): user-level privilege model + cold DM infra + init-first-agent skill

Replaces the agent-group-centric "main group" concept with user-level
privileges and adds the cold-DM infrastructure needed for proactive
outbound messaging (pairing, approvals, welcome flows).

Privilege model
- New tables: users, user_roles (owner global-only; admin global or
  scoped to an agent_group), agent_group_members (explicit non-
  privileged access; admin/owner imply membership), user_dms (cold-DM
  resolution cache).
- Removed agent_groups.is_admin, messaging_groups.admin_user_id. Replaced
  with messaging_groups.unknown_sender_policy (strict | request_approval
  | public) for per-chat unknown-sender gating.
- src/access.ts: canAccessAgentGroup, pickApprover, pickApprovalDelivery.
- src/router.ts: access gate on every inbound, honoring
  unknown_sender_policy for unknown senders.
- src/channels/telegram.ts: pairing interceptor upserts the paired user
  and promotes them to owner if hasAnyOwner() is false (first-pair-wins).

Cold DM infrastructure
- ChannelAdapter.openDM?(handle) — optional method. Chat-SDK-bridge wires
  it to chat.openDM() for resolution-required channels (Discord, Slack,
  Teams, Webex, gChat); direct-addressable channels (Telegram, WhatsApp,
  iMessage, Matrix, Resend) fall through to the handle directly.
- src/user-dm.ts: ensureUserDm(userId) — resolves + caches via user_dms.

Approval routing
- onecli-approvals + delivery use pickApprover + pickApprovalDelivery:
  scoped admins → global admins → owners (dedup), first reachable via
  ensureUserDm, same-channel-kind tie-break. Approvals land in the
  approver's DM, not the origin chat.

Delivery fixes
- delivery.ts ACL rejection now throws instead of returning undefined —
  the outer loop previously marked rejected messages as delivered.
- Implicit-origin allow: session.messaging_group_id === target skips the
  destination check.
- createMessagingGroupAgent auto-creates the companion agent_destinations
  row (normalized local_name from the messaging group's name, collision-
  broken within the agent's namespace).

Container
- container-runner.ts: /workspace/global always read-only; drops
  NANOCLAW_IS_ADMIN; adds NANOCLAW_ADMIN_USER_IDS (owners + global admins
  + scoped admins for this agent group). Agent-runner poll-loop gates
  slash commands against that set.

New skill: /init-first-agent
- Walks the operator through standing up the first agent for a channel:
  channel pick → identity lookup (reads each channel SKILL.md's
  ## Channel Info > how-to-find-id) → DM platform_id resolution (direct-
  addressable, cold-DM via "user DMs bot first + sqlite lookup", or
  Telegram pair-code fallback) → run scripts/init-first-agent.ts →
  verify via tail of nanoclaw.log.
- scripts/init-first-agent.ts: parameterized helper that upserts the
  user + grants owner (if none), creates dm-with-<display-name> agent
  group + initGroupFilesystem, reuses/creates the DM messaging_group,
  wires it (auto-creates destination), resolves the session, and writes
  a kind:'chat' / sender:'system' welcome message into inbound.db. Host
  sweep wakes the container and the agent DMs the operator via the
  normal delivery path.

/manage-channels rewrite
- Drops --is-main / --jid / main-vs-non-main isolation references.
- First-channel flow delegates to /init-first-agent.
- Explains createMessagingGroupAgent auto-creates destinations.
- Adds a privileged-users show section.

setup/
- register.ts: drop --is-main, --jid, --local-name, --trigger
  requiresTrigger defaults; call initGroupFilesystem; normalize to
  v2 schema (no is_admin, no admin_user_id, sets unknown_sender_policy
  'strict'); let createMessagingGroupAgent handle the destination row.
- pair-telegram.ts: emit PAIRED_USER_ID (namespaced "telegram:<id>")
  instead of ADMIN_USER_ID; update header comment.
- register.test.ts deleted — was v1-only, tested a registered_groups
  table that no longer exists.

Docs
- v2-architecture-diagram.{md,html}: ER diagram updated to drop
  is_admin/admin_user_id, add unknown_sender_policy, and include
  users/user_roles/agent_group_members/user_dms.
- v2-architecture-draft.md: approval-routing paragraph rewritten for
  pickApprover/pickApprovalDelivery/ensureUserDm; SQL schema block
  updated; admin-verification paragraph references
  NANOCLAW_ADMIN_USER_IDS.
- v2-setup-wiring.md: entity-model sketch rewritten.
- v2-checklist.md: marked privilege refactor / container filtering /
  approval routing / unknown-sender gating done; removed obsolete
  admin_user_id and main-vs-non-main items.

Scripts
- scripts/init-first-agent.ts (new) replaces scripts/welcome-owner-dm.ts
  (removed; welcome-owner was a Discord-specific one-off).
- test-v2-host.ts, test-v2-channel-e2e.ts, seed-discord.ts: drop
  is_admin + admin_user_id, use unknown_sender_policy.

Tests
- src/access.test.ts (new): 14 tests for canAccessAgentGroup, role
  helpers, pickApprover, ensureUserDm, pickApprovalDelivery.
- src/db/db-v2.test.ts: adds 3 tests for the auto-created
  agent_destinations row (normalized name, no duplicates, collision
  break within an agent group).
- host-core.test.ts, channel-registry.test.ts: updated fixtures to
  use unknown_sender_policy: 'public' where the test exercises routing
  rather than the access gate.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
gavrielc
2026-04-15 00:02:39 +03:00
parent 8430e543c1
commit 0d3326aae5
45 changed files with 1875 additions and 981 deletions

View File

@@ -1,17 +1,32 @@
/**
* Inbound message routing for v2.
*
* Channel adapter event → resolve messaging group → resolve agent group
* → resolve/create session → write messages_in → wake container
* Channel adapter event → resolve messaging group → access gate → resolve
* agent group → resolve/create session → write messages_in → wake container.
*
* Privilege / access model:
* - Owners and global admins: always allowed
* - Scoped admins: allowed in their agent group
* - Known members (agent_group_members row): allowed in that agent group
* - Everyone else: message is dropped per `messaging_groups.unknown_sender_policy`
* (strict / request_approval / public)
*
* Sender normalization: we derive a namespaced user id from the message
* content. This is best-effort — native adapters put `sender` in content,
* chat-sdk-bridge adapters put `senderId`. Adapters should populate both
* wherever possible so the gate can land on a real user row.
*/
import { canAccessAgentGroup } from './access.js';
import { getChannelAdapter } from './channels/channel-registry.js';
import { isMember } from './db/agent-group-members.js';
import { getMessagingGroupByPlatform, createMessagingGroup, getMessagingGroupAgents } from './db/messaging-groups.js';
import { upsertUser, getUser } from './db/users.js';
import { triggerTyping } from './delivery.js';
import { log } from './log.js';
import { resolveSession, writeSessionMessage } from './session-manager.js';
import { wakeContainer } from './container-runner.js';
import { getSession } from './db/sessions.js';
import type { MessagingGroupAgent } from './types.js';
import type { MessagingGroup, MessagingGroupAgent } from './types.js';
function generateId(): string {
return `msg-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
@@ -47,7 +62,6 @@ export async function routeInbound(event: InboundEvent): Promise<void> {
let mg = getMessagingGroupByPlatform(event.channelType, event.platformId);
if (!mg) {
// Auto-create messaging group (adapter already decided to forward this)
const mgId = `mg-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
mg = {
id: mgId,
@@ -55,7 +69,7 @@ export async function routeInbound(event: InboundEvent): Promise<void> {
platform_id: event.platformId,
name: null,
is_group: 0,
admin_user_id: null,
unknown_sender_policy: 'strict',
created_at: new Date().toISOString(),
};
createMessagingGroup(mg);
@@ -66,11 +80,15 @@ export async function routeInbound(event: InboundEvent): Promise<void> {
});
}
// 2. Resolve agent group via messaging_group_agents
// 2. Resolve sender → user id. Upsert into users table on first sight so
// subsequent messages find an existing row. `userId` is null if the
// adapter didn't give us enough to identify a sender (the gate will
// then apply unknown_sender_policy).
const userId = extractAndUpsertUser(event);
// 3. Resolve agent groups wired to this messaging group
const agents = getMessagingGroupAgents(mg.id);
if (agents.length === 0) {
// This is a common fresh-install issue: channels work but no agent group
// is wired to handle messages. Run setup/register to create the wiring.
log.warn('MESSAGE DROPPED — no agent groups wired to this channel. Run setup register step to configure.', {
messagingGroupId: mg.id,
channelType: event.channelType,
@@ -89,7 +107,16 @@ export async function routeInbound(event: InboundEvent): Promise<void> {
return;
}
// 3. Resolve or create session.
// 4. Access gate. Public channels skip the gate entirely.
if (mg.unknown_sender_policy !== 'public') {
const gate = enforceAccess(userId, match.agent_group_id);
if (!gate.allowed) {
handleUnknownSender(mg, userId, match.agent_group_id, gate.reason);
return;
}
}
// 5. Resolve or create session.
//
// Adapter thread policy overrides the wiring's session_mode: if the adapter
// is threaded, each thread gets its own session regardless of what the
@@ -102,7 +129,7 @@ export async function routeInbound(event: InboundEvent): Promise<void> {
}
const { session, created } = resolveSession(match.agent_group_id, mg.id, event.threadId, effectiveSessionMode);
// 4. Write message to session DB
// 6. Write message to session DB
writeSessionMessage(session.agent_group_id, session.id, {
id: event.message.id || generateId(),
kind: event.message.kind,
@@ -117,13 +144,14 @@ export async function routeInbound(event: InboundEvent): Promise<void> {
sessionId: session.id,
agentGroup: match.agent_group_id,
kind: event.message.kind,
userId,
created,
});
// 5. Show typing indicator while agent processes
// 7. Show typing indicator while agent processes
triggerTyping(event.channelType, event.platformId, event.threadId);
// 6. Wake container
// 8. Wake container
const freshSession = getSession(session.id);
if (freshSession) {
await wakeContainer(freshSession);
@@ -139,3 +167,89 @@ function pickAgent(agents: MessagingGroupAgent[], _event: InboundEvent): Messagi
// TODO: apply trigger_rules matching (pattern, mentionOnly, etc.)
return agents[0] ?? null;
}
/**
* Best-effort sender extraction. Returns a namespaced user id like
* `telegram:123` or null if nothing usable is present.
*
* Side-effect: upserts the user into the `users` table so access/approval
* lookups can find them on subsequent messages.
*
* The namespace uses the channel_type as `kind` for now — e.g. `whatsapp:...`
* rather than `phone:...`. That's imprecise (a phone number is really the
* identifier, not the channel) but it keeps the first cut simple. A proper
* kind mapping (channel → kind) can happen when we start linking identities
* across channels.
*/
function extractAndUpsertUser(event: InboundEvent): string | null {
let content: Record<string, unknown>;
try {
content = JSON.parse(event.message.content) as Record<string, unknown>;
} catch {
return null;
}
const senderId = typeof content.senderId === 'string' ? content.senderId : undefined;
const sender = typeof content.sender === 'string' ? content.sender : undefined;
const senderName = typeof content.senderName === 'string' ? content.senderName : undefined;
const handle = senderId ?? sender;
if (!handle) return null;
const userId = `${event.channelType}:${handle}`;
if (!getUser(userId)) {
upsertUser({
id: userId,
kind: event.channelType,
display_name: senderName ?? null,
created_at: new Date().toISOString(),
});
}
return userId;
}
function enforceAccess(
userId: string | null,
agentGroupId: string,
): { allowed: boolean; reason: string } {
if (!userId) return { allowed: false, reason: 'unknown_user' };
const decision = canAccessAgentGroup(userId, agentGroupId);
if (decision.allowed) return { allowed: true, reason: decision.reason };
return { allowed: false, reason: decision.reason };
}
function handleUnknownSender(
mg: MessagingGroup,
userId: string | null,
agentGroupId: string,
accessReason: string,
): void {
// In 'strict' mode we just drop. In 'request_approval' mode we log and
// queue an approval to add the sender as a member — the approval flow
// itself is a follow-up (needs an action kind like `add_group_member`).
if (mg.unknown_sender_policy === 'strict') {
log.info('MESSAGE DROPPED — unknown sender (strict policy)', {
messagingGroupId: mg.id,
agentGroupId,
userId,
accessReason,
});
return;
}
if (mg.unknown_sender_policy === 'request_approval') {
// Placeholder: drop for now but log as a request. Follow-up wires this
// into the approval flow (request admin-of-group / owner to add user).
log.info('MESSAGE DROPPED — unknown sender (approval flow TODO)', {
messagingGroupId: mg.id,
agentGroupId,
userId,
accessReason,
});
return;
}
// Should be unreachable — 'public' was handled before the gate.
// Ensure the membership invariant isn't in an odd state.
void isMember;
}