Files
nanoclaw/src/types.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

192 lines
5.0 KiB
TypeScript

// ── Central DB entities ──
export interface AgentGroup {
id: string;
name: string;
folder: string;
agent_provider: string | null;
container_config: string | null; // JSON: { additionalMounts, timeout }
created_at: string;
}
export type UnknownSenderPolicy = 'strict' | 'request_approval' | 'public';
export interface MessagingGroup {
id: string;
channel_type: string;
platform_id: string;
name: string | null;
is_group: number; // 0 | 1
unknown_sender_policy: UnknownSenderPolicy;
created_at: string;
}
// ── Identity & privilege ──
/**
* User = a messaging-platform identifier. Namespaced so distinct channels
* with numeric IDs don't collide: "phone:+1555...", "tg:123", "discord:456",
* "email:a@x.com". A single human with a phone AND a telegram handle has
* two separate users — no cross-channel linking (yet).
*/
export interface User {
id: string;
kind: string; // 'phone' | 'email' | 'discord' | 'telegram' | 'matrix' | ...
display_name: string | null;
created_at: string;
}
export type UserRoleKind = 'owner' | 'admin';
/**
* Role grant. Owner is always global. Admin is either global
* (agent_group_id = null) or scoped to a specific agent group.
* Admin @ A implicitly makes the user a member of A — we do not require
* a separate agent_group_members row for admins.
*/
export interface UserRole {
user_id: string;
role: UserRoleKind;
agent_group_id: string | null;
granted_by: string | null;
granted_at: string;
}
/** "Known" membership in an agent group — required for unprivileged users. */
export interface AgentGroupMember {
user_id: string;
agent_group_id: string;
added_by: string | null;
added_at: string;
}
/** Cached DM channel for a user on a specific channel_type. */
export interface UserDm {
user_id: string;
channel_type: string;
messaging_group_id: string;
resolved_at: string;
}
export interface MessagingGroupAgent {
id: string;
messaging_group_id: string;
agent_group_id: string;
trigger_rules: string | null; // JSON: { pattern, mentionOnly, excludeSenders, includeSenders }
response_scope: 'all' | 'triggered' | 'allowlisted';
session_mode: 'shared' | 'per-thread' | 'agent-shared';
priority: number;
created_at: string;
}
export interface Session {
id: string;
agent_group_id: string;
messaging_group_id: string | null;
thread_id: string | null;
agent_provider: string | null;
status: 'active' | 'closed';
container_status: 'running' | 'idle' | 'stopped';
last_active: string | null;
created_at: string;
}
// ── Session DB entities ──
export type MessageInKind = 'chat' | 'chat-sdk' | 'task' | 'webhook' | 'system';
export type MessageInStatus = 'pending' | 'processing' | 'completed' | 'failed';
export interface MessageIn {
id: string;
kind: MessageInKind;
timestamp: string;
status: MessageInStatus;
status_changed: string | null;
process_after: string | null;
recurrence: string | null;
tries: number;
platform_id: string | null;
channel_type: string | null;
thread_id: string | null;
content: string; // JSON blob
}
export interface MessageOut {
id: string;
in_reply_to: string | null;
timestamp: string;
delivered: number; // 0 | 1
deliver_after: string | null;
recurrence: string | null;
kind: string;
platform_id: string | null;
channel_type: string | null;
thread_id: string | null;
content: string; // JSON blob
}
// ── Pending questions (central DB) ──
export interface PendingQuestion {
question_id: string;
session_id: string;
message_out_id: string;
platform_id: string | null;
channel_type: string | null;
thread_id: string | null;
title: string;
options: import('./channels/ask-question.js').NormalizedOption[];
created_at: string;
}
// ── Pending approvals (central DB) ──
export interface PendingApproval {
approval_id: string;
session_id: string | null;
request_id: string;
action: string;
payload: string; // JSON
created_at: string;
agent_group_id: string | null;
channel_type: string | null;
platform_id: string | null;
platform_message_id: string | null;
expires_at: string | null;
status: 'pending' | 'approved' | 'rejected' | 'expired';
title: string;
options_json: string;
}
// ── Pending credentials (central DB) ──
export type PendingCredentialStatus = 'pending' | 'submitted' | 'saved' | 'rejected' | 'failed';
export interface PendingCredential {
id: string;
agent_group_id: string;
session_id: string | null;
name: string;
type: 'generic' | 'anthropic';
host_pattern: string;
path_pattern: string | null;
header_name: string | null;
value_format: string | null;
description: string | null;
channel_type: string;
platform_id: string;
platform_message_id: string | null;
status: PendingCredentialStatus;
created_at: string;
}
// ── Agent destinations (central DB) ──
export interface AgentDestination {
agent_group_id: string;
local_name: string;
target_type: 'channel' | 'agent';
target_id: string;
created_at: string;
}