Files
nanoclaw/setup/register.ts
gavrielc 0d3326aae5 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>
2026-04-15 00:03:51 +03:00

260 lines
8.4 KiB
TypeScript

/**
* Step: register — Create v2 entities (agent group, messaging group, wiring).
*
* Writes to the v2 central DB (data/v2.db) — NOT the v1 store/messages.db.
* Creates: agent_group, messaging_group, messaging_group_agents.
*/
import fs from 'fs';
import path from 'path';
import { DATA_DIR } from '../src/config.js';
import { initDb } from '../src/db/connection.js';
import { runMigrations } from '../src/db/migrations/index.js';
import { createAgentGroup, getAgentGroupByFolder } from '../src/db/agent-groups.js';
import {
createMessagingGroup,
createMessagingGroupAgent,
getMessagingGroupByPlatform,
getMessagingGroupAgentByPair,
} from '../src/db/messaging-groups.js';
import { isValidGroupFolder } from '../src/group-folder.js';
import { initGroupFilesystem } from '../src/group-init.js';
import { log } from '../src/log.js';
import { resolveSession, writeSessionMessage } from '../src/session-manager.js';
import { emitStatus } from './status.js';
interface RegisterArgs {
/** Platform-specific channel/group ID (Discord channel ID, Slack channel, etc.) */
platformId: string;
/** Human-readable name for the messaging group */
name: string;
/** Trigger pattern (regex or keyword) */
trigger: string;
/** Agent group folder name */
folder: string;
/** Channel type (discord, slack, telegram, etc.) */
channel: string;
/** Whether messages require the trigger pattern to activate */
requiresTrigger: boolean;
/** Display name for the assistant */
assistantName: string;
/** Session mode: 'shared' (one session per channel) or 'per-thread' */
sessionMode: string;
}
function parseArgs(args: string[]): RegisterArgs {
const result: RegisterArgs = {
platformId: '',
name: '',
trigger: '',
folder: '',
channel: 'discord',
requiresTrigger: true,
assistantName: 'Andy',
sessionMode: 'shared',
};
for (let i = 0; i < args.length; i++) {
switch (args[i]) {
case '--platform-id':
result.platformId = args[++i] || '';
break;
case '--name':
result.name = args[++i] || '';
break;
case '--trigger':
result.trigger = args[++i] || '';
break;
case '--folder':
result.folder = args[++i] || '';
break;
case '--channel':
result.channel = (args[++i] || '').toLowerCase();
break;
case '--no-trigger-required':
result.requiresTrigger = false;
break;
case '--assistant-name':
result.assistantName = args[++i] || 'Andy';
break;
case '--session-mode':
result.sessionMode = args[++i] || 'shared';
break;
}
}
return result;
}
function generateId(prefix: string): string {
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
}
export async function run(args: string[]): Promise<void> {
const projectRoot = process.cwd();
const parsed = parseArgs(args);
if (!parsed.platformId || !parsed.name || !parsed.folder) {
emitStatus('REGISTER_CHANNEL', {
STATUS: 'failed',
ERROR: 'missing_required_args',
LOG: 'logs/setup.log',
});
process.exit(4);
}
if (!isValidGroupFolder(parsed.folder)) {
emitStatus('REGISTER_CHANNEL', {
STATUS: 'failed',
ERROR: 'invalid_folder',
LOG: 'logs/setup.log',
});
process.exit(4);
}
// Chat SDK adapters prefix platform IDs with the channel type
// (e.g. "telegram:123", "discord:guild:channel"). Normalize here so
// the stored ID always matches what the adapter sends at runtime.
if (!parsed.platformId.startsWith(`${parsed.channel}:`)) {
parsed.platformId = `${parsed.channel}:${parsed.platformId}`;
}
log.info('Registering channel', parsed);
// Init v2 central DB
fs.mkdirSync(path.join(projectRoot, 'data'), { recursive: true });
const dbPath = path.join(DATA_DIR, 'v2.db');
const db = initDb(dbPath);
runMigrations(db);
// 1. Create or find agent group
let agentGroup = getAgentGroupByFolder(parsed.folder);
if (!agentGroup) {
const agId = generateId('ag');
createAgentGroup({
id: agId,
name: parsed.assistantName,
folder: parsed.folder,
agent_provider: null,
container_config: null,
created_at: new Date().toISOString(),
});
agentGroup = getAgentGroupByFolder(parsed.folder)!;
log.info('Created agent group', { id: agId, folder: parsed.folder });
}
initGroupFilesystem(agentGroup);
// 2. Create or find messaging group
let messagingGroup = getMessagingGroupByPlatform(parsed.channel, parsed.platformId);
if (!messagingGroup) {
const mgId = generateId('mg');
createMessagingGroup({
id: mgId,
channel_type: parsed.channel,
platform_id: parsed.platformId,
name: parsed.name,
is_group: 1,
unknown_sender_policy: 'strict',
created_at: new Date().toISOString(),
});
messagingGroup = getMessagingGroupByPlatform(parsed.channel, parsed.platformId)!;
log.info('Created messaging group', { id: mgId, channel: parsed.channel, platformId: parsed.platformId });
}
// 3. Wire agent to messaging group — createMessagingGroupAgent auto-creates
// the companion agent_destinations row so delivery's ACL admits this target.
let newlyWired = false;
const existing = getMessagingGroupAgentByPair(messagingGroup.id, agentGroup.id);
if (!existing) {
newlyWired = true;
const mgaId = generateId('mga');
const triggerRules = parsed.trigger
? JSON.stringify({
pattern: parsed.trigger,
requiresTrigger: parsed.requiresTrigger,
})
: null;
createMessagingGroupAgent({
id: mgaId,
messaging_group_id: messagingGroup.id,
agent_group_id: agentGroup.id,
trigger_rules: triggerRules,
response_scope: 'all',
session_mode: parsed.sessionMode,
priority: 0,
created_at: new Date().toISOString(),
});
log.info('Wired agent to messaging group', {
mgaId,
agentGroup: agentGroup.id,
messagingGroup: messagingGroup.id,
});
}
// 4. Send onboarding message — only on first wiring, not re-registration
if (newlyWired) {
const { session } = resolveSession(agentGroup.id, messagingGroup.id, null, parsed.sessionMode as 'shared' | 'per-thread' | 'agent-shared');
writeSessionMessage(agentGroup.id, session.id, {
id: generateId('onboard'),
kind: 'task',
timestamp: new Date().toISOString(),
platformId: parsed.platformId,
channelType: parsed.channel,
content: JSON.stringify({
prompt: `A new ${parsed.channel} channel has been connected. Run /welcome to introduce yourself to the user.`,
}),
});
log.info('Onboarding message written', { sessionId: session.id, channel: parsed.channel });
}
// 5. Update assistant name in CLAUDE.md files if different from default
let nameUpdated = false;
if (parsed.assistantName !== 'Andy') {
log.info('Updating assistant name', { from: 'Andy', to: parsed.assistantName });
const groupsDir = path.join(projectRoot, 'groups');
const mdFiles = fs
.readdirSync(groupsDir)
.map((d) => path.join(groupsDir, d, 'CLAUDE.md'))
.filter((f) => fs.existsSync(f));
for (const mdFile of mdFiles) {
let content = fs.readFileSync(mdFile, 'utf-8');
content = content.replace(/^# Andy$/m, `# ${parsed.assistantName}`);
content = content.replace(/You are Andy/g, `You are ${parsed.assistantName}`);
fs.writeFileSync(mdFile, content);
log.info('Updated CLAUDE.md', { file: mdFile });
}
// Update .env
const envFile = path.join(projectRoot, '.env');
if (fs.existsSync(envFile)) {
let envContent = fs.readFileSync(envFile, 'utf-8');
if (envContent.includes('ASSISTANT_NAME=')) {
envContent = envContent.replace(/^ASSISTANT_NAME=.*$/m, `ASSISTANT_NAME="${parsed.assistantName}"`);
} else {
envContent += `\nASSISTANT_NAME="${parsed.assistantName}"`;
}
fs.writeFileSync(envFile, envContent);
} else {
fs.writeFileSync(envFile, `ASSISTANT_NAME="${parsed.assistantName}"\n`);
}
log.info('Set ASSISTANT_NAME in .env');
nameUpdated = true;
}
emitStatus('REGISTER_CHANNEL', {
PLATFORM_ID: parsed.platformId,
NAME: parsed.name,
FOLDER: parsed.folder,
CHANNEL: parsed.channel,
TRIGGER: parsed.trigger,
REQUIRES_TRIGGER: parsed.requiresTrigger,
ASSISTANT_NAME: parsed.assistantName,
SESSION_MODE: parsed.sessionMode,
NAME_UPDATED: nameUpdated,
STATUS: 'success',
LOG: 'logs/setup.log',
});
}