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:
115
src/access.ts
Normal file
115
src/access.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* Access control + approval routing.
|
||||
*
|
||||
* Privilege is user-level, not group-level. A user holds zero or more roles
|
||||
* (owner | admin) via `user_roles`, and is optionally "known" in specific
|
||||
* agent groups via `agent_group_members`. Admins are implicitly members of
|
||||
* the groups they administer.
|
||||
*
|
||||
* Sensitive actions trigger an approval flow, routed to the admin of the
|
||||
* originating agent group; if none, the owner. Approval delivery lands in
|
||||
* the approver's DM on (ideally) the same channel kind as the originating
|
||||
* request. DM resolution (including cold DMs) is handled by ensureUserDm.
|
||||
*/
|
||||
import { getAgentGroup } from './db/agent-groups.js';
|
||||
import { isMember } from './db/agent-group-members.js';
|
||||
import {
|
||||
getAdminsOfAgentGroup,
|
||||
getGlobalAdmins,
|
||||
getOwners,
|
||||
hasAdminPrivilege,
|
||||
isAdminOfAgentGroup,
|
||||
isGlobalAdmin,
|
||||
isOwner,
|
||||
} from './db/user-roles.js';
|
||||
import { getUser } from './db/users.js';
|
||||
import { ensureUserDm } from './user-dm.js';
|
||||
import type { MessagingGroup } from './types.js';
|
||||
|
||||
export type AccessDecision =
|
||||
| { allowed: true; reason: 'owner' | 'global_admin' | 'admin_of_group' | 'member' }
|
||||
| { allowed: false; reason: 'unknown_user' | 'not_member' };
|
||||
|
||||
/** Can this user interact with this agent group? */
|
||||
export function canAccessAgentGroup(userId: string, agentGroupId: string): AccessDecision {
|
||||
if (!getUser(userId)) return { allowed: false, reason: 'unknown_user' };
|
||||
if (isOwner(userId)) return { allowed: true, reason: 'owner' };
|
||||
if (isGlobalAdmin(userId)) return { allowed: true, reason: 'global_admin' };
|
||||
if (isAdminOfAgentGroup(userId, agentGroupId)) return { allowed: true, reason: 'admin_of_group' };
|
||||
if (isMember(userId, agentGroupId)) return { allowed: true, reason: 'member' };
|
||||
return { allowed: false, reason: 'not_member' };
|
||||
}
|
||||
|
||||
/** Can this user perform privileged (admin) operations on this agent group? */
|
||||
export function canAdminAgentGroup(userId: string, agentGroupId: string): boolean {
|
||||
return hasAdminPrivilege(userId, agentGroupId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ordered list of user IDs eligible to approve an action for the given agent
|
||||
* group. Preference: admins @ that group → global admins → owners.
|
||||
*
|
||||
* The approver-picking policy is to try local admins first (they have direct
|
||||
* context for the group), then fall back to global scope.
|
||||
*/
|
||||
export function pickApprover(agentGroupId: string | null): string[] {
|
||||
const approvers: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
const add = (id: string): void => {
|
||||
if (!seen.has(id)) {
|
||||
seen.add(id);
|
||||
approvers.push(id);
|
||||
}
|
||||
};
|
||||
|
||||
if (agentGroupId) {
|
||||
for (const r of getAdminsOfAgentGroup(agentGroupId)) add(r.user_id);
|
||||
}
|
||||
for (const r of getGlobalAdmins()) add(r.user_id);
|
||||
for (const r of getOwners()) add(r.user_id);
|
||||
|
||||
return approvers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk the approver list and return the first (approverId, messagingGroup)
|
||||
* pair we can actually deliver to. Returns null if nobody is reachable.
|
||||
*
|
||||
* Tie-break rule (per model): prefer approvers reachable on the same channel
|
||||
* kind as the origin; else first in list. Resolution uses ensureUserDm,
|
||||
* which may trigger a platform openDM call on cache miss — that's how we
|
||||
* support cold DMs to users who have never messaged the bot.
|
||||
*/
|
||||
export async function pickApprovalDelivery(
|
||||
approvers: string[],
|
||||
originChannelType: string,
|
||||
): Promise<{ userId: string; messagingGroup: MessagingGroup } | null> {
|
||||
// Pass 1: approvers whose channel matches the origin (prefix on user id).
|
||||
if (originChannelType) {
|
||||
for (const userId of approvers) {
|
||||
if (channelTypeOf(userId) !== originChannelType) continue;
|
||||
const mg = await ensureUserDm(userId);
|
||||
if (mg) return { userId, messagingGroup: mg };
|
||||
}
|
||||
}
|
||||
// Pass 2: any reachable approver, in order.
|
||||
for (const userId of approvers) {
|
||||
const mg = await ensureUserDm(userId);
|
||||
if (mg) return { userId, messagingGroup: mg };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the agent group id for a session's originating request. Used by
|
||||
* approval routing so we know which scope to pick admins from.
|
||||
*/
|
||||
export function agentGroupIdForSession(sessionAgentGroupId: string | null): string | null {
|
||||
if (!sessionAgentGroupId) return null;
|
||||
return getAgentGroup(sessionAgentGroupId)?.id ?? null;
|
||||
}
|
||||
|
||||
function channelTypeOf(userId: string): string {
|
||||
const idx = userId.indexOf(':');
|
||||
return idx < 0 ? '' : userId.slice(0, idx);
|
||||
}
|
||||
Reference in New Issue
Block a user