mirror of
https://github.com/qwibitai/nanoclaw.git
synced 2026-06-12 18:11:51 +08:00
0d3326aae5
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>
184 lines
5.5 KiB
TypeScript
184 lines
5.5 KiB
TypeScript
/**
|
|
* Real end-to-end test of v2: host router → Docker container → agent-runner → delivery.
|
|
*
|
|
* 1. Init central DB with agent group + messaging group + wiring
|
|
* 2. Route an inbound message (creates session, writes inbound.db, spawns container)
|
|
* 3. Container runs v2 agent-runner, polls inbound.db, queries Claude, writes outbound.db
|
|
* 4. Poll outbound.db for messages_out response
|
|
*
|
|
* Usage: npx tsx scripts/test-v2-host.ts
|
|
*/
|
|
import Database from 'better-sqlite3';
|
|
import fs from 'fs';
|
|
import path from 'path';
|
|
|
|
const TEST_DIR = '/tmp/nanoclaw-v2-e2e';
|
|
if (fs.existsSync(TEST_DIR)) fs.rmSync(TEST_DIR, { recursive: true });
|
|
fs.mkdirSync(TEST_DIR, { recursive: true });
|
|
|
|
// --- Step 1: Init central DB ---
|
|
console.log('\n=== Step 1: Init central DB ===');
|
|
|
|
import { initDb } from '../src/db/connection.js';
|
|
import { runMigrations } from '../src/db/migrations/index.js';
|
|
import { createAgentGroup } from '../src/db/agent-groups.js';
|
|
import { createMessagingGroup, createMessagingGroupAgent } from '../src/db/messaging-groups.js';
|
|
|
|
const centralDb = initDb(path.join(TEST_DIR, 'v2.db'));
|
|
runMigrations(centralDb);
|
|
|
|
// Create groups dir for agent folder mount
|
|
const groupsDir = path.resolve(process.cwd(), 'groups');
|
|
const testGroupDir = path.join(groupsDir, 'test-agent-e2e');
|
|
fs.mkdirSync(testGroupDir, { recursive: true });
|
|
fs.writeFileSync(path.join(testGroupDir, 'CLAUDE.md'), '# Test Agent\nYou are a test agent. Be brief.\n');
|
|
|
|
createAgentGroup({
|
|
id: 'ag-e2e',
|
|
name: 'E2E Test Agent',
|
|
folder: 'test-agent-e2e',
|
|
agent_provider: 'claude',
|
|
container_config: null,
|
|
created_at: new Date().toISOString(),
|
|
});
|
|
|
|
createMessagingGroup({
|
|
id: 'mg-e2e',
|
|
channel_type: 'test',
|
|
platform_id: 'e2e-channel',
|
|
name: 'E2E Test Channel',
|
|
is_group: 0,
|
|
unknown_sender_policy: 'public',
|
|
created_at: new Date().toISOString(),
|
|
});
|
|
|
|
createMessagingGroupAgent({
|
|
id: 'mga-e2e',
|
|
messaging_group_id: 'mg-e2e',
|
|
agent_group_id: 'ag-e2e',
|
|
trigger_rules: null,
|
|
response_scope: 'all',
|
|
session_mode: 'shared',
|
|
priority: 0,
|
|
created_at: new Date().toISOString(),
|
|
});
|
|
|
|
console.log('✓ Central DB initialized');
|
|
|
|
// --- Step 2: Route inbound message (spawns container) ---
|
|
console.log('\n=== Step 2: Route inbound message ===');
|
|
|
|
import { routeInbound } from '../src/router.js';
|
|
import { findSession } from '../src/db/sessions.js';
|
|
import { inboundDbPath, outboundDbPath } from '../src/session-manager.js';
|
|
|
|
await routeInbound({
|
|
channelType: 'test',
|
|
platformId: 'e2e-channel',
|
|
threadId: null,
|
|
message: {
|
|
id: 'msg-e2e-1',
|
|
kind: 'chat',
|
|
content: JSON.stringify({
|
|
sender: 'Gavriel',
|
|
text: 'Say "E2E works!" and nothing else. Do not use any tools.',
|
|
}),
|
|
timestamp: new Date().toISOString(),
|
|
},
|
|
});
|
|
|
|
const session = findSession('mg-e2e', null);
|
|
if (!session) {
|
|
console.log('✗ No session created!');
|
|
process.exit(1);
|
|
}
|
|
console.log(`✓ Session: ${session.id}`);
|
|
console.log(`✓ Container status: ${session.container_status}`);
|
|
|
|
const inDbPath = inboundDbPath('ag-e2e', session.id);
|
|
const outDbPath = outboundDbPath('ag-e2e', session.id);
|
|
console.log(`✓ Inbound DB: ${inDbPath}`);
|
|
console.log(`✓ Outbound DB: ${outDbPath}`);
|
|
|
|
// --- Step 3: Wait for response ---
|
|
console.log('\n=== Step 3: Waiting for Claude response... ===');
|
|
|
|
const startTime = Date.now();
|
|
const TIMEOUT_MS = 120_000;
|
|
|
|
const checkForResponse = (): boolean => {
|
|
try {
|
|
const db = new Database(outDbPath, { readonly: true });
|
|
const out = db.prepare('SELECT * FROM messages_out').all() as Array<Record<string, unknown>>;
|
|
db.close();
|
|
return out.length > 0;
|
|
} catch {
|
|
return false;
|
|
}
|
|
};
|
|
|
|
await new Promise<void>((resolve) => {
|
|
const poll = () => {
|
|
if (checkForResponse()) {
|
|
resolve();
|
|
return;
|
|
}
|
|
if (Date.now() - startTime > TIMEOUT_MS) {
|
|
console.log(`\n✗ Timed out after ${TIMEOUT_MS / 1000}s`);
|
|
printState();
|
|
process.exit(1);
|
|
}
|
|
const elapsed = Math.floor((Date.now() - startTime) / 1000);
|
|
if (elapsed > 0 && elapsed % 10 === 0) {
|
|
process.stdout.write(` ${elapsed}s...`);
|
|
}
|
|
setTimeout(poll, 1000);
|
|
};
|
|
poll();
|
|
});
|
|
|
|
// --- Step 4: Print results ---
|
|
console.log('\n\n=== Results ===');
|
|
printState();
|
|
|
|
// Clean up test group dir
|
|
fs.rmSync(testGroupDir, { recursive: true, force: true });
|
|
|
|
process.exit(0);
|
|
|
|
function printState() {
|
|
try {
|
|
const inDb = new Database(inDbPath, { readonly: true });
|
|
const inRows = inDb.prepare('SELECT * FROM messages_in').all() as Array<Record<string, unknown>>;
|
|
inDb.close();
|
|
|
|
console.log('\nmessages_in (inbound.db):');
|
|
for (const r of inRows) {
|
|
console.log(` [${r.id}] status=${r.status} kind=${r.kind}`);
|
|
}
|
|
} catch (err) {
|
|
console.log(` (could not read inbound DB: ${err})`);
|
|
}
|
|
|
|
try {
|
|
const outDb = new Database(outDbPath, { readonly: true });
|
|
const outRows = outDb.prepare('SELECT * FROM messages_out').all() as Array<Record<string, unknown>>;
|
|
const ackRows = outDb.prepare('SELECT * FROM processing_ack').all() as Array<Record<string, unknown>>;
|
|
outDb.close();
|
|
|
|
console.log('\nmessages_out (outbound.db):');
|
|
for (const r of outRows) {
|
|
const content = JSON.parse(r.content as string);
|
|
console.log(` [${r.id}] kind=${r.kind}`);
|
|
console.log(` → ${content.text}`);
|
|
}
|
|
|
|
console.log('\nprocessing_ack (outbound.db):');
|
|
for (const r of ackRows) {
|
|
console.log(` [${r.message_id}] status=${r.status} changed=${r.status_changed}`);
|
|
}
|
|
} catch (err) {
|
|
console.log(` (could not read outbound DB: ${err})`);
|
|
}
|
|
}
|