feat(router,cli): replyTo override + CLI admin-transport flows

- InboundEvent gains an optional replyTo; router stamps the row's address
  fields from it when set, so replies can route to a different channel than
  the one the inbound came in on.
- ChannelSetup adds onInboundEvent for admin-transport adapters that build
  the full event themselves.
- CLI wire format accepts {text, to, reply_to}. Routed messages go through
  onInboundEvent and do not evict an active chat client.
- init-first-agent hands the DM welcome to the running service via
  data/cli.sock — synchronous wake, no sweep wait. Fails loudly if the
  service is down; no silent fallback.
- Split the CLI scratch-agent bootstrap into scripts/init-cli-agent.ts;
  init-first-agent is DM-only.

Agents cannot set replyTo: it lives only on the inbound/router seam and is
consumed once when writing messages_in.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
gavrielc
2026-04-20 23:30:47 +03:00
parent dadf258136
commit 6c26c0413a
15 changed files with 503 additions and 213 deletions

179
scripts/init-cli-agent.ts Normal file
View File

@@ -0,0 +1,179 @@
/**
* Initialize the scratch CLI agent used during `/new-setup`.
*
* Creates the synthetic `cli:local` user, grants owner role if no owner
* exists yet, builds an agent group with a minimal CLAUDE.md, and wires it
* to the CLI messaging group so `pnpm run chat` works immediately.
*
* No welcome is staged — the operator's first `pnpm run chat` is the
* natural wake, and the agent introduces itself on first contact per its
* CLAUDE.md.
*
* Runs alongside the service (WAL-mode sqlite) — does NOT initialize
* channel adapters, so there's no Gateway conflict.
*
* Usage:
* pnpm exec tsx scripts/init-cli-agent.ts \
* --display-name "Gavriel" \
* [--agent-name "Andy"]
*/
import path from 'path';
import { DATA_DIR } from '../src/config.js';
import { createAgentGroup, getAgentGroupByFolder } from '../src/db/agent-groups.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 { normalizeName } from '../src/modules/agent-to-agent/db/agent-destinations.js';
import { grantRole, hasAnyOwner } from '../src/modules/permissions/db/user-roles.js';
import { upsertUser } from '../src/modules/permissions/db/users.js';
import { initGroupFilesystem } from '../src/group-init.js';
import type { AgentGroup, MessagingGroup } from '../src/types.js';
const CLI_CHANNEL = 'cli';
const CLI_PLATFORM_ID = 'local';
const CLI_SYNTHETIC_USER_ID = `${CLI_CHANNEL}:${CLI_PLATFORM_ID}`;
interface Args {
displayName: string;
agentName: string;
}
function parseArgs(argv: string[]): Args {
let displayName: string | undefined;
let agentName: string | undefined;
for (let i = 0; i < argv.length; i++) {
const key = argv[i];
const val = argv[i + 1];
if (key === '--display-name') {
displayName = val;
i++;
} else if (key === '--agent-name') {
agentName = val;
i++;
}
}
if (!displayName) {
console.error('Missing required arg: --display-name');
console.error('See scripts/init-cli-agent.ts header for usage.');
process.exit(2);
}
return {
displayName,
agentName: agentName?.trim() || displayName,
};
}
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);
const now = new Date().toISOString();
// 1. Synthetic CLI user + owner grant if none exists.
upsertUser({
id: CLI_SYNTHETIC_USER_ID,
kind: CLI_CHANNEL,
display_name: args.displayName,
created_at: now,
});
let promotedToOwner = false;
if (!hasAnyOwner()) {
grantRole({
user_id: CLI_SYNTHETIC_USER_ID,
role: 'owner',
agent_group_id: null,
granted_by: null,
granted_at: now,
});
promotedToOwner = true;
}
// 2. Agent group + filesystem.
const folder = `cli-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,
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 the user first reaches out, introduce yourself briefly and invite them to chat. Keep replies concise.',
});
// 3. CLI messaging group + wiring.
let cliMg: MessagingGroup | undefined = getMessagingGroupByPlatform(CLI_CHANNEL, CLI_PLATFORM_ID);
if (!cliMg) {
cliMg = {
id: generateId('mg'),
channel_type: CLI_CHANNEL,
platform_id: CLI_PLATFORM_ID,
name: 'Local CLI',
is_group: 0,
unknown_sender_policy: 'public',
created_at: now,
};
createMessagingGroup(cliMg);
console.log(`Created CLI messaging group: ${cliMg.id}`);
}
const existing = getMessagingGroupAgentByPair(cliMg.id, ag.id);
if (!existing) {
createMessagingGroupAgent({
id: generateId('mga'),
messaging_group_id: cliMg.id,
agent_group_id: ag.id,
engage_mode: 'pattern',
engage_pattern: '.',
sender_scope: 'all',
ignored_message_policy: 'drop',
session_mode: 'shared',
priority: 0,
created_at: now,
});
console.log(`Wired cli: ${cliMg.id} -> ${ag.id}`);
} else {
console.log(`Wiring already exists: ${existing.id}`);
}
console.log('');
console.log('Init complete.');
console.log(
` owner: ${CLI_SYNTHETIC_USER_ID}${promotedToOwner ? ' (promoted on first owner)' : ''}`,
);
console.log(` agent: ${ag.name} [${ag.id}] @ groups/${folder}`);
console.log(` channel: cli/${CLI_PLATFORM_ID}`);
console.log('');
console.log('Run `pnpm run chat hi` to talk to your agent.');
}
main().catch((err) => {
console.error(err);
process.exit(1);
});

View File

@@ -1,43 +1,39 @@
/**
* Init the first (or Nth) NanoClaw v2 agent.
* Init the first (or Nth) NanoClaw v2 agent for a DM channel.
*
* Two modes:
* Wires a real DM channel (discord, telegram, etc.) to a new agent group
* (and the local CLI channel as a convenience bonus), then hands a welcome
* message to the running service via its CLI socket. The service routes
* that message into the DM session, which wakes the container synchronously —
* the agent processes the welcome and DMs the operator through the normal
* delivery path.
*
* 1. **DM channel mode** (default): wires a real DM channel (discord, telegram,
* etc.) + the CLI channel to the same agent, stages a welcome into the DM
* session so the agent greets the operator over that channel.
*
* 2. **CLI-only mode** (`--cli-only`): wires only the CLI channel. Used by
* `/new-setup` to get to a working 2-way CLI chat with the bare minimum.
* Owner grant uses a synthetic `cli:local` user so admin-gated flows work.
* For the CLI-only scratch agent used during `/new-setup`, see
* `scripts/init-cli-agent.ts` — that's a distinct flow and doesn't run
* through here.
*
* Creates/reuses: user, owner grant (if none), agent group + filesystem,
* messaging group(s), wiring, session. Stages a system welcome message so
* the host sweep wakes the container and the agent sends the greeting via
* the normal delivery path.
* messaging group(s), wiring.
*
* Runs alongside the service (WAL-mode sqlite) — does NOT initialize
* channel adapters, so there's no Gateway conflict.
* Runs alongside the service (WAL-mode sqlite + CLI socket IPC) — does NOT
* initialize channel adapters, so there's no Gateway conflict. Requires
* the service to be running: the welcome hand-off goes over the CLI socket
* and fails loudly if the service isn't up.
*
* Usage:
* # DM mode
* pnpm exec 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: ..."]
*
* # CLI-only mode
* pnpm exec tsx scripts/init-first-agent.ts --cli-only \
* --display-name "Gavriel" \
* [--agent-name "Andy"] \
* [--welcome "System instruction: ..."]
* [--welcome "System instruction: ..."] \
* [--no-cli-bonus]
*
* For direct-addressable channels (telegram, whatsapp, etc.), --platform-id
* is typically the same as the handle in --user-id, with the channel prefix.
*/
import net from 'net';
import path from 'path';
import { DATA_DIR } from '../src/config.js';
@@ -54,11 +50,9 @@ import { normalizeName } from '../src/modules/agent-to-agent/db/agent-destinatio
import { grantRole, hasAnyOwner } from '../src/modules/permissions/db/user-roles.js';
import { upsertUser } from '../src/modules/permissions/db/users.js';
import { initGroupFilesystem } from '../src/group-init.js';
import { resolveSession, writeSessionMessage } from '../src/session-manager.js';
import type { AgentGroup, MessagingGroup } from '../src/types.js';
interface Args {
cliOnly: boolean;
noCliBonus: boolean;
channel: string;
userId: string;
@@ -73,17 +67,13 @@ const DEFAULT_WELCOME =
const CLI_CHANNEL = 'cli';
const CLI_PLATFORM_ID = 'local';
const CLI_SYNTHETIC_USER_ID = `${CLI_CHANNEL}:${CLI_PLATFORM_ID}`;
function parseArgs(argv: string[]): Args {
const out: Partial<Args> = { cliOnly: false, noCliBonus: false };
const out: Partial<Args> = { noCliBonus: false };
for (let i = 0; i < argv.length; i++) {
const key = argv[i];
const val = argv[i + 1];
switch (key) {
case '--cli-only':
out.cliOnly = true;
break;
case '--no-cli-bonus':
out.noCliBonus = true;
break;
@@ -114,42 +104,23 @@ function parseArgs(argv: string[]): Args {
}
}
if (!out.displayName) {
console.error('Missing required arg: --display-name');
console.error('See scripts/init-first-agent.ts header for usage.');
process.exit(2);
}
if (out.cliOnly) {
// CLI-only: channel/user/platform default to the synthetic local CLI identity.
return {
cliOnly: true,
noCliBonus: out.noCliBonus ?? false,
channel: CLI_CHANNEL,
userId: CLI_SYNTHETIC_USER_ID,
platformId: CLI_PLATFORM_ID,
displayName: out.displayName,
agentName: out.agentName?.trim() || out.displayName,
welcome: out.welcome?.trim() || DEFAULT_WELCOME,
};
}
const required: (keyof Args)[] = ['channel', 'userId', 'platformId'];
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(
`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 {
cliOnly: false,
noCliBonus: out.noCliBonus ?? false,
channel: out.channel!,
userId: out.userId!,
platformId: out.platformId!,
displayName: out.displayName,
agentName: out.agentName?.trim() || out.displayName,
displayName: out.displayName!,
agentName: out.agentName?.trim() || out.displayName!,
welcome: out.welcome?.trim() || DEFAULT_WELCOME,
};
}
@@ -217,7 +188,6 @@ async function main(): Promise<void> {
const now = new Date().toISOString();
// 1. User + (conditional) owner grant.
// In cli-only mode, the synthetic `cli:local` user becomes the first owner.
const userId = namespacedUserId(args.channel, args.userId);
upsertUser({
id: userId,
@@ -238,10 +208,8 @@ async function main(): Promise<void> {
promotedToOwner = true;
}
// 2. Agent group + filesystem
const folder = args.cliOnly
? `cli-with-${normalizeName(args.displayName)}`
: `dm-with-${normalizeName(args.displayName)}`;
// 2. Agent group + filesystem.
const folder = `dm-with-${normalizeName(args.displayName)}`;
let ag: AgentGroup | undefined = getAgentGroupByFolder(folder);
if (!ag) {
const agId = generateId('ag');
@@ -261,89 +229,115 @@ async function main(): Promise<void> {
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.',
'When the user first reaches out (or you receive a system welcome prompt), introduce yourself briefly and invite them to chat. Keep replies concise.',
});
// 3. Primary messaging group + wiring + welcome session.
// In DM mode: the DM messaging group is primary, CLI is wired as a bonus.
// In cli-only mode: the CLI messaging group is primary; no DM group.
const cliMg = ensureCliMessagingGroup(now);
let primaryMg: MessagingGroup;
if (args.cliOnly) {
primaryMg = cliMg;
// 3. DM messaging group.
const platformId = namespacedPlatformId(args.channel, args.platformId);
let dmMg = getMessagingGroupByPlatform(args.channel, platformId);
if (!dmMg) {
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,
});
dmMg = getMessagingGroupByPlatform(args.channel, platformId)!;
console.log(`Created messaging group: ${dmMg.id} (${platformId})`);
} else {
const platformId = namespacedPlatformId(args.channel, args.platformId);
let dmMg = getMessagingGroupByPlatform(args.channel, platformId);
if (!dmMg) {
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,
});
dmMg = getMessagingGroupByPlatform(args.channel, platformId)!;
console.log(`Created messaging group: ${dmMg.id} (${platformId})`);
} else {
console.log(`Reusing messaging group: ${dmMg.id} (${platformId})`);
}
primaryMg = dmMg;
console.log(`Reusing messaging group: ${dmMg.id} (${platformId})`);
}
// Wire primary (DM or CLI), auto-creates companion agent_destinations row.
wireIfMissing(primaryMg, ag, now, args.cliOnly ? 'cli' : 'dm');
// In DM mode also wire CLI so `pnpm run chat` works immediately.
// Skip the bonus when --no-cli-bonus is set — used by /new-setup-2 so the
// throwaway CLI-only agent from /new-setup still owns CLI routing cleanly.
if (!args.cliOnly && !args.noCliBonus) {
// 4. Wire DM (auto-creates companion agent_destinations row) and,
// unless suppressed, also wire the CLI channel so `pnpm run chat` works
// against the new agent immediately. `/new-setup-2` sets --no-cli-bonus
// so the scratch CLI agent from `/new-setup` keeps owning CLI routing.
wireIfMissing(dmMg, ag, now, 'dm');
if (!args.noCliBonus) {
const cliMg = ensureCliMessagingGroup(now);
wireIfMissing(cliMg, ag, now, 'cli-bonus');
}
// 4. Session + staged welcome (on the primary messaging group)
const { session, created } = resolveSession(ag.id, primaryMg.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: primaryMg.platform_id,
channelType: primaryMg.channel_type,
threadId: null,
content: JSON.stringify({
text: args.welcome,
sender: 'system',
senderId: 'system',
}),
});
// 5. Welcome delivery over the CLI socket. Router picks up the line,
// writes the message into the DM session's inbound.db, and wakes the
// container synchronously — no sweep wait.
await sendWelcomeViaCliSocket(dmMg, args.welcome);
console.log('');
console.log('Init complete.');
console.log(` owner: ${userId}${promotedToOwner ? ' (promoted on first owner)' : ''}`);
console.log(` agent: ${ag.name} [${ag.id}] @ groups/${folder}`);
if (args.cliOnly) {
console.log(` channel: cli/${CLI_PLATFORM_ID}`);
} else {
console.log(` channel: ${args.channel} ${primaryMg.platform_id}`);
if (!args.noCliBonus) {
console.log(` cli: cli/${CLI_PLATFORM_ID} wired — try \`pnpm run chat hi\``);
}
console.log(` channel: ${args.channel} ${dmMg.platform_id}`);
if (!args.noCliBonus) {
console.log(` cli: cli/${CLI_PLATFORM_ID} wired — try \`pnpm run chat hi\``);
}
console.log(` session: ${session.id}`);
console.log('');
console.log(
args.cliOnly
? 'Host sweep (<=60s) will wake the container. Try `pnpm run chat hi`.'
: 'Host sweep (<=60s) will wake the container and the agent will send the welcome DM.',
);
console.log('Welcome DM queued — the agent will greet you shortly.');
}
/**
* Hand the welcome to the running service via its CLI Unix socket. The
* service's CLI adapter receives `{text, to}`, builds an InboundEvent
* targeting the DM messaging group, and calls routeInbound(). Router writes
* the message into inbound.db and wakes the container synchronously.
*
* Throws if the socket isn't reachable — this script requires the service
* to be running.
*/
async function sendWelcomeViaCliSocket(dmMg: MessagingGroup, welcome: string): Promise<void> {
const sockPath = path.join(DATA_DIR, 'cli.sock');
await new Promise<void>((resolve, reject) => {
const socket = net.connect(sockPath);
let settled = false;
const settle = (err: Error | null) => {
if (settled) return;
settled = true;
try {
socket.end();
} catch {
/* noop */
}
if (err) reject(err);
else resolve();
};
socket.once('error', (err) =>
settle(
new Error(
`CLI socket at ${sockPath} not reachable: ${err.message}. Is the NanoClaw service running?`,
),
),
);
socket.once('connect', () => {
const payload =
JSON.stringify({
text: welcome,
to: {
channelType: dmMg.channel_type,
platformId: dmMg.platform_id,
threadId: null,
},
}) + '\n';
socket.write(payload, (err) => {
if (err) {
settle(err);
return;
}
// Brief flush delay so the router picks up the line before we close.
// Router handles it synchronously once read, so 50ms is plenty.
setTimeout(() => settle(null), 50);
});
});
});
}
main().catch((err) => {
console.error(err);
console.error(err instanceof Error ? err.message : err);
process.exit(1);
});