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

@@ -3,7 +3,7 @@ import type { MessageInRow } from './db/messages-in.js';
/**
* Command categories for messages starting with '/'.
* - admin: requires NANOCLAW_ADMIN_USER_ID check
* - admin: sender must be in NANOCLAW_ADMIN_USER_IDS
* - filtered: silently drop (mark completed without processing)
* - passthrough: pass raw to the agent (no XML wrapping)
* - none: not a command — format normally

View File

@@ -10,7 +10,7 @@
* - SESSION_HEARTBEAT_PATH: heartbeat file path (default: /workspace/.heartbeat)
* - AGENT_PROVIDER: 'claude' | 'mock' (default: claude)
* - NANOCLAW_ASSISTANT_NAME: assistant name for transcript archiving
* - NANOCLAW_ADMIN_USER_ID: admin user ID for permission checks
* - NANOCLAW_ADMIN_USER_IDS: comma-separated user IDs allowed to run admin commands
*
* Mount structure:
* /workspace/
@@ -39,7 +39,12 @@ const CWD = '/workspace/agent';
async function main(): Promise<void> {
const providerName = (process.env.AGENT_PROVIDER || 'claude') as ProviderName;
const assistantName = process.env.NANOCLAW_ASSISTANT_NAME;
const adminUserId = process.env.NANOCLAW_ADMIN_USER_ID;
const adminUserIds = new Set(
(process.env.NANOCLAW_ADMIN_USER_IDS || '')
.split(',')
.map((s) => s.trim())
.filter(Boolean),
);
log(`Starting v2 agent-runner (provider: ${providerName})`);
@@ -105,7 +110,7 @@ async function main(): Promise<void> {
provider,
cwd: CWD,
systemContext: { instructions },
adminUserId,
adminUserIds,
});
}

View File

@@ -21,17 +21,11 @@ function log(msg: string): void {
console.error(`[mcp-tools] ${msg}`);
}
// Only admin agents get the create_agent tool. Non-admins never see it in the
// listTools response; the host also re-checks permission on receive as defense
// in depth (see delivery.ts create_agent handler).
const isAdmin = process.env.NANOCLAW_IS_ADMIN === '1';
const conditionalAgentTools = isAdmin ? agentTools : [];
const allTools: McpToolDefinition[] = [
...coreTools,
...schedulingTools,
...interactiveTools,
...conditionalAgentTools,
...agentTools,
...selfModTools,
...credentialTools,
];

View File

@@ -24,8 +24,12 @@ export interface PollLoopConfig {
systemContext?: {
instructions?: string;
};
/** Admin user ID for permission checks on admin commands (e.g. /clear). */
adminUserId?: string;
/**
* Set of user IDs allowed to run admin commands (e.g. /clear) in this
* agent group. Host populates from owners + global admins + scoped admins
* at container wake time, so role changes take effect on next spawn.
*/
adminUserIds?: Set<string>;
}
/**
@@ -75,7 +79,7 @@ export async function runPollLoop(config: PollLoopConfig): Promise<void> {
const routing = extractRouting(messages);
// Handle commands: categorize chat messages
const adminUserId = config.adminUserId;
const adminUserIds = config.adminUserIds ?? new Set<string>();
const normalMessages = [];
const commandIds: string[] = [];
@@ -95,7 +99,7 @@ export async function runPollLoop(config: PollLoopConfig): Promise<void> {
}
if (cmdInfo.category === 'admin') {
if (!adminUserId || cmdInfo.senderId !== adminUserId) {
if (!cmdInfo.senderId || !adminUserIds.has(cmdInfo.senderId)) {
log(`Admin command denied: ${cmdInfo.command} from ${cmdInfo.senderId} (msg: ${msg.id})`);
writeMessageOut({
id: generateId(),

View File

@@ -1,100 +0,0 @@
---
name: capabilities
description: Show what this NanoClaw instance can do — installed skills, available tools, and system info. Read-only. Use when the user asks what the bot can do, what's installed, or runs /capabilities.
---
# /capabilities — System Capabilities Report
Generate a structured read-only report of what this NanoClaw instance can do.
**Main-channel check:** Only the main channel has `/workspace/project` mounted. Run:
```bash
test -d /workspace/project && echo "MAIN" || echo "NOT_MAIN"
```
If `NOT_MAIN`, respond with:
> This command is available in your main chat only. Send `/capabilities` there to see what I can do.
Then stop — do not generate the report.
## How to gather the information
Run these commands and compile the results into the report format below.
### 1. Installed skills
List skill directories available to you:
```bash
ls -1 /home/node/.claude/skills/ 2>/dev/null || echo "No skills found"
```
Each directory is an installed skill. The directory name is the skill name (e.g., `agent-browser``/agent-browser`).
### 2. Available tools
Read the allowed tools from your SDK configuration. You always have access to:
- **Core:** Bash, Read, Write, Edit, Glob, Grep
- **Web:** WebSearch, WebFetch
- **Orchestration:** Task, TaskOutput, TaskStop, TeamCreate, TeamDelete, SendMessage
- **Other:** TodoWrite, ToolSearch, Skill, NotebookEdit
- **MCP:** mcp__nanoclaw__* (messaging, tasks, group management)
### 3. MCP server tools
The NanoClaw MCP server exposes these tools (via `mcp__nanoclaw__*` prefix):
- `send_message` — send a message to the user/group
- `schedule_task` — schedule a recurring or one-time task
- `list_tasks` — list scheduled tasks
- `pause_task` — pause a scheduled task
- `resume_task` — resume a paused task
- `cancel_task` — cancel and delete a task
- `update_task` — update an existing task
- `register_group` — register a new chat/group (main only)
### 4. Container skills (Bash tools)
Check for executable tools in the container:
```bash
which agent-browser 2>/dev/null && echo "agent-browser: available" || echo "agent-browser: not found"
```
### 5. Group info
```bash
ls /workspace/group/CLAUDE.md 2>/dev/null && echo "Group memory: yes" || echo "Group memory: no"
ls /workspace/extra/ 2>/dev/null && echo "Extra mounts: $(ls /workspace/extra/ 2>/dev/null | wc -l | tr -d ' ')" || echo "Extra mounts: none"
```
## Report format
Present the report as a clean, readable message. Example:
```
📋 *NanoClaw Capabilities*
*Installed Skills:*
• /agent-browser — Browse the web, fill forms, extract data
• /capabilities — This report
(list all found skills)
*Tools:*
• Core: Bash, Read, Write, Edit, Glob, Grep
• Web: WebSearch, WebFetch
• Orchestration: Task, TeamCreate, SendMessage
• MCP: send_message, schedule_task, list_tasks, pause/resume/cancel/update_task, register_group
*Container Tools:*
• agent-browser: ✓
*System:*
• Group memory: yes/no
• Extra mounts: N directories
• Main channel: yes
```
Adapt the output based on what you actually find — don't list things that aren't installed.
**See also:** `/status` for a quick health check of session, workspace, and tasks.

View File

@@ -1,104 +0,0 @@
---
name: status
description: Quick read-only health check — session context, workspace mounts, tool availability, and task snapshot. Use when the user asks for system status or runs /status.
---
# /status — System Status Check
Generate a quick read-only status report of the current agent environment.
**Main-channel check:** Only the main channel has `/workspace/project` mounted. Run:
```bash
test -d /workspace/project && echo "MAIN" || echo "NOT_MAIN"
```
If `NOT_MAIN`, respond with:
> This command is available in your main chat only. Send `/status` there to check system status.
Then stop — do not generate the report.
## How to gather the information
Run the checks below and compile results into the report format.
### 1. Session context
```bash
echo "Timestamp: $(date)"
echo "Working dir: $(pwd)"
echo "Channel: main"
```
### 2. Workspace and mount visibility
```bash
echo "=== Workspace ==="
ls /workspace/ 2>/dev/null
echo "=== Group folder ==="
ls /workspace/group/ 2>/dev/null | head -20
echo "=== Extra mounts ==="
ls /workspace/extra/ 2>/dev/null || echo "none"
echo "=== IPC ==="
ls /workspace/ipc/ 2>/dev/null
```
### 3. Tool availability
Confirm which tool families are available to you:
- **Core:** Bash, Read, Write, Edit, Glob, Grep
- **Web:** WebSearch, WebFetch
- **Orchestration:** Task, TaskOutput, TaskStop, TeamCreate, TeamDelete, SendMessage
- **MCP:** mcp__nanoclaw__* (send_message, schedule_task, list_tasks, pause_task, resume_task, cancel_task, update_task, register_group)
### 4. Container utilities
```bash
which agent-browser 2>/dev/null && echo "agent-browser: available" || echo "agent-browser: not installed"
node --version 2>/dev/null
claude --version 2>/dev/null
```
### 5. Task snapshot
Use the MCP tool to list tasks:
```
Call mcp__nanoclaw__list_tasks to get scheduled tasks.
```
If no tasks exist, report "No scheduled tasks."
## Report format
Present as a clean, readable message:
```
🔍 *NanoClaw Status*
*Session:*
• Channel: main
• Time: 2026-03-14 09:30 UTC
• Working dir: /workspace/group
*Workspace:*
• Group folder: ✓ (N files)
• Extra mounts: none / N directories
• IPC: ✓ (messages, tasks, input)
*Tools:*
• Core: ✓ Web: ✓ Orchestration: ✓ MCP: ✓
*Container:*
• agent-browser: ✓ / not installed
• Node: vXX.X.X
• Claude Code: vX.X.X
*Scheduled Tasks:*
• N active tasks / No scheduled tasks
```
Adapt based on what you actually find. Keep it concise — this is a quick health check, not a deep diagnostic.
**See also:** `/capabilities` for a full list of installed skills and tools.