Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(community): MOVE-FLAT 11 bot routes to /community under unified actor (phase 3)
Simone455a3bb98260
diff --git a/src/web/src/app/api/community/ack/route.ts b/src/web/src/app/api/community/ack/route.tsnew file mode 100644index 000000000..46fa4412f--- /dev/null+++ b/src/web/src/app/api/community/ack/route.ts@@ -0,0 +1,99 @@+import { NextResponse, type NextRequest } from "next/server"+import { queries, withD1Retry, CommunityAgentAckRequestSchema } from "@alook/shared"+import { getDb } from "@/lib/db"+import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"+import { resolveTargetForMember } from "@/lib/community/resolve-ref"+import { isDmTarget } from "@/lib/community/message-handler"+import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"++/**+ * POST /api/community/ack — plan §7. The ONLY endpoint that advances+ * `lastReadSeq` (`inboxPull` never mutates read state — debt #2 correction).+ * Each cursor's `channel` ref is resolved read-only (no DM/thread+ * auto-create — a stale ref must never materialize a row as a side effect+ * of an ack) and membership-gated before `bumpReadCursor`.+ *+ * Moved from /agent (plan §4 MOVE, §9 phase 3); bot-only, human actor → 403 via requireBot (Gener #116).+ *+ * Best-effort per cursor, NOT fail-fast: every good cursor is applied and its+ * waterline advanced regardless of any sibling cursor failing. A single+ * unresolvable cursor (e.g. a forum_post whose ref can't parse back) must+ * never stall the healthy cursors behind it — that regressed their waterlines+ * and muted the bot in every channel with unread. Bad cursors are collected+ * into `failed[]` with a coarse `code`; the response is ALWAYS 200 (partial+ * success is not a request-level error — the good cursors DID apply, and the+ * daemon must not treat the whole call as failed). Only a genuine D1 exception+ * escaping `withD1Retry` propagates as a 500 so the daemon retries the batch.+ */+export const POST = withCommunityActor(async (req: NextRequest, ctx) => {+ const gate = requireBot(ctx.actor)+ if (!gate.ok) return gate.response+ const { userId: botUserId } = 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 = CommunityAgentAckRequestSchema.safeParse(raw)+ if (!parsed.success) {+ return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })+ }++ const applied: Array<{ channel: string; seq: number }> = []+ const failed: Array<{ channel: string; seq: number; code: "unresolvable" | "forbidden" | "no_such_seq"; error: string }> = []++ for (const cursor of parsed.data.cursors) {+ const resolved = await resolveTargetForMember(db, botUserId, cursor.channel, {+ createDmIfMissing: false,+ createThreadIfMissing: false,+ callerKind: "bot",+ })+ if ("error" in resolved) {+ failed.push({ channel: cursor.channel, seq: cursor.seq, code: "unresolvable", error: resolved.message })+ continue+ }++ const scopeTarget = { channelId: resolved.channelId }++ if (isDmTarget(resolved)) {+ const gate = await requireDMAccess(db, resolved.channelId, botUserId)+ if (!gate.ok) {+ failed.push({ channel: cursor.channel, seq: cursor.seq, code: "forbidden", error: gate.error })+ continue+ }+ } else {+ const gate = await requireChannelMember(db, resolved.channelId, botUserId)+ if (!gate.ok) {+ failed.push({ channel: cursor.channel, seq: cursor.seq, code: "forbidden", error: gate.error })+ continue+ }+ }++ // Idempotent write — safe to retry a transient D1 blip (same treatment as+ // the human-facing routes). A real "no such seq" is a structured `null`+ // return below, not a thrown error, so it is never retried. A genuine D1+ // exception escaping withD1Retry is NOT caught here — it propagates as a+ // 500 so the daemon retries the whole batch (never swallow infra failures+ // into `failed`).+ const bumped = await withD1Retry(+ () => queries.communityReadState.bumpReadCursor(db, botUserId, scopeTarget, cursor.seq),+ { route: "community/agent/ack:bump" },+ )+ if (!bumped) {+ failed.push({+ channel: cursor.channel,+ seq: cursor.seq,+ code: "no_such_seq",+ error: `no message with seq #${cursor.seq} in ${cursor.channel}`,+ })+ continue+ }+ applied.push({ channel: cursor.channel, seq: cursor.seq })+ }++ return NextResponse.json({ ok: failed.length === 0, applied, failed })+})diff --git a/src/web/src/app/api/community/attachmentDownload/route.ts b/src/web/src/app/api/community/attachmentDownload/route.tsnew file mode 100644index 000000000..a0be90950--- /dev/null+++ b/src/web/src/app/api/community/attachmentDownload/route.ts@@ -0,0 +1,115 @@+import { NextResponse, type NextRequest } from "next/server"+import { queries, createLogger, CommunityAgentAttachmentDownloadRequestSchema } from "@alook/shared"+import { getDb } from "@/lib/db"+import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"+import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"++const log = createLogger({ service: "community-agent-attachment-download" })++/**+ * RFC 5987 filename encoding for `X-Alook-Filename`. Percent-encodes+ * everything outside the RFC 5987 attr-char set. The daemon-side client+ * decodes before writing to disk so non-ASCII filenames (`图表.png`) round+ * trip safely.+ */+function encodeRfc5987(value: string): string {+ return encodeURIComponent(value)+ .replace(/['()]/g, escape)+ .replace(/\*/g, "%2A")+}++/**+ * POST /api/community/attachmentDownload+ *+ * Moved from /agent (plan §4 MOVE-FLAT, §9 phase 3); bot-only, human actor →+ * 403 via requireBot.+ *+ * Body: `{ id }`.+ * Response: raw binary body + `Content-Type`, `Content-Length`,+ * `X-Alook-Filename` (RFC 5987 percent-encoded).+ *+ * Enumeration-safe: every "you can't have this" path returns the same 404+ * with body "attachment not found" — pending-vs-persisted, wrong-owner, and+ * genuine 404 are indistinguishable to a prober. A distinct 502 fires only+ * when the DB row exists but R2 has drifted (infra fault, not user-facing+ * gate).+ *+ * The body is buffered (`arrayBuffer`) inside the top-level try/catch so an+ * R2 stream error becomes a structured 500 instead of a truncated 200 the+ * daemon-side helper can't parse. The daemon `callDownload` already+ * buffers via `res.arrayBuffer()` (attachments are capped at 25 MB), so no+ * streaming behavior is lost.+ */+export const POST = withCommunityActor(async (req: NextRequest, ctx) => {+ const gate = requireBot(ctx.actor)+ if (!gate.ok) return gate.response+ const botUserId = gate.bot.userId+ try {+ let raw: unknown+ try {+ raw = await req.json()+ } catch {+ return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })+ }+ const parsed = CommunityAgentAttachmentDownloadRequestSchema.safeParse(raw)+ if (!parsed.success) {+ return NextResponse.json({ error: "invalid payload" }, { status: 400 })+ }++ const db = getDb(ctx.env.DB)+ const row = await queries.communityAttachment.getAttachmentById(db, parsed.data.id)+ if (!row) {+ return NextResponse.json({ error: "attachment not found" }, { status: 404 })+ }++ if (row.messageId === null) {+ // Pending row — only the uploading bot may see it (round-trip verify).+ if (row.uploaderId !== botUserId) {+ return NextResponse.json({ error: "attachment not found" }, { status: 404 })+ }+ } else {+ // Persisted row — resolve target scope, then run the standard membership+ // gate. Rewrite any non-2xx to a generic 404 so a prober can't tell+ // "not a member" from "row doesn't exist".+ const message = await queries.communityMessage.getMessage(db, row.messageId)+ if (!message) {+ return NextResponse.json({ error: "attachment not found" }, { status: 404 })+ }+ const channelType = await queries.communityChannel.getChannelType(db, message.channelId)+ if (channelType === "dm") {+ const gate = await requireDMAccess(db, message.channelId, botUserId)+ if (!gate.ok) return NextResponse.json({ error: "attachment not found" }, { status: 404 })+ } else {+ const gate = await requireChannelMember(db, message.channelId, botUserId)+ if (!gate.ok) return NextResponse.json({ error: "attachment not found" }, { status: 404 })+ }+ }++ const obj = await ctx.env.COMMUNITY_MEDIA.get(row.r2Key)+ if (!obj) {+ // Row exists but R2 has no object — infra fault, distinct from the+ // enumeration-safe 404 above.+ return NextResponse.json({ error: "attachment storage unavailable" }, { status: 502 })+ }++ const contentType = row.contentType || obj.httpMetadata?.contentType || "application/octet-stream"+ const size = row.size ?? obj.size+ const headers: Record<string, string> = {+ "Content-Type": contentType,+ "X-Alook-Filename": encodeRfc5987(row.filename),+ }+ if (typeof size === "number") headers["Content-Length"] = String(size)++ // Buffer here (inside try/catch) so an R2 stream mid-read error surfaces+ // as a structured 500 rather than a truncated 200 the client can't parse.+ const buffer = await obj.arrayBuffer()+ return new Response(buffer, { headers })+ } catch (err) {+ log.error("attachment_route_failure", {+ route: "attachmentDownload",+ botUserId: botUserId,+ cause: err instanceof Error ? err.stack ?? err.message : String(err),+ })+ return NextResponse.json({ error: "internal error", code: "internal" }, { status: 500 })+ }+})diff --git a/src/web/src/app/api/community/attachmentUpload/route.ts b/src/web/src/app/api/community/attachmentUpload/route.tsnew file mode 100644index 000000000..03cfba1be--- /dev/null+++ b/src/web/src/app/api/community/attachmentUpload/route.ts@@ -0,0 +1,108 @@+import { NextResponse, type NextRequest } from "next/server"+import { queries, createLogger } from "@alook/shared"+import { getDb } from "@/lib/db"+import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"+import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"+import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"+import { handleAttachmentUpload } from "@/lib/community/upload"++const log = createLogger({ service: "community-agent-attachment-upload" })++/**+ * POST /api/community/attachmentUpload?target=<ref> — moved from+ * /api/community/agent/attachmentUpload (plan §4 MOVE-FLAT, §9 phase 3).+ *+ * Body: multipart/form-data with a single `file` field.+ * Response: `{ id, filename, contentType, size }` — no url, no r2 key (the+ * bot-shaped result: returns a stable pending id, unlike the human upload route+ * which returns a url). Ref-addressed via `?target=<ref>` (kept, not id —+ * Gener #68), so it stays flat and can't fold onto an `[id]` route (Fork B).+ * Bot-only → human actor rejected 403 (`requireBot`, Gener #116). `target` is+ * resolved through `resolveTargetForMember` so the bot's membership ++ * write-permission gate is identical to `send`. Handler body unchanged from the+ * /agent original except the wrapper + identity source (ctx.botUserId →+ * botUserId).+ */+export const POST = withCommunityActor(async (req: NextRequest, ctx) => {+ const gate0 = requireBot(ctx.actor)+ if (!gate0.ok) return gate0.response+ const botUserId = gate0.bot.userId++ // Track any R2 blob written before the D1 insert throws so the catch below+ // can best-effort delete it. Hoisted here so the try/catch can see it.+ let r2KeyToCleanUp: string | null = null++ try {+ const target = req.nextUrl.searchParams.get("target")+ if (!target) {+ return NextResponse.json({ error: "missing target query param" }, { status: 400 })+ }++ const db = getDb(ctx.env.DB)++ const resolved = await resolveTargetForMember(db, botUserId, target)+ if ("error" in resolved) return resolveErrorResponse(resolved)++ let kind: "channel" | "dm"+ let targetId: string+ if (resolved.kind === "dm") {+ const gate = await requireDMAccess(db, resolved.channelId, botUserId)+ if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })+ kind = "dm"+ targetId = resolved.channelId+ } else {+ const gate = await requireChannelMember(db, resolved.channelId, botUserId)+ if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })+ kind = "channel"+ targetId = resolved.channelId+ }++ const result = await handleAttachmentUpload(req, ctx.env, kind, targetId, {+ uploader: "bot",+ uploaderUserId: botUserId,+ })+ if (!result.ok) return result.response++ // R2 blob is committed — remember its key so the D1-throw path can+ // compensate.+ r2KeyToCleanUp = result.r2Key++ const row = await queries.communityAttachment.createPendingAttachment(db, {+ uploaderId: botUserId,+ targetId,+ r2Key: result.r2Key,+ filename: result.filename,+ contentType: result.contentType,+ size: result.size,+ })++ return NextResponse.json({+ id: row.id,+ filename: row.filename,+ contentType: result.contentType || "application/octet-stream",+ size: result.size,+ })+ } catch (err) {+ let r2KeyCleaned = false+ if (r2KeyToCleanUp !== null) {+ try {+ await ctx.env.COMMUNITY_MEDIA.delete(r2KeyToCleanUp)+ r2KeyCleaned = true+ } catch (cleanupErr) {+ log.error("attachment_route_r2_cleanup_failed", {+ route: "attachmentUpload",+ botUserId,+ r2Key: r2KeyToCleanUp,+ cleanupErr: cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr),+ })+ }+ }+ log.error("attachment_route_failure", {+ route: "attachmentUpload",+ botUserId,+ r2KeyCleaned,+ cause: err instanceof Error ? err.stack ?? err.message : String(err),+ })+ return NextResponse.json({ error: "internal error", code: "internal" }, { status: 500 })+ }+})diff --git a/src/web/src/app/api/community/channelMember/route.ts b/src/web/src/app/api/community/channelMember/route.tsnew file mode 100644index 000000000..ce44c6b66--- /dev/null+++ b/src/web/src/app/api/community/channelMember/route.ts@@ -0,0 +1,135 @@+import { NextResponse, type NextRequest } from "next/server"+import {+ queries,+ CommunityAgentChannelMemberRequestSchema,+ DM_SERVER,+ formatHandle,+ isThread,+ parseRef,+} from "@alook/shared"+import type {+ CommunityCliChannelMemberResult as ChannelMemberResult,+ CommunityCliServerMember as ServerMember,+} from "@alook/shared"+import { getDb } from "@/lib/db"+import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"+import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"+import { requireChannelAccess } from "@/lib/community/permissions"++/**+ * POST /api/community/channelMember — `alook channel member --channel <ref>`.+ * Returns the followed members of a channel/thread.+ *+ * Moved from /agent (plan §4 MOVE-FLAT, §9 phase 3); bot-only, human actor →+ * 403 via requireBot.+ *+ * Branches by resolved target:+ * - DM ref → 400 (channel-scoped). Rejected UP FRONT (before+ * `resolveTargetForMember`) so an un-opened DM surfaces the correct+ * channel-scoped 400 instead of a misleading 404 "dm not found".+ * - thread (`type = "thread"`) → always private on the wire; returns the+ * participant roster (`community_thread_participant`). Threads are the+ * NOTIFY dimension: they carry their own notify set irrespective of the+ * parent channel's public/private state. Forum posts share this shape but+ * are not agent-addressable via any current ref grammar, so this branch+ * only fires for threads reached via `<server>/<channel>/#N`.+ * - public top-level channel/forum → `{ visibility: "public", hint }` (no+ * roster enumeration — every server member can see it, so the agent should+ * use `alook server member --server <name>` instead).+ * - private channel / private forum → `{ visibility: "private", members }`+ * sourced from `resolveScopeMembers` (the same audience the fan-out and+ * human UI use).+ */+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)++ let raw: unknown+ try {+ raw = await req.json()+ } catch {+ return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })+ }+ const parsed = CommunityAgentChannelMemberRequestSchema.safeParse(raw)+ if (!parsed.success) {+ return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })+ }++ // Reject DM refs up front: an un-opened DM would otherwise trip+ // `resolveTargetForMember`'s 404 "dm not found" before the DM-branch guard+ // below could emit the specific channel-scoped 400.+ try {+ const p = parseRef(parsed.data.channel)+ if (p.server === DM_SERVER) {+ return NextResponse.json(+ { error: "channel member is channel-scoped — DM refs are not supported" },+ { status: 400 },+ )+ }+ } catch {+ // Fall through — resolveTargetForMember returns the canonical 400.+ }++ const resolved = await resolveTargetForMember(db, botUserId, parsed.data.channel, {+ createDmIfMissing: false,+ createThreadIfMissing: false,+ callerKind: "bot",+ })+ if ("error" in resolved) return resolveErrorResponse(resolved)+ if (resolved.kind === "dm") {+ return NextResponse.json(+ { error: "channel member is channel-scoped — DM refs are not supported" },+ { status: 400 },+ )+ }++ const channelId = resolved.channelId+ const access = await requireChannelAccess(db, channelId, botUserId)+ if (!access.ok) return NextResponse.json({ error: access.error }, { status: access.status })++ const { channel, isPrivate } = access.value++ // Thread branch: the NOTIFY dimension — the roster is the participant set+ // (`community_thread_participant`), always private on the wire regardless of+ // the parent's public/private state. Forum posts are not agent-addressable,+ // so this handler only sees `thread` or top-level channel rows here.+ if (isThread(channel.type)) {+ const userIds = await queries.communityThread.listThreadParticipantUserIds(db, channelId)+ const members = await hydrateMembers(db, channel.serverId, userIds)+ return NextResponse.json<ChannelMemberResult>({ visibility: "private", members })+ }++ if (!isPrivate) {+ const server = await queries.communityServer.getServer(db, channel.serverId)+ const serverName = server?.name ?? channel.serverId+ const hint = `This channel is public. Use \`alook server member --server ${serverName}\` to list who can see it.`+ return NextResponse.json<ChannelMemberResult>({ visibility: "public", hint })+ }++ const scoped = await queries.communityMembersResolver.resolveScopeMembers(db, { scope: "channel", scopeId: channelId })+ const userIds = scoped.map((s) => s.userId)+ const members = await hydrateMembers(db, channel.serverId, userIds)+ return NextResponse.json<ChannelMemberResult>({ visibility: "private", members })+})++/**+ * Hydrate a user id list into `ServerMember[]` — mirrors `listMembers`'s+ * mapping (formatHandle, default role "member", nickname iff set). Users+ * whose account is soft-deleted drop out via `getMembersByUserIds`'s inner+ * join on `user`. Users missing a `community_server_member` row (shouldn't+ * happen in normal flow) also drop out; they never surface as a stub row.+ */+async function hydrateMembers(+ db: ReturnType<typeof getDb>,+ serverId: string,+ userIds: string[],+): Promise<ServerMember[]> {+ if (userIds.length === 0) return []+ const rows = await queries.communityMember.getMembersByUserIds(db, serverId, userIds)+ return rows.map((r) => ({+ handle: formatHandle(r.userName ?? "", r.discriminator ?? "0000"),+ role: r.role ?? "member",+ }))+}diff --git a/src/web/src/app/api/community/inboxPull/route.ts b/src/web/src/app/api/community/inboxPull/route.tsnew file mode 100644index 000000000..16a2cced3--- /dev/null+++ b/src/web/src/app/api/community/inboxPull/route.ts@@ -0,0 +1,83 @@+import { NextResponse, type NextRequest } from "next/server"+import { queries, withD1Retry, CommunityAgentInboxPullRequestSchema } from "@alook/shared"+import { getDb } from "@/lib/db"+import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"++const MAX_PULL = 200++/**+ * POST /api/community/inboxPull — plan §7.+ *+ * Moved from /agent (plan §4 MOVE, §9 phase 3); bot-only, human actor → 403 via requireBot (Gener #116).+ *+ * Grouped-by-channel fill (v4 decision): `ORDER BY channel_id, seq ASC`, one+ * channel's unread always drained fully before the next starts — `seq` is a+ * per-scope counter, so raw cross-channel seq comparison is meaningless (see+ * `listUnreadMessagesForAgent`'s doc comment). Excludes the bot's own+ * authored messages. Never mutates read state — `ack` is the only mutator+ * (debt #2 correction).+ */+export const POST = withCommunityActor(async (req: NextRequest, ctx) => {+ const gate = requireBot(ctx.actor)+ if (!gate.ok) return gate.response+ const { userId: botUserId } = gate.bot++ const db = getDb(ctx.env.DB)++ // Body is optional (`InboxPullRequest = { max? }`) — an empty/missing body+ // is equivalent to `{}`, not a 400. Only a body that parses to JSON but+ // fails schema validation (e.g. `max` out of range) is rejected.+ let raw: unknown = {}+ try {+ const text = await req.text()+ if (text) raw = JSON.parse(text)+ } catch {+ return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })+ }+ const parsed = CommunityAgentInboxPullRequestSchema.safeParse(raw)+ if (!parsed.success) {+ return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })+ }+ const max = Math.min(parsed.data.max ?? MAX_PULL, MAX_PULL)++ // Fetch one extra row to detect whether more unread remain beyond `max`.+ // Each D1 call is wrapped in withD1Retry so a transient miniflare/D1 blip+ // (`internal error; reference`, on isRetryableD1Error's list) is retried+ // instead of surfacing as a hard 500 to the bot — the same armor the+ // human-facing bootstrap route already has. A non-transient throw still+ // propagates (withD1Retry rethrows once retries are exhausted / on a+ // non-retryable error).+ const rows = await withD1Retry(+ () => queries.communityAgentInbox.listUnreadMessagesForAgent(db, botUserId, { max: max + 1 }),+ { route: "community/agent/inboxPull:list-unread" },+ )+ const hasMore = rows.length > max+ const page = hasMore ? rows.slice(0, max) : rows++ // Batch-fetch attachments in one query (plan §Inbox projection). Pending+ // rows (message_id = NULL) never match this inArray, so agent-uploaded+ // pending rows are naturally excluded from the inbox.+ const messageIds = page.map((r) => r.id)+ const attachmentRows = await withD1Retry(+ () => queries.communityAttachment.listByMessageIds(db, messageIds),+ { route: "community/agent/inboxPull:attachments" },+ )+ const attachmentsByMessageId = new Map<string, Array<{ id: string; filename: string; contentType: string | null; size: number | null }>>()+ for (const a of attachmentRows) {+ if (!a.messageId) continue+ const list = attachmentsByMessageId.get(a.messageId) ?? []+ list.push({ id: a.id, filename: a.filename, contentType: a.contentType, size: a.size })+ attachmentsByMessageId.set(a.messageId, list)+ }++ const messages = await withD1Retry(+ () => queries.communityAgentInbox.toAgentMessages(+ db,+ page,+ botUserId,+ attachmentsByMessageId,+ ),+ { route: "community/agent/inboxPull:hydrate" },+ )+ return NextResponse.json({ messages, hasMore })+})diff --git a/src/web/src/app/api/community/inboxSnapshot/route.ts b/src/web/src/app/api/community/inboxSnapshot/route.tsnew file mode 100644index 000000000..b4330f74b--- /dev/null+++ b/src/web/src/app/api/community/inboxSnapshot/route.ts@@ -0,0 +1,27 @@+import { NextResponse, type NextRequest } from "next/server"+import { queries } from "@alook/shared"+import { getDb } from "@/lib/db"+import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"++/**+ * POST /api/community/inboxSnapshot — plan §7. Body `{}`.+ * Non-consuming bodiless summary of pending unread, bucketed per channel/DM.+ *+ * Moved from /agent (plan §4 MOVE, §9 phase 3); bot-only, human actor → 403 via requireBot (Gener #116).+ */+export const POST = withCommunityActor(async (_req: NextRequest, ctx) => {+ const gate = requireBot(ctx.actor)+ if (!gate.ok) return gate.response+ const { userId: botUserId } = gate.bot++ const db = getDb(ctx.env.DB)++ const snapshot = await queries.communityAgentInbox.getInboxSnapshotForAgent(db, botUserId)+ const rows = await queries.communityAgentInbox.toInboxRows(db, snapshot, botUserId)++ return NextResponse.json({+ rows,+ pendingChannels: rows.length,+ pendingMessages: rows.reduce((n, r) => n + r.pendingCount, 0),+ })+})diff --git a/src/web/src/app/api/community/nap/route.ts b/src/web/src/app/api/community/nap/route.tsnew file mode 100644index 000000000..857370cc7--- /dev/null+++ b/src/web/src/app/api/community/nap/route.ts@@ -0,0 +1,82 @@+import { NextResponse, type NextRequest } from "next/server"+import { nanoid } from "nanoid"+import {+ queries,+ makeRuntimeConfig,+ resolveModelConfig,+ formatHandle,+ CommunityAgentNapRequestSchema,+} from "@alook/shared"+import { getDb } from "@/lib/db"+import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"+import { pushAgentNapToMachine } from "@/lib/community/bot-push"++/**+ * POST /api/community/nap — `alook nap --handoff <file>|--text <s>`.+ *+ * Moved from /agent (plan §4 MOVE, §9 phase 3); bot-only, human actor → 403 via requireBot (Gener #116).+ *+ * Agent-self-initiated session reset. The self-serve twin of the owner+ * `reset-session` route: build the bot's RuntimeConfig → push `agent:nap`+ * (carrying the mandatory handoff) to the bot's OWN machine → on delivery+ * (`sent > 0`) write the `nap` audit row. If the daemon is offline+ * (`sent === 0`) return 409 and write NO audit row — the audit signals a real+ * nap landed at the daemon, not a request. Notifies no one: a nap is the+ * agent's private self-state change.+ *+ * Auth is `withAgentRunnerAuth` (runner key), so the bot acts on ITSELF —+ * `ctx.botUserId`/`ctx.machineId` come from the authenticated runner, not a+ * request field, so an agent can only nap itself.+ */+export const POST = withCommunityActor(async (req: NextRequest, ctx) => {+ const gate = requireBot(ctx.actor)+ if (!gate.ok) return gate.response+ const { userId: botUserId, machineId } = 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 = CommunityAgentNapRequestSchema.safeParse(raw)+ if (!parsed.success) {+ return NextResponse.json({ error: "handoff is required", details: parsed.error.flatten() }, { status: 400 })+ }+ const handoff = parsed.data.handoff++ // Resolve the bot's own wake context (runtime + model) to build the config+ // the daemon needs to respawn a fresh session. `botUserId` is the caller.+ const wakeCtx = await queries.communityBot.getBotWakeContext(db, botUserId)+ if (wakeCtx.state !== "ready") {+ return NextResponse.json({ error: wakeCtx.state }, { status: 409 })+ }++ const config = makeRuntimeConfig({+ runtime: wakeCtx.runtime,+ model: resolveModelConfig(wakeCtx.runtime, wakeCtx.modelName),+ agentName: wakeCtx.name,+ agentHandle: `@${formatHandle(wakeCtx.name, wakeCtx.discriminator)}`,+ })+ const launchId = nanoid()++ const { sent } = await pushAgentNapToMachine(ctx.env, machineId, {+ agentId: botUserId,+ config,+ launchId,+ handoff,+ })+ if (sent === 0) {+ return NextResponse.json(+ { error: "daemon offline — cannot nap right now" },+ { status: 409 },+ )+ }++ // Audit on delivery only (mirrors reset/model-switch). No notification.+ await queries.communityBotAuditLog.insertBotAuditNap(db, { botId: botUserId })++ return NextResponse.json({ napped: true })+})diff --git a/src/web/src/app/api/community/reactAdd/route.ts b/src/web/src/app/api/community/reactAdd/route.tsnew file mode 100644index 000000000..8b2afee51--- /dev/null+++ b/src/web/src/app/api/community/reactAdd/route.ts@@ -0,0 +1,98 @@+import { NextResponse, type NextRequest } from "next/server"+import {+ queries,+ CommunityAgentReactAddRequestSchema,+ MAX_EMOJI_BYTES,+ WS_EVENTS,+ isUniqueConstraintError,+} from "@alook/shared"+import { getDb } from "@/lib/db"+import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"+import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"+import { isDmTarget } from "@/lib/community/message-handler"+import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"+import { fanOutToChannel, fanOutToDM } from "@/lib/community/fanout"++/**+ * POST /api/community/reactAdd — agent-facing counterpart of the user+ * route's PUT /api/community/messages/[id]/reactions/[emoji]. Body+ * `{ channel, seq, emoji }`; identity is the bearer voucher (never a+ * client-supplied agentId). Duplicates are idempotent: the DB unique+ * constraint on `(messageId, userId, emoji)` throws, `isUniqueConstraintError`+ * catches it, and the endpoint returns `{ ok:true, duplicate:true }` without+ * a fan-out.+ * Moved from /agent (plan §4 MOVE-FLAT, §9 phase 3); bot-only, human actor → 403 via requireBot.+ */+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)++ let raw: unknown+ try {+ raw = await req.json()+ } catch {+ return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })+ }+ const parsed = CommunityAgentReactAddRequestSchema.safeParse(raw)+ if (!parsed.success) {+ return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })+ }+ const body = parsed.data++ if (Buffer.byteLength(body.emoji, "utf8") > MAX_EMOJI_BYTES) {+ return NextResponse.json({ error: "emoji too long" }, { status: 400 })+ }++ const resolved = await resolveTargetForMember(db, botUserId, body.channel, {+ createDmIfMissing: false,+ createThreadIfMissing: false,+ callerKind: "bot",+ })+ if ("error" in resolved) return resolveErrorResponse(resolved)++ const scopeTarget = { channelId: resolved.channelId }++ if (isDmTarget(resolved)) {+ const gate = await requireDMAccess(db, resolved.channelId, botUserId)+ if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })+ } else {+ const gate = await requireChannelMember(db, resolved.channelId, botUserId)+ if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })+ }++ const row = await queries.communityMessage.getMessageByChannelAndSeq(db, scopeTarget, body.seq)+ if (!row) {+ return NextResponse.json({ error: `no message with seq #${body.seq} in ${body.channel}` }, { status: 404 })+ }++ try {+ await queries.communityReaction.addReaction(db, {+ messageId: row.id,+ userId: botUserId,+ emoji: body.emoji,+ })+ } catch (e) {+ if (isUniqueConstraintError(e)) {+ return NextResponse.json({ ok: true, duplicate: true })+ }+ throw e+ }++ const event = {+ type: WS_EVENTS.REACTION_ADD as typeof WS_EVENTS.REACTION_ADD,+ messageId: row.id,+ userId: botUserId,+ emoji: body.emoji,+ channelId: resolved.channelId,+ }++ if (isDmTarget(resolved)) {+ await fanOutToDM(resolved.channelId, event, { excludeUserId: botUserId })+ } else {+ await fanOutToChannel(resolved.channelId, event, { excludeUserId: botUserId })+ }++ return NextResponse.json({ ok: true })+})diff --git a/src/web/src/app/api/community/read/route.ts b/src/web/src/app/api/community/read/route.tsnew file mode 100644index 000000000..b8460cdb2--- /dev/null+++ b/src/web/src/app/api/community/read/route.ts@@ -0,0 +1,60 @@+import { NextResponse, type NextRequest } from "next/server"+import { queries, CommunityAgentReadRequestSchema } from "@alook/shared"+import { getDb } from "@/lib/db"+import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"+import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"+import { isDmTarget } from "@/lib/community/message-handler"+import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"++/**+ * POST /api/community/read — plan §7. Seq-anchored pagination (NOT+ * `createdAt`-based) — pick at most one of `before`/`after`/`around`+ * (enforced at the Zod layer). Response is `{ items, hasMore, latestSeq? }`+ * — `items`, not `messages` (that name is reserved for `inboxPull`'s shape).+ * Moved from /agent (plan §4 MOVE-FLAT, §9 phase 3); bot-only, human actor → 403 via requireBot.+ */+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)++ let raw: unknown+ try {+ raw = await req.json()+ } catch {+ return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })+ }+ const parsed = CommunityAgentReadRequestSchema.safeParse(raw)+ if (!parsed.success) {+ return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })+ }+ const body = parsed.data++ const resolved = await resolveTargetForMember(db, botUserId, body.channel, {+ createDmIfMissing: false,+ createThreadIfMissing: false,+ callerKind: "bot",+ })+ if ("error" in resolved) return resolveErrorResponse(resolved)++ const scopeTarget = { channelId: resolved.channelId }++ if (isDmTarget(resolved)) {+ const gate = await requireDMAccess(db, resolved.channelId, botUserId)+ if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })+ } else {+ const gate = await requireChannelMember(db, resolved.channelId, botUserId)+ if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })+ }++ const { items, hasMore, latestSeq } = await queries.communityAgentInbox.listMessagesBySeq(db, scopeTarget, {+ before: body.before,+ after: body.after,+ around: body.around,+ limit: body.limit,+ })+ const messages = await queries.communityAgentInbox.toAgentMessages(db, items, botUserId)++ return NextResponse.json({ items: messages, hasMore, ...(latestSeq !== undefined ? { latestSeq } : {}) })+})diff --git a/src/web/src/app/api/community/resolve/route.ts b/src/web/src/app/api/community/resolve/route.tsnew file mode 100644index 000000000..a83f55ca7--- /dev/null+++ b/src/web/src/app/api/community/resolve/route.ts@@ -0,0 +1,83 @@+import { NextResponse, type NextRequest } from "next/server"+import { queries, CommunityAgentResolveRequestSchema } from "@alook/shared"+import { getDb } from "@/lib/db"+import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"+import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"+import { isDmTarget } from "@/lib/community/message-handler"+import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"++/**+ * POST /api/community/resolve — moved from /api/community/agent/resolve+ * (plan §4 MOVE-FLAT, §9 phase 3). Body `{ channel, seq }` — a REF + seq (kept,+ * not id-addressed: Gener #68). Ref-in-body is why this can't fold onto the+ * `[id]`-parameterized human message routes (Fork B): the bot holds a ref, the+ * CLI has no DB to resolve it into a channelId, so `resolveTargetForMember`+ * must run server-side.+ *+ * Bot-only verb: a human actor is rejected 403 (`requireBot`, Gener #116). The+ * handler body is unchanged from the /agent original — only the wrapper+ * (withAgentRunnerAuth → withCommunityActor) and the identity source+ * (ctx.botUserId → ctx.actor.userId) differ. `seq === 0` is the legacy+ * pre-migration sentinel, rejected 404.+ */+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)++ let raw: unknown+ try {+ raw = await req.json()+ } catch {+ return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })+ }+ const parsed = CommunityAgentResolveRequestSchema.safeParse(raw)+ if (!parsed.success) {+ return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })+ }+ const body = parsed.data++ if (body.seq === 0) {+ return NextResponse.json({ error: "seq 0 is not a real message" }, { status: 404 })+ }++ const resolved = await resolveTargetForMember(db, botUserId, body.channel, {+ createDmIfMissing: false,+ createThreadIfMissing: false,+ callerKind: "bot",+ })+ if ("error" in resolved) return resolveErrorResponse(resolved)++ const scopeTarget = { channelId: resolved.channelId }++ if (isDmTarget(resolved)) {+ const gate = await requireDMAccess(db, resolved.channelId, botUserId)+ if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })+ } else {+ const gate = await requireChannelMember(db, resolved.channelId, botUserId)+ if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })+ }++ const row = await queries.communityMessage.getMessageByChannelAndSeq(db, scopeTarget, body.seq)+ if (!row) {+ return NextResponse.json({ error: `no message with seq #${body.seq} in ${body.channel}` }, { status: 404 })+ }++ const attachmentRows = await queries.communityAttachment.listByMessageIds(db, [row.id])+ const attachments = attachmentRows.map((a) => ({+ id: a.id,+ filename: a.filename,+ contentType: a.contentType,+ size: a.size,+ }))++ const message = await queries.communityAgentInbox.toAgentMessage(+ db,+ row,+ botUserId,+ attachments,+ )+ return NextResponse.json({ message })+})diff --git a/src/web/src/app/api/community/send/route.ts b/src/web/src/app/api/community/send/route.tsnew file mode 100644index 000000000..47c28bdc4--- /dev/null+++ b/src/web/src/app/api/community/send/route.ts@@ -0,0 +1,235 @@+import { NextResponse, type NextRequest } from "next/server"+import { queries, withD1Retry, CommunityAgentSendRequestSchema } from "@alook/shared"+import { getDb } from "@/lib/db"+import { withCommunityActor, requireBot } from "@/lib/middleware/community-actor"+import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"+import { requireChannelMember, requireDMAccess } from "@/lib/community/permissions"+import { createCommunityMessage, isDmTarget, type MessageTarget } from "@/lib/community/message-handler"++/**+ * POST /api/community/send — moved from /api/community/agent/send (plan §4+ * MOVE-FLAT, §9 phase 3). Ref-addressed bot send: body `{ channel, content,+ * attachments, replyToSeq?, seenUpToSeq?, nonce? }` where `channel` is a REF+ * (kept, not id — Gener #68). This is why it CANNOT fold onto the human+ * `channels/[id]/messages` POST (Fork B): a bot holds a ref, the CLI can't+ * resolve it to a channelId, so `resolveTargetForMember` runs server-side (and+ * that resolve is also where create-DM/thread-if-missing happens). Humans send+ * via the `[id]` route; this flat verb is bot-only → human actor rejected 403+ * (`requireBot`, Gener #116). Handler body is unchanged from the /agent+ * original except the wrapper + identity source (ctx.botUserId → botUserId).+ *+ * Single resolve, WITH create flags (`createDmIfMissing`/`createThreadIfMissing:+ * true`), rather than a read-only-then-mutating double resolve. Behaviorally+ * identical: a DM/thread row can only be auto-created when it has NEVER had a+ * message sent to it, so that scope's `community_message_seq` counter is absent+ * (`latestSeq === 0`) — it is IMPOSSIBLE for the alignment gate to block a send+ * into a target that doesn't exist yet (blocking requires `latestSeq > seen`,+ * `seen >= 0` always). So auto-create never fires on a request this gate would+ * have blocked — a single resolve is safe and avoids a redundant round trip.+ */+export const POST = withCommunityActor(async (req: NextRequest, ctx) => {+ const gate0 = requireBot(ctx.actor)+ if (!gate0.ok) return gate0.response+ const botUserId = gate0.bot.userId++ 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 = CommunityAgentSendRequestSchema.safeParse(raw)+ if (!parsed.success) {+ return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })+ }+ const body = parsed.data++ const resolved = await resolveTargetForMember(db, botUserId, body.channel, {+ createDmIfMissing: true,+ createThreadIfMissing: true,+ callerKind: "bot",+ })+ if ("error" in resolved) return resolveErrorResponse(resolved)++ const scopeTarget = { channelId: resolved.channelId }++ // Channel-alignment gate (plan §7, debt #2 corrected) — no bypass. The+ // server is the source of truth for the "seen" waterline: a client that+ // omits `seenUpToSeq` is checked against its OWN tracked `lastReadSeq`,+ // never allowed to skip the gate by simply not sending the field.+ //+ // "Unaligned" means the bot has an unread message it could actually PULL —+ // so the gate shares `inboxPull`'s deliverability predicate (join baseline ++ // not-own) via `hasDeliverableUnreadForAgentScope`, NOT the raw channel+ // `nextSeq`. A late joiner (@mentioned into a channel/thread with backlog)+ // has pre-join messages the pull will never deliver; gating on `nextSeq`+ // would block it forever while the pull hands over nothing to advance its+ // `lastReadSeq` — a permanent wedge. `latestSeq` is still fetched: it feeds+ // the optimistic `expectedSeq` claim below and the `blocked` response shape.+ // Each D1 call is wrapped in withD1Retry so a transient miniflare/D1 blip+ // retries instead of hard-500ing the bot (same armor as bootstrap). The+ // alignment DECISION (blocked/unaligned) and the CAS 409 below are+ // structured returns, not thrown errors, so they never enter the retry —+ // only genuine D1 exceptions do (Cecilia red line: never retry business+ // failures).+ const [latestSeq, readState] = await Promise.all([+ withD1Retry(+ () => queries.communityAgentInbox.getLatestSeqForScope(db, resolved.channelId),+ { route: "community/send:latest-seq" },+ ),+ withD1Retry(+ () => queries.communityReadState.getReadState(db, { userId: botUserId, ...scopeTarget }),+ { route: "community/send:read-state" },+ ),+ ])+ const seen = body.seenUpToSeq ?? readState?.lastReadSeq ?? 0+ const hasUnread = await withD1Retry(+ () => queries.communityAgentInbox.hasDeliverableUnreadForAgentScope(+ db,+ botUserId,+ resolved.channelId,+ seen,+ ),+ { route: "community/send:has-unread" },+ )+ if (hasUnread) {+ return NextResponse.json({+ state: "blocked",+ reason: "unaligned",+ unreadCount: Math.max(0, latestSeq - seen),+ latestSeq,+ })+ }++ // Permission gate + MessageTarget reconstruction (plan §5 — threads are+ // channels for routing, but `createCommunityMessage` needs the full+ // 3-variant union to fire `CHILD_CHANNEL_UPDATE` for thread replies).+ let target: MessageTarget+ if (isDmTarget(resolved)) {+ const gate = await requireDMAccess(db, resolved.channelId, botUserId)+ if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })+ target = { kind: "dm", channelId: resolved.channelId, otherUserId: resolved.otherUserId }+ } else {+ const gate = await requireChannelMember(db, resolved.channelId, botUserId)+ if (!gate.ok) return NextResponse.json({ error: gate.error }, { status: gate.status })+ const channel = gate.value+ // Only threads have a non-null parentChannelId in this path — the ref+ // resolver filters name lookups to top-level (parent_channel_id IS NULL)+ // and thread refs (`#N`) create/reuse rows with type="thread". Forum+ // posts are not addressable by any agent ref today, so no `forum_post`+ // arm is needed here.+ target = channel.parentChannelId+ ? {+ kind: "thread",+ channelId: channel.id,+ parentChannelId: channel.parentChannelId,+ serverId: channel.serverId,+ }+ : { kind: "channel", channelId: channel.id, serverId: channel.serverId }+ }++ // Attachments (plan agent-attachment-pipeline.md §Send). Validate every+ // pending id belongs to this bot, kind, and target BEFORE reservation —+ // the (uploader_id, kind, target_id) tuple is a single indexed lookup.+ // Any mismatch returns the same generic 400, no leakage of which id failed.+ const attachmentTargetId = target.channelId+ if (body.attachments.length > 0) {+ const rows = await withD1Retry(+ () => queries.communityAttachment.findPendingAttachmentsForBot(db, {+ ids: body.attachments,+ uploaderId: botUserId,+ targetId: attachmentTargetId,+ }),+ { route: "community/send:attachments" },+ )+ if (rows.length !== body.attachments.length) {+ return NextResponse.json(+ { error: "attachment not found or not attachable to this target" },+ { status: 400 },+ )+ }+ }++ // Reply/cite (plan agent-reply-cite.md §Write) — resolve the cited seq to a+ // message id WITHIN `scopeTarget` (the same channel/DM this send targets).+ // Scope-first: a `replyToSeq` can never cross-cite into another scope. A seq+ // with no matching message here (typo, wrong scope, deleted) is a hard 400 —+ // nothing is posted.+ let replyToId: string | undefined+ if (body.replyToSeq !== undefined) {+ const replyTarget = await withD1Retry(+ () => queries.communityMessage.getMessageByChannelAndSeq(+ db,+ scopeTarget,+ body.replyToSeq!,+ ),+ { route: "community/send:reply-lookup" },+ )+ if (!replyTarget) {+ return NextResponse.json(+ { error: `reply target #${body.replyToSeq} not found in ${body.channel}` },+ { status: 400 },+ )+ }+ replyToId = replyTarget.id+ }++ // `expectedSeq: latestSeq` reuses the exact snapshot the alignment gate+ // above already fetched — no new query. If another agent's `send` wins+ // the race between that snapshot and this claim, `createCommunityMessage`+ // returns a 409 and we translate it into the SAME `blocked`/`unaligned`+ // shape the gate above returns, with a freshly re-fetched `latestSeq` (the+ // stale one is now off-by-at-least-one). The daemon's existing "blocked →+ // inbox pull → retry" handling needs no changes for this (plan §4).+ // NOT wrapped in withD1Retry: createCommunityMessage is a CAS-guarded write+ // (`expectedSeq`). Blindly retrying it on a transient could re-attempt a+ // partially-applied claim; its own conflict handling returns a structured+ // 409 (below) which the daemon already realigns on. Its internal transient+ // resilience, if any, belongs inside the handler, not a blanket outer retry.+ const result = await createCommunityMessage({+ db,+ authorId: botUserId,+ target,+ body: { content: body.content.text, replyToId },+ source: "cli",+ expectedSeq: latestSeq,+ attachmentIds: body.attachments.length > 0 ? body.attachments : undefined,+ clientNonce: body.nonce,+ })+ if (!result.ok) {+ if (result.status === 409) {+ const freshLatestSeq = await withD1Retry(+ () => queries.communityAgentInbox.getLatestSeqForScope(db, resolved.channelId),+ { route: "community/send:fresh-latest-seq" },+ )+ return NextResponse.json({+ state: "blocked",+ reason: "unaligned",+ unreadCount: Math.max(0, freshLatestSeq - seen),+ latestSeq: freshLatestSeq,+ })+ }+ return NextResponse.json({ error: result.error }, { status: result.status })+ }++ // `createCommunityMessage` already fetched the reserved attachments via+ // listByMessageIds (ordered by `position`, which we stamped 0..N-1 in+ // caller order at reservation time). Project directly off `result.attachments`+ // instead of re-issuing the same query.+ const orderedAttachments = (result.attachments ?? []).map((a) => ({+ id: a.id,+ filename: a.filename,+ contentType: a.contentType,+ size: a.size,+ }))++ const message = await queries.communityAgentInbox.toAgentMessage(+ db,+ result.row,+ botUserId,+ orderedAttachments,+ )+ return NextResponse.json({ state: "sent", message, deduped: result.deduped })+})diff --git a/src/web/src/lib/middleware/community-actor.test.ts b/src/web/src/lib/middleware/community-actor.test.tsindex ffe4ad983..02b124c13 100644--- a/src/web/src/lib/middleware/community-actor.test.ts+++ b/src/web/src/lib/middleware/community-actor.test.ts@@ -109,8 +109,13 @@ describe("rejectBot / requireBot guards", () => {expect(rejectBot(human)).toBeNull()})- it("requireBot: 403 for a human, null for a bot", () => {- expect(requireBot(human)?.status).toBe(403)- expect(requireBot(bot)).toBeNull()+ it("requireBot: 403 for a human; narrows to the bot actor for a bot", () => {+ const humanGate = requireBot(human)+ expect(humanGate.ok).toBe(false)+ if (!humanGate.ok) expect(humanGate.response.status).toBe(403)++ const botGate = requireBot(bot)+ expect(botGate.ok).toBe(true)+ if (botGate.ok) expect(botGate.bot).toEqual({ kind: "bot", userId: "b", ownerUserId: "o", machineId: "m" })})})diff --git a/src/web/src/lib/middleware/community-actor.ts b/src/web/src/lib/middleware/community-actor.tsindex cfe33f8da..2d65bcffe 100644--- a/src/web/src/lib/middleware/community-actor.ts+++ b/src/web/src/lib/middleware/community-actor.ts@@ -140,13 +140,25 @@ export function rejectBot(actor: CommunityActor): NextResponse | null {return null}+/** The bot arm of {@link CommunityActor}, with `ownerUserId`/`machineId`. */+export type BotActor = Extract<CommunityActor, { kind: "bot" }>+/*** Symmetric guard for a bot-only verb (inboxPull/inboxSnapshot/ack/nap, and* resolve as a bot op): a human actor → 403 (capability symmetry, Gener #116).+ *+ * Returns the NARROWED bot actor on success so callers get typed access to+ * `ownerUserId`/`machineId` (nap, joinServer, friendRequest need them) without+ * a second discriminant check. Usage:+ * const gate = requireBot(ctx.actor)+ * if (!gate.ok) return gate.response+ * gate.bot.userId // + .ownerUserId / .machineId*/-export function requireBot(actor: CommunityActor): NextResponse | null {+export function requireBot(+ actor: CommunityActor,+): { ok: true; bot: BotActor } | { ok: false; response: NextResponse } {if (actor.kind !== "bot") {- return NextResponse.json({ error: "forbidden: bot-only endpoint" }, { status: 403 })+ return { ok: false, response: NextResponse.json({ error: "forbidden: bot-only endpoint" }, { status: 403 }) }}- return null+ return { ok: true, bot: actor }}