Revert "fix(init-first-agent): seed welcome via inbound.db; drop --no-cli-bonus"

This reverts commit 9fe529984a.
This commit is contained in:
gavrielc
2026-04-21 15:20:06 +03:00
parent 77e6d3bc66
commit 40ddc94d0a
3 changed files with 121 additions and 45 deletions

View File

@@ -87,13 +87,13 @@ The script:
2. Creates the `agent_groups` row and calls `initGroupFilesystem` at `groups/dm-with-<name>/`. 2. Creates the `agent_groups` row and calls `initGroupFilesystem` at `groups/dm-with-<name>/`.
3. Reuses or creates the DM `messaging_groups` row. 3. Reuses or creates the DM `messaging_groups` row.
4. Wires them via `messaging_group_agents` (which auto-creates the companion `agent_destinations` row). 4. Wires them via `messaging_group_agents` (which auto-creates the companion `agent_destinations` row).
5. Seeds the welcome message directly into the DM session's `inbound.db` (sender tagged `System`). The running service's host-sweep picks it up on the next pass and wakes the container through the normal path — no CLI-socket hand-off, no `cli:local` identity on the new agent's permission surface. 5. Hands the welcome message to the running service via its CLI socket (`data/cli.sock`), targeting the DM messaging group. The service routes it into the DM session, which wakes the container synchronously. If the socket isn't reachable (service down), falls back to a direct `inbound.db` write that the next host sweep picks up.
Show the script's output to the user. Show the script's output to the user.
## 5. Verify ## 5. Verify
The welcome is written to `inbound.db` immediately; the wait is host-sweep pickup (≤60s) plus container cold-start (~60s on first launch) before the agent processes the message and the reply flows through `outbound.db` to the channel. The welcome DM is queued synchronously; the only wait is container cold-start (~60s on first launch) before the agent processes the message and the reply flows through `outbound.db` to the channel.
Do not tail the log or poll in a sleep loop. Ask the user in plain text: Do not tail the log or poll in a sleep loop. Ask the user in plain text:

View File

@@ -92,7 +92,7 @@ When the user picks one:
``` ```
2. **Capture platform IDs.** After the `/add-<channel>` skill finishes (or after inline credentials for Telegram), you need two values: the operator's user-id on that platform, and the chat/channel platform-id. Each channel surfaces these differently — consult the **Channel Info** section at the bottom of that skill's `SKILL.md` for the exact path. For Telegram, run `pnpm exec tsx setup/index.ts --step pair-telegram -- --intent <main|wire-to:folder|new-agent:folder>` directly and follow its `PAIR_TELEGRAM_ISSUED`/`PAIR_TELEGRAM STATUS=success` blocks — `PLATFORM_ID` and `ADMIN_USER_ID` land in the success block. 2. **Capture platform IDs.** After the `/add-<channel>` skill finishes (or after inline credentials for Telegram), you need two values: the operator's user-id on that platform, and the chat/channel platform-id. Each channel surfaces these differently — consult the **Channel Info** section at the bottom of that skill's `SKILL.md` for the exact path. For Telegram, run `pnpm exec tsx setup/index.ts --step pair-telegram -- --intent <main|wire-to:folder|new-agent:folder>` directly and follow its `PAIR_TELEGRAM_ISSUED`/`PAIR_TELEGRAM STATUS=success` blocks — `PLATFORM_ID` and `ADMIN_USER_ID` land in the success block.
3. **Wire the agent.** Run `init-first-agent.ts` in DM mode: 3. **Wire the agent.** Run `init-first-agent.ts` in DM mode with `--no-cli-bonus` (this keeps the new agent off the CLI messaging group so the pre-existing throwaway agent still owns CLI routing cleanly):
``` ```
pnpm exec tsx scripts/init-first-agent.ts \ pnpm exec tsx scripts/init-first-agent.ts \
@@ -100,7 +100,8 @@ When the user picks one:
--user-id "<platform-user-id>" \ --user-id "<platform-user-id>" \
--platform-id "<platform-chat-id>" \ --platform-id "<platform-chat-id>" \
--display-name "<OPERATOR_NAME>" \ --display-name "<OPERATOR_NAME>" \
--agent-name "<AGENT_NAME>" --agent-name "<AGENT_NAME>" \
--no-cli-bonus
``` ```
4. **Announce.** On success, emit the encouragement line verbatim: 4. **Announce.** On success, emit the encouragement line verbatim:

View File

@@ -1,25 +1,24 @@
/** /**
* Init the first (or Nth) NanoClaw v2 agent for a DM channel. * Init the first (or Nth) NanoClaw v2 agent for a DM channel.
* *
* Wires a real DM channel (discord, telegram, etc.) to a new agent group, * Wires a real DM channel (discord, telegram, etc.) to a new agent group
* then seeds a welcome message directly into the session's inbound DB. The * (and the local CLI channel as a convenience bonus), then hands a welcome
* running service's host-sweep picks it up on its next pass (within * message to the running service via its CLI socket. The service routes
* SWEEP_INTERVAL_MS) and wakes the container through the normal path; the * that message into the DM session, which wakes the container synchronously —
* agent introduces itself via the channel. * the agent processes the welcome and DMs the operator through the normal
* delivery path.
* *
* CLI channel wiring is NOT touched here — `scripts/init-cli-agent.ts` owns * For the CLI-only scratch agent used during `/new-setup`, see
* the cli/local messaging group and its scratch agent. Keeping the two * `scripts/init-cli-agent.ts` — that's a distinct flow and doesn't run
* scripts disjoint means no `cli:local` identity ever appears on the new * through here.
* agent's permission surface, so the unknown-sender approval card that used
* to fire when the welcome was queued via the CLI admin socket no longer
* happens.
* *
* Creates/reuses: user, owner grant (if none), agent group + filesystem, * Creates/reuses: user, owner grant (if none), agent group + filesystem,
* messaging group, wiring, session, welcome message. * messaging group(s), wiring.
* *
* Runs alongside the service (WAL-mode sqlite) — does NOT initialize channel * Runs alongside the service (WAL-mode sqlite + CLI socket IPC) — does NOT
* adapters, so there's no Gateway conflict. No IPC to the service is needed; * initialize channel adapters, so there's no Gateway conflict. Requires
* the sweep is the sole hand-off. * the service to be running: the welcome hand-off goes over the CLI socket
* and fails loudly if the service isn't up.
* *
* Usage: * Usage:
* pnpm exec tsx scripts/init-first-agent.ts \ * pnpm exec tsx scripts/init-first-agent.ts \
@@ -28,11 +27,13 @@
* --platform-id discord:@me:1491573333382523708 \ * --platform-id discord:@me:1491573333382523708 \
* --display-name "Gavriel" \ * --display-name "Gavriel" \
* [--agent-name "Andy"] \ * [--agent-name "Andy"] \
* [--welcome "System instruction: ..."] * [--welcome "System instruction: ..."] \
* [--no-cli-bonus]
* *
* For direct-addressable channels (telegram, whatsapp, etc.), --platform-id * For direct-addressable channels (telegram, whatsapp, etc.), --platform-id
* is typically the same as the handle in --user-id, with the channel prefix. * is typically the same as the handle in --user-id, with the channel prefix.
*/ */
import net from 'net';
import path from 'path'; import path from 'path';
import { DATA_DIR } from '../src/config.js'; import { DATA_DIR } from '../src/config.js';
@@ -49,10 +50,10 @@ import { normalizeName } from '../src/modules/agent-to-agent/db/agent-destinatio
import { grantRole, hasAnyOwner } from '../src/modules/permissions/db/user-roles.js'; import { grantRole, hasAnyOwner } from '../src/modules/permissions/db/user-roles.js';
import { upsertUser } from '../src/modules/permissions/db/users.js'; import { upsertUser } from '../src/modules/permissions/db/users.js';
import { initGroupFilesystem } from '../src/group-init.js'; import { initGroupFilesystem } from '../src/group-init.js';
import { resolveSession, writeSessionMessage } from '../src/session-manager.js';
import type { AgentGroup, MessagingGroup } from '../src/types.js'; import type { AgentGroup, MessagingGroup } from '../src/types.js';
interface Args { interface Args {
noCliBonus: boolean;
channel: string; channel: string;
userId: string; userId: string;
platformId: string; platformId: string;
@@ -64,12 +65,18 @@ interface Args {
const DEFAULT_WELCOME = const DEFAULT_WELCOME =
'System instruction: run /welcome to introduce yourself to the user on this new channel.'; 'System instruction: run /welcome to introduce yourself to the user on this new channel.';
const CLI_CHANNEL = 'cli';
const CLI_PLATFORM_ID = 'local';
function parseArgs(argv: string[]): Args { function parseArgs(argv: string[]): Args {
const out: Partial<Args> = {}; const out: Partial<Args> = { noCliBonus: false };
for (let i = 0; i < argv.length; i++) { for (let i = 0; i < argv.length; i++) {
const key = argv[i]; const key = argv[i];
const val = argv[i + 1]; const val = argv[i + 1];
switch (key) { switch (key) {
case '--no-cli-bonus':
out.noCliBonus = true;
break;
case '--channel': case '--channel':
out.channel = (val ?? '').toLowerCase(); out.channel = (val ?? '').toLowerCase();
i++; i++;
@@ -108,6 +115,7 @@ function parseArgs(argv: string[]): Args {
} }
return { return {
noCliBonus: out.noCliBonus ?? false,
channel: out.channel!, channel: out.channel!,
userId: out.userId!, userId: out.userId!,
platformId: out.platformId!, platformId: out.platformId!,
@@ -129,6 +137,24 @@ function generateId(prefix: string): string {
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
} }
function ensureCliMessagingGroup(now: string): MessagingGroup {
let cliMg = getMessagingGroupByPlatform(CLI_CHANNEL, CLI_PLATFORM_ID);
if (cliMg) return 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}`);
return cliMg;
}
function wireIfMissing(mg: MessagingGroup, ag: AgentGroup, now: string, label: string): void { function wireIfMissing(mg: MessagingGroup, ag: AgentGroup, now: string, label: string): void {
const existing = getMessagingGroupAgentByPair(mg.id, ag.id); const existing = getMessagingGroupAgentByPair(mg.id, ag.id);
if (existing) { if (existing) {
@@ -139,8 +165,9 @@ function wireIfMissing(mg: MessagingGroup, ag: AgentGroup, now: string, label: s
id: generateId('mga'), id: generateId('mga'),
messaging_group_id: mg.id, messaging_group_id: mg.id,
agent_group_id: ag.id, agent_group_id: ag.id,
// DMs default to "respond to everything" via a '.' regex. Group chats // DM / CLI (is_group=0) default to "respond to everything" via a '.' regex.
// default to mention-only; admins can upgrade via /manage-channels. // Group chats default to mention-only; admins can upgrade to mention-sticky
// via /manage-channels once the agent is in use.
engage_mode: mg.is_group === 0 ? 'pattern' : 'mention', engage_mode: mg.is_group === 0 ? 'pattern' : 'mention',
engage_pattern: mg.is_group === 0 ? '.' : null, engage_pattern: mg.is_group === 0 ? '.' : null,
sender_scope: 'all', sender_scope: 'all',
@@ -225,40 +252,88 @@ async function main(): Promise<void> {
console.log(`Reusing messaging group: ${dmMg.id} (${platformId})`); console.log(`Reusing messaging group: ${dmMg.id} (${platformId})`);
} }
// 4. Wire DM. // 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'); wireIfMissing(dmMg, ag, now, 'dm');
if (!args.noCliBonus) {
const cliMg = ensureCliMessagingGroup(now);
wireIfMissing(cliMg, ag, now, 'cli-bonus');
}
// 5. Seed the welcome directly into the session's inbound.db. The running // 5. Welcome delivery over the CLI socket. Router picks up the line,
// service's sweep will observe trigger=1 and wake the container on its next // writes the message into the DM session's inbound.db, and wakes the
// pass — no IPC, no CLI socket, no `cli:local` sender in the router path. // container synchronously — no sweep wait.
seedWelcome(ag.id, dmMg, args.welcome); await sendWelcomeViaCliSocket(dmMg, args.welcome);
console.log(''); console.log('');
console.log('Init complete.'); console.log('Init complete.');
console.log(` owner: ${userId}${promotedToOwner ? ' (promoted on first owner)' : ''}`); console.log(` owner: ${userId}${promotedToOwner ? ' (promoted on first owner)' : ''}`);
console.log(` agent: ${ag.name} [${ag.id}] @ groups/${folder}`); console.log(` agent: ${ag.name} [${ag.id}] @ groups/${folder}`);
console.log(` channel: ${args.channel} ${dmMg.platform_id}`); 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(''); console.log('');
console.log('Welcome seeded — the agent will greet you on the next sweep pass.'); console.log('Welcome DM queued — the agent will greet you shortly.');
} }
/** /**
* Write the welcome as a due inbound message on a shared session for the * Hand the welcome to the running service via its CLI Unix socket. The
* new agent group + messaging group pair. Sender is tagged "System" — the * service's CLI adapter receives `{text, to}`, builds an InboundEvent
* welcome carries no real user identity and never crosses the router's * targeting the DM messaging group, and calls routeInbound(). Router writes
* sender-approval gate. * 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.
*/ */
function seedWelcome(agentGroupId: string, mg: MessagingGroup, welcome: string): void { async function sendWelcomeViaCliSocket(dmMg: MessagingGroup, welcome: string): Promise<void> {
const { session } = resolveSession(agentGroupId, mg.id, null, 'shared'); const sockPath = path.join(DATA_DIR, 'cli.sock');
writeSessionMessage(agentGroupId, session.id, {
id: generateId('welcome'), await new Promise<void>((resolve, reject) => {
kind: 'chat', const socket = net.connect(sockPath);
timestamp: new Date().toISOString(), let settled = false;
channelType: mg.channel_type,
platformId: mg.platform_id, const settle = (err: Error | null) => {
threadId: null, if (settled) return;
content: JSON.stringify({ text: welcome, sender: 'System' }), settled = true;
trigger: 1, 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);
});
});
}); });
} }