Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): FOLD listServers + MOVE-FLAT listFriends/friendRequest (phase 4b)

Simone24f080857817
diff --git a/src/web/src/app/api/community/friendRequest/route.ts b/src/web/src/app/api/community/friendRequest/route.ts
new file mode 100644
index 000000000..70dce804f
--- /dev/null
+++ b/src/web/src/app/api/community/friendRequest/route.ts
@@ -0,0 +1,143 @@
+import { NextResponse, type NextRequest } from "next/server"
+import {
+ queries,
+ CommunityAgentFriendRequestSchema,
+ parseNameAndTag,
+ isBlocked,
+} from "@alook/shared"
+import { getDb } from "@/lib/db"
+import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"
+import { requireNotBlocked } from "@/lib/community/permissions"
+import { broadcastToUserSafe } from "@/lib/community/fanout"
+import { logAudit, COMMUNITY_AUDIT_ACTIONS } from "@/lib/community/audit"
+
+/**
+ * POST /api/community/friendRequest — moved from
+ * /api/community/agent/friendRequest (plan §4, §9 phase 4). MOVE-FLAT, not FOLD
+ * onto POST /friends/request: the bot flow has DIFFERENT semantics — sibling-bot
+ * auto-accept, always-owner-gated (needsOwnerApproval), and a lean
+ * `{friendshipId, status, hint}` response — vs the human route's direct
+ * send + full-friendship response. Per the plan's judgment rule (Melly #113:
+ * different semantics → keep distinct under the unified actor), and matching
+ * batch1 which kept friendRequest as a distinct RPC. Bot-only → human actor
+ * rejected 403 (the human uses /friends/request, which itself already rejects
+ * bots). Audit BOT_FRIEND_REQUESTED / BOT_FRIEND_REQUEST_SUPERSEDED preserved
+ * (§6). Body unchanged from the /agent original except wrapper + identity.
+ */
+export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
+ const gate = requireBot(ctx.actor)
+ if (!gate.ok) return gate.response
+ const { userId: botUserId, ownerUserId } = gate.bot
+
+ const db = getDb(ctx.env.DB)
+
+ let raw: unknown
+ try {
+ raw = await req.json()
+ } catch {
+ return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })
+ }
+ const parsed = CommunityAgentFriendRequestSchema.safeParse(raw)
+ if (!parsed.success) {
+ return NextResponse.json({ error: "invalid payload" }, { status: 400 })
+ }
+
+ // Only the human `name#0042` handle is accepted.
+ const handle = parseNameAndTag(parsed.data.username)
+ if (!handle) {
+ return NextResponse.json({ error: "username must be in name#0042 form" }, { status: 400 })
+ }
+ const target = await queries.user.getUserByNameAndDiscriminator(db, handle.name, handle.discriminator)
+ if (!target) return NextResponse.json({ error: "user not found" }, { status: 404 })
+
+ // Guards in order (design steps 3–4).
+ if (target.id === botUserId) {
+ return NextResponse.json({ error: "cannot friend yourself" }, { status: 400 })
+ }
+ if (target.id === ownerUserId) {
+ // Owner ↔ bot is synthetic; no row can exist.
+ return NextResponse.json({ error: "already friends", code: "already_friends" }, { status: 409 })
+ }
+
+ // Resolve internal flags to detect the sibling-bot case.
+ const targetInternal = await queries.user.getUserInternal(db, target.id)
+ if (!targetInternal || targetInternal.deletedAt !== null) {
+ return NextResponse.json({ error: "user not found" }, { status: 404 })
+ }
+
+ // Sibling auto-accept branch (design step 5).
+ if (targetInternal.isBot === true && targetInternal.ownerUserId === ownerUserId) {
+ const block = await requireNotBlocked(db, botUserId, target.id)
+ if (!block.ok) return NextResponse.json({ error: "blocked", code: "blocked" }, { status: 403 })
+
+ const result = await queries.communityFriendship.ensureSiblingBotFriendship(db, {
+ botA: botUserId,
+ botB: target.id,
+ })
+ if (result.blocked) {
+ return NextResponse.json({ error: "blocked", code: "blocked" }, { status: 403 })
+ }
+ return NextResponse.json({ friendshipId: result.friendshipId, status: "accepted", hint: null })
+ }
+
+ // Belt-and-suspenders (sendRequest also checks).
+ const block = await requireNotBlocked(db, botUserId, target.id)
+ if (!block.ok) return NextResponse.json({ error: "blocked", code: "blocked" }, { status: 403 })
+
+ let result
+ try {
+ result = await queries.communityFriendship.sendRequest(db, {
+ requesterId: botUserId,
+ addresseeId: target.id,
+ })
+ } catch (err: unknown) {
+ if (err instanceof Error) {
+ if (isBlocked(err.message)) {
+ return NextResponse.json({ error: "blocked", code: "blocked" }, { status: 403 })
+ }
+ if (err.message === "already friends") {
+ return NextResponse.json({ error: "already friends", code: "already_friends" }, { status: 409 })
+ }
+ if (err.message === "friend request already sent") {
+ return NextResponse.json(
+ { error: "friend request already sent", code: "friend_request_already_sent" },
+ { status: 409 },
+ )
+ }
+ }
+ throw err
+ }
+
+ for (const b of result.broadcasts) {
+ await broadcastToUserSafe(b.userId, b.event)
+ }
+
+ logAudit(db, {
+ serverId: null,
+ actorId: botUserId,
+ action: COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_REQUESTED,
+ targetType: "user",
+ targetId: target.id,
+ changes: JSON.stringify({ requesterBotId: botUserId, addresseeId: target.id }),
+ })
+ for (const supersededId of result.supersededIds) {
+ logAudit(db, {
+ serverId: null,
+ actorId: botUserId,
+ action: COMMUNITY_AUDIT_ACTIONS.BOT_FRIEND_REQUEST_SUPERSEDED,
+ targetType: "friendship",
+ targetId: supersededId,
+ changes: JSON.stringify({ supersededBy: result.friendship.id }),
+ })
+ }
+
+ // Bot-origin sendRequest always sets needsOwnerApproval, so this is always
+ // the pending variant. Resolve the owner's display name for the hint copy.
+ const owner = await queries.user.getUserPublic(db, ownerUserId)
+ const ownerDisplayName = owner?.name ?? "your owner"
+ return NextResponse.json({
+ friendshipId: result.friendship.id,
+ status: "pending",
+ hint: `Your owner ${ownerDisplayName} needs to approve this request in DM.`,
+ })
+})
diff --git a/src/web/src/app/api/community/listFriends/route.ts b/src/web/src/app/api/community/listFriends/route.ts
new file mode 100644
index 000000000..5b11d650c
--- /dev/null
+++ b/src/web/src/app/api/community/listFriends/route.ts
@@ -0,0 +1,74 @@
+import { NextResponse, type NextRequest } from "next/server"
+import { queries } from "@alook/shared"
+import type { FriendCard } from "@alook/shared"
+import { getDb } from "@/lib/db"
+import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"
+import { wsDoFetch } from "@/lib/broadcast"
+
+/**
+ * POST /api/community/listFriends — moved from /api/community/agent/listFriends
+ * (plan §4, §9 phase 4). MOVE-FLAT, not FOLD onto GET /friends: the bot's
+ * friend list has DIFFERENT semantics from the human's — it aggregates three
+ * buckets (accepted + pendingOutgoing + pendingIncoming) with presence via
+ * `listAgentFriends`, whereas the human GET /friends returns accepted + blocked
+ * (pending is a separate /friends/pending route). Per the plan's judgment rule
+ * (Melly #113: different semantics → keep distinct under the unified actor,
+ * bot-gated), and matching batch1 which also kept listFriends as a distinct RPC.
+ * Bot-only → human actor rejected 403. Never emits `isBot`. Body unchanged from
+ * the /agent original except wrapper + identity source.
+ */
+export const POST = withCommunityActor(async (_req: NextRequest, ctx) => {
+ const gate = requireBot(ctx.actor)
+ if (!gate.ok) return gate.response
+ const botUserId = gate.bot.userId
+
+ const db = getDb(ctx.env.DB)
+
+ const buckets = await queries.communityFriendship.listAgentFriends(db, botUserId)
+
+ // Presence is WS-connection-based (see friends/presence route) — one bulk
+ // check across every peer id in every bucket.
+ const allPeerIds = [
+ ...buckets.accepted,
+ ...buckets.pendingOutgoing,
+ ...buckets.pendingIncoming,
+ ].map((r) => r.peerUserId)
+ const uniquePeerIds = [...new Set(allPeerIds)]
+ let onlineSet = new Set<string>()
+ if (uniquePeerIds.length > 0) {
+ try {
+ const resp = await wsDoFetch(
+ ctx.env,
+ "/presence/users",
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ ids: uniquePeerIds }),
+ },
+ { label: botUserId },
+ )
+ if (resp.ok) {
+ const data = (await resp.json()) as { online: string[] }
+ if (Array.isArray(data.online)) onlineSet = new Set(data.online)
+ }
+ } catch {
+ /* presence best-effort — default everyone offline */
+ }
+ }
+
+ const toCard = (r: (typeof buckets.accepted)[number]): FriendCard => ({
+ userId: r.peerUserId,
+ handle: `${r.name}#${r.discriminator}`,
+ name: r.name,
+ bio: r.aboutMe ?? null,
+ statusText: r.statusText ?? null,
+ statusEmoji: r.statusEmoji ?? null,
+ presence: onlineSet.has(r.peerUserId) ? "online" : "offline",
+ })
+
+ return NextResponse.json({
+ accepted: buckets.accepted.map(toCard),
+ pendingOutgoing: buckets.pendingOutgoing.map(toCard),
+ pendingIncoming: buckets.pendingIncoming.map(toCard),
+ })
+})
diff --git a/src/web/src/app/api/community/servers/route.ts b/src/web/src/app/api/community/servers/route.ts
index bb913e113..36c25a7b2 100644
--- a/src/web/src/app/api/community/servers/route.ts
+++ b/src/web/src/app/api/community/servers/route.ts
@@ -1,5 +1,4 @@
import { NextRequest } from "next/server"
-import { withAuth } from "@/lib/middleware/auth"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
import {
@@ -10,17 +9,35 @@ import {
WS_EVENTS,
slugify,
} from "@alook/shared"
+import { withCommunityActor, rejectBot } from "@/lib/middleware/community-actor"
import { fanOutToServerMembers } from "@/lib/community/fanout"
import { serverIconUrl } from "@/lib/community/storage"
-export const GET = withAuth(async (_req, ctx) => {
+/**
+ * GET — list "my servers", serving both a human and a bot via the unified actor
+ * (plan §4 FOLD of /agent/listServers, §9 phase 4). Both list via
+ * `listUserServers(actor.userId)`; the response is a superset (full server rows
+ * incl. id+name+icon) — the web client uses the UI fields, the bot's daemon
+ * projects each row down to `{id, name}` (the old lean listServers shape).
+ * No actor.kind branch needed: `userId` is common to both callers.
+ */
+export const GET = withCommunityActor(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
- const rows = await queries.communityServer.listUserServers(db, ctx.userId)
+ const rows = await queries.communityServer.listUserServers(db, ctx.actor.userId)
const servers = rows.map((row) => ({ ...row, icon: serverIconUrl(row) }))
return writeJSON({ servers })
})
-export const POST = withAuth(async (req: NextRequest, ctx) => {
+/**
+ * POST — create a server. Human-only: there is no bot create-server verb today,
+ * so a bot actor is rejected 403 (`rejectBot`) rather than silently granted a
+ * new capability by the actor unification (plan §5 — capabilities are explicit,
+ * not "whatever the route happens to accept").
+ */
+export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
+ const denied = rejectBot(ctx.actor)
+ if (denied) return denied
+
const db = getDb(ctx.env.DB)
let body: { name?: string; description?: string }
@@ -56,7 +73,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
const { server, ownerMember } = await queries.communityServer.createServer(db, {
name,
description,
- ownerId: ctx.userId,
+ ownerId: ctx.actor.userId,
})
fanOutToServerMembers(server.id, {
@@ -64,7 +81,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
serverId: server.id,
member: {
id: ownerMember.id,
- userId: ctx.userId,
+ userId: ctx.actor.userId,
name: ownerMember.userName,
discriminator: ownerMember.userDiscriminator,
avatar: ownerMember.userImage ?? undefined,