Files
nanoclaw/scripts/init-first-agent.ts
T
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

244 lines
7.4 KiB
TypeScript

/**
* Init the first (or Nth) NanoClaw v2 agent for a DM channel.
*
* Creates/reuses: user, owner grant (if none), agent group + filesystem,
* DM messaging group, wiring, session. Stages a system welcome message so
* the host sweep wakes the container and the agent DMs the operator via
* the normal delivery path.
*
* Runs alongside the service (WAL-mode sqlite) — does NOT initialize
* channel adapters, so there's no Gateway conflict.
*
* Usage:
* npx tsx scripts/init-first-agent.ts \
* --channel discord \
* --user-id discord:1470183333427675709 \
* --platform-id discord:@me:1491573333382523708 \
* --display-name "Gavriel" \
* [--agent-name "Andy"] \
* [--welcome "System instruction: ..."]
*
* For direct-addressable channels (telegram, whatsapp, etc.), --platform-id
* is typically the same as the handle in --user-id, with the channel prefix.
*/
import path from 'path';
import { DATA_DIR } from '../src/config.js';
import { createAgentGroup, getAgentGroupByFolder } from '../src/db/agent-groups.js';
import { normalizeName } from '../src/db/agent-destinations.js';
import { initDb } from '../src/db/connection.js';
import {
createMessagingGroup,
createMessagingGroupAgent,
getMessagingGroupAgentByPair,
getMessagingGroupByPlatform,
} from '../src/db/messaging-groups.js';
import { runMigrations } from '../src/db/migrations/index.js';
import { grantRole, hasAnyOwner } from '../src/db/user-roles.js';
import { upsertUser } from '../src/db/users.js';
import { initGroupFilesystem } from '../src/group-init.js';
import { resolveSession, writeSessionMessage } from '../src/session-manager.js';
import type { AgentGroup } from '../src/types.js';
interface Args {
channel: string;
userId: string;
platformId: string;
displayName: string;
agentName: string;
welcome: string;
}
const DEFAULT_WELCOME =
'System instruction: please send a short, friendly welcome message to the user. ' +
'Introduce yourself as their NanoClaw agent, confirm the channel is working, and invite them to chat. ' +
'Keep it under three sentences.';
function parseArgs(argv: string[]): Args {
const out: Partial<Args> = {};
for (let i = 0; i < argv.length; i++) {
const key = argv[i];
const val = argv[i + 1];
switch (key) {
case '--channel':
out.channel = (val ?? '').toLowerCase();
i++;
break;
case '--user-id':
out.userId = val;
i++;
break;
case '--platform-id':
out.platformId = val;
i++;
break;
case '--display-name':
out.displayName = val;
i++;
break;
case '--agent-name':
out.agentName = val;
i++;
break;
case '--welcome':
out.welcome = val;
i++;
break;
}
}
const required: (keyof Args)[] = ['channel', 'userId', 'platformId', 'displayName'];
const missing = required.filter((k) => !out[k]);
if (missing.length) {
console.error(`Missing required args: ${missing.map((k) => `--${k.replace(/([A-Z])/g, '-$1').toLowerCase()}`).join(', ')}`);
console.error('See scripts/init-first-agent.ts header for usage.');
process.exit(2);
}
return {
channel: out.channel!,
userId: out.userId!,
platformId: out.platformId!,
displayName: out.displayName!,
agentName: out.agentName?.trim() || out.displayName!,
welcome: out.welcome?.trim() || DEFAULT_WELCOME,
};
}
function namespacedUserId(channel: string, raw: string): string {
return raw.includes(':') ? raw : `${channel}:${raw}`;
}
function namespacedPlatformId(channel: string, raw: string): string {
return raw.startsWith(`${channel}:`) ? raw : `${channel}:${raw}`;
}
function generateId(prefix: string): string {
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
}
async function main(): Promise<void> {
const args = parseArgs(process.argv.slice(2));
const db = initDb(path.join(DATA_DIR, 'v2.db'));
runMigrations(db); // idempotent
const now = new Date().toISOString();
// 1. User + (conditional) owner grant
const userId = namespacedUserId(args.channel, args.userId);
upsertUser({
id: userId,
kind: args.channel,
display_name: args.displayName,
created_at: now,
});
let promotedToOwner = false;
if (!hasAnyOwner()) {
grantRole({
user_id: userId,
role: 'owner',
agent_group_id: null,
granted_by: null,
granted_at: now,
});
promotedToOwner = true;
}
// 2. Agent group + filesystem
const folder = `dm-with-${normalizeName(args.displayName)}`;
let ag: AgentGroup | undefined = getAgentGroupByFolder(folder);
if (!ag) {
const agId = generateId('ag');
createAgentGroup({
id: agId,
name: args.agentName,
folder,
agent_provider: null,
container_config: null,
created_at: now,
});
ag = getAgentGroupByFolder(folder)!;
console.log(`Created agent group: ${ag.id} (${folder})`);
} else {
console.log(`Reusing agent group: ${ag.id} (${folder})`);
}
initGroupFilesystem(ag, {
instructions:
`# ${args.agentName}\n\n` +
`You are ${args.agentName}, a personal NanoClaw agent for ${args.displayName}. ` +
'When you receive a system welcome prompt, introduce yourself briefly and invite them to chat. Keep replies concise.',
});
// 3. DM messaging group
const platformId = namespacedPlatformId(args.channel, args.platformId);
let mg = getMessagingGroupByPlatform(args.channel, platformId);
if (!mg) {
const mgId = generateId('mg');
createMessagingGroup({
id: mgId,
channel_type: args.channel,
platform_id: platformId,
name: args.displayName,
is_group: 0,
unknown_sender_policy: 'strict',
created_at: now,
});
mg = getMessagingGroupByPlatform(args.channel, platformId)!;
console.log(`Created messaging group: ${mg.id} (${platformId})`);
} else {
console.log(`Reusing messaging group: ${mg.id} (${platformId})`);
}
// 4. Wire (auto-creates the companion agent_destinations row)
const existingMga = getMessagingGroupAgentByPair(mg.id, ag.id);
if (!existingMga) {
createMessagingGroupAgent({
id: generateId('mga'),
messaging_group_id: mg.id,
agent_group_id: ag.id,
trigger_rules: null,
response_scope: 'all',
session_mode: 'shared',
priority: 0,
created_at: now,
});
console.log(`Wired ${mg.id} -> ${ag.id}`);
} else {
console.log(`Wiring already exists: ${existingMga.id}`);
}
// 5. Session + staged welcome message
const { session, created } = resolveSession(ag.id, mg.id, null, 'shared');
console.log(`${created ? 'Created' : 'Reusing'} session: ${session.id}`);
writeSessionMessage(ag.id, session.id, {
id: generateId('sys-welcome'),
kind: 'chat',
timestamp: now,
platformId: mg.platform_id,
channelType: args.channel,
threadId: null,
content: JSON.stringify({
text: args.welcome,
sender: 'system',
senderId: 'system',
}),
});
console.log('');
console.log('Init complete.');
console.log(` owner: ${userId}${promotedToOwner ? ' (promoted on first owner)' : ''}`);
console.log(` agent: ${ag.name} [${ag.id}] @ groups/${folder}`);
console.log(` channel: ${args.channel} ${platformId}`);
console.log(` session: ${session.id}`);
console.log('');
console.log('Host sweep (<=60s) will wake the container and the agent will send the welcome DM.');
}
main().catch((err) => {
console.error(err);
process.exit(1);
});