11 Commits

Author SHA1 Message Date
340eed8aa3 feat(guild): restore system-key bypass + isSystem msg path
Resurrects the x-fabric-system-key bypass + isSystem branch on POST
/channels/:id/messages, dropped in ca20df7 when dialectic stopped
broadcasting topic lifecycle events to Fabric. Re-enabling now because
Fabric.OpenclawPlugin's close-sub-discussion needs to write a callback
into a parent channel as a system-authored message (not as the closing
host), with an optional precision wakeup so the recruitment workflow can
resume immediately after an interview sub-discussion closes.

Three coupled bits:

1. ApiKeyGuard pre-Bearer bypass: when x-fabric-system-key matches
   FABRIC_BACKEND_GUILD_COMMANDS_SYNC_KEY, set req.isSystem=true and
   skip the Bearer check. Intentionally reuses the existing commands
   sync env — same shared secret, same consumer (the OpenclawPlugin
   reads channels.fabric.commandsSyncKey for both paths). One less env
   to rotate, one less secret to manage.

2. messaging.controller POST /channels/:id/messages adds an isSystem
   branch (runs before the participant gate):

   - Looks up the channel directly (not via assertParticipant).
   - Persists with sentinel author 00000000-0000-0000-0000-000000000000,
     same UUID the old impl used.
   - Translates <@user.name:NAME> mentions like the regular path.
   - When wakeupUserId is set, delivers via emitMessageTargeted so that
     exactly that one recipient receives wakeup=true; everyone else gets
     wakeup=false. When omitted, delivers via emitMessageCreated with an
     empty wakeUserIds set so nobody is woken — silent system log.

   Two intentional differences from the 985b06a original:
   - No xType=announce restriction. The original was limited to announce
     because that was Dialectic's only use case; we now need this on dm /
     general / discuss / etc. for the sub-discussion callback. Closed
     channels are still rejected (409) on both paths.
   - The wakeupUserId field is new — old impl only ever sent silent
     announces.

3. DTO carries wakeupUserId? optional string. Ignored on the regular
   user-bearer path; load-bearing on the system path.

Shared helper: extracted commands.controller's private safeEqual into
src/common/safe-equal.ts so api-key.guard.ts can use the same constant-
time check. Vitest spec covers equal / inequal / length-mismatch / empty
cases. Existing unit tests still pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 20:51:19 +01:00
h z
3f77c0e35d fix(agent-presence): upsert atomically — kill first-time-insert race (#3) 2026-05-26 02:06:20 +00:00
38b4665321 fix(agent-presence): upsert atomically — kill first-time-insert race
Previous setStatus() did read-modify-write:
  findOne → if-exists save / else create+save

Two concurrent first-time writes for the same userId both saw no row,
both INSERT'd, second hit unique-key (agent_presences.PRIMARY) and 500'd
with "Duplicate entry '<userId>' for key 'agent_presences.PRIMARY'" —
visible in prod (2026-05-25 23:23:35Z) when Fabric.OpenclawPlugin's
presence-sync emitted two PUTs ~10 ms apart for the same agent (its
tick-overlap is being fixed separately in nav/Fabric.OpenclawPlugin).

Replace with repo.upsert(values, ['userId']) — compiles to MySQL
`INSERT … ON DUPLICATE KEY UPDATE`, atomic at the storage engine,
no read needed, no race window. Synthesize the returned entity from
the values we just wrote rather than a SELECT round-trip; controller
only reads {userId, status} off it.

Sim verified with 5 parallel PUTs to a fresh userId: all 200, no
Duplicate errors in guild log (was: 1 × 200 + 4 × 500 with the
old code).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 02:25:07 +01:00
ca20df7618 refactor(guild): drop system-key bypass + announce-only-system limit
Pairs with Dialectic.Backend@5cf4302 which removes the backend-driven
broadcaster that was the only consumer of the x-fabric-system-key
header path. Backend cleanup is complete on the consumer side; this
removes the producer-side surface.

Removed:
  - ApiKeyGuard: x-fabric-system-key bypass branch (sysExpected /
    sysProvided / req.isSystem flag) — only Bearer flow remains.
  - messaging.controller.create(): the entire 'if (req.isSystem)'
    branch including the SYSTEM_USER_ID='00000000-...-0000' sentinel
    persistence path.
  - messaging.controller.create(): the 'if (xType === announce) throw
    announce_system_only' gate. Announce channels are now ordinary
    channels — any participant can POST. Use case: agents post one-off
    recruitment broadcasts via fabric-send-message (e.g. dialectic
    'come participate in topic X' messages).
  - cli/gen-system-api-key.ts: deleted (was the generator for the env
    that's no longer read).

Kept:
  - channel.purpose field + PATCH /api/channels/:id (member auth for
    setting purpose — agents use this to label channels for
    fabric-channel-list discoverability).
  - cli/print-commands-sync-key.ts (separate key, separate lifecycle).
  - GuildRole.isSystem flag (unrelated — system-role permission gate).
2026-05-23 23:49:47 +01:00
cb7b3bb5fe feat(channel-discovery): add purpose column + PATCH /api/channels/:id
Adds a free-form 'purpose' text field on Channel so agents (or anyone
creating a channel via API) can describe what the channel is for —
'debate broadcasts', 'security alerts', etc. — and other agents can
later find the right channel by intent rather than channel id.

Wire:
  - Channel.purpose (text, nullable; TypeORM synchronize auto-adds)
  - POST /api/channels accepts optional 'purpose' in body
  - GET /api/channels returns purpose on every row (already returns the
    full entity via {...c})
  - PATCH /api/channels/:id { purpose } — member-or-public auth (mirrors
    the close() rule). Today only 'purpose' is patchable; other fields
    would get their own typed branch.

Frontend create form continues to omit the field — purpose stays optional.
This pairs with Fabric.OpenclawPlugin's fabric-channel-set-purpose tool +
fabric-channel-list returning purpose, so agent workflows can say 'find
an announce channel about X' instead of pinning a UUID.
2026-05-23 19:22:00 +01:00
985b06a886 feat(guild): system-key bypass + announce-only system path + gen CLI
Three coupled changes that let Dialectic.Backend (and future system
broadcasters) post to announce channels without needing a Fabric user
bearer.

1. ApiKeyGuard: when x-fabric-system-key matches
   FABRIC_BACKEND_GUILD_SYSTEM_API_KEY env, skip the Bearer requirement
   and set req.isSystem=true. Pre-Bearer system bypass; no per-user
   session token needed. Empty env -> bypass disabled (closed by default).

2. messaging.controller POST /channels/:id/messages: when req.isSystem,
   skip assertParticipant + fetch channel directly. Enforce xType=announce
   (system key only writes to announce channels - never to regular chats).
   Persist with sentinel author 00000000-0000-0000-0000-000000000000.
   Emit message.created + realtime.emitMessageCreated with xType=announce
   so the Phase 1 busy-discard logic kicks in for recipients.

3. New cli: src/cli/gen-system-api-key.ts. Generates a random 32-byte
   hex key (same shape as agent + admin keys) and prints it. Does NOT
   store - operator pastes into compose env and restarts guild. Pattern
   mirrors the existing print-commands-sync-key.ts.

Removes the need for a FABRIC_BOT_BEARER_TOKEN concept entirely - the
system key alone is sufficient. announce-channel posts by regular
authenticated users (who happen to know channel id but no system key)
are now 403 announce_system_only.
2026-05-23 17:49:53 +01:00
80ee9082f3 feat(guild): announce channel type + agent-presence + busy-discard
Phase 1 of DIALECTIC-V2 — adds Fabric infrastructure for
system-broadcast channels with HF-status-aware delivery filtering.

New channel x_type 'announce':
- channels.entity.ts + channels.service.ts + realtime.gateway.ts
  enum + union extended.
- computeDelivery() adds an 'announce' case: recipient with
  presence='busy' → 'skip' (discarded silently); other presences →
  'observer' (delivered, no wake). System-broadcast semantics —
  agents proactively check their announce inbox when they're ready,
  not interrupted out of band.
- messaging.controller POST guard: announce-type channels reject
  posts that don't present x-fabric-system-key header matching
  FABRIC_BACKEND_GUILD_SYSTEM_API_KEY env. Empty env = no system
  caller is valid (closed-by-default).

New entity + module agent_presences:
- agent-presence.entity.ts: per-user (userId PK) status enum
  (idle/on_call/busy/exhausted/offline/unknown), source tag, updatedAt
- agent-presence.service.ts: getStatus/getStatusMap (bulk for
  delivery-time fanout) + setStatus (upsert)
- agent-presence.controller.ts: GET + PUT /agents/:userId/presence
- agent-presence.module.ts: TypeORM forFeature + wired into AppModule
- buildTypeOrmConfig() entities list extended

RealtimeGateway wiring:
- New optional  field on the gateway (typed loosely to avoid
  circular import). RealtimeModule.onModuleInit() assigns from the
  injected AgentPresenceService — degrades gracefully (no busy-discard,
  treat all as 'unknown') if presence wiring is ever removed.
- emitMessageCreated pre-loads presence per fanout only when xType is
  'announce' (other xTypes bypass the lookup entirely).

Note: actual presence data writes come from Fabric.OpenclawPlugin's
presence-sync loop (separate commit on that submodule); without it,
all rows are 'unknown' and announce delivery falls through to the
default observer behavior (no busy filtering). System-only POST gate
is independent and works immediately.

See /home/hzhang/arch/DIALECTIC-V2-DESIGN.md sections 7 + 10 Phase 1.
2026-05-23 11:31:47 +01:00
801b562999 Merge pull request 'feat(triage): 3-state delivery + admin observer + admin cache' (#2) from feat/triage-3state-delivery into main 2026-05-22 21:59:19 +00:00
7cb046d785 feat(triage): 3-state delivery + admin observer + admin cache
Triage channels now compute a 3-state delivery decision per recipient
(wake / observer / skip) instead of the binary wakeup flag, and route
according to:

  1. author never gets back their own message            → skip
  2. wake_mapping member (on-duty)                       → wake
  3. mention (NEW: was 'skip' for triage before)         → wake
  4. Center-scoped admin (at most 1)                     → observer
  5. anyone else                                         → skip
                                                         (was 'deliver wake=false')

Skipping means the websocket emit is omitted entirely — the recipient's
openclaw plugin never sees the message and the agent's session stays
free of background noise. Observer means delivered with wakeup=false
(silent UI / no model dispatch on the plugin side).

## What this PR ships

### realtime/realtime.gateway.ts
- new `computeDelivery()` returns DeliveryDecision = 'wake'|'observer'|'skip'
- old `computeWakeup()` kept as a deprecated wrapper for callers that
  still want the boolean answer (treats observer + skip as false)
- `emitMessageCreated` accepts `adminUserId?: string|null` and now
  short-circuits on 'skip' (no socket emit at all)
- general kept its current behavior; custom kept its current behavior
  (members not in wake_mapping become observer instead of `wake=false`)
  — the user-visible bit is just that the response field is the same
  `wakeup: boolean`; the explicit 'skip' is new for triage

### common/center-auth.ts
- `fetchAdminEmail()` calls GET `${center}/auth/admin-email` with the
  existing x-api-key (same auth as introspect/resolve-names). Returns
  `{email, userId}` or `null` on either "no admin" or any error

### common/admin-cache.service.ts (NEW)
- `AdminCacheService` — in-memory cache, 1-day TTL, lazy refresh.
  `get(force=true)` bypasses TTL for cli-triggered refresh
- exposed by MessagingModule

### messaging/messaging.controller.ts
- non-rotating branch threads `adminUserId` into emitMessageCreated

### cli/admin-refresh.ts (NEW)
- `node dist/cli/admin-refresh.js` — force-refresh cache and print
  before/after JSON. Use after a Center `user set-admin` so triage
  delivery picks up the new admin without waiting for 24h TTL

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 22:14:05 +01:00
e635faea9c Merge pull request 'feat(realtime): push channel.joined/left events to user-scoped rooms' (#1) from feat/push-channel-membership-events into main 2026-05-21 07:12:51 +00:00
30069377e7 feat(realtime): push channel.joined/left events to user-scoped rooms
Backend half of the plugin push-based channel sync (companion to
nav/Fabric.OpenclawPlugin#1 follow-up). Before this, the OpenClaw
fabric inbound had to poll `/api/channels?guildId=...` every 60s to
discover newly-joined channels (any DM another user just dragged the
agent into). Now the server tells the agent's socket directly so
sub/unsub is realtime.

Changes:
- realtime.gateway.ts:
  * handleConnection joins the socket into a `user:<userId>` room.
    All of a user's connected sockets now share that room.
  * New `emitToUser(userId, event, data)` helper that emits into
    that room. No-op for offline users (next connect resyncs via the
    plugin's initial channel-list fetch).
- channels.service.ts:
  * Inject RealtimeGateway (RealtimeModule is @Global, no module
    plumbing needed).
  * Private `notifyMembership(kind, channelId, userIds, extra)`
    helper that emits `channel.<kind>` (joined|left) with payload
    {channelId, userId, xType, occurredAt}.
  * create(): emit channel.joined to every seeded member (creator +
    explicit memberUserIds + triage on-duty).
  * joinChannel(): emit channel.joined to userId (only if the row was
    actually inserted, idempotent on existing membership).
  * leaveChannel(): emit channel.left to userId iff a row was
    actually deleted.

Event shape:
  {
    channelId: string,
    userId: string,
    xType?: string,
    occurredAt: ISO string,
  }

Client-side contract (fabric plugin):
  socket.on('channel.joined', m => socket.emit('join_channel', {channelId: m.channelId}))
  socket.on('channel.left',   m => socket.emit('leave_channel', {channelId: m.channelId}))

The plugin keeps its 60s polling resync as a safety net for missed
events (transient socket drops between emit and reconnect, partial
failures, etc).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 08:07:46 +01:00
21 changed files with 689 additions and 48 deletions

View File

@@ -0,0 +1,42 @@
import { BadRequestException, Body, Controller, Get, Param, Put } from '@nestjs/common';
import { AgentPresenceService, PresenceStatus } from './agent-presence.service.js';
const VALID: PresenceStatus[] = ['idle', 'on_call', 'busy', 'exhausted', 'offline', 'unknown'];
interface PutBody {
status?: string;
source?: string;
}
@Controller('agents/:userId/presence')
export class AgentPresenceController {
constructor(private readonly svc: AgentPresenceService) {}
/**
* Read a user's current presence cache row.
* Auth: ApiKeyGuard (global). Any introspected center user can read.
*/
@Get()
async get(@Param('userId') userId: string): Promise<{ userId: string; status: PresenceStatus }> {
const status = await this.svc.getStatus(userId);
return { userId, status };
}
/**
* Push a presence update. Called by Fabric.OpenclawPlugin's
* `presence-sync` loop on each delta. Auth: ApiKeyGuard (global) +
* the plugin uses its center-introspected api key.
*
* `source` is a debug tag describing who pushed (e.g. 'hf-plugin',
* 'manual'). Stored verbatim for trail.
*/
@Put()
async put(@Param('userId') userId: string, @Body() body: PutBody): Promise<{ userId: string; status: PresenceStatus }> {
if (!body?.status || !VALID.includes(body.status as PresenceStatus)) {
throw new BadRequestException(`status must be one of ${VALID.join('|')}`);
}
const source = (body.source ?? 'unknown').slice(0, 64);
const row = await this.svc.setStatus(userId, body.status as PresenceStatus, source);
return { userId: row.userId, status: row.status };
}
}

View File

@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AgentPresence } from '../entities/agent-presence.entity.js';
import { AgentPresenceController } from './agent-presence.controller.js';
import { AgentPresenceService } from './agent-presence.service.js';
@Module({
imports: [TypeOrmModule.forFeature([AgentPresence])],
controllers: [AgentPresenceController],
providers: [AgentPresenceService],
exports: [AgentPresenceService],
})
export class AgentPresenceModule {}

View File

@@ -0,0 +1,61 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AgentPresence } from '../entities/agent-presence.entity.js';
export type PresenceStatus = 'idle' | 'on_call' | 'busy' | 'exhausted' | 'offline' | 'unknown';
@Injectable()
export class AgentPresenceService {
constructor(
@InjectRepository(AgentPresence)
private readonly repo: Repository<AgentPresence>,
) {}
/**
* Get a user's current presence. Returns 'unknown' if no row.
* Used by `RealtimeGateway` per-recipient when xType === 'announce'.
*/
async getStatus(userId: string): Promise<PresenceStatus> {
if (!userId) return 'unknown';
const row = await this.repo.findOne({ where: { userId } });
return row?.status ?? 'unknown';
}
/** Bulk variant for delivery-time lookups across many recipients in one trip. */
async getStatusMap(userIds: string[]): Promise<Map<string, PresenceStatus>> {
const out = new Map<string, PresenceStatus>();
for (const id of userIds) out.set(id, 'unknown');
if (userIds.length === 0) return out;
const rows = await this.repo
.createQueryBuilder('p')
.where('p.userId IN (:...ids)', { ids: userIds })
.getMany();
for (const r of rows) out.set(r.userId, r.status);
return out;
}
/**
* Upsert a user's presence. Source is a free-text tag for debugging
* (e.g. "hf-plugin", "manual", "test"). PUT /agents/:id/presence
* calls this; the plugin pushes only on diff so writes are sparse.
*
* Implementation note: the older findOne+save split was a read-modify-
* write race — two concurrent first-time writes for the same userId
* would both read no row, both INSERT, second hits unique-key dup
* (`agent_presences.PRIMARY`) and 500s. Fabric.OpenclawPlugin's
* presence-sync occasionally fires two PUTs for the same agent within
* ~10 ms (tick overlap on its side — separate fix in the plugin),
* which surfaced this race in prod.
*
* `repo.upsert(values, conflictPaths)` compiles to MySQL
* `INSERT … ON DUPLICATE KEY UPDATE` and is atomic at the storage
* engine level — no read needed, no race window. We synthesize the
* returned entity from what we just wrote rather than round-tripping
* a SELECT — the controller only reads {userId, status} off it.
*/
async setStatus(userId: string, status: PresenceStatus, source: string): Promise<AgentPresence> {
await this.repo.upsert({ userId, status, source }, ['userId']);
return this.repo.create({ userId, status, source });
}
}

View File

@@ -16,6 +16,7 @@ import { MembersModule } from './members/members.module.js';
import { FilesModule } from './files/files.module.js';
import { CanvasModule } from './canvas/canvas.module.js';
import { CommandsModule } from './commands/commands.module.js';
import { AgentPresenceModule } from './agents/agent-presence.module.js';
@Module({
imports: [
@@ -30,6 +31,7 @@ import { CommandsModule } from './commands/commands.module.js';
FilesModule,
CanvasModule,
CommandsModule,
AgentPresenceModule,
],
controllers: [HealthController, MetricsController],
providers: [

View File

@@ -1,4 +1,4 @@
import { Body, Controller, Get, Param, Post, Query, Req, UnauthorizedException } from '@nestjs/common';
import { BadRequestException, Body, Controller, Get, Param, Patch, Post, Query, Req, UnauthorizedException } from '@nestjs/common';
import { ChannelsService } from './channels.service.js';
// ApiKeyGuard attaches the introspected Center user id onto the request.
@@ -32,11 +32,33 @@ export class ChannelsController {
bypassUserIds: Array.isArray(body.bypassUserIds)
? (body.bypassUserIds as string[])
: [],
purpose: body.purpose as string | undefined,
},
userId,
);
}
// Patch a channel's free-form purpose. Body: { purpose: string }. Pass
// empty string to clear. Auth: channel member (or anyone for public
// channels, mirroring close()). Frontend doesn't call this today —
// intended for agent-side use (fabric-channel-set-purpose tool).
@Patch(':id')
patch(
@Req() req: AuthedRequest,
@Param('id') channelId: string,
@Body() body: Record<string, unknown>,
) {
const userId = req.userId ?? '';
if (!userId) throw new UnauthorizedException('missing user');
// Only `purpose` is patchable today. Future patchable fields would
// get their own typed branch; we explicitly NOT allow {} no-op patches
// because that signals a caller bug.
if (typeof body.purpose !== 'string') {
throw new BadRequestException('purpose (string) is required');
}
return this.channelsService.updatePurpose(channelId, userId, body.purpose);
}
// Move an order member into the bypass list (discuss/work only).
@Post(':id/bypass')
bypass(

View File

@@ -5,8 +5,9 @@ import { Channel } from '../entities/channel.entity.js';
import { ChannelMember } from '../entities/channel-member.entity.js';
import { WakeMapping } from '../entities/wake-mapping.entity.js';
import { TurnService } from './turn.service.js';
import { RealtimeGateway } from '../realtime/realtime.gateway.js';
const X_TYPES = ['general', 'work', 'report', 'discuss', 'triage', 'custom', 'dm'] as const;
const X_TYPES = ['general', 'work', 'report', 'discuss', 'triage', 'custom', 'dm', 'announce'] as const;
type XType = (typeof X_TYPES)[number];
type CreateChannelInput = {
@@ -23,6 +24,10 @@ type CreateChannelInput = {
// discuss/work only: members excluded from rotation (no wakeup unless
// @-mentioned). order and bypass partition the members disjointly.
bypassUserIds?: string[];
// Free-form description of what this channel is for. Optional; agents
// typically fill it when creating, members can later edit via
// PATCH /api/channels/:id.
purpose?: string;
};
@Injectable()
@@ -35,8 +40,34 @@ export class ChannelsService {
@InjectRepository(WakeMapping)
private readonly wakeRepo: Repository<WakeMapping>,
private readonly turnService: TurnService,
// RealtimeGateway is provided by the global RealtimeModule. Used to
// push channel.joined / channel.left so connected clients (e.g. the
// OpenClaw fabric plugin) can sub/unsub socket.io rooms immediately
// instead of waiting for the polling fallback.
private readonly realtime: RealtimeGateway,
) {}
// Push a channel membership change to each affected user's socket-room.
// Best-effort: offline users see the new state on their next connect
// (the inbound runs an initial channel-list fetch on connect).
private notifyMembership(
kind: 'joined' | 'left',
channelId: string,
userIds: string[] | Set<string>,
extra: Record<string, unknown> = {},
): void {
const ids = userIds instanceof Set ? [...userIds] : userIds;
const payload = {
channelId,
...extra,
occurredAt: new Date().toISOString(),
};
for (const u of ids) {
if (!u) continue;
this.realtime.emitToUser(u, `channel.${kind}`, { ...payload, userId: u });
}
}
// Channels visible to a user within a guild:
// - every public channel of the guild (incl. ones created before the user
// joined the guild), OR
@@ -93,6 +124,7 @@ export class ChannelsService {
if (channel.xType === 'discuss' || channel.xType === 'work') {
await this.turnService.onMemberAdded(channelId, userId);
}
this.notifyMembership('joined', channelId, [userId], { xType: channel.xType });
}
return { status: 'ok', channelId, userId, member: true };
}
@@ -102,11 +134,14 @@ export class ChannelsService {
if (!channel) throw new NotFoundException('channel not found');
// remove every channel-scoped row that references this user
await this.memberRepo.delete({ channelId, userId });
const deleted = await this.memberRepo.delete({ channelId, userId });
await this.wakeRepo.delete({ channelId, userId });
if (channel.xType === 'discuss' || channel.xType === 'work') {
await this.turnService.onMemberRemoved(channelId, userId);
}
if ((deleted.affected ?? 0) > 0) {
this.notifyMembership('left', channelId, [userId], { xType: channel.xType });
}
return { status: 'ok', channelId, userId, member: false };
}
@@ -135,6 +170,9 @@ export class ChannelsService {
// allowed (create() always makes a fresh one, no dedup).
const isPublic = xType === 'dm' ? false : Boolean(input.isPublic);
const purposeRaw = String(input.purpose ?? '').trim();
const purpose = purposeRaw === '' ? null : purposeRaw;
const channel = await this.channelRepo.save(
this.channelRepo.create({
guildId,
@@ -143,6 +181,7 @@ export class ChannelsService {
kind: input.kind === 'announcement' ? 'announcement' : 'text',
isPrivate: !isPublic,
isPublic,
purpose,
lastSeq: 0,
}),
);
@@ -160,6 +199,12 @@ export class ChannelsService {
[...memberIds].map((userId) => this.memberRepo.create({ channelId: channel.id, userId })),
);
// Push channel.joined to every seeded member (creator + invitees +
// triage on-duty) so their connected sockets sub the new room
// immediately. Skips offline users — next connect's channel-list
// fetch covers them.
this.notifyMembership('joined', channel.id, memberIds, { xType });
// wake_mapping: triage -> the on-duty user; custom -> each listener
const wakeUserIds = new Set<string>();
if (xType === 'triage') wakeUserIds.add(onDuty);
@@ -182,6 +227,27 @@ export class ChannelsService {
return channel;
}
// Update a channel's free-form purpose. Any channel member may do this
// (or any guild user if the channel is public, mirroring closeChannel's
// member-or-public rule). Pass an empty string to clear.
async updatePurpose(channelId: string, actorUserId: string, purpose: string) {
const channel = await this.channelRepo.findOne({ where: { id: channelId } });
if (!channel) throw new NotFoundException('channel not found');
const member = await this.memberRepo.findOne({ where: { channelId, userId: actorUserId } });
if (!member && !channel.isPublic) {
throw new ForbiddenException('not a channel member');
}
const trimmed = String(purpose ?? '').trim();
channel.purpose = trimmed === '' ? null : trimmed;
const saved = await this.channelRepo.save(channel);
return {
id: saved.id,
name: saved.name,
xType: saved.xType,
purpose: saved.purpose,
};
}
// Move an order member into the bypass list (discuss/work only).
// Any channel member may do this.
async moveToBypass(channelId: string, actorUserId: string, targetUserId: string) {

39
src/cli/admin-refresh.ts Normal file
View File

@@ -0,0 +1,39 @@
// Operator convenience: force-refresh the in-memory Center admin cache
// without waiting for the 1-day TTL. Used after `center user set-admin`
// to make new admin visible immediately to triage delivery.
//
// Usage (inside the deployed container):
// docker exec fabric-backend-guild node dist/cli/admin-refresh.js
//
// Prints the (possibly null) result as JSON. Exit 0 always — a "no
// admin" outcome is a valid state, not an error.
import 'reflect-metadata';
import { NestFactory } from '@nestjs/core';
import { AppModule } from '../app.module.js';
import { AdminCacheService } from '../common/admin-cache.service.js';
async function main() {
const app = await NestFactory.createApplicationContext(AppModule, { logger: ['error', 'warn'] });
try {
const cache = app.get(AdminCacheService);
const before = cache.snapshot();
const after = await cache.get(true);
process.stdout.write(
JSON.stringify({
ok: true,
before,
after,
changed: JSON.stringify(before) !== JSON.stringify(after),
}) + '\n',
);
} finally {
await app.close();
}
}
void main().catch((error: unknown) => {
const message = error instanceof Error ? error.message : 'unknown error';
process.stderr.write(JSON.stringify({ ok: false, error: message }) + '\n');
process.exit(1);
});

View File

@@ -8,19 +8,12 @@ import {
Req,
UnauthorizedException,
} from '@nestjs/common';
import { timingSafeEqual } from 'node:crypto';
import { CommandsService } from './commands.service.js';
import { SyncCommandsDto } from './dto.sync-commands.dto.js';
import { safeEqual } from '../common/safe-equal.js';
type AuthedRequest = { userId?: string };
function safeEqual(a: string, b: string): boolean {
const ab = Buffer.from(a);
const bb = Buffer.from(b);
if (ab.length !== bb.length) return false;
return timingSafeEqual(ab, bb);
}
@Controller('commands')
export class CommandsController {
constructor(private readonly commands: CommandsService) {}

View File

@@ -0,0 +1,73 @@
/**
* Center-scoped admin cache.
*
* Holds the at-most-one admin user (email + userId) fetched from Center.
* Used to decide who to deliver triage messages to as a silent observer
* (wake=false), regardless of on-duty / mention status.
*
* Refresh policy (per spec, 2026-05-22):
* • TTL = 1 day. Center admin changes are rare; agents tolerate a
* day's stale cache without surprises
* • on first lookup the cache lazy-fetches
* • cli `admin refresh` forces an out-of-band refresh without waiting
* for TTL expiry
*
* Failure mode: a Center fetch error is treated identically to "no
* admin" — guild keeps operating without an observer. The cache holds
* the failed-fetch decision for the same TTL so we don't hammer Center.
*/
import { Injectable, Logger } from '@nestjs/common';
import { fetchAdminEmail } from './center-auth.js';
const ADMIN_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
export interface CachedAdmin {
email: string;
userId: string;
}
@Injectable()
export class AdminCacheService {
private readonly logger = new Logger(AdminCacheService.name);
private cached: CachedAdmin | null = null;
private cachedAt = 0;
private inflight: Promise<CachedAdmin | null> | null = null;
/**
* Return the cached admin, fetching from Center if the cache is empty
* or older than the TTL. Returns null if no admin is set.
*
* `force=true` bypasses the cache and refreshes immediately — used by
* the cli refresh command.
*/
async get(force = false): Promise<CachedAdmin | null> {
const fresh = Date.now() - this.cachedAt < ADMIN_CACHE_TTL_MS;
if (!force && this.cachedAt > 0 && fresh) {
return this.cached;
}
if (this.inflight) return this.inflight;
this.inflight = (async () => {
try {
const result = await fetchAdminEmail();
this.cached = result;
this.cachedAt = Date.now();
this.logger.log(
`admin cache refreshed: ${result ? `${result.email} (${result.userId})` : 'no admin set'}`,
);
return result;
} finally {
this.inflight = null;
}
})();
return this.inflight;
}
/** Snapshot of the cached admin (no fetch). Returns null if not yet
* populated. Used by the hot delivery path which doesn't want to
* block on a Center round-trip. */
snapshot(): CachedAdmin | null {
return this.cached;
}
}

View File

@@ -5,6 +5,7 @@ import {
UnauthorizedException,
} from '@nestjs/common';
import { introspectGuildToken } from './center-auth.js';
import { safeEqual } from './safe-equal.js';
@Injectable()
export class ApiKeyGuard implements CanActivate {
@@ -21,6 +22,25 @@ export class ApiKeyGuard implements CanActivate {
return true;
}
// System-key bypass: when a caller presents x-fabric-system-key
// matching FABRIC_BACKEND_GUILD_COMMANDS_SYNC_KEY (intentionally the
// same shared secret as x-commands-sync-key — both legitimate
// consumers are Fabric.OpenclawPlugin), skip the Bearer requirement
// and mark this as a system caller. Downstream handlers (e.g.
// messaging.controller POST /channels/:id/messages) gate on
// req.isSystem to take the system-author code path.
//
// Empty env → bypass disabled (no system caller ever valid; closed
// by default). Header carries the secret as-is; we constant-time
// compare against the env value.
const sysExpected = (process.env.FABRIC_BACKEND_GUILD_COMMANDS_SYNC_KEY ?? '').trim();
const sysHeader = req.headers['x-fabric-system-key'];
const sysProvided = Array.isArray(sysHeader) ? sysHeader[0] : sysHeader;
if (sysExpected && sysProvided && safeEqual(sysProvided, sysExpected)) {
(req as { isSystem?: boolean }).isSystem = true;
return true;
}
const auth = req.headers['authorization'];
const authValue = Array.isArray(auth) ? auth[0] : auth;
let token = authValue?.startsWith('Bearer ') ? authValue.slice(7) : '';

View File

@@ -26,6 +26,31 @@ export async function introspectGuildToken(token: string): Promise<{ active: boo
};
}
/**
* Fetch the single Center-scoped admin user (if any).
* Same x-api-key auth as introspect / resolve-names.
* Returns `null` when no admin is set OR the request fails (treated
* identically — the guild simply falls back to "no admin observer").
*/
export async function fetchAdminEmail(): Promise<{ email: string; userId: string } | null> {
const centerBaseUrl = process.env.FABRIC_BACKEND_GUILD_CENTER_BASE_URL;
const centerApiKey = process.env.FABRIC_BACKEND_GUILD_CENTER_API_KEY;
if (!centerBaseUrl || !centerApiKey) return null;
try {
const res = await fetch(`${centerBaseUrl}/api/auth/admin-email`, {
method: 'GET',
headers: { 'x-api-key': centerApiKey },
});
if (!res.ok) return null;
const data = (await res.json()) as { email?: string; userId?: string } | null;
if (!data || !data.email || !data.userId) return null;
return { email: data.email, userId: data.userId };
} catch {
return null;
}
}
// Resolve <@user.name:NAME> names to userIds within this guild node via
// Center. Unresolved names are simply absent from the returned map.
export async function resolveUserNames(names: string[]): Promise<Record<string, string>> {

View File

@@ -0,0 +1,25 @@
import { describe, it, expect } from 'vitest';
import { safeEqual } from './safe-equal.js';
describe('safeEqual', () => {
it('returns true for identical non-empty strings', () => {
expect(safeEqual('abc123', 'abc123')).toBe(true);
});
it('returns false for different strings of same length', () => {
expect(safeEqual('abc123', 'abc124')).toBe(false);
});
it('returns false for differing lengths', () => {
expect(safeEqual('abc', 'abcd')).toBe(false);
});
it('handles empty strings', () => {
// both empty is technically equal — but downstream callers should
// explicitly check for empty expected before invoking. We just
// document the constant-time-comparison primitive's behavior.
expect(safeEqual('', '')).toBe(true);
expect(safeEqual('a', '')).toBe(false);
expect(safeEqual('', 'a')).toBe(false);
});
});

12
src/common/safe-equal.ts Normal file
View File

@@ -0,0 +1,12 @@
import { timingSafeEqual } from 'node:crypto';
// Constant-time string comparison. Returns false for length mismatch (the
// length difference itself is observable, but the per-byte loop isn't).
// Used for shared-secret header checks (commands-sync-key, system-key,
// etc.) to keep timing-oracle attacks off the table.
export function safeEqual(a: string, b: string): boolean {
const ab = Buffer.from(a);
const bb = Buffer.from(b);
if (ab.length !== bb.length) return false;
return timingSafeEqual(ab, bb);
}

View File

@@ -14,6 +14,7 @@ import { IdempotencyRecord } from './entities/idempotency-record.entity.js';
import { StoredFile } from './entities/stored-file.entity.js';
import { ChannelCanvas } from './entities/channel-canvas.entity.js';
import { GuildCommand } from './entities/guild-command.entity.js';
import { AgentPresence } from './entities/agent-presence.entity.js';
export const buildTypeOrmConfig = (): TypeOrmModuleOptions => ({
type: 'mysql',
@@ -38,6 +39,7 @@ export const buildTypeOrmConfig = (): TypeOrmModuleOptions => ({
StoredFile,
ChannelCanvas,
GuildCommand,
AgentPresence,
],
synchronize: (process.env.FABRIC_BACKEND_GUILD_DB_SYNC ?? 'true') === 'true',
logging: (process.env.FABRIC_BACKEND_GUILD_DB_LOGGING ?? 'false') === 'true',

View File

@@ -0,0 +1,35 @@
import { Column, Entity, PrimaryColumn, UpdateDateColumn } from 'typeorm';
/**
* Per-user (typically agent) presence cache.
*
* Populated by Fabric.OpenclawPlugin's presence-sync loop: every ~30s
* it reads each connected agent's HF status from the cross-plugin
* `globalThis.__hfAgentStatus.get(agentId)` (exposed by
* HarborForge.OpenclawPlugin) and pushes diffs via
* `PUT /agents/:userId/presence`.
*
* Used by `RealtimeGateway.computeDelivery` for `announce`-type
* channels to skip delivery to recipients whose status is `busy`.
* Defaults to `unknown` if no row exists (treated as not-busy).
*/
@Entity('agent_presences')
export class AgentPresence {
// Same id as the Fabric Center user id (UUID v4 string, char(36)).
@PrimaryColumn({ type: 'char', length: 36 })
userId!: string;
@Column({
type: 'enum',
enum: ['idle', 'on_call', 'busy', 'exhausted', 'offline', 'unknown'],
default: 'unknown',
})
status!: 'idle' | 'on_call' | 'busy' | 'exhausted' | 'offline' | 'unknown';
/** Free-text source tag for debugging ("hf-plugin", "manual", etc.). */
@Column({ type: 'varchar', length: 64, default: 'unknown' })
source!: string;
@UpdateDateColumn()
updatedAt!: Date;
}

View File

@@ -16,13 +16,23 @@ export class Channel {
@Column({
name: 'x_type',
type: 'enum',
enum: ['general', 'work', 'report', 'discuss', 'triage', 'custom', 'dm'],
enum: ['general', 'work', 'report', 'discuss', 'triage', 'custom', 'dm', 'announce'],
})
xType!: 'general' | 'work' | 'report' | 'discuss' | 'triage' | 'custom' | 'dm';
xType!: 'general' | 'work' | 'report' | 'discuss' | 'triage' | 'custom' | 'dm' | 'announce';
@Column({ type: 'varchar', length: 16, default: 'text' })
kind!: 'text' | 'announcement';
// Free-form description of what this channel is for — what topics get
// posted, who participates, why it exists. Surfaced via GET /api/channels
// so agents can pick a channel by intent ("which announce channel is for
// debate broadcasts?") without channel id hard-coded into workflows.
// Any channel member can set it via PATCH /api/channels/:id (writes
// require membership the same way moveToBypass / close do). The frontend
// create form does NOT post this today — purpose stays optional.
@Column({ type: 'text', nullable: true })
purpose!: string | null;
@Column({ type: 'boolean', default: false })
isPrivate!: boolean;

View File

@@ -56,4 +56,14 @@ export class CreateMessageDto {
@IsString()
@MaxLength(64)
authorUserId?: string;
// System-author path only (x-fabric-system-key gated). When set, the
// message is delivered via emitMessageTargeted so this single recipient
// gets wakeup=true; everyone else in the channel sees wakeup=false. For
// regular (user-bearer) posts this field is ignored. Used by
// close-sub-discussion to precisely wake the host on callback.
@IsOptional()
@IsString()
@MaxLength(64)
wakeupUserId?: string;
}

View File

@@ -21,6 +21,7 @@ import { ChannelMember } from '../entities/channel-member.entity.js';
import { Message } from '../entities/message.entity.js';
import { IdempotencyRecord } from '../entities/idempotency-record.entity.js';
import { WakeMapping } from '../entities/wake-mapping.entity.js';
import { AdminCacheService } from '../common/admin-cache.service.js';
import { parseSlashCommand } from '../channels/slash-commands.js';
import { parseMentions, extractNameMentions, replaceNameMentions } from '../channels/mentions.js';
import { resolveUserNames } from '../common/center-auth.js';
@@ -50,6 +51,7 @@ export class MessagingController {
private readonly turn: TurnService,
private readonly events: EventsService,
private readonly realtime: RealtimeGateway,
private readonly adminCache: AdminCacheService,
) {}
private async getIdempotentResponse(
@@ -154,16 +156,78 @@ export class MessagingController {
async create(
@Param('id') channelId: string,
@Body() body: CreateMessageDto,
@Req() req: { userId?: string },
@Req() req: { userId?: string; isSystem?: boolean },
@Headers('idempotency-key') idempotencyKey?: string,
) {
const scope = `POST:/channels/${channelId}/messages`;
const existed = await this.getIdempotentResponse(scope, idempotencyKey);
if (existed) return existed;
// System caller (ApiKeyGuard set isSystem from x-fabric-system-key):
// skip the per-user participant check; resolve channel directly.
// System posts are allowed into any non-closed channel — used by
// Fabric.OpenclawPlugin to write `close-sub-discussion` callbacks
// back to a parent channel that the host agent may not be currently
// "in" from the backend's perspective, and to deliver guide-injected
// system intros into sub-discussion channels without needing to log
// in as a real user. Author is a sentinel UUID that no real user
// ever has; `wakeupUserId` (optional) lets the caller precisely wake
// one recipient (e.g. the host of a closing sub-discussion).
if (req.isSystem) {
const sysChannel = await this.channelRepo.findOne({ where: { id: channelId } });
if (!sysChannel) throw new NotFoundException('channel not found');
if (sysChannel.closed) {
throw new ConflictException({ error: 'channel_closed', message: 'channel is closed' });
}
const SYSTEM_USER_ID = '00000000-0000-0000-0000-000000000000';
let sysContent = body.content ?? '';
const sysNames = extractNameMentions(sysContent);
if (sysNames.length) {
const nameMap = await resolveUserNames(sysNames);
sysContent = replaceNameMentions(sysContent, nameMap);
}
const sysMessage = await this.persistMessage(channelId, {
authorUserId: SYSTEM_USER_ID,
content: sysContent,
clientMessageId: body.clientMessageId,
replyToMessageId: body.replyToMessageId,
mentions: body.mentions,
attachments: body.attachments,
});
const sysView = this.toView(sysMessage) as Record<string, unknown>;
await this.saveIdempotentResponse(scope, idempotencyKey, sysView);
await this.events.emit({
eventType: 'message.created',
channelId,
actorId: SYSTEM_USER_ID,
data: sysView,
});
// wakeupUserId set -> emitMessageTargeted wakes exactly that user
// (everyone else gets the same message with wakeup=false).
// wakeupUserId omitted/null -> emitMessageCreated routes via the
// channel's xType-specific 3-state delivery with empty wakeSet, so
// nobody is woken (the message lands in history only).
const wakeupUserId = typeof body.wakeupUserId === 'string' ? body.wakeupUserId.trim() : '';
if (wakeupUserId) {
await this.realtime.emitMessageTargeted(channelId, sysView, wakeupUserId);
} else {
await this.realtime.emitMessageCreated(channelId, sysView, {
xType: sysChannel.xType ?? 'general',
authorUserId: SYSTEM_USER_ID,
wakeUserIds: new Set<string>(),
});
}
return sysView;
}
// Guild C-1: caller must be a participant of the channel, and the
// author is always the authenticated user — body.authorUserId is
// ignored so a caller can never post as someone else.
//
// announce channels: any participant can POST. Use case is one-off
// recruitment / broadcast messages posted by the agent that just
// created the originating topic (e.g. dialectic invites). No
// server-side privileged path — author is always a real user.
const userId = String(req.userId ?? '');
if (!userId) throw new ForbiddenException('missing user');
const channel = await this.assertParticipant(channelId, userId);
@@ -225,16 +289,19 @@ export class MessagingController {
const decision = await this.turn.onNormalMessage(channelId, authorUserId, mentionIds);
await this.realtime.emitMessageTargeted(channelId, responseBody, decision.wakeupUserId);
} else {
// general/report/triage/custom: wakeup from x_type + wake_mapping;
// general also honors the message's at-list
// general/report/triage/custom: 3-state delivery
// (wake / observer / skip) — see realtime.gateway.computeDelivery.
// Center-scoped admin (cached, 1d TTL) gets `observer` on triage.
const wakeRows = await this.wakeRepo.find({ where: { channelId } });
const wakeUserIds = new Set(wakeRows.map((w) => w.userId));
const mentionUserIds = new Set(mentionIds.filter((id) => id !== authorUserId));
const admin = await this.adminCache.get();
await this.realtime.emitMessageCreated(channelId, responseBody, {
xType,
authorUserId,
wakeUserIds,
mentionUserIds,
adminUserId: admin?.userId ?? null,
});
}

View File

@@ -6,9 +6,12 @@ import { ChannelMember } from '../entities/channel-member.entity.js';
import { Message } from '../entities/message.entity.js';
import { IdempotencyRecord } from '../entities/idempotency-record.entity.js';
import { WakeMapping } from '../entities/wake-mapping.entity.js';
import { AdminCacheService } from '../common/admin-cache.service.js';
@Module({
imports: [TypeOrmModule.forFeature([Channel, ChannelMember, Message, IdempotencyRecord, WakeMapping])],
controllers: [MessagingController],
providers: [AdminCacheService],
exports: [AdminCacheService],
})
export class MessagingModule {}

View File

@@ -11,17 +11,94 @@ import { Logger } from '@nestjs/common';
import { Server, Socket } from 'socket.io';
import { introspectGuildToken } from '../common/center-auth.js';
type XType = 'general' | 'work' | 'report' | 'discuss' | 'triage' | 'custom' | 'dm';
type XType = 'general' | 'work' | 'report' | 'discuss' | 'triage' | 'custom' | 'dm' | 'announce';
// Wakeup for non-rotating channels only (general/report/triage/custom).
// discuss/work go through TurnService + emitMessageTargeted, never here.
// Precedence:
// 1. the author never gets woken by their own message
// 2. triage/custom: only wake users in the channel's wake_mapping
// (mentions change nothing here)
// 3. general: if the message has an at-list, wake only the at'd users;
// otherwise wake everyone
// 4. report (and anything else): wake nobody
/**
* Cross-presence info needed by `announce`-type delivery: a recipient
* with hf-side status === 'busy' has the message discarded silently
* (don't enter their session, no UI emit). Other statuses + non-announce
* channels are unaffected. Presence is sourced from the
* `agent_presences` table populated by Fabric.OpenclawPlugin's
* presence-sync loop (which reads from HF plugin's `__hfAgentStatus`).
*/
export type PresenceStatus = 'idle' | 'on_call' | 'busy' | 'exhausted' | 'offline' | 'unknown';
/**
* Per-recipient delivery decision for a non-rotating channel message.
*
* • `wake` — push the event AND wake the recipient (model turn fires)
* • `observer` — push the event with wakeup=false (silent; UI displays
* but the openclaw plugin records-only without dispatch). Currently
* used for the Center admin observing triage traffic
* • `skip` — don't even emit the event to this recipient
*
* Wakeup-only channels (general/report/dm/custom) never return
* 'observer'; the legacy behaviour is preserved end-to-end.
*
* Precedence for triage (the only place 'skip' / 'observer' fire):
* 1. author never gets back their own message
* 2. wake_mapping (on-duty) → wake
* 3. mention → wake (NEW: was 'skip' before — see Fabric PR 'triage
* mention exception')
* 4. admin (Center-scoped, at most one) → observer
* 5. everyone else → skip (was 'deliver, wakeup=false' before)
*/
export type DeliveryDecision = 'wake' | 'observer' | 'skip';
export interface ComputeDeliveryArgs {
xType: XType;
recipientUserId: string;
authorUserId: string;
wakeUserIds: Set<string>;
mentionUserIds?: Set<string>;
/** Single Center-scoped admin userId, or null. */
adminUserId?: string | null;
/** Recipient's current presence; only consulted for `announce` xType. Defaults to 'unknown' (treated as not-busy). */
recipientPresence?: PresenceStatus;
}
export function computeDelivery(args: ComputeDeliveryArgs): DeliveryDecision {
const { xType, recipientUserId, authorUserId, wakeUserIds, mentionUserIds, adminUserId, recipientPresence } = args;
if (recipientUserId === authorUserId) return 'skip';
switch (xType) {
case 'triage':
if (wakeUserIds.has(recipientUserId)) return 'wake';
if (mentionUserIds?.has(recipientUserId)) return 'wake';
if (adminUserId && recipientUserId === adminUserId) return 'observer';
return 'skip';
case 'general':
if (mentionUserIds && mentionUserIds.size > 0) {
return mentionUserIds.has(recipientUserId) ? 'wake' : 'observer';
}
return 'wake';
case 'custom':
// wake_mapping decides who wakes; everyone else still sees the
// message (observer) — preserves the legacy "deliver to all, wake
// some" contract for custom channels.
return wakeUserIds.has(recipientUserId) ? 'wake' : 'observer';
case 'dm':
return 'wake';
case 'announce':
// System-broadcast channels (e.g. Dialectic topic announcements).
// Recipients with HF status === 'busy' have the message discarded
// silently — busy agents should not be distracted by signup pings
// they can't act on. All other presences (idle/on_call/exhausted/
// offline/unknown) get the message as 'observer' (no wake): the
// channel itself is browsable; agents proactively decide what to
// do with announcements when they next look at their inbox.
if (recipientPresence === 'busy') return 'skip';
return 'observer';
default:
// report (and anything else): deliver as observer, no wake
return 'observer';
}
}
/**
* @deprecated Use computeDelivery (returns 3-state). Kept for any
* external callers; treats 'observer' and 'skip' both as `false`.
*/
export function computeWakeup(args: {
xType: XType;
recipientUserId: string;
@@ -29,23 +106,7 @@ export function computeWakeup(args: {
wakeUserIds: Set<string>;
mentionUserIds?: Set<string>;
}): boolean {
const { xType, recipientUserId, authorUserId, wakeUserIds, mentionUserIds } = args;
if (recipientUserId === authorUserId) return false;
switch (xType) {
case 'general':
if (mentionUserIds && mentionUserIds.size > 0) {
return mentionUserIds.has(recipientUserId);
}
return true;
case 'triage':
case 'custom':
return wakeUserIds.has(recipientUserId);
case 'dm':
// 1:1 conversation: every non-author participant is always woken.
return true;
default:
return false;
}
return computeDelivery(args) === 'wake';
}
@WebSocketGateway({
@@ -61,6 +122,12 @@ export class RealtimeGateway implements OnGatewayConnection, OnGatewayDisconnect
private readonly logger = new Logger(RealtimeGateway.name);
private readonly onlineUsers = new Set<string>();
// Optional: injected at module wiring time. Used by emitMessageCreated
// to pre-load recipient presence for announce-type channels.
// Typed loosely to avoid a circular import between realtime and agents
// modules; the actual interface lives in agents/agent-presence.service.
presence?: { getStatusMap(ids: string[]): Promise<Map<string, PresenceStatus>> };
private userIdFromClient(client: Socket): string {
const authUser = client.handshake.auth?.userId;
const headerUser = client.handshake.headers['x-user-id'];
@@ -96,6 +163,10 @@ export class RealtimeGateway implements OnGatewayConnection, OnGatewayDisconnect
const userId = result.user.id || this.userIdFromClient(client);
client.data.userId = userId;
this.onlineUsers.add(userId);
// Per-user room: lets server code emit user-scoped events (e.g.
// channel.joined when membership changes) without bookkeeping a
// userId→sockets map. All of this user's sockets receive the event.
client.join(`user:${userId}`);
this.server.emit('presence.online', {
userId,
onlineCount: this.onlineUsers.size,
@@ -171,7 +242,19 @@ export class RealtimeGateway implements OnGatewayConnection, OnGatewayDisconnect
this.server.to(`channel:${channelId}`).emit(event, data);
}
// Emits message.created per-recipient so each carries its own `wakeup` flag.
// Emit a user-scoped event to all sockets currently connected for `userId`
// (via the `user:<userId>` room joined in handleConnection). No-op for
// offline users — the next connect's initial channel-list fetch covers it.
emitToUser(userId: string, event: string, data: Record<string, unknown>): void {
if (!userId) return;
this.server.to(`user:${userId}`).emit(event, data);
}
// Emits message.created per-recipient using the 3-state delivery
// decision (wake / observer / skip). Skipped recipients receive
// nothing — used by triage channels to keep non-on-duty / non-mention
// / non-admin users completely out of the loop, and by announce
// channels to suppress delivery to recipients whose presence is busy.
async emitMessageCreated(
channelId: string,
data: Record<string, unknown>,
@@ -180,19 +263,41 @@ export class RealtimeGateway implements OnGatewayConnection, OnGatewayDisconnect
authorUserId: string;
wakeUserIds: Set<string>;
mentionUserIds?: Set<string>;
/** Single Center-scoped admin userId (or null). */
adminUserId?: string | null;
},
): Promise<void> {
const sockets = await this.server.in(`channel:${channelId}`).fetchSockets();
// For announce-type channels, pre-load presence for all recipients
// in one query so the per-recipient loop doesn't fan out to N round
// trips. For other xTypes, presence is irrelevant — skip the lookup.
let presenceMap: Map<string, PresenceStatus> | undefined;
if (ctx.xType === 'announce' && this.presence) {
const recipientIds = sockets
.map((s) => (typeof s.data.userId === 'string' ? (s.data.userId as string) : ''))
.filter((id) => id && !id.startsWith('anon:'));
presenceMap = await this.presence.getStatusMap(recipientIds);
}
for (const s of sockets) {
const recipientUserId = typeof s.data.userId === 'string' ? s.data.userId : `anon:${s.id}`;
const wakeup = computeWakeup({
const decision = computeDelivery({
xType: ctx.xType,
recipientUserId,
authorUserId: ctx.authorUserId,
wakeUserIds: ctx.wakeUserIds,
mentionUserIds: ctx.mentionUserIds,
adminUserId: ctx.adminUserId,
recipientPresence: presenceMap?.get(recipientUserId) ?? 'unknown',
});
if (decision === 'skip') continue;
s.emit('message.created', {
...data,
channelId,
wakeup: decision === 'wake',
xType: ctx.xType,
});
s.emit('message.created', { ...data, channelId, wakeup, xType: ctx.xType });
}
}

View File

@@ -1,9 +1,25 @@
import { Global, Module } from '@nestjs/common';
import { Global, Module, OnModuleInit } from '@nestjs/common';
import { RealtimeGateway } from './realtime.gateway.js';
import { AgentPresenceModule } from '../agents/agent-presence.module.js';
import { AgentPresenceService } from '../agents/agent-presence.service.js';
@Global()
@Module({
imports: [AgentPresenceModule],
providers: [RealtimeGateway],
exports: [RealtimeGateway],
})
export class RealtimeModule {}
export class RealtimeModule implements OnModuleInit {
// Wire presence into the gateway at startup. Using assignment (vs
// constructor injection) keeps the gateway free of the agents-module
// import — no risk of circular dependency, and announce-channel
// delivery degrades gracefully (presence stays undefined → 'unknown'
// status → no busy-discard) if AgentPresenceModule is ever removed.
constructor(
private readonly gateway: RealtimeGateway,
private readonly presence: AgentPresenceService,
) {}
onModuleInit(): void {
this.gateway.presence = this.presence;
}
}